• mukesh gupta
  • ALL STAR
  • 6694 Points
  • Member since 2015
  • 9X Salesforce Certified
  • hcl

  • Chatter
    Feed
  • 202
    Best Answers
  • 2
    Likes Received
  • 1
    Likes Given
  • 122
    Questions
  • 1558
    Replies
Q->  Insert 100 student’s records. Rollback all the inserted records if the number of successful insertion is less than 80
Hi all
It's really urgent I am totally new to coding I want to import my excel file to my custom object Sample__c to create new records using visual force page but even after searching, I am unable to complete it and am totally stuck.
I have an excel file with columns Name, Email, Phone and need to import the values to Sample__c fields Name__c, Email__c, Phone__c but can't do this any help from experts as I already followed all the links related to this now I need full code.
Thanks
Hello,
How can i calculate the number of API users in the org,please
how can i insert the a lead record through apex class?
JS:
----
import { LightningElement,api } from 'lwc';
import TITLE_FIELD from '@salesforce/schema/Contact.Title';
export default class RecordEditFormLWC extends LightningElement {
// Expose a field to make it available in the template
    selectedValues = TITLE_FIELD; //t to store in a title text field
    // Flexipage provides recordId and objectApiName
    @api recordId;
    @api objectApiName;
    value = [];
    get options() {
        return [
            { label: 'Ross', value: 'option1' },
            { label: 'Rachel', value: 'option2' },
        ];
    }
    get selectedValue() {
        return this.value.join(',');
        console.log('selected values are '+value);
    }
    handleChange(e) {
        this.value = e.detail.value;
    }
}

HTML:
-------
<template>
<lightning-record-edit-form
    object-api-name="Contact"
    record-id={recordId}>
    
 <lightning-checkbox-group name="Checkbox Group"
                              label="Checkbox Group"
                              options={options}
                              value={value}
                              onchange={handleChange}></lightning-checkbox-group>
                                  <p>Selected Values are: {selectedValues}</p>
<lightning-input-field field-name={selectedValue}></lightning-input-field>
    <div class="slds-var-m-top_medium">
        <lightning-button variant="brand" type="submit" label="Save">
        </lightning-button>
    </div>
</lightning-record-edit-form>
</template>
During Salesforce Maintenance, when someone emailed to the Email Service Address of Email to Case. What will happen? I am aware that the case will be queued after the maintenance. But what about the Created Date? Will it be adjusted or the same when the email has been received?

Thanks in advance!
trigger EmailUpdation on Opportunity (before update) {
    
    
    Set<Id> accId = new Set<Id>();
    Set<String> oppEmail = new Set<String>();
    Set<String> oldEmail = new Set<String>();
    List<Opportunity> accRelaOppEmail = new List<Opportunity>();
    

    for(Opportunity opp: Trigger.new){
        
        oppEmail.add(opp.Email__c);
        
        accId.add(opp.AccountId);
    }
    
    
    accRelaOppEmail= [Select Id, Email__c from Opportunity where AccountId in :accId and Account_Email__c in :opp.Email__c];
    
    for(Opportunity opp: accRelaOppEmail){
        
        oldEmail.add(opp.Email__c);
     }
    
    for(Opportunity opp: trigger.new){

        if(oldEmail.contains(opp.Email__c) && oldEmail.size() != accRelaOppEmail.size() ){
            

            

    
         }
       }
    }
can someone help me with this
how to list more then 50000 record using Data table in lwc please help.
 
If I want to get an account phone and update it on Opportunity,  the field name is  'Account_Phone__c'  please help me write a trigger to achieve this 
Thank you in advance.
I'd like to create a formula that would mark a checkbox as true if a field is changed in 1 of 3 ways

We have a field called AUM and three levels based on the AUM.  I need to create a checkbox when a specific level is met.  For instance, if the AUM went from 600k to 700k, then the checkbox is true.  But I only want the box checked IF the amount changes.  

This is the formula I started with, I know it's incorrect, but would like suggestions....  Thanks!

If (Assets_Under_Management__c  (ISCHANGED) >= 700000, true,false)
Hello all,

I have a checkbox field in my custom registration form for the community users.

Lightning component:

<aura:attribute name="explicitOptIn" type="Boolean" required="false" default="false"/>

<div id="sfdc_opt_in_container" class="sfdc">
               
                <ui:inputcheckbox aura:id="checkbox1" value="{!v.explicitOptIn}" change="{!c.oncheck}" class="input sfdc_explicitOptIn sfdc"/>
                Privacy Policy.
            </div>

Lightning controller Helper

oncheck: function(component,event,helper) {
        var checkbox = component.find('checkbox1').get('v.value');        
        component.set("v.explicitOptIn",checkbox);
    }

