function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TechSteveTechSteve 

Variable use in list, soql and for loops as objects value

Hi all, the code below allows me to find the last record greated on the MSQoL__c object and display the name field.

I have a number of different objects that could need to be displayed with this. Now 9 nested if statements could do the job but it wouldn't be pretty. I am carrying the object name in the url from the page no problem but can't get a variable to work within the select statement or in the 'for loop' as the custom object, nor in the list< >. It is found by a for loop but can't use it.

Is there a way to achieve this? all ideas gratefully excepted.

 

 public ApexPages.StandardSetController setrec {
        get {          
            if(setrec == null){    
                setrec = new ApexPages.StandardSetController(Database.getQueryLocator(
                  [SELECT name
                    From MSQoL__c
                    Where MSQClient__c = :ApexPages.currentPage().getParameters().get('cid') Order By name DESC limit 1]));       
            }
            for(Integer i=0; i<mystrings.size(); i++){
                if (ApexPages.currentPage().getParameters().get('form') == mystrings[i]){
                    System.debug(i);
                    MSQoL__c a = [SELECT name From MSQoL__c Where MSQClient__c = :ApexPages.currentPage().getParameters().get('cid') Order By name DESC limit 1];
                    pn.RelformRec__c = a.name;
                }
            }
            return setrec;      
        }
        set;
    }

    // Initialize setrec and return a list of records read by the rec call and the field name you want to see..
  
    public List<MSQoL__c> getSISs() {
         return (List<MSQoL__c>) setrec.getRecords();
    }

WizradWizrad

Constructor your SOQL query as a string and use Database.query(string).

TechSteveTechSteve

Sorry Wizrad, I am new to this and your reply is not clear.

Can I replace the objects in red with a variable from the array or is that not possible?

 

for(Integer i=0; i<mystrings.size(); i++){
                if (ApexPages.currentPage().getParameters().get('form') == mystrings[i]){
                    System.debug(i);
                    if(ApexPages.currentPage().getParameters().get('cid') != null){
                        MSQoL__c a = [SELECT name From MSQoL__c Where MSQClient__c = :ApexPages.currentPage().getParameters().get('cid') Order By name DESC limit 1];
                        pn.RelformRec__c = a.name;
                    }

WizradWizrad

Yes, but youll have to build the entire query as a string.

 

String myQuery = 'SELECT Id FROM Account';
Database.query(myQuery);

 You can write code that could modify the string and put whatever sobject type is applicable there, instead of "Account"