• Danish Hoda
  • SMARTIE
  • 1832 Points
  • Member since 2016
  • Salesforce Enthusiast|Lightning Champion
  • Cognizant


  • Chatter
    Feed
  • 61
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 448
    Replies
Hello
In my org, we already have the standard email-to-case setup. It uses our customercare@mycompany.com email address.
We also have "Case Auto Response Rule" that catches all emails coming to customercare@mycompany.com and sends a templated response with the case id.
Now, I have written a custome InboundEmailHandler to catch all incoming emails, check the subject line and do stuff in code.

Problem/Question:
Instead of creating a new email address to use for this customer handler, I would like to connect this to our main customercare@mycompany.com email address.  Any emails sent to this address should first go through my custom handler and then do email-to-case and Case Auto Response.

Any help would be greatly appreciated
I am getting null as value after desearlise of the callout response
 
List<Map<String, Object>> myMaps = new List<Map<String, Object>>();
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://priyesh01.github.io/SampleJson/JsonDummy.json');
request.setMethod('GET');
HttpResponse response = http.send(request);
System.debug('$$Response'+response.getBody());
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
   System.debug('I am able to hit end point');
   Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
       		myMaps = new List<Map<String, Object>>();
      List<Object> draftAlarmsRequest = (List<Object>) results.get('draftAlarmsRequest');
  system.debug('$$ draftAlarmsRequest '+draftAlarmsRequest);
}
I am geeting null in the draftAlarmsRequest.

 
I am using Flow before save to update name field of opportunity and its causing my test classes fail FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]
Hi All,
I am learning the salesforce and wanted to understand the below which in the Trigger concept.

I get the below result
Code: [SELECT Id,Name,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
output: {0012w00000CWweoAAD=Account:{Id=0012w00000CWweoAAD, Name=Grapes & Melons}}

and then I tried accessing the Opportunities by useing the below code line
Code:
System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities);

output:
acctsWithOpps.get(a.Id).Opportunities.size()=(Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b2mCAAQ, Name=Grapes & Melons Opportunity}, Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b2mMAAQ, Name=Grapes & Melons Opty}, Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b44SAAQ, Name=Grapes & Melons Opportunity})

How do i need to write the code to access each opportunity field details if i wanted to access. Let say I wanted to check a particular type of opportunity is existed or not and then do an operation.

Thank you!
Hello, I have two record types: X1 and X2

Controling picklist: Type has values 1, 2, 3, 4, 5
Dependent picklist: Subtype has A, B, C, D, E

For record type X1 I need the Subtype value to equal A if Type equals value 1.
For record type X2 I need the Subtype alue to equal B if Type equals value 1.

Is this possible in any way or do I have to create twice as much values in Type field availible only for some record types?
Hello everyone!

I am using apex:commandLink for a VF list page but it is opening the wrong edit page. The edit button is currently opening the edit opportunity product details and I need it to open the Product Line Item schedules instead (this page: /related/OpportunityLineItemSchedules/view). I have tried using different actions, a custom URL, and a ton of other options but I can't get anything to work. Does anyone have an answer? 

Thanks! 

VF page with the button: 
User-added image
Current Code:
<apex:page standardController="Opportunity" action="{!getOLIS}" tabStyle="Opportunity" extensions="OpportunityScheduleExtension" lightningStylesheets="true">
 <apex:form >
     <apex:pageBlock >
     <apex:pageBlockTable value="{!lstOLIS}" var="lst" >
          <apex:column headerValue="Product" value="{!lst.OpportunityLineItem.Product2Id}"/>
          <apex:column headerValue="Date" value="{!lst.ScheduleDate}"/>
          <apex:column headerValue="Revenue" value="{!lst.Revenue}"/>
         <apex:column ><apex:commandLink action="{!edit}" value="Edit" id="EstablishOpportunityLineItemSchedules"/></apex:column>
     </apex:pageBlockTable>
     </apex:pageBlock>
 </apex:form>
</apex:page>
 
public with sharing class OpportunityScheduleExtension {
    Opportunity objOpp;
    public list<OpportunityLineItemSchedule> lstOLIS {get;set;}
    public OpportunityScheduleExtension(ApexPages.StandardController controller) {
        this.objOpp= (Opportunity)controller.getRecord();
    }
    
   
    public void getOLIS(){
        lstOLIS = new list<OpportunityLineItemSchedule >();
        system.debug('objOpp---------->'+objOpp);
        for(OpportunityLineItemSchedule objOLIS:[Select Id, ScheduleDate, Revenue,
                                                 OpportunityLineItem.Product2.Name,
                                                 Description,Product_Name2__c, NAME__c
                                                 from OpportunityLineItemSchedule 
                                                 where OpportunityLineItem.OpportunityId =:objOpp.Id] ){
            lstOLIS.add(objOLIS);                                             
        }
    }    
}

 
I tried learning Apex coding only to realize it will take a while to learn significant enough to create the triggers that I want which I can do with native declarative tools.