I am getting an error as "This page has an error. You might just need to refresh it. Unable to find action 'oncheck' on the controller."

Could somebody please help here on this.
Can someone help me with this trigger?
Avoid deletion of related contact while deleting account which has rating as 'warm' and No_of_Employees__c is not empty(add error message).
I've tried this, but not working and not showing error message.
trigger AvoidContactDel on Account (before delete) {
    list<account> acc = new list<account>();
    list<contact> con = new list<contact>();
    set<id> ids = new set<id>();
    for(account a : trigger.old){
    ids.add(a.id);
    }
    con = [select id,lastname from contact where accountid IN : ids ];
    //acc = [select id,name,stage,No_of_Employees__c from account where id in : ids];
    for(account a : trigger.old){
        for(contact c : con){
        if(a.id == c.accountid && a.rating == 'Warm' && a.No_of_Employees__c != null){
            a.adderror('you are not allow to delete this contact for some reasons');     
        }
        }
    }
    
}
       
 
  • August 13, 2022
  • Like
  • 0
APEX CLASS :
Public with sharing  class viewholderdetails{


   public string name{set;get;}
 public list<Policy_Holder__c> Message {set;get;}
Public list<Policy_Holder__c> Message2 {set;get;}
      
 
     public void getdata() {
     
     
     
       Message = [SELECT id,(SELECT id, Name, Due_date__c, Premium_Start_Date__c,  Premium_End_date__c, Premium_Type__c, Total_amt_paid__c FROM Life_Insurances__r)
      
FROM Policy_Holder__c WHERE Policy_ID__c =: name];
  
  Message2 = [SELECT id,(SELECT id, Name, Due_date__c, Premium_Start_Date__c,  Premium_End_date__c, Premium_Type__c, Total_amt_paid__c FROM Motor_Insurances__r)
      
FROM Policy_Holder__c WHERE Policy_ID__c =: name];
  
  }
     
        }


Visualforce page :

<apex:page Controller="viewholderdetails">
    <apex:form >

   <apex:pageBlock title="Life Insurance Project">
        <apex:pageMessages />
       <apex:pageBlockSection title="Insurance datiles">
           
           
            Enter Policy holder ID :<apex:inputtext value="{!name}"/>  
         
           
 

           <apex:commandButton value="Submit"   action="{!getdata}"/>
       
         </apex:pageBlockSection>  
 
          <apex:pageBlock >
           <apex:pageMessages />
         
                     
                      <apex:pageBlockTable value="{!Message.Life_Insurances__r}" var="me" >
 
                     
                     <apex:column value="{!me.Name}" />  
                     <apex:column value="{!me.Due_date__c}"/>
                     <apex:column value="{!me.Premium_Start_Date__c}"/>
                     
                       
                      <apex:column value="{!me.Premium_End_date__c}"/>
                      <apex:column value="{!me.Premium_Type__c}"/>
                            <apex:column value="{!me.Total_amt_paid__c }">
      </apex:column>
                       
                       

               
                </apex:pageBlockTable>
                 </apex:pageBlock >
                 
                 
                 <apex:pageBlock >
         
                  <apex:pageBlockTable value="{!Message2.Motor_Insurances__r}" var="m1" >
 
 
                     
                     <apex:column value="{!m1.Name}" />  
                     <apex:column value="{!m1.Due_date__c}"/>
                     <apex:column value="{!m1.Premium_Start_Date__c}"/>
                     
                       
                      <apex:column value="{!m1.Premium_End_date__c}"/>
                      <apex:column value="{!m1.Premium_Type__c}"/>
                            <apex:column value="{!m1.Total_amt_paid__c }">
      </apex:column>
                       
                       

               
                </apex:pageBlockTable>
 
                     
           
                       
                       
 </apex:pageBlock >
               
                         
                         
                    </apex:pageBlock>  

               
                                           
    </apex:form>
</apex:page>
Can anyone guide me  how to use this in vf components  or can i attach this directly in email template?

vf page
<apex:page standardController="Salary_Detail__c" extensions="salarydetails" renderAs="pdf" >

<table>
         <apex:repeat value="{!Salary_Detail__c}" var="a" >
            <tr>
                 
                       <td  >Emp Code</td>
                       
                        <td >{!Salary_Detail__c.Employee_ID__c}
                      
                         </td>                     
              </apex:repeat >
</table> </apex:page>


-------------------
vf page apex class

public class salarydetails {

public Salary_Detail__c SalaryDetail{get;set;}
        private ApexPages.StandardController controller;
        public SalaryDetails(ApexPages.StandardController controller){
                //this.SalaryDetail = (Salary_Detail__c)StandardController.getRecord();
        }

