Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

If I have the following variables and query, how can assign the values of each field to their corresponding boolean? The fields are Checkboxes on the 'myObj' object.

public with sharing class MyClass {

    Boolean one;
    Boolean two;
    Boolean three;
    Boolean four;

    public MyClass(ApexPages.StandardController stdController) {

        planid = stdController.getId();

        String query = 
            'SELECT one__c, two__c, three__c, four__c, FROM myObj__c WHERE ID = :planid ';

    }

}

Cheers!

share|improve this question

3 Answers 3

up vote 5 down vote accepted

Since you are using id in the where clause your query will return only a single record. In that case you case execute the query using database.query() method and assign the variables.

public with sharing class MyClass {

    Boolean one;
    Boolean two;
    Boolean three;
    Boolean four;

    public MyClass(ApexPages.StandardController stdController) {

        planid = stdController.getId();

        String query = 'SELECT one__c, two__c, three__c, four__c, FROM myObj__c WHERE ID = :planid limit 1';

        myObj__c obj = database.query(query);
        one = obj.one__c;
        two = obj.two__c;
        three = obj.three__c;
        four = obj.four__c;

    }

}

I have added a LIMIT statement to the soql. This way you can assign the result to a single variable. For further understanding, you can also refer the below link: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm

share|improve this answer

One way of doing this to define the sObject as a class level variable and ccess the object fields wherever required instead of separate variables.

public with sharing class MyClass {

    public myObj__c myObj {get; set; }

    public MyClass(ApexPages.StandardController stdController) {

        planid = stdController.getId();

        myObj = [SELECT one__c, two__c, three__c, four__c, FROM myObj__c WHERE ID = :planid  limit 1];

    }

}

then you can directly access myObj.one__c , myObj.two__c etc.. wherever you need it.

share|improve this answer

Query for the record & assign from there:

List<MyObj__c> myObList = database.query(query);

MyObj__c myObj = new MyObj__c();

if (!myObList.isEmpty()) {

    myObj = myObList[0];
}

one = myObj.One__c;
two = myObj.Two__c;
three = myObj.Three__c;
four = myObj.Four__c;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.