I want to know if Visualforce is faster to learn than Apex and if it's even possible to learn without learning Apex first? 
JS Controller :   method calling from Comp button.
 
createContact: function(component, event, helper){ //
         
         var createRecordEvent = $A.get('e.force:createRecord');
      
            createRecordEvent.setParams({
                'entityApiName': 'Contact',
                "defaultFieldValues": {
                    'Phone' : '415-240-6590'}
            });
            createRecordEvent.fire();
        
    }

Getting error : This page has an error. You might just need to refresh it. Action failed: c:getContactComp$controller$createContact [Cannot read property 'setParams' of undefined] Failing descriptor: {c:getContactComp$controller$createContact}



Requirmeent: on click of button, want to display create contact screen with default phone or any field.
Hi There,

I have created Email alerts with required informaiton(Template, sender and to Address etc.) on Work order object.
FYi, It redirected me to classic email alert page when clicked on "Creat new email alert" while I am building application in Lightning. I am using Play ground environent and with system administrator role.

Now once Email alert is created, I created a new process using process builder. Based on Criteria, I am calling a flow in action 1 and in action 2, i am trying to call a email alert. But when i select email alert, i dont see any existing email alerts coming up in drop down. I cross checked and objets referred are same for both email alert and process builder.

Am I missing anything with regards to permissions, page layout etc,.? Why my email alerts are not showing up in auto search control? Any help pls.?

Thanks,
Ravi
Hi All,
I'm little confused to choose  trigger/process builder with my scenario could you please help me with this.
I have parent and child objects with Lookup relationship. I need to auto update parent picklist field with conditions as follows
1.If parent has child records created in last 2 months from todays date update to valueA
2.If parent has child records in the past and there have not been any childs in last 2 months from todays date then ValueB
3.If parent never have any childs update to valueC

I hope we cant  use process builder for this and trigger is preferred to write on child object but which trigger context i should use.
Could any one please give me an idea how to do this.
thank you.
<apex:page controller="Task2Apex">
    <apex:form >
        <apex:pageBlock title="Account Name" >
            <apex:selectList value="{!selectedAccId}" size="1">
                <apex:selectOptions value="{!AccountNames}" />
                <apex:actionSupport event="onchange" action="{!showContacts}" reRender="op" />
            </apex:selectList><br/><br/>
            
         <apex:outputPanel id="op">
            <b><apex:outputText value="Related Contacts" rendered="{!renderPBtable}"/></b>
            <b><apex:outputText value="No Contacts on this Account" rendered="{!noContact}" style="color: red;"/></b>
            <apex:pageblockTable title="Contacts" value="{!conlist}" var="sc" id="relatedContactsBlock" rendered="{!renderPBtable}">
                <apex:column value="{!sc.name}"/>
                <apex:column value="{!sc.phone}"/>
            </apex:pageblockTable>
        </apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class Task2Apex {

    public Id selectedAccId{get;set;} 

    public List<Contact> conlist {get;set;}   
    
    public Boolean renderPBtable {get;set;}
    
    public Boolean noContact {get;set;}

    public List<SelectOption> getAccountNames() {
        List<SelectOption> accOptions= new List<SelectOption>();
        system.debug(selectedAccId);
        accOptions.add( new SelectOption('','--Select--'));
        for(Account acc : [select Id,name from Account ] ) {
            accOptions.add(new SelectOption(acc.Id,acc.name));
        }
        return accOptions;
    }

    public PageReference showContacts(){
        conlist=[select name,phone from Contact where Accountid=: selectedAccId];
        if(conlist.size() > 0)
        {
            renderPBtable = true; 
            noContact = false;
        }
        else
        {
            renderPBtable = false;
            noContact = true;
        }
        return null;   
    }
  
}

I want to Include edit link on each child record.
Thanks in Advance.
I have a situation where i want to display the field value which should show sub string value of field inside aura iteration eg email field is test1.user1@gmail.com i want to display value as test1.user1. ho can i achieve this?
<th data-label="Id" scope="row">
          <div class="slds-truncate" title="Cloudhub">
        <a href="{!'/one/one.app?#/sObject/'+ singleRec.Id + '/view'}" target="_blank">{!singleRec.Email}</a>                                           </div>
                                        </th>

 