        Public PageReference saveRecord() {
                insert SalaryDetail;
                PageReference pr = new PageReference('/'+SalaryDetail.id);
                pr.setRedirect(true);
            return pr;}}

Thanks in advance
Hi All,

We are invoking the AURA component in VF page. We are passing record id from VF page to AURA component. 
The issue is, this record id is not avaiable in JS controller init method. It showing as undefined 

Code sample:

VF Page Code Sample:
<apex:page sidebar="false" showHeader="false" standardStylesheets="false">       
    <!-- Lightening Component code version starts -->
        <apex:includeLightning />
        <div  id="LightningCompContainer" />   
    <script>
        $Lightning.use("c:SampleAURA_App", function() {
            $Lightning.createComponent("c:SampleAURA_Component", {
            },
            "LightningCompContainer",
            function(component) {
               component.set("v.QuoteIDFromVfPage",'{!$CurrentPage.parameters.id}');
            });
        }); 
    </script>   
</apex:page>

AURA Lightening Component Code Sample:

<aura:component implements="force:appHostable" access="global" >    
    
    <!-- Handler - Init Method -->
    <aura:handler name="init" value="{!this}" action="{!c.initLoad}"/>
</aura:component>

JS Controller Code Sample:
({
    initLoad : function(component, event, helper) { 
        //Created var that store the recordIds of selected rows.
        var recordid = component.get("v.QuoteIDFromVfPage");
        alert('====>'+recordid);
     },
})

Final result is: Alert popup is showing "undefined"

One observation is:
This ID is not avoilable only in init method. The record ID is available in other JS controller methods which are triggerd from button.


Please help me on this issue

Thanks in advance,
Surendra
 
Hi all, help me to write test class
public class myjob 
{
@AuraEnabled(cacheable=true)
    Public static List<Job_Requirement__c> myservice()
    {
        list<Job_Requirement__c> lstjob = [select id, Name, Service_Name__c, Type__c from Job_Requirement__c where
                                          Type__c='Standard'];
        return lstjob;
    }

@AuraEnabled(cacheable=true)
    Public static List<Job_Requirement__c> myservicegeneral()
    {
        list<Job_Requirement__c> lstjobgeneral = [select id, Name, Service_Name__c, Type__c from Job_Requirement__c where
                                          Type__c='Specialty'];
        return lstjobgeneral;
    }
    @AuraEnabled(cacheable=true)
    Public static List<Job_Requirement__c> myservicinteriror()
    {
        list<Job_Requirement__c> lstjobinteriror = [select id, Name, Service_Name__c, Type__c from Job_Requirement__c where
                                          Type__c='Custom Named'];
        return lstjobinteriror;
    }

    @AuraEnabled(cacheable=false)
    Public static List<Job_Requirement__c> getStandardWorkOrders()
    {
        list<Job_Requirement__c> lstjob = [select id, Name, Service_Name__c, Type__c from Job_Requirement__c ];
                                          //Type__c='Standard'];
        return lstjob;
    }

    Public static List<Job_Requirement__c> getSpecialityWokOrders()
    {
        list<Job_Requirement__c> lstjobgeneral = [select id, Name, Service_Name__c, Type__c from Job_Requirement__c where
                                          Type__c='Specialty'];
        return lstjobgeneral;
    }
}
Hello There, I have lwc which shows list of contact records and I added editable='true' in result page it's getting edit but not getting saved, I'm not sure where and how to query update query
Can anyone help me in writing code to save the updated record.

// html code
<template>
     <h2> Contact Datatable</h2>     
         <lightning-datatable data={wiredContacts.data} columns={columns} key-field="Id">
         </lightning-datatable>     
 </template>

// js code
import { LightningElement ,api, wire, track} from 'lwc';
import getContactList from '@salesforce/apex/method.getContactList';
export default class contactRecord extends LightningElement {
   
         @track columns = [
          { label: 'Name', fieldName: 'Name', editable: true},
          { label: 'Id', fieldName: 'Id'},
            {label: 'Email', fieldName: 'Email'}
      ];
      @track conList;
      @track error;
      @wire(getContactList)
      wiredContacts;
}

// class code
public with sharing class method {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList() {
        return [SELECT Id, Name, email
            FROM Contact];
    }
}
Hello there, I have created lwc for showing contact records but I want to show associated account name also but in result page it shows blank in account field
can anyone pls assist in this. my code as follows.
//html
<template>
     <h2> Contact Datatable</h2>
     <template if:true={conList}>
         <lightning-datatable data={conList} columns={columns} key-field="Id">
         </lightning-datatable>
     </template>
     <template if:true={error}>
         {error}
     </template>
 </template>

