+ Start a Discussion
Hari nadh babu Eluru 7Hari nadh babu Eluru 7 
take a picklist which is having options male,female,others. if user select male and click button then show male students only in vf page
 
<apex:page controller="ChooseGender">
<apex:form >
    <apex:selectList id="ChooseGender" value="{!CG}" size="1">
            <apex:selectOption itemValue="Male" itemLabel="Male"/>
            <apex:selectOption itemValue="Female" itemLabel="Female"/>
            <apex:selectOption itemValue="Others" itemLabel="Others"/>
        </apex:selectList> 
<apex:commandButton value="Click me" action="{!PSO}"/>
</apex:form>
</apex:page>

 
Best Answer chosen by Hari nadh babu Eluru 7
Suraj Tripathi 47Suraj Tripathi 47
Hi Hari,

Pleare try this Here is the code:

VF PAge:
<apex:page controller="ChooseGender">
<apex:form >
    <apex:pageBlock>
    <apex:selectList id="ChooseGender" value="{!CG}" size="1">
            <apex:selectOption itemValue="Male" itemLabel="Male"/>
            <apex:selectOption itemValue="Female" itemLabel="Female"/>
            <apex:selectOption itemValue="Others" itemLabel="Others"/>
        </apex:selectList> 
<apex:commandButton value="Click me" action="{!PSO}"/>
    
    <apex:pageBlockTable value="{!stu}" var="c">
                <apex:column value="{!c.Name}"/>
                <apex:column value="{!c.Gender__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
</apex:form>
</apex:page>

Apex Class:
public class ChooseGender {
    public string CG {set;get;}
    
    public list<Student__c> stu {set;get;}   
    public void PSO(){
        stu = new  List<Student__c>();
        stu = [select Id, Name, Gender__c from Student__c where Gender__c =:CG];
        system.debug('stuList ::'+stu);
    }
}

Hope this will help you.
Thanks
PraviPravi 
i want to write a utility class, class name: XYZ, Custom Object Name: ABC__c, Field Name: C_ABC__c
class XYZ access the data from ABC__c but for a Case(Case Object is lookup with field C_ABC__c)
My Understanding: if I want to access data of custom object related to case then i need to fetch the Case ID, if i fetch the Case Id then i get the data related with ABC__c
I Try this:
public class XYZ{ public static List<ABC__c> str(String Name){ List<ABC__c> alist = new List<ABC__c>(); //this line is just for try
List<ABC__c> alist = [Select Id From ABC__c];
} return alist; }

I am stuck, how i access the data ABC__c from Case
Best Answer chosen by Pravi
mukesh guptamukesh gupta
Hi Parvi

Please follow below code:-
 
List<Case> cList = [Select Id, (Select Id, Name from ABC(relationshipName) ) From Case ]
  
  
  for(ABC__c abc : cList.ABC){
   // you can access ABC__c object details from case
   // like abc.Id ,abc.Name etc
  
  }

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
YiQin HeYiQin He 
Hi, 

I created a lightning component as a quick action button. In the component, I have a cancel button that I want it closed when user clicks.
User-added image