Hello, I need to delete certain documents. This is the code I've been using:
    List<ContentDocumentLink > docs;
        docs = [SELECT Id, Linkedentity.name, Linkedentity.id,ContentDocument.CreatedDate  
                FROM contentDocumentLink 
                WHERE Linkedentityid 
                IN (SELECT Id FROM lead where createddate < Last_N_Days:7  ];  
            delete docs;

After I execute this, it looks like the contentDocumentLinks become deleted, however my storage usage is still the same number and percentage.Will the above code completely delete those files? 
On a visual-force page of a workorder record, I've to display list of workorders created for the same location where the createddate is within the last 30 days of the creationdate of the current record.
For ex: If the current record was created on Jan 31st for a location A, I want to display all the workorders that were created from Jan 1st to 31st for location A.

This is the query I've but it obviously displays records created in last 30 days but not the records created in last 30 days of createddate of the current record. How can I modify my query?
CWOs=[SELECT Id, Status, location.Name, createddate FROM WorkOrder WHERE location.Name = : getwo().location.Name and id != : getwo().id and recordtype.name = 'Child' and createddate = LAST_N_DAYS:30 ORDER BY CreatedDate asc];

 
  • April 13, 2020
  • Like
  • 0
<apex:page standardController="Campaign" extensions="ForSaleLookupOnCampaignController"> 
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");                  
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
   
}
    </script>
    <apex:form >
        <apex:pageBlock >
             <apex:pageBlockButtons >
                <apex:commandButton value="Save" style="width: 100px; height: 30px" action="{!processSelected}" rerender="table2"/>
            </apex:pageBlockButtons>
            <p style="font-size: 15px;font-weight: bold;">Select FID :</p><apex:inputfield style="width: 200px; height: 30px" value="{!Campaign.For_Sale__c}" id="forsaleid"/><br/>
            <apex:pageblockSection title="Related Campaign Members" collapsible="false">
                <apex:pageBlockTable value="{!wrapcontactList}" var="conWrap" id="table" title="All Related Campaign Members">     
                    <apex:column >
                        <!--apex:facet name="header">
                          <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                         </apex:facet-->
                        <apex:inputCheckbox value="{!conWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!conWrap.con.Name}" />
                    <apex:column value="{!conWrap.con.Account.name}" />
                </apex:pageBlockTable>
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
public class ForSaleLookupOnCampaignController { 
    public List<CampaignMember> Campaignmemberlist{get;set;} 
    public Campaign cmp {get;set;} 
    public List<wrapContact> wrapcontactList {get; set;}
    public List<Contact> selectedcontacts{get;set;}
    set<id>conid=new set<ID>();
    public String ID { get; set;}
    set<id>ForSaleid=new set<id>();
    public ForSaleLookupOnCampaignController (ApexPages.StandardController standardControllerParam) {
        this.cmp = (Campaign)standardControllerParam.getRecord();
        Campaignmemberlist = [SELECT id,name,Campaignid,Company__c,type,For_Sale__c,Contact.For_Sale__c  FROM CampaignMember WHERE Campaignid = : ApexPages.currentPage().getParameters().get('id') ];
        for(CampaignMember cm:Campaignmemberlist){
            conid.add(cm.ContactId);
            ForSaleid.add(cm.For_Sale__c);
        }
        //
        if(wrapContactList == null) {
            wrapContactList = new List<wrapContact>();
            for(Contact c: [select Id,Name,Account.name,For_Sale__c from Contact where id=:conid]) {
                wrapContactList.add(new wrapContact(c));
            }
        }
        
    }
    public PageReference processSelected() {
        PageReference pr;
        selectedcontacts = new List<contact>();
        system.debug('for sale '+cmp.For_Sale__c);
        for(wrapContact wrapcontactObj : wrapcontactList) {
            if(wrapcontactObj.selected == true) {
                selectedcontacts.add(wrapcontactObj.con);
                
            }
        }
        for(contact s:selectedcontacts){
            s.For_Sale__c=cmp.For_Sale__c;
        }
            try{
                
                database.update(selectedcontacts);
                
            }catch( Exception e ){
                ApexPages.addMessages(e);
            }
            system.debug('selectedcontacts'+selectedcontacts);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'FID Update on Contact'));
      return pr;   
    }
    public class wrapContact {
        public Contact con {get; set;}
        public string forsaleid{get;set;}
        public Boolean selected {get; set;}
        
        public wrapContact(Contact c) {
            con = c;
            forsaleid=c.For_Sale__c;
            selected = false;
        }
    }
}
How should I show success message on VF Page
& another thing is
here <apex:inputfield style="width: 200px; height: 30px" value="{!Campaign.For_Sale__c}" id="forsaleid"/> when I click on button & page is load the value is already populate on this but I want to clear this value when page populate how can I do that?


 

I have 2 array

-> The First array consists of all the values.

-> In the second array, consist of selected values  Here I need to filter the value which is already present