//js code
import { LightningElement ,api, wire, track} from 'lwc';
import getContactList from '@salesforce/apex/method.getContactList';
export default class contactRecord extends LightningElement {
   
         @track columns = [
          { label: 'Name', fieldName: 'Name' },
          { label: 'Id', fieldName: 'Id'},
            {label: 'Account', fieldName: 'Account.Name'},
            {label: 'Email', fieldName: 'Email'}
      ];
    @track conList;
    @track error;
    @wire(getContactList)
    wiredContacts({
        error,
        data
    }) {
        if (data) {
            this.conList = data;
        } else if (error) {
            this.error = error;
        }
    }
}
------------------------
// class code
public with sharing class method {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList() {
        return [SELECT Id, Name, Account.Name, email
            FROM Contact];
    }
}
--------------------------------------------------------
Hi All,

I need to update row item value on change event
 
<template for:each={selectedOlis} for:item="oli" for:index="index">
    <div key={oli.Id}>
        {oli.Name} &nbsp; {index}
        <lightning-input type= "string" data-index={index} label="Address" value={oli.address}
            placeholder="Quantity" onchange={handleListInputChange}>
        </lightning-input>
        
    </div>
	</template>

JS:-

handleListInputChange(event){
//wheen user type then  update value={oli.address}
}

Please suggest
Hi Expert,

I am using Lightning-data-table with rowaction (VIEW, EDIT, DELETE).
but dropdown list cut off. not visible all options, i know solution if height added in  class 
.slds-scrollable_y, 
but not able to set height in this class

User-added image

Can you please assist






How can set 

this LWC Quickaction component
Hi All,

I am using Lightning-data-table with rowaction (VIEW, EDIT, DELETE).
but dropdown list cut off. not visible all options

this LWC Quickaction component
User-added image

Please suggest.
Hi All,

I need to update Custom label from LWC. my Custom label is Hello {0} and {1}.

How to update by LWC,


Thanks
Hi Team,

I want to hide Liightning componet Close Button(Top right corner) or cross button.User-added image 
when i click on quick action then one of lightning component assosciated with it and open, but need to remove close button.

Please suggest

 
I am using a process buider:- 

if user cloned any opportunity then one of my process builder should not execute, after creation of this opportunity if user edit this opportunity then process builder should execute.

Please suggest
Hi Expert,

I have a custom field on Task object, and now i want to update task by API. i have tried to update by Postman, but facing error.
 
{
        "message": "insufficient access rights on object id",
        "errorCode": "INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY",
        "fields": []
    }

 Please suggest

Regards
Mukesh
Hi Expert,

I am using add error method, when criteria match then addError method call, but here script doenot stop and execute next loop.

i want to stop script when addError call. i have used break; return; but nothing happen

 
for (Opportunity currOpp: newOpportunities_1){
              System.debug('currOpp name '+currOpp.name);
            if (currOpp.RecordTypeId!=PMRecordTypeId.Id  ){
                currOpp.addError(Label.pmr);   
               
            }
          }

for (Opportunity currOpp: newOpportunities_2){
              System.debug('currOpp name '+currOpp.name);
         
          }

Thanks 
Mukesh

 
Hi Expert ,

I am creating dynamic check boxes that's crated perfect, change event is not working for created check boxes;

when i select any check box then get error
getting error :- Unable to find action 'handleSelectedOLI' on the controller 
 
