how to define and print a list in apex class - salesforce

syntax for defining and printing a list in an apex class for a custom/standard object in sales force .
public class listpgm {
list <integer>Teacher__c =new list();
}

For Standard Object
List<Account> accs = new List<Account>();//Creating a List for Account Object.
Ex :
List accs = [SELECT Id, Name FROM Account WHERE Name = 'SomeName'];
For Custom Object
List<ObjectName__c> Cust_Object = new List<ObjectName__c>();//Creating a List for Custom Object.
It depends how you want to display the list in User Interface.You can bind List to <apex:repeat>,<apex:Pageblocktable>,<apex:datatable>...and you can bind list to <apex:SelectList>.
Check here : Displaying the list in Pageblocktable.

Related

Dynamic change of field value using sObject

I'm trying to use sObject to dynamically change Name field objects across while organization.
I've tried using SomeId.getSObjectType().newSObject(SomeId) to create the sObject, but when I try to change the Name field I have error
Variable does not exist: Name
Map<Id, string> idsToUpdate = new Map<Id, string>();
// Put the Id's and associated name values in the map
List<SObject> sObjectsToUpdate = new List<SObject>();
foreach(Id idToUpdate : idsToUpdate.keySet) {
SObject o1 = idToUpdate.getSObjectType().newSObject(idToUpdate);
o1.Name = idsToUpdate.get(idToUpdate);
sObjectsToUpdate.add(o1);
}
update sObjectsToUpdate;
As I can see other posts, this is the way of creation dynamic update of objects.
Any idea why this happens?
Not all objects have a name field, you should check for the existence of the name field before trying to set the field also you must use the put method
Map <String, Schema.SObjectField> fieldMap = o1.getSobjectType().getDescribe().fields.getMap();
if(fieldMap.containsKey('Name')){
o1.put('Name', 'Test');
}

I to assign a default account to a custom object using Visualforce page

I am new to salesforce development. I am trying to create a visualforce page which helps to insert a new record into the custom object. Custom object has master-detail relationship with account. I am having issue when assiging a default value to the Account. The account already exists in the accounts table. Here is the Apex class I am trying.
public class RelatedAccount{
public Account parent {get; set;}
public RelatedAccount(ApexPages.StandardController controller){
Transaction__c child = (Transaction__c)controller.getRecord();
if (child.Account__c != null) { parent = [Select ID,Name FROM Account WHERE Account.Name = :'1Company Inc.,' LIMIT 1];
child.Account__c = parent;
}
}}
I am getting the error : "Illegal assignment from Account to Id"
Thanks In advance.
This should work:
child.Account__c = parent.Id
In your case you try to put the "whole" account object object into the Lookup field. But this just needs the Id of the parent account.

Flow: Use new type for variable?

I have a simple new class X which holds some results of a callout to an external system.
In a flow I need a variable of type X. Is there any way to declare a variable of that new type in a flow?
My new class is:
public class FooCalloutResult {
public Boolean success;
public Map<Id, Boolean> results;
public List<String> messages;
public FooCalloutResult() {
success = false;
results = new Map<Id, Boolean>();
messages = new List<String>();
}
}
If you want to get some data in a flow from an apex class you need to have an Process Invocable method - this is done by adding the #InvocableMethod annotation.
Example:
global class lookUpAccountAnnotation {
#InvocableMethod
public static List<String> getAccountIds(List<String> names) {
List<Id> accountIds = new List<Id>();
List<Account> accounts = [SELECT Id FROM Account WHERE Name in :names];
for (Account account : accounts) {
accountIds.add(account.Id);
}
return accountIds;
}
}
With this annotation the class will appear in your list of available elements in the Flow and you need to put the Input and Output that will go into it.
Depending on what kind of operation you want to do you might need to use the Process.plugin interface instead. Please check this article to see which option supports what kind of data to decide on what you need - https://help.salesforce.com/articleView?id=vpm_designer_elements_apex.htm&type=5

Salesforce apex controller extension for custom object and visualforce page