Hi, I am new to LWC ​​​​​​, trying dynamically add/remove rows for a table scenario. I can able to add the row by click on the + button. After added that rows I want to enter some values in text boxes and save into account object by click on save buttton. Also do the delete action as well to delete the specific row by click on delete button. 

I am facing issue with save & delete records. How I can solve this? Can anyone give me some guidence to solve.

AddDeleteRow
dynamicAddRow.html

<template>
                  
    <div class="slds-m-around--xx-large">
        <div class="slds-float_right slds-p-bottom_small">
            <h1 class="slds-page-header__title">Add Row
                <lightning-button-icon icon-name="utility:add"  size="large" variant="bare" alternative-text="Add" onclick={addRow}> </lightning-button-icon>
            </h1>
        </div>
        <div class="container-fluid">        
            <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div class="slds-truncate">#</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Name">Account Name</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Account Number">Account Number</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Phone">Phone</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Action">Action</div>
                        </th>
                    </tr>
                </thead>   
                <tbody>      
                    
                    <template for:each={accountList} for:item="acc" for:index="index">
                        <tr key={acc.Id}> 
                            <td>{index}</td>                                                  
                            <td>
                                <lightning-input label="Name" value={acc.Name} onchange={handleNameChange}></lightning-input>                               
                            </td>
                            <td>
                                <lightning-input label="Account Number" value={acc.AccountNumber} onchange={handleAccountNumberChange}></lightning-input>                        
                            </td>
                            <td>
                                <lightning-input label="Phone" value={acc.Phone} onchange={handlePhoneChange}></lightning-input>
                            </td>
                            <td>
                                <a onclick={removeRow}> 
                                    <lightning-icon icon-name="utility:delete" size="small" style="margin-top: -4px; margin-right: 0px;" ></lightning-icon>
                                    <span class="slds-assistive-text">Delete</span>
                                </a>
                            </td> 
                        </tr>
                    </template>
                     
                </tbody>
            </table>
            <div class="slds-align_absolute-center slds-p-top_small">                
                <lightning-button name="Save" label="Save" onclick={saveRecord} ></lightning-button>
            </div>
        </div>
    </div>

</template>
 
dynamicAddRow.js

import { LightningElement, track,api } from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ACCOUNTNUMBER_FIELD from '@salesforce/schema/Account.AccountNumber';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import saveAccounts from '@salesforce/apex/AccountController.saveAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreateDynamicRecord extends LightningElement {
    @track accountList = []; 
    @track index = 0;
    @api recordId;
    @track name = NAME_FIELD;
    @track industry = ACCOUNTNUMBER_FIELD;
    @track phone = PHONE_FIELD;

    @api record = {
        firstName : '',
        lastName : '',
        Email : '',
        Phone : '',
        Title : ''
    }

    addRow(){

        this.index++;
   
        this.accountList.push ({
            sobjectType: 'Account',
            Name: '',
            AccountNumber : '',
            Phone: ''
        });

        console.log('Enter ',this.accountList);
        
       // this.accountList.push(this.record);
        //console.log(' After adding Record List ', this.accountList);
    }
    
    removeRow(){

        var index = this.index;
      
        if(this.accountList.length>1)
           this.accountList.splice(index, 1);

        //this.dispatchEvent(new CustomEvent('deleterow', {detail: this.index}));
        //console.log(' After adding Record List ', this.dispatchEvent);
    } 

    acc = {
        Name : this.name,
        AccountNumber : this.accNumber,
        Phone : this.phone
    }

    handleNameChange(event) {
        this.acc.Name = event.target.value;
        console.log("name", this.acc.Name);
    }
    
    handleAccountNumberChange(event) {
        this.acc.AccountNumber = event.target.value;
        console.log("AccountNumber", this.acc.AccountNumber);
    }
    
    handlePhoneChange(event) {
        this.acc.Phone = event.target.value;
        console.log("Phone", this.acc.Phone);
    }
    
    saveRecord(){        
        saveAccounts(this.acc.accountList)
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.acc.Name = '';
                    this.acc.AccountNumber = '';
                    this.acc.Phone = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Account created successfully',
                            variant: 'success',
                        }),
                    );
                }
                
                console.log(JSON.stringify(result));
                console.log("result", this.message);
                /*console.log(' After adding Record List ', result);
                this.accountList = result;
                console.log(' After adding Record List ', this.accountList);*/
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log("error", JSON.stringify(this.error));
            });
    }
      
}
 
AccountController.apex  