for(var i = 0; i<5; i++){
 $A.createComponent(
            "ui:inputCheckbox",
            {
                "aura:id": "checkBoxOLI",
                "value":chekboxVal,
                "change": component.getReference("c.handleSelectedOLI")
            },
            function(newButton, status, errorMessage){
                //Add the new button to the body array
                if (status === "SUCCESS") {
                    var body = component.get("v.body");
                    //body.push(newButton);
                    component.set("v.body", newButton);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                    // Show offline error
                }
                else if (status === "ERROR") {
                    console.log("Error: " + errorMessage);
                    // Show error message
                }
            }
        );  
		
handleSelectedOLI: function(component, event, helper) {
        alert('change ecevt ');
    
    },

Please suggest

Regards
Mukesh
Hi Expert,

I want to destroy selected check box when user try to select all and click on delete buttion.
 without destroy this is exist already and make extra check boxes that's was previously deleted so now i want to destroy selected items

Below code is creating check boxes:-

this is select All check box
<ui:inputCheckbox value = "{!v.isSelectAll}" change="{!c.handleSelectAllOLI}" aura:id="selectAll"/>

this is list of check boxes:-
<aura:iteration items="{!v.DEFProductInstance}" var="item" indexVar = "indx">
<ui:inputCheckbox aura:id="checkBox" />
 </aura:iteration>


Please suggest

Thanks
When manager reject opportunity then error message display from trigger, but i want to bypass addError message in apex trigger. for spicific condition user face addError message, but when opportuntiy reject by manager then i want to by pass this error message.

Please suggest

Regards
Mukesh 
Hi Expert,

I am using below code but not able to get maximum length  on keyUp event.

 
<ui:inputCurrency class="slds-input" aura:id="curr" format="##,##,###,##0.00" maxlength="6" updateOn="keyup" keyup = "{!c.changesValueInput}"/>

Please suggest
 
Hi Expert,

I am creating contact by 'e.force:createRecord', but now i want to created contact record Id. after this event. 

Can you please suggest.

Regards
Mukesh 
Hi Expert,

I am trying to create a lwc project in VS code, but when i try to create 
then facing error:

command 'sfdx.force.project.create' not foundUser-added imagePlease suggest.

I am using jdk1.8.0_231 for 64 bit
Hi expert,

I have multiple country picklist in lightning compont that's is iterating in Table TR
we i choose any picklist value 'UAS' and click on save button than this picklist should be disable.

but when i change of picklist then picklist disable on selection time. but i want to disable on save button.

Please suggest
<aura:iteration items="{!v.CountryDetails}" var="item" >
<tr> 
<td class="slds-cell-wrap">
                        <lightning:select name="statusFld" label="" value="{!item.Country__c}" disabled="{!item.Country__c == 'Closed Won')}">
                            <option value="--None--">--None--</option>
                            <aura:iteration items="{!v.listCountry}" var="val">
                                <option value="{!val.value}" selected="{!val.value==item.Country__c}">{!val.key}</option>
                            </aura:iteration>
                        </lightning:select>
                    </td>
</tr>
</aura:iteration>

 
Hi I am using visualforce page to open Lightninng component in new tab:-

on opportunity object -->> button & Link (Name:-AddProduct)

add URL parameter :- 

/apex/OppProduct_VFP?oppId={!Opportunity.Id}

when user click on 'AddProduct' button then below VF page open in new tab with lightnig component:-

OppProduct_VFP:-
<apex:page controller="TestController" tabStyle="Opportunity" lightningStylesheets="true">
    <apex:includeLightning />
    <div class="slds" style="margin-top:10px;margin-left:10px;"> 
        <div id="lightning" />
    </div>
   
    <script>
    

        $Lightning.use("c:AddProductApp", function() {
            $Lightning.createComponent(
                "c:AddProduct",
                {recordId : "{!OpportunityId}"},
                "lightning",
                function(cmp) {
                   
            });
        });
    </script>
</apex:page>

i have a close button in AddProductController to close this tab but not able to closed this tab getting UNDEFINED in console log. i am not able to get TabId by this code.

 
Close : function(component, event, helper){
        var workspaceAPI = component.find("workspace"); // mentioned in component 
          workspaceAPI.isConsoleNavigation().then(function(consoleResponse) {  
              console.log('consoleResponse-->>> '+consoleResponse) // return undefined
              workspaceAPI.getFocusedTabInfo().then(function(tabResponse) {
                  console.log('tabResponse-->> '+tabResponse)// return undefined
                   var isSubtab = tabResponse.isSubtab;
                  console.log('isSubtab-->> '+isSubtab);// return undefined
              });
        });
Please suggest and let me know where i am wrong
​​​​​​​
I am using a lightning componet, whrn i click on a button then this coponent open. on this component i have a close button. when i click on this closed button page redirect to previous page, but tab not closed.

i am using below code for tab close
closeFocusedTab : function(component, event, helper) {
         var workspaceAPI = component.find("workspace");
        //alert(workspaceAPI);
        workspaceAPI.getFocusedTabInfo().then(function(response) {
            //alert('aaaa -- '+response);
            var focusedTabId = response.tabId;
            workspaceAPI.closeTab({tabId: focusedTabId});
        })
        .catch(function(error) {
            console.log(error);
        });

    
    }

    Can you please suggest.

User-added image
Hi Expert,

I want to add attachment on record creation time in apex code, but in attachment custom code  we need record Id, but record is not created. so how achive this functionality,

Example: when we fill any exam from then we can attachemtn or document, and then save the record.

Thanks
 
Hi Expert,

i want to open a popup box that should be open when user logged In. when user  closed this then this will not reopen for this session. if user logged in again then popup should be open .

what i have done:

create a lightning component and added this on home page layout. but this popup open again and again when home page refresh. 

So can you please suggest what should i use sothat model popup should open once for current session.

Regards
Mukesh
Hi Expert,

I want to use Remote Objects in lightning component , below code is working in visualforce  pages, but now i need to implement this code in lightning component.

for example:- 
  <!-- Remote Objects definition to set accessible sObjects and fields -->
    <apex:remoteObjects >
        <apex:remoteObjectModel name="Warehouse__c" jsShorthand="Warehouse" 
            fields="Name,Id">
            <apex:remoteObjectField name="Phone__c" jsShorthand="Phone"/>
        </apex:remoteObjectModel>
    </apex:remoteObjects>

Thanks
Mukesh
Hi Expert,

I want to create some demo on marketing cloud  journey builder. Can any one share about how to acces journey builder in markeing cloud.

Thanks
Mukesh
Hi Expert,

I need to create an application for me to send SMS directly from Salesforce. Please suggest.

User-added image
Hi Expert,

I am using a test class for coverage 75% code, but few things are not covered. Can any one suggest what is going wrong.

this my test Class: --
@isTest
public class TestProfessorSelectCourse {
    @isTest static void ProfessorCourse(){
       
        
        Professor__c prof = new Professor__c(Name ='JP',Email__c='jp@gmail.com');
        insert prof;
        
        Class__c cls = new Class__c(name='12G', Class_Teacher__c = prof.id);
        insert cls;
        
        Course__c cors = new Course__c(Professor__c=prof.id,Class__c =cls.id, name='Ruby', Start_Date__c= Date.today() , End_date__c= Date.newInstance(2017,03,20));
       	//Professor__c prof = new Professor__c(Name ='JP');
        //cors.Professor__c = prof.Name;
        insert cors;
    }
}

and below is my main class


User-added image

Thanks 
Mukesh
Whenever trying to execute the below code I am getting the error:


global class batchclass implements Database.Batchable<sObject>,Database.Stateful{
    global integer countopp;
    global Decimal sumamount;
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query='Select id, Customer_segment__c ,(select accountid,amount,Stagename,Createddate from Opportunities) from Account Limit 500';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> lstacc)
    {
         AggregateResult[] gr= [SELECT Accountid,SUM(Amount) optyamt,Count(Id) cid FROM Opportunity Where Accountid IN:lstacc Group by Accountid];
    
    for(AggregateResult ag:gr){
        sumamount = (Decimal)ag.get('optyamt');
        countopp=(integer)ag.get('cid');
    }

        for(account acc:lstacc){
            if(sumamount<50000 && countopp>1){
                        acc.Customer_segment__c = 'Hot';
            }
            else if(sumamount>=50000 && countopp>1){
                        acc.Customer_segment__c = 'Medium';
            }
             else{
            acc.Customer_segment__c = 'Low';
        }
        update lstacc;
    }
    }
    global void finish(Database.BatchableContext BC){
        system.debug('finish'); 
    }
}
I want to calculate Roll up summary for Closed Won Opportunities for the current year. How do achieve this?
Hello there so below I did get the ageing days but i want to get hours too can someone help please
TEXT(

CASE(MOD( DATEVALUE(LastModifiedDate) - DATE(1985,6,24),7),
0 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,2,2,3,3,4,4,5,5,5,6,5,1),
1 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,2,2,3,3,4,4,4,5,4,6,5,1),
2 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,2,2,3,3,3,4,3,5,4,6,5,1),
3 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,2,2,2,3,2,4,3,5,4,6,5,1),
4 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,1,2,1,3,2,4,3,5,4,6,5,1),
5 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,0,2,1,3,2,4,3,5,4,6,5,0),
6 , CASE( MOD( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) ,7),1,1,2,2,3,3,4,4,5,5,6,5,0),
999)
+
(FLOOR(( DATEVALUE(NOW ()) - DATEVALUE(LastModifiedDate) )/7)*5)
)& " Day"
Hello,

