I'm getting this error while running this VF Page  Error: SObject row was retrieved via SOQL without querying the requested field: Task.LastModifiedById An unexpected error has occurred. Your development organization has been notified.  VF Page: &lt;apex:page standardController=&quot;task&quot; extensions=&quot;TaskHistoryController&quot;&gt;   &lt;apex:form &gt;    &lt;apex:pageBlock &gt;        &lt;apex:pageMessages escape=&quot;false&quot;/&gt;      &lt;/apex:pageBlock&gt;   &lt;/apex:form&gt;    &lt;/apex:page&gt;  Contrloller: public with sharing class TaskHistoryController {    Task objTask; String objTaskId;  public TaskHistoryController(ApexPages.StandardController controller) {     objTask = (Task)controller.getRecord();     Id taskId = objTask.Id;     List&lt;Task_Activity_History__c&gt; listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId];      Task_Activity_History__c taskHistory1 = listTaskActivityHistory.get(0);     Task_Activity_History__c taskHistory2 = listTaskActivityHistory.get(1);     String newValue1 = taskHistory1.New_Value__c;     String newValue2 = taskHistory2.New_Value__c;     String resultAll = buildTemplate(objTask);     ApexPages.Message infoPage = new ApexPages.Message(ApexPages.Severity.INFO, resultAll);     ApexPages.addMessage(infoPage); }  public String buildTemplate(Task task) {     Id lastModifiedBy = task.LastModifiedById;     String userName = '';     List&lt;User&gt; listOfUsers = [SELECT Id, IsActive, LastModifiedById, Name FROM User where Id = :lastModifiedBy];     for(User user :listOfUsers) {         userName = user.Name;     }     Id taskId = task.Id;     List&lt;Task_Activity_History__c&gt; listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId];     String pageHTMLContent = '&lt;HTML&gt;&lt;HEAD&gt;&lt;STYLE&gt;table.user_class, .user_class th, .user_class td { border: 1px solid black; padding: 10px; } table.user_class th { text-align: center; } &lt;/STYLE&gt;&lt;/HEAD&gt;&lt;BODY&gt;&lt;TABLE class=&quot;user_class&quot;&gt;';     pageHTMLContent += '&lt;TR&gt;&lt;TH&gt;Comment Old Value&lt;/TH&gt;&lt;TH&gt;Comment New Value&lt;/TH&gt;&lt;TH&gt;Last Modified By&lt;/TH&gt;&lt;TH&gt;Last Modified Date&lt;/TH&gt;';     for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {         String newValue1 = taskActivityHistory.Old_Value__c;         String newValue2 = taskActivityHistory.New_Value__c;         String lastModifiedById = taskActivityHistory.LastModifiedById;         DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;         pageHTMLContent += '&lt;TR&gt;';         pageHTMLContent += '&lt;TD&gt;' + newValue1 + '&lt;/TD&gt;&lt;TD&gt;' + newValue2 + '&lt;/TD&gt;&lt;TD&gt;' + userName + '&lt;/TD&gt;&lt;TD&gt;' + lastModifiedByDate + '&lt;/TD&gt;';         pageHTMLContent += '&lt;/TR&gt;';         System.debug('pageHTMLContent7 ' + pageHTMLContent);     }     pageHTMLContent += '&lt;/TABLE&gt;&lt;/BODY&gt;&lt;/HTML&gt;';      return pageHTMLContent; }    } Please advise an appropriate solution. Could you please advise how to populate the page with different values depending on the user name who last modified the task record?
120449
I am getting this error with the code below. I've looked into the other cases on here. In my case I am referring to a relationship name (__r) which I am assuming is pulling correctly. It's a field which is a lookup to User :   Agreement_CSH_to_be_completed_by__r  Here is the code which is giving me problems :   public void doManagedClients() {         addMsg('Starting processing of Managed Clients.');         Integer startSize = CSH_Data.size();          String SOQL = 'Select Id, OwnerId, Owner.UserName, Account__c, RecordTypeId, Name, Agreement_Client_Status_History__c ' +             'From Contract_Terms__c Where ' +             '   ( recordtypeid = \''+ ((String)A_N_Rectype).substring(0,15) + '\' ) and ' +                '   Agreement_Client_Status_History__c = \'Monthly\' ' +             'order by createddate desc nulls first' ; system.debug('#####333#### ');               addMsg(DEBUG,'Managed Query is: ' + SOQL + '\n');         for (Contract_Terms__c a: Database.Query(SOQL)) {             if (!a.Agreement_CSH_to_be_completed_by__r.isActive) {                 totalInactiveOwners++;                  addMsg('Account: ' + a.Name +  ', has an inactive owner.  Username: ' + a.Agreement_CSH_to_be_completed_by__r.isActive + '.');             } else {                             totalManagedCSHs++;                 addMsg(DEBUG,'Creating a Managed CSH for Account: ' + a);                 CSH_Data.add(new CSH_and_Share_Pair(a, createClientStatusHistory(a)));                 needflush(false);                 if (error) break;             }         }         needflush(true);         addMsg('End of Managed Clients.');           }   Is it just because I don't have a.Agreement_CSH_to_be_completed_by__r included in the SOQL ? I thought I got different errors for that, so I'm a little confused.  Thank you for your help.
82389
I have a contact in a generic sObject in apex and while I'm able to easily get detail field values using   sObject.get('MyContactField__c')  I'm not able to get fields off the related parent object, and I'm sure the related field is in memory, based on the debug logs. This returns a runtime error:  sObject.get('Account.MyAccountField__c')  with the error     Invalid field Account.MyAccountField__c' for Contact   How do I get a field value off of a parent on a generic sObject?
115907
I am trying to addError on the opportunities based on one condition. But getting System.FinalException: SObject row does not allow errors error while saving the record. Below I have given the code snippet. Please let me know how I can resolve the issue.  if(Trigger.isUpdate &amp;&amp; Trigger.isBefore){         map&lt;Id,Opportunity&gt; newOpptyMap = (map&lt;Id,Opportunity&gt;)trigger.newMap;         OpportunityTriggerHelper.checkforStageDuration(newOpptyMap,Trigger.OldMap);     }   The function is below where I am adding the error statement  public static void checkforStageDuration(Map&lt;Id,Opportunity&gt; oldMap, Map&lt;Id,Opportunity&gt; newMap){         Map&lt;Id,Opportunity&gt; recordsToCheck = new Map&lt;Id,Opportunity&gt;();         for(Id oppId : newMap.keyset()){             if(newMap.get(oppId).StageName != oldMap.get(oppId).StageName){                 recordsToCheck.put(oppId,newMap.get(oppId));             }         }         List&lt;Opportunity_Stage_History__c&gt; oppStageHistory = [select Id,Expected_Stage_Duration__c,Opportunity__c,Duration__c,Reason_For_Delay__c from Opportunity_Stage_History__c where Opportunity__c IN :recordsToCheck.keyset()];         for(Opportunity_Stage_History__c oppHistory : oppStageHistory){             if(oppHistory.Duration__c&gt;oppHistory.Expected_Stage_Duration__c &amp;&amp; oppHistory.Reason_For_Delay__c==null){                 newMap.get(oppHistory.Opportunity__c).addError('The Opportunity has crossed it\'s Stage Duration, Please fill the Reason for Delay !!');             }         }     }
99826
Why my soql query is returning 'RecordTypeId' instead of the fields mentioned in the query?  Here's my query:  SELECT Id, Name, ABC, (SELECT Id, XYZ FROM InnerObject) FROM OuterObj   Note: My query contains a subquery.
82536
I am upserting list of records based on externalId as follows:  List&lt;Database.upsertResult&gt; results = Database.upsert(lstRecords, CustomObject__c.External_Id__c,true);   The results returns as follows:  (Database.UpsertResult[getErrors=();                         getId=a1k0j000000P6CmAAK;                         isCreated=true;                         isSuccess=true;],   Database.UpsertResult[getErrors=();                         getId=a1k0j000000P6CNAA0;                         isCreated=false;                         isSuccess=true;])   The first record is inserted and 2nd record is updated.  Since I am upserting based on externalId, I need to know for which ExternalId the records have been successfully inserted or updated.   doesn't expose any methods. It returns SalesforceId and NOT externalId  I need a results structure like this:  (Database.UpsertResult[getErrors=();                         getExternalId = '1234';                         getId=a1k0j000000P6CmAAK;                         isCreated=true;                         isSuccess=true;],   Database.UpsertResult[getErrors=();                         getExternalId = '1235';                         getId=a1k0j000000P6CNAA0;                         isCreated=false;                         isSuccess=true;])   What would be the best way to achieve this.
28494
I have an apex class which fetches and upserts data from external source to Salesforce. Below is the batch class: global class PolicyCalloutBatchClass implements Database.Batchable&lt;Integer&gt;,Database.AllowsCallouts, Database.Stateful {     global Iterable&lt;Integer&gt; start(Database.BatchableContext context) {         Integer[] values = new Integer[0];         while(values.size() &lt; 2999 || Test.isRunningTest()) values.add(values.size());         return values;     }     global void execute(Database.BatchableContext context, Integer[] values) {                  HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();         JsonParser objJsonParser = (JsonParser) JSON.deserialize(policyresponse, JsonParser.class);                    JsonParser.cls_value clsValue = objJsonParser.value;         Map&lt;String, JsonParser.cls_data&gt; clsDataMap = new Map&lt;String, JsonParser.cls_data&gt;();         for(JsonParser.cls_data objClsData: clsValue.data){             clsDataMap.put(objClsData.id, objClsData);         }         list&lt;Policy__c&gt; updatelist = new list&lt;Policy__c&gt;();         for (String eachIdFromMap : clsDataMap.keySet()){                          Policy__c policy = new Policy__c(                 unique_id__c = clsDataMap.get(eachIdFromMap).id,                 agent_id__c = clsDataMap.get(eachIdFromMap).agentId);             updatelist.add(policy);           }         try{             upsert updatelist unique_id__c;             }         catch(DmlException e){             system.debug('This class didnt compile');         }     }     global void finish(Database.BatchableContext context) {              } }  Below is my Mock test class: @isTest global class MockHttpResponseGenerator implements HttpCalloutMock {     // Implement this interface method     global HTTPResponse respond(HTTPRequest req) {           HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();                         return policyres;     } }  Below is my test class: @isTest  private class PolicyUpdateController_Test {     static testMethod void testPostCallout() {         Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());                    Test.startTest();       Database.executeBatch(new PolicyCalloutBatchClass(), 50);          Test.stopTest();              } }  Now, when I run the above test class, either the test class runs forever without any output or I could see the error as  System.LimitException: Too many callouts: 101  Can anyone please let me know if there is any way to get this done? Thanks!
81364
I'm working on a custom search page, which will search through the fields of the Project object. I use dynamic SOQL query similar to that:  String query = 'SELECT Name, Status__c ...      FROM Project__c WHERE Name LIKE \'%' + String.escapeSingleQuotes(name)      +'%\' + ' OR Status__c = \'' + String.escapeSingleQuotes(status) +'\''; List&lt;Project__c&gt; projects = Database.query(query);   But when I try to add to filter criteria Description__c field, which is Long Text Area, get the following error:  System.QueryException: field 'Description__c' can not be filtered in query call  How can I use Long Text Area fields in filtering of results?
31142
I am trying to write a VF page to list all the id and name columns from a custom object but found an error "List has more than 1 row" in the VF page.  Can anyone tell me what have I done wrong?  VF Page:  &lt;apex:page Controller="MP_controller" showHeader="false" sidebar="false"&gt;   &lt;apex:pageBlock&gt;      &lt;apex:pageBlockTable value="{! mp}" var="item"&gt;         &lt;apex:column value="{! item.id}"/&gt;         &lt;apex:column value="{! item.name}"/&gt;       &lt;/apex:pageBlockTable&gt;   &lt;/apex:pageBlock&gt; &lt;/apex:page&gt;   Apex controller  global with sharing class MP_controller {     public Merchant_Profile__c mp{get;set;}     public MP_controller(){         mp = [SELECT                  ID, name, Profile_account_name__c, Merchant_ID__c, Bank_Code__c, Country_Code__c,                 Currency_Code__c, Merchant_Level__c, Merchant_Type__c, MSO__c, Region__c,                 Retail_Products__c, Transaction_Mode__c, Created_Date__c, Date_Disabled__c, Date_Live__c,                 Merchant_Category_Code__c                FROM Merchant_Profile__c               WHERE Profile_Account_Name__c = '001O000000bQFnyIAG'];     } }
5648
Declared a string and assigned SOQL value as shown below. While running I am getting an error.   String country = 'United States'; String accountQuery = 'SELECT Id,BillingPostalCode,County_Name__c '+      'FROM Account WHERE zipCodeLen__c =9 AND AND BillingCountry = '+ Country;   System.QueryException: unexpected token: 'AND'  System.QueryException: expecting a colon, found 'United'
83578
i need to count total number of records in an sObject which can have around one million records. Will the code below work ? If no, how can this be done ? I dont need to use this in a vf page.   I will be using this COUNT() SOQL Query in a batch class which is scheduled to run at specific time.  AggregateResult results = database.query('SELECT COUNT(id) result FROM someSObject');     System.debug('No of ids are: '+results.get('result'));
32675
I have a VF page that is the 'edit' page for a certain object. I have a button 'Clone'. Upon clicking this button, I wish to be redirected to a new edit page with all the previous objects fields still intact (except for a few that should be cleared and set to default). Note that this new object should not be inserted until I click 'Save'. The Id of the object should be different compared to the previous object, so that on Save, the previous object is not overwritten.   I am thinking I will split this up into two parts, an apex method, and a javascript method for resetting the fields:  &lt;apex:commandButton action="{!saveAsTemplate}" onclick="initTemplate();" value="Clone" /&gt;   The javascript portion is easy enough, but I'm having trouble of figuring out what to do on the apex side, besides for setting the id of the record to null.
76988
To query a single record we have below two approach :  Approach 1. Assign record to a single Account variable as shown below:  Account accountToGet = [SELECT Name From Account where name = 'UniqueAccount' LIMIT 1];   With above line, it throws below error if no record founds : System.QueryException: List has no rows for assignment to SObject  Approach 2. Assign single record to a List variable as mention below :   List&lt;Account&gt; lstAccount = [SELECT Name From Account where name = 'Unknown Account'];    Even if SOQL returns no records, above line doesn't throws an error. We can use below line to avoid NULL errors.  if(!lstAccount.IsEmpty())     System.debug('No Error');   To handle NULL exception in Approach 1, we need to handle NULL exception in try....catch. It looks like an approach where we will error to occur and then handle it in try....catch.  With Approach 2, we can avoid exception to occur and without using try..catch.. also the code will work.  Based on above approaches, I think approach 2 is fine to prevent errors. Can anyone give me suggestion that why should not we use approach 2?
107598
String queryFields = null;              for(Schema.FieldSetMember field : SObjectType.Task.FieldSets.Activity_Detail_Page.getFields()){                  queryFields = (queryFields == null ? field.getFieldPath() : queryFields+', '+field.getFieldPath());               }                String query = 'Select '+queryFields+' from Task where Id=\''+activityId+'\'';               task = Database.query(query);   i'll creating a field-set,now how do i add link on any field?  above code is  for dynamically query creation . below code of page   &lt;apex:pageBlock title="Activity" id="Block1"&gt;       &lt;apex:pageBlockSection title="Activity Detail"&gt;         &lt;apex:repeat value="{!$ObjectType.Task.FieldSets.Activity_Detail_Page}" var="field"&gt;             &lt;apex:outputField value="{!Task[field.fieldPath]}" /&gt;         &lt;/apex:repeat&gt;     &lt;/apex:pageBlockSection&gt; &lt;/apex:pageBlock&gt;    As per the image attached, I want to add a link in Rounded field that liks to account. Can any one help me?
57464
I'm looking for a way to do a SOQL request to get a Task record, but I keep ending up with this error:     Error: Compile Error: No such column 'What' on entity 'Task'. If you   are attempting to use a custom field, be sure to append the '__c'   after the custom field name. Please reference your WSDL or the   describe call for the appropriate names. at line 59 column 25   The 'What' field is labeled as 'Related To' (it's a standard field of the Activity object).  Here's my request generating this error:  Task task = [SELECT Type FROM Task WHERE What = :this.person.Id];   Thanks for your solutions.
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
78056
I am using Salesforce's REST API to (1) retrieve a list of object IDs according to a query, then (2) retrieve the records that correlate to those IDs.  I am familiar with the Salesforce composite documentation .    My request looks like this:  POST: /services/data/v48.0/composite  {     "allOrNone":false,     "compositeRequest": [ {         "method":"GET",         "url": "/services/data/v48.0/query?q=SELECT+Id+FROM+My_Entity+WHERE+(CreatedById+!=+'asdfghjkl')",         "referenceId": "myEntity"         },{         "method":"GET",         "url": "/services/data/v48.0/composite/sobjects/My_Entity?ids=@{myEntity.records[0].Id}",         "referenceId":"myObject"     }] }   My response:  {     "compositeResponse" : [ {         "body" : {             "totalSize" : 21,             "done" : true,             "records" : [ {                 "attributes" : {                     "type" : "My_Entity",                     "url" : "/services/data/v48.0/sobjects/My_Entity/a0D6g000xxxxxxx"                 },                 "Id" : "a0D6g000xxxxxxx"                 }, {*record2*}, {*etc*}             ]},             "httpHeaders" : { },             "httpStatusCode" : 200,             "referenceId" : "myEntity"         }, {         "body" : [ {         "errorCode" : "PROCESSING_HALTED",         "message" : "'myEntity.records' references an invalid Datatype. Only Strings and primitive data types are allowed to be referenced from previous operations."         } ],         "httpHeaders" : { },         "httpStatusCode" : 400,         "referenceId" : "myObject"     } ] }   The first subrequest (the query) executes without errors.  My problem is the second subrequest.  I understand from  that I can refer to the ID of a single item (e.g. myEntity.records[0].Id).  Question: How do I use all items from myEntity.records in the second subrequest?
3180
If I have a custom controller and a custom visualforce page, and I'm passing an ID as a query param, how can I get the associated record for that ID from within the VF page?  public class MyCustomController() {   ... legacy code here }  &lt;apex:page controller="MyCustomController"&gt;   &lt;apex:outputText value="{! SOME VF SYNTAX TO RETRIEVE RECORD GIVEN QUERY PARAM ID}" /&gt; &lt;/apex:page&gt;