public with sharing class AccountController { 
 
    @AuraEnabled( cacheable = true ) 
    public static List< Account > getAccounts() { 
      
        return [ SELECT Id, Name, Industry FROM Account LIMIT 10 ]; 
         
    } 
     
    @AuraEnabled( cacheable = true )
    public static void saveAccounts(List<Account> accList){
        Insert accList;
        /*if(accList.size()>0 && accList != null){
            insert accList;
        }*/
    } 
}
Thanks 
Siva
 
Hi, I want to build a component which has a saves button on its UI.
And when i hit the button ,it's together navigate to the next component and save the data on first one.
Hi,

I'm using the Kingswaysoft SSIS integration to import and update records in Salesforce. One step imports Opportunities and links them to exisitng Accounts and Contacts (we have Person Accounts).

However, some records fail with the dreaded INVALID_FIELD_FOR_INSERT_UPDATE error on ContactId. I can't work out why this happens, because many similar records in the same batch pass and are imported correctly with the Contact link.

I would appreciate some help identifying what the cause could be so I can fix it to always work for all reords.

Thanks
in following code 

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId]; return result;
}
}
what is the use of this bold line in above code can any one explain mein simple words.
thank you
I am working on Lightning aura components. The problem is in my servide side apex controller, its not returning the expected result. Te result is [Object,Object]

BoatSearchResults.cmp

<aura:component controller = "BoatSearchResults" implements="flexipage:availableForAllPageTypes" access="global" >
   <aura:attribute name="boats" type="Boat__c[]"/>

     <lightning:layout multipleRows="true">
           <lightning:button variant="brand" label="Search" onclick="{! c.searchBoat }" aura:id="SearchButton" />
        <aura:if isTrue="{!v.boats.length > 0}">
            <aura:iteration items="{!v.boats}" var="bot">
                <lightning:layoutItem  size="3" flexibility="grow" class="slds-m-around_small">
                    <c:BoatTile boat="{!bot}" />
                </lightning:layoutItem>
            </aura:iteration>
            <aura:set attribute="else">
                <lightning:layoutItem class="slds-align_absolute-center" flexibility="auto" padding="around-small">
                    <ui:outputText value="No boats found" />
                </lightning:layoutItem>
            </aura:set>
        </aura:if>
    </lightning:layout>
  
</aura:component>

js file