Yet another admin getting over their head in a foray into Apex.  I wrote a visualforce page (Cutting_ItemsShown) that required a custom controller (CuttingItemsShownController).  The VF page displays a list of associated records to the Task based on the Cutting_ID__c field on the Products_Cutting__c object.  These two parts work well, the trouble comes when trying to write a test class for the controller.
 
@isTest 
public class CuttingItemsShownControllerTest 
{
    static testMethod void testMethod1() 
    {   Account testAccount = new Account();
        testAccount.Name = 'Test Account';
        insert testAccount;
        
        Task testTask = new Task();
        testTask.RecordTypeId='0120y000000IBKkAAO' ;
        testTask.Subject='Cutting';
        testTask.Who_did_we_cut_against__c='Competitor';
        testTask.Did_We_Win__c='Yes';
        testTask.Whatid = 'testAccount.id';
        insert testTask;
        
        Products_Cutting__c item = new Products_Cutting__c ();
        item.Cutting_ID__c = testTask.id;
        item.Product_Code__c = '01tC0000004OvjpIAC';
        item.Name = 'SKUCode';
        item.Flavor__c = 'Company';
        item.Yield__c = 'Company';
        item.External_Texture__c = 'Company';
        item.Internal_Texture__c = 'Company';
        item.Cooked_Color__c = 'Company';
        item.Hold_Time__c = 'Company';
        item.Length__c = 'Company';
        item.Defects_Appearance__c = 'Company';
        item.Competitor_Item__c = '1234567901234';
        item.account_name__c = testAccount.Name;
        insert item;
        
        contract contr = new contract();
        // add all required field
        
        Test.StartTest(); 

            //ApexPages.currentPage().getParameters().put('id', String.valueOf(testTask.id));
            //CuttingItemsShownController  test = new CuttingItemsShownController(ApexPages.StandardController(testTask));
            //ApexPages.StandardController sc = new ApexPages.StandardController(item);
            //CuttingItemsShownController  testCutting = new CuttingItemsShownController(ApexPages.CuttingItemsShownController(testTask));
            PageReference pageRef = Page.Cutting_ItemsShown;
            pageRef.getParameters().put('Cutting_Id__c', testTask.id );
            pageRef.getParameters().put('Product_Code__c', '01tC0000004OvjpIAC');
            Test.setCurrentPage(pageRef);

            CuttingItemsShownController testTask1 = new CuttingItemsShownController(new ApexPages.StandardController(testTask));
            testTask.redirPage();    
        Test.StopTest();
     


            testCutting.cancel(); 
            testCutting.add ();

        Test.StopTest();
    }
}