But the problem is that I cannot find any document explain how to close the modal dialog. This is the ui code:
<aura:component controller="ContactController" implements="force:lightningQuickActionWithoutHeader,force:hasRecordId" >
    <style>
        .changeRecordTypeRow {
        margin-top: 1.5rem;
        margin-bottom: 0;
        margin-left: 0;
        margin-right: 0;
        }
        
        .changeRecordTypeLeftColumn {
        float: left;
        text-align: right;
        padding-right: 1.5rem;
        width: 35%;
        font-size: .8125rem;
        color: rgb(84, 105, 141);
        }
        
        .changeRecordTypeRightColumn {
        float: right;
        text-align: left;
        width: 65%;
        }
        
        .modal-body
        {
        	height:auto !important;
        	padding:0;
        }
        
        .forceChatterLightningComponent .bodyWrapper{height:100%;width:100%;padding:0;box-sizing:border-box}
    </style>
    <div class="modal-header slds-modal__header">
        <h2 class="title slds-text-heading--medium" >Change Contact Type</h2>
    </div>
    <div class="scrollable slds-modal__content slds-p-around--medium">
        <div class="changeRecordTypeRow">
            <fieldset class="slds-form-element">
                <div class="changeRecordTypeLeftColumn">
                    <legend class="form-element__legend slds-form-element__label">Select a record type</legend>
                </div>
                <div class="changeRecordTypeRightColumn slds-form-element__control">

                    <span class="slds-radio">
                        <input type="radio" id="radio_PrimaryContact" name="recordType" />
                        <label class="slds-radio__label" for="radio_PrimaryContact">
                            <span class="slds-radio--faux"></span>
                            <span class="slds-form-element__label">Primary Contact</span>
                        </label>
                    </span>
                    <span class="slds-radio">
                        <input type="radio" id="radio_SecondaryContact" name="recordType" />
                        <label class="slds-radio__label" for="radio_SecondaryContact">
                            <span class="slds-radio--faux"></span>
                            <span class="slds-form-element__label">Secondary Contact</span>
                        </label>
                    </span>
                </div>
            </fieldset>
        </div>
	</div>
    <div class="modal-footer slds-modal__footer">
    	<div class="forceChangeRecordTypeFooter">
        	<button type="button" class="slds-button slds-button--neutral .slds-modal__close" aura:id="btnCancel" >
            	Cancel
            </button>
            <button type="button" class="slds-button slds-button--brand" aura:id="btnSave">
            	Save
            </button>
        </div>
    </div>
</aura:component>
Does anyone have similar experience? Thanks in advance.
Best Answer chosen by YiQin He
YiQin HeYiQin He
Hi Karthik,

Thanks for the reply. I've already found the solution.
Call this method $A.get("e.force:closeQuickAction").fire() will close the modal dialog.

Yiqin
Siddharth PatniSiddharth Patni 
String baseURL =  'https://' + System.URL.getSalesforceBaseUrl().getHost();
                String queryStr = 'SELECT+NumLinesCovered,ApexClassOrTriggerId,ApexClassOrTrigger.Name,NumLinesUncovered,Coverage+FROM+ApexCodeCoverageAggregate';
                String ENDPOINT = baseURL + '/services/data/v40.0/tooling/';
               
                HttpRequest req = new HttpRequest();
                req.setEndpoint(ENDPOINT + 'query/?q=' + queryStr);
               
                req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID() );
                req.setHeader('Content-Type', 'application/json');
                req.setMethod('GET');
                req.setTimeout(80000);
                system.debug('end'+req);
            Http http = new Http();
            HTTPResponse res = http.send(req);
           