I have 2 custom objects i have created and due to the limitations of salesforce lists and reports i cant get more then 255 characters to be displayed on a long textarea.
Sales_Trip__c
- Name - string
- Date_From - date
- Date_To - date
- Salesman - lookup User
Sales_Trip_Visit__c
- Sales_Trip - master-detail
- Account - master-detail
- Notes - Long Textarea
- Date - date
so i'm trying to create a new visualforce page that displays the sales_trip_visit__c's in a table ordered by Sales_Trip_Visit__c.Date
I have the page working using the Sales_Trip__c standard controller
But that returns the visits unordered.
From what i can tell i cant do that within the page so i am attempting to create an extension for the Sales_Trip__c standard controller that has a method that returns a list of visits ordered by the date.
This is what i have so far and i think i'm not doing something right.
public class mySalesTripControllerExtension {
private final Sales_Trip__c satr;
public mySalesTripControllerExtension(ApexPages.StandardController stdController) {
this.satr = (Sales_Trip__c)stdController.getRecord();
}
public List<Sales_Trip_Visits__c> getVisitList() {
con = new List<Sales_Trip_Visits__c>();
con = [SELECT Date, Account.Name, Notes FROM Sales_Trip_Visits__c WHERE Sales_Trip__c.id = :this.satr.id ORDER BY Date]
return con;
}
}
I'm getting the following error but i think I am doing it completely wrong.
Error: Compile Error: sObject type 'Sales_Trip_Visits__c' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names. at line 18 column 15
Thanks for the help this is now my revised code. and i have kept the nameing convention i am using which is a duplicate custom object same fields / same relationships just a different name ( original had a rich textarea. _2 has a long textarea
public class mySalesTripControllerExtension {
private final Sales_Trip__c satr;
// The extension constructor initializes the private member
// variable acct by using the getRecord method from the standard
// controller.
public mySalesTripControllerExtension(ApexPages.StandardController stdController) {
this.satr = (Sales_Trip__c)stdController.getRecord();
}
public List<Sales_Trip_Visit_2__c> getVisitList() {
Sales_Trip_Visit_2__c con = [SELECT Date__c, Account__r.Name, Notes__c FROM Sales_Trip_Visit_2__c WHERE Sales_Trip__r.Id = :satr.id ORDER BY Date__c];
return con;
}
}
Current error.
Error: Compile Error: Return value must be of type: LIST<Sales_Trip_Visit_2__c> at line 16 column 9
First of all you can make a sorting on a page but you will have to use some javascript for it. A better approach would be as you're doing to make the sorting on the controller side.
You making it right overall except the error i mentioned in a comment.
Here is modified code
public List<Sales_Trip_Visits__c> getVisitList() {
Sales_Trip_Visits__c con = [SELECT Date__c, Account__r.Name, Notes__c FROM Sales_Trip_Visits__c WHERE Id = :satr.id ORDER BY Date__c]
return con;
}

Salesforce (SFDC) - public, static, global keywords - use one list for entire class?

I'm having a hard understanding using public, static, and global keywords with my variables and methods.
Below is a snippet of my code. What I'm trying to do is upon page load, in my constructor create a Set of accountIDs that the user has access to (8-33 this is working). This set will be used to filter queries used in later methods.
What I'm finding is that public pageReference runSearch() has access to 'terrAccSet', but the public static List getsearchAccounts does not have access to it.
If I change it to public static Set terrAccSet, I don't get data in either of the system.debugs - what can I do?
global with sharing class MyClass {
public static List<FRM_Metrics_gne__c> accountSearchGmap {get; set;}
public Set<Id> terrAccSet;
public List<String> terrIdList;
//Constructor
public MyClass() {
terrAccSet = new Set<Id>();
terrIdList = new List<String>();
Set<Id> grpIdSet = new Set<Id>();
Id uid = '00570000001R95e'; //member of TWO territories
//UserTerritory Utid = [SELECT TerritoryId FROM UserTerritory where UserId = :userInfo.getUserId()];
List<UserTerritory> Utid = [SELECT TerritoryId FROM UserTerritory where UserId =: uid ];
for(UserTerritory usrTerr: Utid){
terrIdList.add(usrTerr.TerritoryId);
}
List<Group> grp = [Select Id from Group where RelatedID IN :terrIdList];
for (Group eachgroupd : grp ){
grpIdset.add(eachgroupd.Id);
}
List<AccountShare> accountidList = [SELECT AccountId,UserOrGroupId FROM AccountShare where UserOrGroupId in :grpIdset];
//all accounst that the user has access according to territory hiearchy
for(AccountShare eachas:accountidList ){
terrAccSet.add(eachas.AccountId);
}
}
public PageReference runSearch() {
//Has Data
system.debug('**terrAccSet runSearch** '+terrAccSet);
}
public static List<Custom_Object__c> getsearchAccounts(String multiSearchString) {
//terrAccSet variable is missing
system.debug('**terrAccSet getSearchAccounts** '+terrAccSet);
//logic
return accountSearchGmap;
}
}
Below is a snippet of my code. What I'm trying to do is upon page load, in my constructor create a Set of accountIDs that the user has access to (8-33 this is working). This set will be used to filter queries used in later methods.
This set should be an instance property, not static.
Use static when you want to create a method that does not affect the state of a controller or class, eg. a text parser-text in text out.
You should make the class Global if you want to create a package and make your class available outside your package so that other Apex code can invoke it, or if your class will create webService or REST methods to be exposed.
Public should be used to expose properties to the VisualForce pages that will consume the properties. Otherwise, use Private methods and properties for controller side only processing.
public static List getsearchAccounts(String multiSearchString) {
//terrAccSet variable is missing
system.debug('terrAccSet getSearchAccounts '+terrAccSet);
//logic
return accountSearchGmap;
}
This method should not be static because it accesses an instance property (it reads state).
Simple rule of thumb, if it is a visualforce page + controller, you shouldn't need anything static to do your normal work of querying the database and returning data to the page.

Resources