The error received is as in the title:
Error: Compile Error: Constructor not defined: [CuttingItemsShownController].<Constructor>() at line 47 column 53

I'm thinking this has to do with the fact I'm displaying a list, but I'm not sure how to resolve it.  Is there any direction or resources you can provide to help me better understand the problem and the solution?  Thank you.
Q->  Insert 100 student’s records. Rollback all the inserted records if the number of successful insertion is less than 80
Please write code for the below problem....
Insert 5 records in Account object and display the list of records which are successfully inserted.Create related contact and opportunity to those successful accounts and add an opportunity product to those opportunity.. Using dml...
how to add opportunity product to opportunity
Thank you in advance
Hi all
It's really urgent I am totally new to coding I want to import my excel file to my custom object Sample__c to create new records using visual force page but even after searching, I am unable to complete it and am totally stuck.
I have an excel file with columns Name, Email, Phone and need to import the values to Sample__c fields Name__c, Email__c, Phone__c but can't do this any help from experts as I already followed all the links related to this now I need full code.
Thanks
Hi , I am new to salesforce, I have a below scenario, I just wanted to know whether I nned to create a multiple approval processes or can I create one and do the required 


If the Account’s Annual Revenue is > 0, then it will assign to “Initial Approval User” (Queue). If the Initial Approval User approve the case then it will go to next steps else it will be final rejection and update the case status to Rejected, if the Initial Approval User reject the case.

If the Account’s Annual Revenue is > 500, then it will assign to “Immediate Approval User” (Queue). If the Immediate Approval User approve the case then it will go to next steps else it will be final rejection and update the case status to Rejected, if the Immediate Approval User reject the case.
If the Account’s Annual Revenue is > 10,000, then assign it to “Yourself”. If the you approve the case then it will update the case status to Closed else it will be final rejection and update the case status to Rejected, if the Immediate Approval User reject the case. (mandatory)



Thanks & Regards
Suhaas

 
With a button, wheter inside a dashboard or a action? I want to redirect the user to a aura component that is at the bottom of  the page.
TEMPLATECODE:
<template>
    <lightning-card title="Create custom lookup on contact object" >
   
        <div class="slds-p-horizontal_small">
            <c-lwc-product-lookup onselected={myLookupHandle}></c-lwc-product-lookup>
            <c-lwc-quotes-lookup onselected={myQuoteLookupHandle}></c-lwc-quotes-lookup>
           
            <lightning-input label="Sales Price"
                             value={quoteRecord.salesprice}
                             onchange={handleSalesChange}
                             class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element">
            </lightning-input>                        
            <lightning-input label="Quantity"
                             value={quoteRecord.quantity}
                             onchange={handleQuantityChange}
                             class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element">
            </lightning-input>
            <lightning-input label="Discount"
                             value={quoteRecord.discount}
                             onchange={handleDiscountChange}
                             class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element">
            </lightning-input>            
           
            <lightning-button label="Submit"
                              variant="brand"
                              onclick={createLookupContactAction}
                              class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element">
            </lightning-button>                    
        </div>
   
</lightning-card>
</template>