({
       searchBoat : function(component, event) {
            let action = component.get("c.getBoats");
            action.setCallback(this, function(response){
            let state = response.getState();
            if (state === "SUCCESS") {
                console.log('TEST ' + response.getReturnValue());//  this ouput is [Object, Object]
                component.set("v.boats", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
       },
    
   
})

BoatSearchResults.apxc

public with sharing class BoatSearchResults {
    @AuraEnabled
    public static List<Boat__c> getBoats() {
     return [select id,Name,BoatType__c,Contact__c,Picture__c from Boat__c];
    
    }
  
}


BoatTile.cmp

<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute name="boat" type="Boat__c"/>

    <lightning:button class="tile">
        <!-- Image -->
        <div style="{!'background-image: url(\'' + v.boat.Picture__c + '\')'}" class="innertile">
            <div class="lower-third">
                <h1 class="slds-truncate">{!v.boat.Name}</h1>
            </div>
        </div>
    </lightning:button>
</aura:component>


 
Hi, 
I have a before update trigger on an account number field which increments the number field by 1 every time a record is updated or created new.
Also, a process builder on the same field and doing the same increments on the same field by one so when I put value "1" in that field it updates it to 4 so does that means trigger executes again after process builder updates that field 
Thanks in advance 
I'm new to Apex and I stumbled upon this. I've a custom object named Cast which has a Rating field. I wanted to update all the Rating values to 3. I selected the Id field and updated all of them.
User-added image

I've a similar problem in which I want to update birth date field of all records where birth date is > 2000. This is my code. However I'm getting an exception SObject row was retrieved via SOQL without querying the requested field:

If I include Birthdate__c field in my query, the error goes away.
List<Person__c> listPersons = [SELECT Id FROM Person__c WHERE BirthDate__c > 2000-01-01];
for(Person__c person : listPersons){
	person.BirthDate__c = person.BirthDate__c.addYears(-100); 
}

try{
 Update listPersons;   
}
catch(DMLException ex){
    System.debug(ex.getMessage());
}
Why is that in my first code sample to update Rating field I was able to do that without selecting itin my query but why do I have to select Birthdate field for my second code?
 
Hello,
I have process builder that updates custom field called "First Activity" when the a Task is created under Lead or Contact. It works fine when the activities are of "log a call" or "creating new task" Type. But when a user sends an Email from Lead or Contact my process builder is not updating "First Activity" field. 

I reached out to Salesforce support they said this is not achivable thru workflow or process builder. They said to try Apex Trigger .... Please help
Any sugestion will be apprciated
-Yeshi 
On my community page(A) I have a LWC component with a button which onclick will call an apex method to create a record. If the create is successfull it needs to redirect to another community page(B). Onclick calls the method handleConfirm.
The issue I am facing is though the record is created/saved succesffully in the backend, the system doesn't redirect to the community page B. It remains on community page A.
Through debug, I confirmed the code under the handleConfrim .then does get executed but nothing happens.    
Below is the code snippet.
connectedCallback() {
        this.prod = something;
        getAsstPrgmLst({aId:this.prod})
        .then(result => {
            // does something in a for loop to populate some options.
        })
        .catch( 
            error => {
                this.error = error;
            })
        .finally(() => this.showflag = true );
    }

handleConfirm(){
        createSubscription({aId: this.asstPgm.Id,
        ep:this.prgm, uId: this.userId})
        .then(result=>{
            this.isSuccess = true;
            this[NavigationMixin.Navigate]({
                type: 'comm__namedPage',
                attributes:{
                    pageName:'connectpageB'
                }
            });
        })
        .catch(error =>{
            this.error = error;
        });
        
    }

What I am doing wrong here? Any suggestions on how I could fix this issue.
I have 2 tabs in application.
first is application, second is summary.
application has some field in which we input data and save,
and summary shows all data entered in application,
Summary 
also has edit button, which redirect to application tab.
I want functionality such that, after redirecting to application tab.
whatever fields are empty in application should be highlited with some message below it
Hi Everyone,

As I am new to apex development. I met with a requirement where I have an apex class and i have written a soql query  which fetches list of accounts and list of its child records in a variable....There are 4 child objects for accounts....My concern is how to get object wise separate records data from the variable..and set it in wrapper class.I can use for loop inside a for loop but we are minding it as a bad practise with out using nested for loop can any one suggest me any thing..mapping account id to child records is became difficult to me...thanks in Advance....
Hi all and thanks for reading!
I'm trying to test this class which uses some custom metadata and I'm having lots of trouble with it:
 
public class SendingSAPServices {
    
    public static final String SERVICE_SYNC_CLIENTE = 'SYNC_CLIENTE';
    public static final String SERVICE_SYNC_SEDE = 'SYNC_SEDE';
    public static final String SERVICE_SYNC_MATERIAL = 'SYNC_MATERIAL';
    public static final String SERVICE_SYNC_PEDIDO = 'SYNC_PEDIDO';
   
	public static void saveBy(List<Account> accounts){   
        
        List<SendingSAP__c> sendingsToInsert = new List<SendingSAP__c>();
        ConfiguracionServiceSAP__mdt confService = getConfiguracionService(SERVICE_SYNC_CLIENTE);
        //accounts.get(0).addError('error 1: ' + confService);
        if(confService != null){
            for(Account account : accounts){
                SendingSAP__c sending = getNew(confService, 'Account__c', account);
                sending.Request__c = SAPServices.getClienteSAPToSync(account);
                sendingsToInsert.add(sending);
            }
            insert sendingsToInsert;
            setLastSendingSAP(sendingsToInsert, accounts, 'Account__c');
        }
    }

This is the test class I've wrote so far:
 
@isTest
public class AccountTriggerHandlerTest {
    
    @testSetup public static void testSetup(){
        


        Account firstAccount = new Account();
        firstAccount.Name = 'First Account';
        firstAccount.SAPStatus__c = 'Pending SAP';
        firstAccount.CodigoCliente__c = '26000000';
        firstAccount.IsNew__c = true;
        insert firstAccount;
        
        Account secondAccount = new Account();
        secondAccount.Name = 'Second Account';
        secondAccount.SAPStatus__c = 'New';
        secondAccount.CodigoCliente__c = '66000000';
        secondAccount.IsNew__c = false;
        insert secondAccount;
    }
    
    @isTest public static void testAccount(){
        
        Test.startTest();
        
        ConfiguracionServiceSAP__mdt confService = [SELECT DeveloperName, MasterLabel, ServiceName__c 
                                                    FROM ConfiguracionServiceSAP__mdt 
                                                    WHERE ServiceName__c  = 'SYNC_CLIENTE' 
                                                    AND DeveloperName = 'DESARROLLO_SYN_CLIENTE'];
        
        Account firstAcc = [SELECT Name from Account WHERE Name = 'First Account'];
        Account secondAcc = [SELECT Name from Account WHERE Name = 'Second Account'];
        secondAcc.SAPStatus__c = 'Pending SAP';
        update secondAcc;
        
        Test.stopTest();

    }
}

This is the pictures of the Custom Metadata I'm using:

User-added imageUser-added image

but when I run the test the class get covered until here
 
if(confService != null){

and then it's all red ....

I need confService to be different to null so I can keep on testing but I don't know how to do this.
I've been googleing lots and lots and read heaps of documentation but I'm unable to solve it ... I'm new to Salesforce in general.

Any help would be more than appreciated.

Thanks for reading​​​​​​​
I need to create a custom button on Account  , when user clicks that button, it should kick a Lightning flow which then turns the record type for Account. Can somebody please point me to the solution as in how to build it.
I have List Button of URL type when I am clicking on it , it is showing 'refused to connect' error. On URL redirection I have used lightning component and also checked for clickjack from session setting , checking and unchecking clickjack options not worked for me.

Can any one help me with this issue.
I am getting this issue in Win'21 pre release org 

 
Hi there,
I wondering when I tried to check to find out my current date then it gives me 2 hours back time.

User-added image    Datetime cDT = System.now();
    system.debug('Date Time: '+cDT);
    String LongDate = cDT.format('EEEE, MMMM d, yyyy');
    system.debug('long Date: '+LongDate);
   datetime d = Datetime.now();
   system.debug('d: '+d);
why my current time is not showing. I have checked the company information which is the exact my location but still the time showing 2 hours back. Please guide me.
 
HI,
I'm getting this error like
System.QueryException: only aggregate expressions use field aliasing


public static list<Property__c> getFilteredProperty(string Location,string BedRoom,string BathRoom,string MaxBudget)
  {
  list<Property__c> allPropertyLists = new list<Property__c>();
  string PropertyQuery = 'SELECT Id,Additional_Rooms__c,Available_From__c,Carpet_area_sqft__c,Covered_Area_sqft__c ';
     PropertyQuery = PropertyQuery+ 'Electricity_Status__c,Facing__c,Floor__c,For_Bachelor__c,For_Family__c,Furnishing_Available__c,Furnish_Type__c,Geo_Map__c,Landmark__c,Location__c,Area__c,Status__c,State__c,country__c,Maintainance_Charge__c,No_of_Balcony__c,No_of_Bathroom__c,No_of_Bedroom__c,Property_Description__c,Property_Main_Image__c,Property_Owner__c,Property_Video_URL__c,Name,Rent__c,Security_Deposit__c,Verified__c,Water_Availability__c ';
     PropertyQuery = PropertyQuery+' FROM Property__c ';
  string WhereClause= 'WHERE Rent__c != NULL';
      system.debug('*****Location'+Location);
      if(string.isNotBlank(Location))
      {
          if(Location !='ALL')
          {
              WhereClause=WhereClause+ ' AND Area__c =:Location ';
          }
      }
      system.debug('*****BedRoom'+BedRoom);
      integer BedRoomCount;
      if(string.isNotBlank(BedRoom))
      {
          if(BedRoom !='ALL')
          {
              BedRoomCount=integer.valueOf(BedRoom);
              WhereClause=WhereClause+ ' AND No_of_Bedroom__c=:BedRoom ' ;
          }
      }
       system.debug('*****BathRoom'+BathRoom);
      integer BathRoomCount;
      if(string.isNotBlank(BathRoom))
      {
          if(BathRoom !='ALL')
          {
              BathRoomCount=integer.valueOf(BathRoom);
              WhereClause=WhereClause+ ' AND No_of_Bathroom__c=:BathRoom ' ;
          }
      }
      system.debug('*****MaxBudget'+MaxBudget);
      double MaxBudgetValue;
      if(string.isNotBlank(MaxBudget))
      {
              MaxBudgetValue=double.valueOf(MaxBudget);
              WhereClause=WhereClause+ ' AND Rent__c <=:MaxBudget ' ;
      }
      PropertyQuery=PropertyQuery+' '+WhereClause;
      system.debug('PropertyQuery' +PropertyQuery);
      allPropertyLists = Database.query(PropertyQuery);
       system.debug('PropertyQuery' +allPropertyLists);     
      return allPropertyLists;
   }public static list<Property__c> getFilteredProperty(string Location,string BedRoom,string BathRoom,string MaxBudget)
  {
  list<Property__c> allPropertyLists = new list<Property__c>();
  string PropertyQuery = 'SELECT Id,Additional_Rooms__c,Available_From__c,Carpet_area_sqft__c,Covered_Area_sqft__c ';
     PropertyQuery = PropertyQuery+ 'Electricity_Status__c,Facing__c,Floor__c,For_Bachelor__c,For_Family__c,Furnishing_Available__c,Furnish_Type__c,Geo_Map__c,Landmark__c,Location__c,Area__c,Status__c,State__c,country__c,Maintainance_Charge__c,No_of_Balcony__c,No_of_Bathroom__c,No_of_Bedroom__c,Property_Description__c,Property_Main_Image__c,Property_Owner__c,Property_Video_URL__c,Name,Rent__c,Security_Deposit__c,Verified__c,Water_Availability__c ';
     PropertyQuery = PropertyQuery+' FROM Property__c ';
  string WhereClause= 'WHERE Rent__c != NULL';
      system.debug('*****Location'+Location);
      if(string.isNotBlank(Location))
      {
          if(Location !='ALL')
          {
              WhereClause=WhereClause+ ' AND Area__c =:Location ';
          }
      }
      system.debug('*****BedRoom'+BedRoom);
      integer BedRoomCount;
      if(string.isNotBlank(BedRoom))
      {
          if(BedRoom !='ALL')
          {
              BedRoomCount=integer.valueOf(BedRoom);
              WhereClause=WhereClause+ ' AND No_of_Bedroom__c=:BedRoom ' ;
          }
      }
       system.debug('*****BathRoom'+BathRoom);
      integer BathRoomCount;
      if(string.isNotBlank(BathRoom))
      {
          if(BathRoom !='ALL')
          {
              BathRoomCount=integer.valueOf(BathRoom);
              WhereClause=WhereClause+ ' AND No_of_Bathroom__c=:BathRoom ' ;
          }
      }
      system.debug('*****MaxBudget'+MaxBudget);
      double MaxBudgetValue;
      if(string.isNotBlank(MaxBudget))
      {
              MaxBudgetValue=double.valueOf(MaxBudget);
              WhereClause=WhereClause+ ' AND Rent__c <=:MaxBudget ' ;
      }
      PropertyQuery=PropertyQuery+' '+WhereClause;
      system.debug('PropertyQuery' +PropertyQuery);
      allPropertyLists = Database.query(PropertyQuery);
       system.debug('PropertyQuery' +allPropertyLists);     
      return allPropertyLists;
   }
Hi all,

I want to create a task when the article is published.

I have written the condition when PublishStatus='Published' in the process builder.

In the action, I am creating a task. But when the article is published, it is not creating a task.

Please let me know what could be the issue.
Hi,

I am trying to query a formula field from a custom grandchild object of the Account object but I get this error "Invalid field PHQ9_Score__c for SObject Account".

Account -> Assessment and Care Plan -> PS Assessment

Here is my code.

Controller:
public class Suspect_List_Controller {
    public final Account act;
    public Suspect_List_Controller(ApexPages.StandardController stdController) {
        this.act = (Account)stdController.getRecord();
    }

   public Id AccountId = ApexPages.currentPage().getParameters().get('id');

   public String PHQ9 = '012360000019nOBAAY';
   
   List<PS_Assessments__c> PHQ9Records = [SELECT Name, CreatedDate, PHQ9_Score__c FROM PS_Assessments__c WHERE Patient_Assessment_and_Care_Plan__r.Account__c = :AccountId AND RecordTypeId = :PHQ9 AND PHQ9_Score__c >= 9 AND CreatedDate= LAST_N_DAYS:365 ORDER BY CreatedDate asc];

   public List<PS_Assessments__c> getPHQ9() {
        return PHQ9Records;
    }
}

Visualforce:
<apex:page standardController="Account" extensions="Suspect_List_Controller">
    <apex:pageBlock title="Suspect List">
        <apex:pageBlockSection title="PHQ9's over 9">
            <apex:pageBlockTable value="{!PHQ9}" var="record">
                <apex:column value="{!record.Name}"/>
                <apex:column value="{!record.CreatedDate}"/>
                <apex:column value="{!record.PHQ9_Score__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

This is only one part of the Visualforce page so using a report or something similar will probably not work.

I am assuming the error is somewhere in the where clause of the query. The PHQ9 score is a formula field on the PS Assessment. The PS assessment has no direct relation to the account but the Assessment and Care Plan does.

Any information on this type of query would be useful.
Hi i have country combobox and selected country combobox two combo box i have when i choose option in country combobox that selected value shown in selected country combobox.
eg;country have choose india option that india shown in selected country combobox
Since being upgraded to the Spring '20 release, a process that we have has stopped saving BR() in a formula to the Rich Text field it is populating. 

Formula in Process:
"... next steps." + BR() + "<b>Next Step - ..."
Saved value on the record:
"... next steps.<b>Next Step - ..."
Furthermore, the saved value is different in scratch orgs:
... next steps.<br>&lt;/b&gt;Next Step - ..."
Expected output:
... next steps._BR_ENCODED_<b>Next Step - ..."
The last known time we have it saving correctly is Friday before our Spring 20 release. We began having abnormal results the morning after the release. The last time this process was modified was 12/18/2019.

Was there a change in behaviour that I missed included with this release? Has anyone else experienced this issue?