getting error  [{"message" :"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] while calling tooling api  from LWC


I have also used Connected app and named credential its not working while called from lwc. but, working as expected while I call it using annoynomous apex  

 
Best Answer chosen by Siddharth Patni
Maharajan CMaharajan C
Hi Siddharth,

Please read the below content from Salesforce Document: 

For security reasons, the Lightning Component framework places restrictions on making API calls from JavaScript code. To call third-party APIs from your component’s JavaScript code, add the API endpoint as a CSP Trusted Site.
To call Salesforce APIs, make the API calls from your component’s Apex controller. Use a named credential to authenticate to Salesforce.

By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability.

Link : https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm

To overcome this use Named Credentials in your Rest API Call to Tooling API as per Salesforce Suggestion.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

Sample Code for Name Creds used in LWC:
https://medium.com/@gurpreetgill.sfdc/how-to-make-a-http-callout-using-lwc-lightning-web-component-3f9294e39115
https://niksdeveloper.com/salesforce/callout-from-lwc-lightning-web-component/

Other reference link:

https://salesforce.stackexchange.com/questions/311507/invalid-session-id-when-using-lwc-to-call-toolingapi-class
https://salesforce.stackexchange.com/questions/218853/lightning-getting-a-401-when-calling-auraenabled-apex-method-to-do-a-rest-call
https://salesforce.stackexchange.com/questions/348575/how-to-resolve-invalid-session-id-error-on-fetching-tooling-api-data


Thanks,
Maharajan.C
Bhavana 7Bhavana 7 

Hi I am Newbie to Development from Salesforce Admin .

I was able to write a trigger for a requirment to create Quote and Quoteline item from custom object named RPR , But i have this sutiation that i already have a trigger in same object which is causing my newly created trigger to get dectiavted .

As per research that i have done i got to know that it can be sloved by creating an apex trigger handler .

This is my newly created trigger .

 

trigger RPRTrigger on RPR__c (after insert) 
{
    List<Quote> quoteList = new List<Quote>();
    List<QuoteLineItem> qliList = new List<QuoteLineItem>();
    
    Pricebookentry pbe = [select Id,pricebook2Id,product2Id from PricebookEntry where product2id = '01t2s00000077OF'];
    Id oppId = [select id from opportunity where id =: '006p000000Abxrb' LIMIT 1].Id;
    if(trigger.isInsert && trigger.isAfter)
    {
        Set<Id> accId = new Set<Id>();
        List<RPR__c> rprList = new List<RPR__c>();
        for(RPR__c rpr : trigger.new)
        {
            rprList.add(rpr);
            accId.add(rpr.Account__c);
        }
        List<Opportunity> oppList = [SELECT Id,Name FROM Opportunity
                                     WHERE AccountId IN : accId];
        System.debug('Account Set'+accId + ' Opportunity List '+ oppList);
        for(RPR__c rprNew : rprList){
            Quote q = new Quote();
            q.Name = 'Teston New Quote'+rprNew.Name;
            
            q.OpportunityId = oppList[0].Id;
            q.Ship_To_City__c = rprNew.Shipment_From__c;
            q.Pricebook2Id = pbe.pricebook2id;
            quoteList.add(q);
        }
        
        if(!quoteList.isEmpty()){
            insert quoteList;
        }
        
        for(Quote q : quoteList){
            QuoteLineItem qli = new QuoteLineItem();
            qli.QuoteId = q.Id;
            qli.quantity = 2;
            qli.pricebookentryId = pbe.id;
            qli.unitprice = 10;
            qli.product2Id = pbe.product2Id;
            qli.Packing_Style__c = q.X1_Packing_Style__c;
            
            qliList.add(qli);
        }
        
        if(!qliList.isEmpty()){
            insert qliList;
        }      
        
    }
}

 

This trigger is getting deactived if the below existing trigger fires .

trigger pullCommentsApproval on RPR__c (before update) {
    Map<Id, RPR__c> oppMap = new Map<Id, RPR__c>([
        Select (Select IsPending, ProcessInstanceId, TargetObjectId, StepStatus, OriginalActorId, ActorId,Actor.Name, RemindersSent, Comments, IsDeleted, CreatedDate, CreatedById, SystemModstamp 
         From ProcessSteps where StepStatus IN ('Approved','Rejected') ORDER BY CreatedDate DESC) From RPR__c WHERE Id IN : Trigger.new]);
    
    for(RPR__c opp: Trigger.new) {
        RPR__c opp1 = oppMap.get(opp.Id);
        opp.Approver_Comments__c = '';
        for (ProcessInstanceHistory processStep : opp1.ProcessSteps) {
            opp.Approver_Comments3__c = 'aa'; //This is a dummy value & field only.
            opp.Approver_Comments__c += 'Comments: ' + processStep.comments + ' . Status: ' + processStep.StepStatus + ' . Date: ' + processStep.CreatedDate +' . Commentor Name: ' + processStep.Actor.Name + '\\';
            //opp.Approved_Date__c = DateTime.parse(system.now().format());
            opp.Approver_Comments3__c = 'aa'; //This is a dummy value & field only, DO NOT DELETE, MAY EFFECT REPORT TYPE
        }
        opp.Approver_Comments3__c = 'aa';
    }
}

 

what should i consider and how i can complete a trigger handler in order make my newly created trigger stable without getting deactivated .

Any suggestions will be a great help ! Thanks in advance :)

 

 

 

Best Answer chosen by Bhavana 7
mukesh guptamukesh gupta
Hi Bhavana,

Please follow below code:-

pullCommentsApproval:-
trigger pullCommentsApproval on RPR__c (after insert,before update) {
TriggerHandler_Controller handlerClass = new TriggerHandler_Controller();


  if(Trigger.isAfter && Trigger.isInsert ){
    handlerClass.afterInsert(Trigger.New);
  }
  
  if(Trigger.before && Trigger.update ){
    handlerClass.beforeUpdate(Trigger.New);
  }



}

TriggerHandler_Controller:-
 
Public class TriggerHandler_Controller(){
  
  public void afterInsert(List<RPR__c> objList){
   List<Quote> quoteList = new List<Quote>();
    List<QuoteLineItem> qliList = new List<QuoteLineItem>();
    
    Pricebookentry pbe = [select Id,pricebook2Id,product2Id from PricebookEntry where product2id = '01t2s00000077OF'];
    Id oppId = [select id from opportunity where id =: '006p000000Abxrb' LIMIT 1].Id;
    
        Set<Id> accId = new Set<Id>();
        List<RPR__c> rprList = new List<RPR__c>();
        for(RPR__c rpr : objList)
        {
            rprList.add(rpr);
            accId.add(rpr.Account__c);
        }
        List<Opportunity> oppList = [SELECT Id,Name FROM Opportunity
                                     WHERE AccountId IN : accId];
        System.debug('Account Set'+accId + ' Opportunity List '+ oppList);
        for(RPR__c rprNew : rprList){
            Quote q = new Quote();
            q.Name = 'Teston New Quote'+rprNew.Name;
            
            q.OpportunityId = oppList[0].Id;
            q.Ship_To_City__c = rprNew.Shipment_From__c;
            q.Pricebook2Id = pbe.pricebook2id;
            quoteList.add(q);
        }
        
        if(!quoteList.isEmpty()){
            insert quoteList;
        }
        
        for(Quote q : quoteList){
            QuoteLineItem qli = new QuoteLineItem();
            qli.QuoteId = q.Id;
            qli.quantity = 2;
            qli.pricebookentryId = pbe.id;
            qli.unitprice = 10;
            qli.product2Id = pbe.product2Id;
            qli.Packing_Style__c = q.X1_Packing_Style__c;
            
            qliList.add(qli);
        }
        
        if(!qliList.isEmpty()){
            insert qliList;
        }      
        
    
  
  
  }
  public void beforeUpdate(List<RPR__c> objList){
  
  Set<Id> RPR_Ids = new Set<Id>();
  for(RPR__c obj : objList){
    RPR_Ids.add(obj.Id);
  }
  
    Map<Id, RPR__c> oppMap = new Map<Id, RPR__c>([
        Select (Select IsPending, ProcessInstanceId, TargetObjectId, StepStatus, OriginalActorId, ActorId,Actor.Name, RemindersSent, Comments, IsDeleted, CreatedDate, CreatedById, SystemModstamp 
         From ProcessSteps where StepStatus IN ('Approved','Rejected') ORDER BY CreatedDate DESC) From RPR__c WHERE Id IN : RPR_Ids]);
    
    for(RPR__c opp: objList) {
        RPR__c opp1 = oppMap.get(opp.Id);
        opp.Approver_Comments__c = '';
        for (ProcessInstanceHistory processStep : opp1.ProcessSteps) {
            opp.Approver_Comments3__c = 'aa'; //This is a dummy value & field only.
            opp.Approver_Comments__c += 'Comments: ' + processStep.comments + ' . Status: ' + processStep.StepStatus + ' . Date: ' + processStep.CreatedDate +' . Commentor Name: ' + processStep.Actor.Name + '\\';
            //opp.Approved_Date__c = DateTime.parse(system.now().format());
            opp.Approver_Comments3__c = 'aa'; //This is a dummy value & field only, DO NOT DELETE, MAY EFFECT REPORT TYPE
        }
        opp.Approver_Comments3__c = 'aa';
    }
  
  }

}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh


 
Nishant Gupta 15Nishant Gupta 15 
I created a lightning component that allows a user to upvote or downvote an 'idea' (custom object). I want a user to be able to vote only once. I need some kind of a check to see if user has previously voted or not. What are the ways achieve this? Thanks in advance.
Best Answer chosen by Nishant Gupta 15
Andrew GAndrew G
Hi Nishant

Quick idea would be to create another custom object - "Idea Vote" with custom fields - Voted by (Lookup - User Account), Related Idea(Lookup - Idea), and possibly - Vote Type (Picklist - Up/Down)

When someone votes, SOQL to get all related "Idea Votes", IF user present, error "already voted".  ELSE create/insert a new "Idea Vote" record.

We are assuming that the user is recognised by Salesforce (logged in).

The idea of the Vote Type as a picklist would be if you wanted to allow someone to change from "Down" vote to "Up" vote, or vice-versa.
You could then use the picklist value in a rollup summary to the "Idea" object to manage your counts.

Regards
Andrew

 
Hari nadh babu Eluru 7Hari nadh babu Eluru 7 
VF code
<apex:page controller="Created_Recently">
    <apex:form >
        <apex:pageblock title="Recently Modified student">
          
            <apex:pageBlockTable value="{!stu}" var="c">
                <apex:column value="{!c.Name}"/>
                <apex:column value="{!c.LastModifiedDate}"/>
                <apex:column value="{!c.Student_Id__c}"/>
            </apex:pageBlockTable>
        </apex:pageblock>        
    </apex:form>
</apex:page>
Apex code
public class Created_Recently {
    
    public List<Student__c> stu {get;set;}
 
    public Created_Recently(){
        DateTime dt = System.Now().addHours(-1);
        stu = [SELECT Student_Id__c,Name, LastModifiedDate FROM Student__c where LastModifiedDate=:dt ORDER BY LastModifiedDate DESC LIMIT 1];
        system.debug('stu'+stu);
        
    }
}

fetch and display students whose records modified recently
in visualforce page
Best Answer chosen by Hari nadh babu Eluru 7
Suraj Tripathi 47Suraj Tripathi 47
Hi Hari,

if you want recently modified records then use this query:
stu = [SELECT Student_Id__c,Name, LastModifiedDate FROM Student__c  ORDER BY LastModifiedDate DESC LIMIT 1];

Hope this will help you.
Thanks
Pritam Gaigole 4Pritam Gaigole 4 
String fake = '2021-12-07T15:32:19.583';
DateTime t = DateTime.valueOfGmt(fake);
system.Debug('Line 17:' + t);
Best Answer chosen by Pritam Gaigole 4
Suraj Tripathi 47Suraj Tripathi 47
Hi Pritam,
Please try this:

String fake = '2021-12-07T15:32:19.583';
DateTime t = DateTime.ValueofGmt(fake.replace('T', ' ')); 
system.Debug('Line 17:' + t);

Hope this will help you.
Thanks
Andréa de FariaAndréa de Faria 
Hello,

In our company, the Task object have a field called "Meeting Notes", which is the standard "Description" Text field of the Task object, but with the label "Meeting Notes".

Please, how can I copy the value from this field in the most recent Taks created and paste it in a custom Event field called "Pre Meetin Notes".

This Event will also be the latest one created.

The Task and the Event will have the same Contact in common.

I tried with Process Builder and formula fields, but none of these worked.

Appreciate your help.
Best Answer chosen by Andréa de Faria
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Andrea,

I have used a lightning flow to achieve it. We are using record trigger flow and only in create scenerio. When ever a new event is created it will copy the description field from the latest task which is associted to the contact.

Record Trigger flow starting condition:

User-added imageget associated latest event:

User-added image
Update the task description:
User-added image
Entire Flow:

User-added image

Let me know if you need any help on it.

If this solution helps, Please mark it as best answer.

Thanks,
 
Hari nadh babu Eluru 7Hari nadh babu Eluru 7 

If user enter min age, max age . fetch all the students in between that min and max age

  • in above example try to load students in ascending order based on age

 
Best Answer chosen by Hari nadh babu Eluru 7
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Hari,

Please find the below VF page and Apex class for that. I have used the Contact object just replace the object name and fields what ever you need.

VF page:
<apex:page Controller="SearchInVFController">
    <apex:form>
        <apex:inputText value="{!minvalue}" label="minvalue"/>
        <apex:inputText value="{!maxvalue}" label="maxvalue"/>
        <apex:commandButton value="Search records" action="{!search}"/>
        <apex:commandButton value="Clear records" action="{!clear}"/>
        <apex:pageBlock title="Search Result">
            <apex:pageBlockTable value="{!acc}" var="a">
                <apex:column value="{!a.name}"/>
                <apex:column value="{!a.id}"/>
                <apex:column value="{!a.Age__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class
 
public class SearchInVFController {
    public list <Contact> acc {get;set;}
    public Decimal minvalue {get;set;}
    public Decimal maxvalue {get;set;}
    public SearchInVFController( ) {
    }
    public void search(){
        string searchquery='select Name,id,Age__c  from Contact where Age__c > :minvalue and Age__c < :maxvalue ORDER  BY Age__c ASC';
        acc= Database.query(searchquery);
    }
    public void clear(){
        acc.clear();
    }
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,