JSCODE:
import { LightningElement,track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
 import QUOTE_LINE_OBJECT from '@salesforce/schema/QuoteLineItem';
import salesPriceField from '@salesforce/schema/QuoteLineItem.UnitPrice';
import  quantityField from '@salesforce/schema/QuoteLineItem.Quantity';
import discountField from '@salesforce/schema/QuoteLineItem.Discount';
import productfieldId from '@salesforce/schema/QuoteLineItem.Product2Id';

import quotefieldId from '@salesforce/schema/QuoteLineItem.QuoteId';

export default class TESTDEAFYULTQUOTESAVE extends NavigationMixin(LightningElement) {
    @track selectedProductId;
    @track selectedQuoteId;
    @track selectedpriceBookEntryId;
    @track quoteId;  
    @track quoteRecord={
       
        salesprice:salesPriceField,  
        quantity:quantityField,
        discount:discountField
    }
   
       
        handleSalesChange(event)
        {
            this.quoteRecord.salesprice=event.target.value;
            window.console.log('salesprice==>'+this.quoteRecord.salesprice);
        }
        handleQuantityChange(event)
        {
            this.quoteRecord.quantity=event.target.value;
            window.console.log('quantity==>'+this.quoteRecord.quantity);
        }
        handleDiscountChange(event)
        {
            this.quoteRecord.discount=event.target.value;
            window.console.log('discount==>'+this.quoteRecord.discount);
        }
        createLookupContactAction(){
            console.log(this.selectedProductId);
            console.log(this.selectedQuoteId);
            const fields = {};
            fields[salesPriceField.fieldApiName] = this.quoteRecord.salesprice;
            fields[quantityField.fieldApiName] = this.quoteRecord.quantity;
            fields[discountField.fieldApiName] = this.quoteRecord.discount;
            fields[productfieldId.fieldApiName] = this.selectedProductId;
            fields[quotefieldId.fieldApiName]=this.selectedQuoteId;
            fields[pricebookEntryIdField.fieldApiName]=this.selectedpriceBookEntryId;
            const recordInput = { apiName: QUOTE_LINE_OBJECT.objectApiName, fields };
            createRecord(recordInput)
                .then(contactobj=> {
                    this.quoteId = contactobj.id;
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Contact record has been created',
                            variant: 'success',
                        }),
                    );
                    this[NavigationMixin.Navigate]({
                        type: 'standard__recordPage',
                        attributes: {
                            recordId: contactobj.id,
                            objectApiName: 'QuoteLineItem',
                            actionName: 'view'
                        },
                    });
   
   
   
                })
                .catch(error => {
   
 console.error("error: " + JSON.stringify(error));

                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Error creating record',
                            message: error.body.message,
                            variant: 'error',
                        }),
                    );
                });          
                }
    myLookupHandle(event){
        console.log(event.detail);
        this.selectedProductId = event.detail;
    }
    myQuoteLookupHandle(event){
        console.log(event.detail);
        this.selectedQuoteId = event.detail;
    }
}

ERROR WAS:
error: {"status":400,"body":{"message":"An error occurred while trying to update the record. Please try again.","statusCode":400,"enhancedErrorType":"RecordError","output":{"errors":[],"fieldErrors":{"PricebookEntryId":[{"constituentField":null,"duplicateRecordError":null,"errorCode":"REQUIRED_FIELD_MISSING","field":"PricebookEntryId","fieldLabel":"Price Book Entry ID","message":"Required fields are missing: [PricebookEntryId]"}]}}},"headers":{}}

Basically Ineed PriceBookEntryId which is missing How this field will added please tell me answer 

Thanks
Saurabh
Hi Everyone,
How to display JSON data by serializing in apex and display in descending order. Please have a look below json data.

let jsonData = [
{‘HouseName’:‘anna’,
‘Kilometers’:75
},
{‘HouseName’:‘nancy’,
‘Kilometers’: 55
},
{‘HouseName’:‘sana’,
‘Kilometers’:95
},
]

By getting this data from FE, parse it in apex, and provide list of housenames based on kilometers in descending order.

O/P-should be- [Sana,Anna,Nancy]
Please help me in Apex code.
Hello,
how are the licences claasified as per the amount and what are the best practices to do it, please ?


thank you for suggestion
Hello,
In my org many users are connecting with the salesforce licneces and many users are using same id for connection.
I wanted to implement MFA and how will this impact these usrs please 

and i have techncial users or API uers, how this will impact hem too
Hello,
How can i calculate the number of API users in the org,please
Hello,

I have to create users for interfacing with differrent external systems, can i use the same user for all the interfaces or is there any best practices to implement, please ?

I have differrent UI integration, system integration, tool usage, etc