• Meghna Vijay 7
  • 763 Points
  • Member since 2016
  • Certified Salesforce Developer
  • Nagarro

  • Chatter
  • 24
    Best Answers
  • 0
    Likes Received
  • 3
    Likes Given
  • 2
  • 172
I need to show text box in the opportunity object for various stages based on the value selected in the drop down menu in salesforce lighting. Please help me on this!!!!
when I convert a lead, the description text goes from to contact. Is there a way to copy the description text into the Account Description?
Good morning from Greece to all the developer wizzards

Recently I followed the module - 
Develop an Account Geolocation App with Aura Components 

and managed to complete it without an issue albight having ZERO coding experience. My relationship to SF is from the admin perspective but I find coding realy facinating since the solutions one can create are "limitless" so I tried to make adjustments to the component and make it work for the contacts as well, BUT having no experience I runned into issues.

First I created the ContactLocator.cmp (tried to make all the necessary changes to fit my requirement)
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
    <lightning:layout horizontalAlign="space" multipleRows="true">
        <lightning:layoutItem size="12"
        <lightning:layoutItem size="12"
        <lightning:layoutItem size="12"
            <div class="slds-box slds-theme_default">
                ContactMap goes here

then I created the ContactLocator tab

then I created the ContatctSearchController.apxc
public with sharing class ContatctSearchController {
    public static List<Contact> searchContacts( String searchTerm ) {
        List<Contact> Contacts = new List<Contact>();
        if ( String.isNotBlank( searchTerm ) ) {
            List<List<SObject>> searchResults = [
                FIND :searchTerm
                RETURNING Contact(
                    Id, Name, Phone,
                    MailingStreet, MailingCity,
                    MailingState, MailingPostalCode
                    ORDER BY Name
                    LIMIT 20
            contacts = searchResults[0];
        return contacts;

then I created the ContactsLoaded.evt
<aura:event type="APPLICATION">
    <aura:attribute name="contacts" type="Contact[]"/>

then I created the ContactSearch.cmp
<aura:component controller="ContatctSearchController">
    <aura:registerEvent name="contactsLoaded" type="c:ContactsLoaded"/>
    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
    <aura:attribute name="searchTerm" type="String" default="Enter Contact Detail"/>
    <lightning:card title="Contact Search" iconName="standard:search">
        <div class="slds-form slds-p-around_x-small">
                placeholder="Search by name, phone, website, or address"

then I created the ContactSearchController.js
    onInit: function( component, event, helper ) {
        // proactively search on component initialization
        var searchTerm = component.get( "v.searchTerm" );
        helper.handleSearch( component, searchTerm );
    onSearchTermChange: function( component, event, helper ) {
        // search anytime the term changes
        var searchTerm = component.get( "v.searchTerm" );
        // to improve performance, particularly for fast typers,
        // we wait a small delay to check when user is done typing
        var delayMillis = 500;
        // get timeout id of pending search action
        var timeoutId = component.get( "v.searchTimeoutId" );
        // cancel pending search action and reset timer
        clearTimeout( timeoutId );
        // delay doing search until user stops typing
        // this improves client-side and server-side performance
        timeoutId = setTimeout( $A.getCallback( function() {
            helper.handleSearch( component, searchTerm );
        }), delayMillis );
        component.set( "v.searchTimeoutId", timeoutId );

then I created the ContactSearchHelper.js
    // code in the helper is reusable by both
    // the controller.js and helper.js files
    handleSearch: function( component, searchTerm ) {
        var action = component.get( "c.searchContacts" );
            searchTerm: searchTerm
        action.setCallback( this, function( response ) {
            var event = $A.get( "e.c:ContactsLoaded" );
                "contacts": response.getReturnValue()
        $A.enqueueAction( action );

then I created the ContactList.cmp​​​​​​​
    <aura:handler event="c:ContactsLoaded" action="{!c.onContactsLoaded}"/>
    <lightning:navigation aura:id="navigation"/>
    <aura:attribute name="rows" type="Map[]"/>
    <aura:attribute name="cols" type="Map[]"/>
    <lightning:card title="Contact List" iconName="standard:contact">

then I created the ContactLstController.js​​​​​​​
    onAccountsLoaded: function( component, event, helper ) {
        var cols = [
                'label': 'Name',
                'fieldName': 'Name',
                'type': 'text'
                'label': 'Phone',
                'fieldName': 'Phone',
                'type': 'phone'
                'label': 'Website',
                'fieldName': 'Website',
                'type': 'url'
                'label': 'Action',
                'type': 'button',
                'typeAttributes': {
                    'label': 'View details',
                    'name': 'view_details'
        component.set( 'v.cols', cols );
        component.set( 'v.rows', event.getParam( 'contacts' ) );
    onRowAction: function( component, event, helper ) {
        var action = event.getParam( 'action' );
        var row = event.getParam( 'row' );
        if ( action.name == 'view_details' ) {
            var navigation = component.find( 'navigation' );
                'type': 'standard__recordPage',
                'attributes': {
                    'objectApiName': 'Contact',
                    'recordId': row.Id,
                    'actionName': 'view'
After this step, I stoped to check if everything was working and beingHoping that I have done everything correct I checked the component in the sales application BUT i received the following error
User-added image

Your help with this issue will be greatly appreciated.

If it is possible, please be so kind to also suggest me any matterial that will fastrack my understanding of coding and lightning components.

With regards
hello everyone Actually I have written one trigger for this scenario  Change the Account Owner to the sales representative assigned to the new zip code but further i want to shorten  this trigger code Can anyone please help me?
Here is my code:
trigger Requirement1 on Account (after update) {
Set<String> setId1=new set<String>();
    Set<Id> setacc=new Set<Id>();
    for(Account acc:Trigger.new)
             String code1 = Trigger.oldMap.get(acc.Id).BillingPostalCode;
             String code2 = acc.BillingPostalCode;
                if (code2 != code1) {
     Map<String,Territory__c> ter1=new Map<String,Territory__c>();
    List<Territory__c> ter2 = [SELECT id,Zip_Code__c,User1__c  FROM Territory__c where Zip_Code__c IN:setId1];
              for (Territory__c ter3 : ter2)
                for(Account acc1:Trigger.new)
                    Territory__c ter3 = ter1.get(acc1.BillingPostalCode);

Hello everybody, 

So I want to use a APEX Class for a one time correction of old data (process for updating contact addresses from accounts came to late). The (batch-)job is finished and works, but when trying to provide the class on my productive environment, I can´t because of missing code coverage.

But since the class won´t be triggered except by me and has no other influence on the system, I don´t understand why Unittests or such would be needed.

So, any idea how to circumvent the problem?

Greetings and thanks in advance


Hi  i am new in Salesforce
I am Beginner
So Please Help me Out from this Scenario

When an Account's Billing Zip/Postal Code field value is changed and entered new value then
this situation will occur
1.Change the Account Owner to the Sales Representative assigned to the new zip code(Sales Representative is users that will be in another custom Object Terriotry object its a lookup )
2.Change the Owner Field of all the Account's Contacts to the same Sales Representative
3.Change the Owner Field of all the Account's Open Opportunities to the Same Sales RepresentativeIn this Image this are the Sales Representative in Custom Object TerritoryIn this Image This are the Custom fileds of territory objectSo Please Help Me out From this Scenario How to Start From where i dont know 

Please Reply As Soon Possible

Neeraj Sharma
I can't figure out how to insert related record ID numbers dynamically. In the sample below they are hard coded and it works as needed, but I need the ID's included in the loop to insert records.

Thank you in advance for you help! 

public class DataListingController {

    public String CID;
    public List<Wrapper> Wrapperlist {get;set;}

    public DataListingController(){
        CID = ApexPages.currentPage().getParameters().get('id');

        //Fetch Referrals
        List<Data_Feed__c> dfList = new List<Data_Feed__c>();

        Wrapperlist = new List<Wrapper>();

        dfList = [SELECT ID, NAME, Rental__r.NAME, Data_Client__r.ID FROM Data_Feed__c WHERE Data_Client__c=:CID ORDER BY Rental__r.NAME];
                for(Data_Feed__c df: dfList) {
                    Wrapper wrap = new Wrapper();
                    wrap.isSelected = FALSE;
                    wrap.dfeedObj = df;

    /* Insert Apartment functionality based on selected records
    public void InsertApartment(){
        for(Wrapper wr : Wrapperlist){
            if(wr.isSelected = true){
                Data_Listing__c dl = new Data_Listing__c();
                    insert dl;
    /* Wrapper class with checkbox and Apartment object. 
    this is also  called as inner class 

    public class Wrapper{
        public boolean isSelected {get;set;}
        public Data_Feed__c dfeedObj {get;set;}
        public Data_List__c dlistObj {get;set;}
Am new to lightning and got stuck up with a small issue.
I have parent component 'TaskModel' which I will be invoking from quick action and will get record ID. I have child (inner component) which also requires record ID, hasRecordId didn't work in child component so I was trying to pass value from parent component using event. I tried all poosible ways (APPLICATION/COMPONENT event) still couldn't find out why child component event method is not executing.

<aura:event type="APPLICATION" description="Event template" >
<aura:attribute name="AccountId" type="String"/>

<aura:component controller="AccountStatforStatus" implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<aura:registerEvent name="navAccountId" type="c:passAccountId"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="showAccount" type="Boolean"/>
<aura:attribute name="recordId" type="Id"/>
<aura:if isTrue="{!v.showAccount}">

    doInit : function(component, event, helper) {
        var evt = $A.get("e.c:passAccountId");
        alert('TM AID '+component.get("v.recordId"));
        var evtAid = component.get("v.recordId");
        alert('event fired');
        /*var compEvent = component.getEvent("navAccountId");
        alert('TM AID '+component.get("v.recordId"));
        var evtAid = component.get("v.recordId");
        var action = component.get("c.getAccountStat");
"accountId": component.get("v.recordId")
// Register the callback function
action.setCallback(this, function(response) {
            var data = response.getReturnValue();
                alert('Not Fire');
                var createRecordEvent = $A.get("e.force:createRecord");
                    "entityApiName": "Task"

<aura:component controller="AccountStatforStatus" implements="force:appHostable,flexipage:availableForAllPageTypes">
<aura:handler event="c:passAccountId" action="{!c.ValueFromApplicationEvent}" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="accountRecordId" type="Id" />
<aura:attribute name="selectedVal" type="String" />
<aura:attribute name="picklistValues" type="Object" />
<lightning:select value="{!v.selectedVal}" name="selectSP" aura:id="selectSP" label="Suspect/Prospect" required="true" >
<option value="" >--Choose One--</option>
<aura:iteration items="{!v.picklistValues}" var="sp">
<option value="{!sp}" text="{!sp}"></option>
<lightning:button variant="brand" label="Update" onclick="{! c.updateAccount }"/>
<lightning:button label="Cancel" />

doInit : function(component, event, helper) {
        var action = component.get("c.getPickListValuesIntoList");
action.setCallback(this, function(response) {
var list = response.getReturnValue();
component.set("v.picklistValues", list);
// Invoke the service
ValueFromApplicationEvent : function(component,event,helper){
var evtAid = event.getParam("AccountId");
alert('Event '+evtAid);
updateAccount : function(component, event, helper) {
var action = component.get("c.updateAccountStat");
alert('Record Id'+component.get("v.accountRecordId"));
"accountId": component.get("v.accountRecordId"),
"accountStat" : component.find("selectSP").get("v.value")
// Register the callback function
action.setCallback(this, function(response) {
var updateResult = response.getReturnValue();
if(updateResult === 'Success'){
alert('Success '+updateResult);
var createRecordEvent = $A.get("e.force:createRecord");
"entityApiName": "Task"
alert('Error '+updateResult);

am not getting value to accountRecordId in child.

Please Help, Thanks in advance.
Is there anyway that we can auto sync the Account Detais to the Customer Portal User details?

Whenever the Account Name is change we want it to auto update the Name under the Customer Portal User details.
  • February 21, 2019
  • Like
  • 0
public class Personal_Information{
       public list<Personal_Information__c> perinfo{get;set;}
       public void  Insertrecord(string name){
              list<Personal_Information__c> listperinfo = new list<Personal_Information__c>();
                 Personal_Information__c  perinfo = new Personal_Information__c();
         perinfo .name = name;
         listperinfo.add(perinfo );
           if(! listperinfo.isEmpty()){
              insert listperinfo;

visualforce page:

<apex:page controller="Personal_Information" sidebar="false">
         <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <div class="col-sm-3">
     <div class="form-group">
      <label for="usr">Name:</label>
      <input type="text" class="form-control" id="usr" value ="{!name}" />
      <button type="button" class="btn btn-success"   action ="{!Insertrecord}" >Save</button>

without use of the salesforce standared fileds, records should have to insert using a custom button , it was not  getting save , any wrong with this??

  • February 08, 2019
  • Like
  • 0
Email Manager Class
public with sharing class EmailManager{
    public static  void sendMail(String [] addresses, String [] subjects, String [] messages) {
        Messaging.SingleEmailMessage [] emails = new Messaging.SingleEmailMessage[]{};
        Integer totalMails = addresses.size();
        for(Integer i=0; i < totalMails; i++){
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new List<String> { addresses[i] });
        Messaging.sendEmail( emails );

Trigger :
trigger ExampleTrigger on Contact (after insert,after delete) {

        Integer recordCount =Trigger.New.size();
        //Call utility method from another class
       EmailManager.sendMail('nmanoharsfdc@gmail.com','calling Class from trigger','my first task');
    else if(Trigger.isDelete)
        //Process after delete

Error : Method does not exist or incorrect signature: void sendMail(String, String, String) from the type EmailManager
Here is the apex class I wrote and scheduled but it is throwing an error.

global class LastLoginEmail2 implements Schedulable {
    global void execute(SchedulableContext SC) {
        List<User> uds =[SELECT Id, LastLoginDate, Email FROM User where IsActive=True];
        EmailTemplate et=[Select id from EmailTemplate where Name=:'Users_Please_login']; 
        Messaging.SingleEmailMessage[] mails = new Messaging.SingleEmailMessage[0];
        for(User u : uds){
            If( u.LastLoginDate<=System.today().addDays(-1)){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
                mail.setSenderDisplayName('Salesforce Support'); 

Here is the error:
Scheduler: failed to execute scheduled job:class: common.apex.async.AsyncApexJobObject, reason: List has no rows for assignment to SObject

I tried it in different ways but still this error is coming, could anyone help me on this please.

I am having some errors in the below code for the trigger to update contact address with Account Address using apex controller

public class ContactUpdateAccountAddress {
    public static void updatecontacts(List<Contact> contactlist){
    public static void updateAddressToContacts(List<Contact> contactlist){
        set<id> accIds = new set<id>();
        list<account> updAccaddr = new list<account>();
        for(contact con : contactlist){
        list<account> acclist = [select id,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry,(select id,MailingStreet,MailingCity, MailingState,MailingPostalCode,MailingCountry from contacts) from account where id in : accIds];
        for(Account acc : updAccaddr) {
        for(Contact con : contactlist){
           con.MailingStreet =  acc.BillingStreet ;
        update contactlist;

trigger ContactUpdateAccountAddressTrigger on Contact (before insert, after update, after delete) {
    if(trigger.isInsert && trigger.isbefore){
Please help me guys. I appreciate your help.
    global static Account getAccountById() {
        RestRequest request = RestContext.request;
        // grab the caseId from the end of the URL
        String accountId = request.requestURI.substring(
        Account result =  [SELECT Id,Name FROM Account WHERE Id = :accountId];
        return result;
    global static void deleteAccount() {
        RestRequest request = RestContext.request;
        String accountId = request.requestURI.substring(
        Account thisAccount = [SELECT Id FROM Account WHERE Id = :accountId];
        delete thisAccount;

Thanks in advance!
Sandeep Chittineni
I have created a visualforce page for contracts on create using the following code.
<apex:page standardController="Contract"  title="New Contract" >
    <apex:sectionHeader subtitle="New Contract"/>
    <apex:form >
        <apex:pageBlock mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
                 <apex:pageBlockSection title="Information"  columns="2">
               <apex:pageblocksection columns="1">
                <!--<apex:inputField value="{!currentRecord.id}"  required="false" />-->
                <apex:inputField value="{!Contract.Account}"  required="true" />
                <apex:inputField value="{!Contract.End_Customer__c}"  required="false" />
                <apex:inputField value="{!Contract.Automatic_Renewal__c}"  required="false" />
                <apex:inputField value="{!Contract.Annual_Adjustment_Percentage__c}"  required="false" />
                <apex:inputField value="{!Contract.Vendor__c}"  required="false" />
                <apex:inputField value="{!Contract.Vat__c}"  required="true" />
                <apex:pageblocksection columns="1">
                <apex:inputField value="{!Contract.Account_Executive__c}"  required="true" />
                <apex:inputField value="{!Contract.Renewal_Type__c}"  required="true" />
                <apex:inputField value="{!Contract.Payment_Terms__c}"  required="true" />
                <apex:inputField value="{!Contract.Invoice_Period__c}"  required="true" />
                <apex:inputField value="{!Contract.StartDate}"  required="false" />
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>


I have assigned the VF page to the new button.
When I try to create a new contract I receive the following error message.

User-added image
When I comment the account field, the process is moving on.
Any ideas on how to resolve this?
This class is working fine it feteches data from Opportunity_Prod_Batch_Record__c (custom object ) and stored the records in third party api but in my custom object having lost of records but when i run this class manually then it is taking randamly only one record i need all the records to post in third party api how can i achive this please help..............

public class Flr_Insert_Records {
    Public static void Insert_Records(){
        /* Http http = new Http();
HttpRequest request = new HttpRequest();
//request.setHeader('Content-Type','multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
//request.setHeader('Authorization','Bearer '+ AuthorizationToken);*/
        List<Opportunity_Prod_Batch_Record__c> oppbatch=[select Edition_Name__c,Opportunity_Id__c,Opportunity_Name__c,Opportunity_Stage__c,Stand_No__c,Banner_name__c
                                                         from Opportunity_Prod_Batch_Record__c  ];
        system.debug('oppbatch List query '+oppbatch);
        // system.debug('Query after serialization '+json.serialize(oppbatch));
        OppWrapper oppwrappervar=new OppWrapper(oppbatch[0].Edition_Name__c,oppbatch[0].Opportunity_Id__c,oppbatch[0].Opportunity_Name__c,
        string jsonbody=Json.serialize(oppwrappervar);
        system.debug('Json body---->'+jsonbody);
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        //request.setHeader('Content-Type','multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
        //request.setHeader('Authorization','Bearer '+ AuthorizationToken);
//request.setBody('[{ "RecordId": "456","RecordName": "moosa traders pvt ltd / The Big 5 Construct Egypt 2018 /  / 093061123", "EventName": "a2JD0000001ns6uMAA U", "RecordStage": "Test Stage Amjad","BannerName": "Test Banner Amjad","StandNo": "Test Stand Amjad"}]');
       HttpResponse response = http.send(request);
        system.debug('Response body '+ response.getBody());
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    public class OppWrapper
        public String EventName {get;set;}
        public String RecordId {get;set;}
        public String RecordName {get;set;}
        public String RecordStage {get;set;}
        public String StandNo {get;set;}
         public String BannerName {get;set;}
        public OppWrapper(String EventName,String RecordId,String RecordName,String RecordStage,String StandNo,String BannerName)
            this.EventName =EventName;
            this.RecordId =RecordId;
            this.RecordName =RecordName;

ex:- in my custom object having 8 records but when i run the class it is posting only one recrod so plesse help to post all records in third party api need urgent........
Hi Team,

I want to create a simple XMl file with few fields...
Below is my code for the same

global class cls_OppFilessent{
     public static string OppFilesend(ID Optid)
       Opportunity rew=new Opportunity();
        rew =[SELECT id,Name,Booking_Date__c,Type,Trade_In__c,VW_Delivery_Date__c FROM Opportunity where id='0067F00000E9VxaQAF'];
      Dom.Document doc = new Dom.Document();
      XmlStreamWriter w = new XmlStreamWriter();
      w.writeStartDocument(null, '1.0');
      w.writeStartElement(null, 'Opportunities', null); //this will be ROOT of <Opportunities> in XML

              w.writeStartElement(null, 'Opportunity', null);//Element <Opportunity>
              w.writeStartElement(null, 'Id', null);//Element </Id>
              w.writeEndElement();//Element </Id>
              //Element <BookingDate>
              w.writeStartElement(null, 'BookingDate', null);
                  //w.writeStartElement(null, 'BookingDate', null);
              w.writeStartElement(null, 'Name', null);
              //Element <TradeIN>
              w.writeStartElement(null, 'TradeIN', null);
             w.writeStartElement(null, 'Type', null);
              //Element <DeliveryDate>
              w.writeStartElement(null, 'DeliveryDate', null);
                w.writeEndDocument();//this will be ROOT CLOSE of </Opportunities> in XML
         string xmlOutput = w.getXmlString();
         system.debug('XML is xmlOutput  '+xmlOutput );
         string xmldata = doc.toXmlString();
         system.debug('XML is '+xmldata);
     Blob  csvBlob;
                csvBlob  = Blob.valueOf(xmldata);  
            }catch(exception e){

                csvBlob  = Blob.valueOf('Some Text');
            return 'Reward feed already sent';
             Attachment attachment = new Attachment();
                attachment.Body = csvBlob ;
                attachment.Name = 'Rewardfile.xml';
                attachment.ParentId = rew.id;
             insert attachment;
           Update rew; 
          return 'XML: '+xmldata;
         return 'XML: '+xmldata; // Pranav - temporary return - remove this once BLOB code is tested

Test Class:

public class test_OppFilessent{
    public static testMethod void m1(){
         /*Time_Based_Mgmnt__c t = new Time_Based_Mgmnt__c ();
        insert t;
        Reward__c rwrd= new Reward__c();
         //   rwrd.Name='test';
            rwrd.Active__c =true;
            rwrd.User__c = userinfo.getUserId();
            rwrd.Time_Based_Mgmnt__c = t.id;
          insert rwrd; 
        //rwrd.Active__c =false;
        //update rwrd;
        ID sfdcOptyID = '0067F00000E9VxaQAF';

But i am getting error as

System.QueryException: List has no rows for assignment to SObject

Class.cls_OppFilessent.OppFilesend: line 5, column 1
Class.test_OppFilessent.m1: line 26, column 1

please help
I want to set a map attribute in aura  but it keeps not setting as supposed 

aura attribute i tried without default as well
    <aura:attribute name="mapDistances" type="Map" default="{}"/>

js controller 

        var mapAccountsToDistance  = new Map();
        // i checked this and is populated as it should key ->  value 
        var mpatest = component.get("v.mapDistances"); // and this gives me error and not getting any values 

Any ideas ? 

  • February 04, 2019
  • Like
  • 0

public class UpdateParentAccount implements Queueable {
private List<Account> accounts;
private ID parent;
public UpdateParentAccount(List<Account> records, ID id) {
this.accounts = records; this.parent = id;
public void execute(QueueableContext context) {
for (Account account : accounts)
account.parentId = parent;
// perform other processing or callout
update accounts;
Should i call approval process from process builder or call approval process from apex using approval class ? I have tried it and done this both way . I need to what is difference , which is preferred and why

In Lightning Web Components Basics trailhead module i am not able to see the application whenever i am trying to push 'Ebikes app' to my scratch org. I have set the scratch org as 'Default'.

User-added image

I am new to Drawloop package and I am seeing this error whenever I click  Drawloop Admin Tab and when trying to send form . Please help.
User-added image

In LWC, on the component load, I am fetching the latitude and longitude of the logged in user and trying to display it on the component. I have created two attributes named lat and lng and marked it with @track decorator so that whenever the value of these attributes is changed, the component will rerender automatically. I am setting the value of these attributes in connectedCallback, but the updated value is not getting reflected on the component. Below is the html and js files.
    <div class="slds-box">
        <div class="slds-text-heading--large">Weather Report - {lat} {lng}</div>
import { LightningElement, track } from 'lwc';

export default class WeatherAppContainer extends LightningElement {
    @track lat;
    @track lng;
    connectedCallback() {
        if (navigator.geolocation) {
        function showPosition(position) {
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            this.lat = position.coords.latitude; 
            this.lng = position.coords.longitude; 
            console.log("lat: ",this.lat);
            console.log("lng: ",this.lng);


The console "position coords lat" prints the value correctly, but the next console statment does not get printed. I am guessing that we cannot use this keyword in the connectedCallback. Any pointers how to solve this? Thanks.
I have to Cange the case  Owner to Queue when case origin equal to chatter and recordtype equal to xyz . 

I'm doing an upload attachment to AWS, but I'm getting this error -- 'You have uncommitted work pending. Please commit or rollback before calling out'
How do I fix this?

    public static void savePDupcsSettings(ForUploadCustomSettings__c upcsSet, String recId){
        ForUploadCustomSettings__c upcs = new ForUploadCustomSettings__c();
        upcs = upcsSet;
        if (upcs.Objects__c != null) {
			if (recordId != null) {
                upcs.Name = upcs.Objects__c +'-'+ upcs.Fields__c +'-'+ upcs.Value__c;
			    update upcs;
            } else {
                ForUploadCustomSettings__c newVal = new ForUploadCustomSettings__c();
                newVal.Name = upcs.Objects__c +'-'+ upcs.Fields__c +'-'+ upcs.Value__c;
                newVal.Objects__c = upcs.Objects__c;
                newVal.Fields__c = upcs.Fields__c;
                newVal.Value__c = upcs.Value__c;
                insert newVal;
        String stage = 'Closed Won';
        ForUploadCustomSettings__c csList = [SELECT Id, Id, Objects__c, Fields__c, Value__c 
                                                              FROM ForUploadCustomSettings__c 
                                                              WHERE Value__c = :stage LIMIT 1];
        if (csList != null) {
            Set<Id> Ids = new Set<Id>();
			for (Opportunity opp : [SELECT Id, Name FROM Opportunity WHERE IsClosed = true AND IsWon = true]) {

			String formattedDateString = Datetime.now().format('EEE, dd MMM yyyy HH:mm:ss z');   
			String host = 's3.amazonaws.com/';
			String method = 'PUT';
			HttpRequest req = new HttpRequest();
			Http http = new Http();

			List<Attachment> att = [SELECT Id, Name, Body, ContentType FROM Attachment WHERE ParentId IN :Ids];
			List<AWScredentialsSettings__c> creds = [SELECT Id, ClientKey__c, SecretKey__c, BucketName__c FROM AWScredentialsSettings__c LIMIT 1];
			if (!att.isEmpty() && !creds.isEmpty()) {
				String bucketname = creds[0].BucketName__c;
				String key = creds[0].ClientKey__c;
				String secret = creds[0].SecretKey__c;
				String attachmentBody = EncodingUtil.base64Encode(att[0].Body);
				String filename = att[0].Name;
				req.setEndpoint('https://' + host + bucketname + '/' + filename); // The file should be uploaded to this path in AWS -- Opportunity/Salesforce Id/Secret Files/filename
				req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
				req.setHeader('Content-Encoding', 'UTF-8');
				req.setHeader('Content-type', att[0].ContentType);
				req.setHeader('Connection', 'keep-alive');
				req.setHeader('Date', formattedDateString);
				req.setHeader('ACL', 'public-read');
				String stringToSign = method+'\n\n\n'+ att[0].ContentType + '\n' + formattedDateString +'\n/'+ bucketname +'/' + filename;
				Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(secret));
				String signed  = EncodingUtil.base64Encode(mac);
				String authHeader = 'AWS' + ' ' + secret + ':' + signed;
			HTTPResponse res = http.send(req);
			System.debug('*Resp:' + String.ValueOF(res.getBody()));
			System.debug('RESPONSE STRING: ' + res.toString());
			System.debug('RESPONSE STATUS: ' + res.getStatus());
			System.debug('STATUS_CODE: ' + res.getStatusCode());

I have a rquirement that, by clickin on a custom button on Contract object  standard recordtypes like OP1,OP2,OP3 page selection should be opened. If we select OP1 recordtype from that picklist  related OP1 page record should be opened and vise versa. How can i acheive this,please help me, I'm new to coding.
  • July 05, 2019
  • Like
  • 0

I am writting  schedulable batch class to delete the apex logs older than one day but on DML statement its giving error "DML operation Delete not allowed on List<ApexLog>". Can we have other way to schedule the same?

Welcome to your suggestions!

 Can anyone helps me out in writing a trigger that will create a contact from lead if lead email does not exists in contact email id. 
Once lead is created, I need to check whether lead.email exists in existing contacts if not then create a new contact
Once the case is closed, closure sms should be sent to Case's Primary Contact.
  • July 04, 2019
  • Like
  • 0
I need to show text box in the opportunity object for various stages based on the value selected in the drop down menu in salesforce lighting. Please help me on this!!!!
I am trying to write a test class for a simple Controller.. I think I am along the right lines but have an error: Invalid type: OpportunitiesController.. please help!

Custom Controller
public class OpportunityController {
    public List<Opportunity> opp {get;set;}

    public OpportunityController() {
        opp = [SELECT Id, Name, CreatedDate, StageName, Placement__c, LDN_Company__c, Description, Job_Title__c, CloseDate, NextStep, Salary__c, Future_Prospects__c, Duration__c, Training_Delivery_Site__c, Qualification_taken__c, Entry_Requirements__c, Key_Responsibilities__c, Skills_Required__c, Account.Name, Account.BillingPostalCode, Account.BillingStreet, Account.BillingCity FROM Opportunity WHERE (StageName = '1 - Qualifying' or StageName = '2 - Booked for CK' or StageName = '3 - Live' or StageName = '4 - Work Trial') AND (Placement__c = 'New Apprentice')];

Test Class method 
static testMethod void myUnitTest2() {
    Opportunity opp = new Opportunity();
    opp.Name = ' test 001';
    insert opp;
    PageReference testPage = new pagereference('/apex/Opportunities');
    ApexPages.currentPage().getParameters().put( 'id', opp.id );

    OpportunitiesController OpportunitiesControllerObj = new OpportunitiesController();
	PageReference pageref = OpportunitiesControllerObj.save();

trigger saleInsertedTrigger on i360__Sale__c (after update) {
     for (i360__Sale__c S: Trigger.new) {
     if(s.EE_Service_Level__c = 'full' || s.EE_Service_Level__c = 'Audit Only'){
    JCFS.API.createJiraIssue('Project ID', 'Issue Type ID');
Hello All,
I have written a code for sending email through APEX. 
I am using a custom field for saving original Email address from Email field of Contact object. And masking the original Email. So my original email field value is 'DuXXX@XXXXX.XXX' and Custom is like 'Dummy@gmail.com'. 
When i am sending the email using Messaging.SingleEmailMessage() API the when i receive email in 'to address' ther are both the values (from custom email field and standard one.) 
How can i remove the standard one from there as i have only added 1 value from custom field in code.
Or it is standard salesforce behaviour.

  • July 03, 2019
  • Like
  • 0
Hi Friends,

I need help in fixing the VF Pages. 
I created a Class and VF Pages where I want to display a Table values. so, I created a Pageblocktable. Now I have 1 issue when I table has values and other table does not have a values it is diplaying both table which looks awkward.
I need to hide the columns if there is no values.

Below is my VF code and Image for your reference.
<apex:panelGrid columns="3" width="90%">
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList1}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Body" >
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList2}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Fridge">
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList3}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Tail Lift" >
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
        </apex:panelGrid> <br/>
Pageblock Table VIew

Kindly advice how can solve this issue.

I am trying to update a date/time field (Actual_Closed_Date__c) with the current date when an opportunity was closed (Stage__c = Closed Won || Stage__c = Closed Lost) using a trigger, any suggestions?
A few time earlier one of my brother also searching solution for Yahoo Backup in Mac OS. He downloaded the Yahoo Backup for Mac on his system. After that, the process becomes quite easy for him because of the support team. They are connected to him throughout the complete conversion process from Yahoo emails to outlook. This is the reason I am suggesting you this tool but one is important this tool will runs in Mac OS only. Visit:- https://www.toolscrunch.com/mac-yahoo-backup.html
Hi guys,
We just created a library named R.apex, which helps simplify the common tasks in apex code development by adopting a functional style.
It offers tons of utility functions to work with lists, sets, maps and sobjects, making apex code clean and readable. We were suffering from the pain points of writing similar Apex code to complete trivial tasks once and once again, and that is the reason why we want to stop that and start to write reusable code. Here are some examples of what R.apex can do:
// Reverse a list
List<Integer> reversedList = R.of(new List<Integer>{ 1, 2, 3 })
// Fina specific account
List<Account> accountList = ...;
Account acc = (Account)R.of(accountList)
    .find(R.whereEq.apply(new Map<String, Object>{
        'LastName' => 'Wilson',
        'IsDeleted' => false

Hopefully R.apex can help make your Apex code development easier, and you are always welcome to give feedback so that we can improve it.

R.apex is an open source project hosted at https://github.com/Click-to-Cloud/R.apex/.
You can check it out. Feel free to clone it, make changes or submit a PR.


Posting this in order to help others who, months from now, might Google "OP_WITH_INVALID_USER_TYPE_EXCEPTION" and find this explanation.


We wrote an Apex trigger on the User object, to insert a custom object record anytime a user updates their Chatter status.  This was done to fulfill a client's requirement to audit all Chatter activity.


The trigger worked fine, until one day the client signed up some Chatter Free users.  When such a user tried to update their status, they got a pop-up with an OP_WITH_INVALID_USER_TYPE_EXCEPTION error.


We scratched our collective heads for awhile.  After all, Apex triggers run in "system mode," right?  That is supposed to mean that "object and field-level permissions of the current user are ignored."  And yet this trigger seemed like it was running in "user mode," enforcing restrictions based on who the current user was.


The root cause turned out to be that a Chatter Free user cannot be the owner of a custom object record, and SFDC by default sets the current user as a new record's first owner.  We discovered this when we realized, via experiment, that Apex triggers fired as the result of actions by Chatter Free users could definitely update an existing record, but were having problems creating records.


So the simple solution was to explicitly set the owner of the new record to some fully-licensed user prior to inserting it.