• Soyab Hussain
  • SMARTIE
  • 660 Points
  • Member since 2019


  • Chatter
    Feed
  • 22
    Best Answers
  • 0
    Likes Received
  • 5
    Likes Given
  • 2
    Questions
  • 80
    Replies
I am completely new to Apex and coding.I have a requirement where I need to create Opportunities for Contact objects when a Picklist field on contact object gets updated.
Which means when the picklist filed is having any of the following values then an opportunity should get created for that contact automatically...
My picklist field values are: Service every year, Service every 6 months, Phone call and Send mail.
Now I need some help in writing the batch apex class and test class for this requirement. Any help is much appreciated.
Thanks in advance.
public class test5 {

  public list<string> lststatename{get;set;}
  public list<string> lstrating{get;set;}
  
  public list<string> lstactive{get;set;}
  public map<string, string> statemap{get;set;}

public map<string, string> activestatusmap{get;set;}

 public set<string> mapkey{get;set;}
 
    public list<string> mapvalue{get;set;}
 public test5(){
 
 
    string  jsonexample1 =  ' { "overalldata": [ {"stateName": "Andrapradesh",  "rating": "5.0" , "active": "yes" }, { "stateName": "Telangana",  "rating": "4.0" ,"active": "no" }, {"stateName": "Banglore",  "rating": "5.0" ,"active": "no"} , {"stateName": "Maharastra",  "rating": "4.5" ,"active": "no" }  ] } ';

   
     map<string,object>  metadatamap= (map<string,object>)json.deserializeuntyped(jsonexample1); 
     
      list<object>  values1= (list<object>)metadatamap.get('overalldata');
        
        
         lststatename= new list<string>();
         lstrating= new list<string>();
         statemap= new map<String, string>();
         
          for(object parsed : values1){
          map<string,object>  values = (map<string,object>)parsed;
          string statename = string.valueof(values.get('stateName'));
          
          string rating= string.valueof(values.get('rating'));
          
          lststatename.add(statename);
             
          lstrating.add(rating);
             
             statemap.put(statename,rating);
             
             }
            
 }
}
Visual force page:
 
<apex:page controller="test5" >

 <apex:form >
   <apex:repeat value="{!statemap}" var="a">
    <apex:selectList >   
               <apex:selectOptions value="{!a}">{!a}</apex:selectOptions>
         </apex:selectList>
   
   </apex:repeat>
            
                                          
      
 
 </apex:form>
 
</apex:page>

Hi..! can any body bind data to the selectlist with statename as itemlabel and rating  as the itemvalue in visualforce page
.. Thank you..!
Hello All,

I have a input form for a custom object Employee with three fields name, designation, phone .
on click of save button only name is getting saved, rest phone and designation fields are empty. 
Here is my code-

HTMl
<template>
    <lightning-card title= "Insert Employee Data" icon-name="standard:account">
        <div class="slds-p-around_x-small">
            <lightning-input label="Employee Name" value={rec.Name} onchange={handleNameChange}></lightning-input>
            <lightning-input label="Designation" value={rec.Designation__c} onchange={handleDesChange}></lightning-input>
            <lightning-input label="Phone" value={rec.Primary_Phone__c} onchange={handlePhnChange}></lightning-input><br/>
            <lightning-button label="Save" onclick={handleClick}></lightning-button>
   
        </div>
    </lightning-card>
</template>

JS
import { LightningElement, track } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Employee__c.Name';
import DESIGNATION_FIELD from '@salesforce/schema/Employee__c.Designation__c';
import PHONE_FIELD from '@salesforce/schema/Employee__c.Primary_Phone__c';
import createEmployee from '@salesforce/apex/createEmployee.createEmployee';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class InputFormForCustomObject extends LightningElement {

    @track name = NAME_FIELD;
    @track designation = DESIGNATION_FIELD;
    @track phone = PHONE_FIELD;
    rec = {
        Name : this.name,
        Designation : this.Designation__c,
        Phone : this.Primary_Phone__c
    }

    handleNameChange(event) {
        this.rec.Name = event.target.value;
        console.log("name1", this.rec.Name);
    }
    
    handleDesChange(event) {
        this.rec.Designation = event.target.value;
        console.log("Designation", this.rec.Designation);
    }
    
    handlePhnChange(event) {
        this.rec.Phone = event.target.value;
        console.log("Phone", this.rec.Phone);
    }

    handleClick() {
        createEmployee({ hs : this.rec })
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.rec.Name = '';
                    this.rec.Designation = '';
                    this.rec.Phone = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Employee created',
                            variant: 'success',
                        }),
                    );
                }
                
                console.log(JSON.stringify(result));
                console.log("result", this.message);
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log("error", JSON.stringify(this.error));
            });
    }
}

Meta Xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
   <apiVersion>45.0</apiVersion>
   <isExposed>true</isExposed>
   <targets>
       <target>lightning__AppPage</target>
       <target>lightning__RecordPage</target>
       <target>lightning__HomePage</target>
   </targets>
</LightningComponentBundle>

Apex
public with sharing class createEmployee {
     @AuraEnabled
    public static Employee__c createEmployee(Employee__c hs) {
        
        insert hs;
        return hs;
    }
}

​​​​​​​​​​​​​​
My Vf Page is 
<apex:page standardController="Class__c" extensions="ManageClassController" >
    <apex:pageBlock > 
        <apex:pageBlockSection >
            <apex:form >
                <apex:pageBlockTable value="{!classList}" var="c" >
                    <apex:column headerValue="class name">
                        <apex:outputText value="{!c.name}"></apex:outputText>
                    </apex:column>
                    <apex:column headerValue="Edit" >
                        <apex:commandLink value="Edit" action="{!editDetails}">
                            <apex:param assignTo="{!classId}" value="{!c.id}" />
                        </apex:commandLink>
                    </apex:column>    
                    <apex:column headerValue="Delete">
                        <apex:commandLink value="Delete">
                            <apex:param assignTo="{!classId}" value="{!c.id}" />
                        </apex:commandLink>
                    </apex:column>   
                </apex:pageBlockTable>
            </apex:form>
        </apex:pageBlockSection>
        <apex:pageBlockSection >
            
            <apex:form rendered="{!flag}">
                <apex:inputField value="{!dummyClass.name}"/>
                <apex:inputField value="{!dummyClass.Fee__c}"/>
                <apex:inputField value="{!dummyClass.Detailed_Description__c}"/>
                <apex:inputField value="{!dummyClass.Max_Size__c}"/>
                <apex:inputField value="{!dummyClass.My_Count__c}"/>
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandLink value=""/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:form>
            
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

My Controller is 
public class ManageClassController {
    public List<Class__c> classList{get;set;}
    public String classId{get;set;}
    public class__c dummyClass{get;set;}
    public boolean flag {get;set;}
    private ApexPages.StandardController controller {get; set;}
    public ManageClassController(ApexPages.StandardController stdController){
        this.controller = stdController;
        this.classList = new List<Class__c>([SELECT id , name from class__c]);
        this.flag=false;
        this.classId = null;
    }
    public void editDetails(){
        System.debug('I came here');
        System.debug('classId = ' + this.classID);
        if(this.classId != null){
            this.dummyClass = [SELECT id , name , fee__c , detailed_description__c , max_size__c , my_count__c FROM class__c where id = :classId];
            this.classId = null;
            this.flag = true;
        }
    }
}

My vf page is running as 
User-added imageand as soon as i press edit link value must get populate in controller but is not going
Debug only logs -
User-added imageThanks in advance
Hi All,
         i have a requirement in which i have a field on lead object called ToBeDeleted__c, which should be true when one of the following condition is true :-
1.lead name contains 'test'   
2.The owner of the lead is inactive.
3.lead has duplicate records than last created record need to be checked.
4.lead is created 1 year or more than one year ago.
I want to create a batch which set the checkbox field true when above condition met.
How to do it ?Can someone guide me with it?
Thanks
Hi,

I need to write a batch class on one of object records whose created date  greater than 5 years .
Please help me to write correct filter condition for this.
trigger CaseHandlerCountAlert on Case (after insert) {
 	
    //Case trigger that will send email alert when 8 cases are created within 7 days.
    
    String messageToSend;
    List <String> ListOfMessages = new List <String>();
    Set <Id> AcctIds = new Set <Id>();
    String messageBody;

    List < AggregateResult > AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co
        FROM Case
        WHERE CreatedDate = LAST_N_DAYS:7 AND Id IN :Trigger.New
        GROUP BY AccountId, Account.Name
        HAVING COUNT(Id) >= 8
    ];

    Map < Id, String > accountIdEmailmessageMap = new Map < Id, String > ();

    for (AggregateResult aggr: AggregateResultList) {
        String messageToSend = 'Account name: ' + aggr.get('name') +
            ' has ' + (Integer) aggr.get('co') +
            ' cases opened in the last 8 days.';
        Id accId = (Id) aggr.get('AccountId');
        accountIdEmailmessageMap.put(accId, messageToSend);
        AcctIds.add(accId);
    }


    List < Case > caseList = [SELECT Id, AccountId, Account.Name, Parent_Project_if_applicable__r.Implementation_status__c,
        Parent_Project_if_applicable__r.PM_Implementation_Status__c,
        Parent_Project_if_applicable__r.RCM_Implementation_Status__c,
        Parent_Project_if_applicable__r.Resource_Coordinator_Email__c,
        Parent_Project_if_applicable__r.Client_Advisor_Email__c                      
        FROM Case
        WHERE AccountId IN: AcctIds];
    
	List<Messaging.SingleEmailMessage> lstASingleEmailMessage = new List<Messaging.SingleEmailMessage>();
    List<Messaging.SingleEmailMessage> lstBSingleEmailMessage = new List<Messaging.SingleEmailMessage>();

    for (Case cl: caseList) {

        if (cl.Parent_Project_if_applicable__r.Implementation_status__c == 'Live - Closed Project' ||
            cl.Parent_Project_if_applicable__r.PM_Implementation_Status__c == 'Live - Closed Project' ||
            cl.Parent_Project_If_Applicable__r.RCM_Implementation_Status__c == 'Live - Closed Project') {
         
            String messageBody = accountIdEmailmessageMap.get(cl.AccountId);
                
                List<String> emailaddr = new List<String>();
                emailaddr.add('CustomerSuccessManagers@test.com');
                
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setSenderDisplayName('Support');
            mail.setToAddresses(emailaddr);   
            mail.Subject = 'Multiple cases created alert message';
            mail.setPlainTextBody(messageBody);
			lstASingleEmailMessage.add(mail);
                
       }     

    }
           Messaging.SendEmailResult[] r = Messaging.sendEmail(lstASingleEmailMessage);


    else{
            String messageBody = accountIdEmailmessageMap.get(cl.AccountId);		
            
			List<String> emailAdds = new List<String>();
            emailAdds.add(cl.Parent_Project_if_applicable__r.Resource_Coordinator_Email__c);
            emailAdds.add(cl.Parent_Project_if_applicable__r.Client_Advisor_Email__c);
            
            Messaging.SingleEmailMessage amail = new Messaging.SingleEmailMessage();
            amail.SetSenderDisplayName('Support');
            amail.setToAddresses(emailAdds);
            amail.Subject = 'Multiple cases created alert message';
            amail.setPlainTextBody(messageBody);
			lstBSingleEmailMessage.add(amail);

        }		
           
                Messaging.SendEmailResult[] r = Messaging.sendEmail(lstBSingleEmailMessage);
     
}

In an effort to keep both email SendEmail methods out side of a `For-Loop`, I have mixed up my {}.  Any help is appreciated.

 
Hello,
Contacts are created by users which has a multi select picklist to capture candidates skillset. 
Job records are created by users which has a multi select picklist to capture what skill set is needed. 
Requirement: Whenever a job record is created, based on what skill set is needed the system needs to find the corresponding contacts (candidates) matching atleast 1 skillset and email them job record. 
trigger JobTrigger on Job__c (after insert) {
    
    Set<String> SkillCode = new Set<String>();
    
    // when a new job is posted, based on Skill_Code__c on job record, get matching contact records based on Candi_Skill_Codes__c
    for (Job__c J : Trigger.new) {
        
        // Skill_Code__c is a multi select picklist value
        if (J.Skill_Code__c != null) {
            
            List<String> JobOrderSkillCode = J.Skill_Code__c.split(';');
            SkillCode.addAll(JobOrderSkillCode);

        }
    }

    //Candi_Skill_Codes__c is a multi select picklist value
    for (Contact C : [SELECT Id, Alert__c, Candi_Skill_Codes__c FROM Contact WHERE Candi_Skill_Codes__c INCLUDES (:SkillCode) AND Alert__c = 'Yes']) {
        // Above query returning 0 results
        // If i change the query to something like, 
        // SELECT Id, Alert__c, Candi_Skill_Codes__c FROM Contact WHERE Candi_Skill_Codes__c INCLUDES ('sfdc', 'developer') AND Alert__c = 'Yes'
        // This query returned 2 results
        // I understand bind variables cannot be used with INCLUDES but i also don't know how to proceed in this scenario, please help
        
    }
    
    //Send an email to matched contacts

}
Hi guys,

I want to send an email notification to users based on two field criterias. These are:
1. the payment method = Barter 
2. the payment amount field has been updated

I have created a custom field to capture the previous amount value when that field has been changed and I have built a workflow rule with a field update for this.

AND(
              ISCHANGED( Payment_Amount__c ),

              NOT(ISBLANK(TEXT(Payment_Amount__c)))
             )
Lightning Component  - 
<aura:component implements="flexipage:availableForAllPageTypes, force:hasRecordId" access="global" controller="addBooks">
    <aura:attribute name="bookToAdd" type="Books__c" />
    <aura:attribute name="authId" type="String" />
    
    <div class="Styling">
        <lightning:card title="Quick register Books">
            
            <lightning:input label = "Book Name : " value="{!v.bookToAdd.Name}" required="true" />
            <lightning:input label = "Book Price : " value="{!v.bookToAdd.Price__c}" required="true" />
            <lightning:button variant="brand" label="Add books" title="Add books" onclick="{! c.addBooks }"/>
        </lightning:card>
    </div>
</aura:component>

JS - 
({
    addBooks : function(component, event, helper) {
        var action = component.get('c.addbooks');
        component.set('v.authId',v.recordId);
        console.log('v.recordId***',v.recordId);
        action.setParams({
            b : component.get('v.bookToAdd'),
            authId : component.get('v.authId')
        });
        action.setCallback(this, function(response){
            
        },'ALL');
        $A.enqueueAction(action);
    }
})

Controller - 
public class addBooks {
    @AuraEnabled
    public static void addbooks(Books__c b, Id authId){
        if((b.Name != NULL ||b.Name !='') && (b.Price__c >0)){
            b.Author__c=authId;
            insert b;
        }
    }
}

I get the following error when I try to enter input -

Error
Hi,
User-added imageI want an action that, when i will click ine of those link then my input box with that name.


im giving my codes..
Component:
<aura:attribute name="String" type="String[]"/>
    
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<lightning:card title="Filtered Values">
<div class="search-field">
<lightning:input aura:id="nameFilter" label="Filter names" onchange="{!c.handleNameFilterChange}" />
</div>
    <!--
<div class="results">
<aura:if isTrue="{!v.contacts.length > 0}">
<p class="has-results">
Showing {!v.contacts.length} contact(s):
</p>
<ol class="slds-list_dotted">
-->
   
    <ol>
        
<aura:iteration items="{!v.String}" var="s">
<li>
<a id="getId" onclick="{!c.handleClick}">
{!s}
</a> 
</li>
       
</aura:iteration>
                                       
    </ol></lightning:card></aura:component>


controller
({
init: function(component, event, helper) {
helper.loadList(component);
},

handleNameFilterChange: function (component, event, helper) {
helper.loadList(component);
},

})

helper
 
({
loadList: function(component) {
var action = component.get("c.allContacts");
var nameFilterString = component.find("nameFilter").get("v.value");
action.setParams({
nameFilterString: nameFilterString
});
action.setCallback(this, function(a) {
component.set("v.String", a.getReturnValue());
});
$A.enqueueAction(action); 
}
})
thanks,
​​​​​​​
HI, 
I am trying to call my method in the anonymous window but it is showing me (Line: 1, Column: 24 Unexpected token '('.) this error. The class is static so it is not necessary to make an object or instance of that class..
AccountContact.onBefore(Account Name='asdf');
This is my code i am inserting an account with the account name
Suppose there is an inputfield/picklist field.........i want to populate an output textbox with the value of input field or value selected in picklist.
how to do this?
as im not a coder, can someone help me writing a test class for this class :
public class NumberTOWordConvertion {

    // Call this method with Number to convert
    public String getNumberTOWordConvertion(Decimal num) {

        Decimal junkVal = num;
        Decimal junkValFiles = junkVal - Math.floor(junkVal);
        junkVal = Math.floor(junkVal);

        String obStr = junkVal.toPlainString();
        String[] numReversed = obStr.split('');
        String[] actnumber = reverse(numReversed);
        String firstHalf = convertInWords(numReversed, actnumber);

        Integer tmp = Math.round(junkValFiles * 100);
        junkValFiles = (Decimal)tmp / 100; System.debug('jj :' + junkValFiles);
        String paisaStr = junkValFiles.toPlainString();
        String secondHalf;
        if (paisaStr == '0') {
            secondHalf = '';
        } else if (paisaStr.length() != 4) {
            paisaStr = paisaStr + '0';
            paisaStr = paisaStr.substring(2);
            String [] numReversedFiles = paisaStr.split('');
            String[] actnumberFiles = reverse(numReversedFiles);
            secondHalf = convertInWords(numReversedFiles, actnumberFiles);
        } else {
            paisaStr = paisaStr.substring(2);
            String [] numReversedFiles = paisaStr.split('');
            String[] actnumberFiles = reverse(numReversedFiles);
            secondHalf = convertInWords(numReversedFiles, actnumberFiles);
        }

        String SumOFHalves = '';

        if (secondHalf.length() > 4) {
            firstHalf = firstHalf.replace('Only', 'JDs And ');
            secondHalf = secondHalf.replace('Only', 'Files Only');
            SumOFHalves = firstHalf + secondHalf;
        } else {
            firstHalf = firstHalf.replace('Only', 'JDs Only');
            SumOFHalves = firstHalf;
        }

        // IF amount has any value
        if (SumOFHalves.length() > 5) {
            return SumOFHalves;
        } else {
            return '';
        }
    }
    // Method reverse the number
    public List<String> reverse(List<String> strToRev) {
        List<String> revList = new List<String>();
        for (Integer i = strToRev.size() - 1; i >= 0; i--) {
            revList.add(strToRev.get(i));
        }
        revList.add('');
        return revList;
    }

    public String convertInWords(String[] numRev, String[] actnum) {
        List<String> iWords = new List<String> {'Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'};
        List<String> ePlace = new List<String> {' Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'};
        List<String> tensPlace = new List<String> {'dummy', ' Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety' };

        Integer iWordsLength = numRev.size();
        String totalWords = '';
        List<String> inWords = new List<String>();
        for (Integer k = 0; k < iWordsLength; k++) {
            inWords.add('');
        }
        String finalWord = '';
        Integer j = 0;

        // Main For loop
        for (Integer i = 0; i < iWordsLength; i++) {

            if (i == 0) {
                if (actnum[i] == '0' || actnum[i + 1] == '1') {
                    inWords[j] = '';
                } else {
                    inWords[j] = iWords[Integer.valueof(actnum[i])];
                }
                inWords[j] = inWords[j] + ' Only';
            } else if (i == 1) {

                if (actnum[i] == '0') {
                    inWords[j] = '';
                } else if (actnum[i] == '1') {
                    inWords[j] = ePlace[Integer.valueof(actnum[i - 1])];
                } else {
                    inWords[j] = tensPlace[Integer.valueof(actnum[i])];
                }
            } else if (i == 2) {
                if (actnum[i] == '0') {
                    inWords[j] = '';
                } else if (actnum[i - 1] != '0' && actnum[i - 2] != '0') {
                    inWords[j] = iWords[Integer.valueof(actnum[i])] + ' Hundred and';
                } else {
                    inWords[j] = iWords[Integer.valueof(actnum[i])] + ' Hundred';
                }
            } else if (i == 3) {
                if (actnum[i] == '0' || actnum[i + 1] == '1') {
                    inWords[j] = '';
                } else {
                    inWords[j] = iWords[Integer.valueof(actnum[i])];
                }
                if (actnum[i + 1] != '0' || Integer.valueof(actnum[i]) > 0) {
                    inWords[j] = inWords[j] + ' Thousand';
                }
            } else if (i == 4) {

                if (actnum[i] == '0') {
                    inWords[j] = '';
                } else if (actnum[i] == '1') {
                    inWords[j] = ePlace[Integer.valueof(actnum[i - 1])];
                } else {
                    inWords[j] = tensPlace[Integer.valueof(actnum[i])];
                }

            } else if (i == 5) {
                if (actnum[i] == '0' || actnum[i + 1] == '1') {
                    inWords[j] = '';
                } else {
                    inWords[j] = iWords[Integer.valueof(actnum[i])];
                }
                if (actnum[i + 1] != '0' || Integer.valueof(actnum[i]) > 0) {
                    inWords[j] = inWords[j] + ' Lakh';
                }
            } else if (i == 6) {

                if (actnum[i] == '0') {
                    inWords[j] = '';
                } else if (actnum[i] == '1') {
                    inWords[j] = ePlace[Integer.valueof(actnum[i - 1])];
                } else {
                    inWords[j] = tensPlace[Integer.valueof(actnum[i])];
                }

            } else if (i == 7) {
                if (actnum[i] == '0' || actnum[i + 1] == '1' ) {
                    inWords[j] = '';
                } else {
                    inWords[j] = iWords[Integer.valueof(actnum[i])];
                }
                inWords[j] = inWords[j] + ' Crore';
            } else if (i == 8) {

                if (actnum[i] == '0') {
                    inWords[j] = '';
                } else if (actnum[i] == '1') {
                    inWords[j] = ePlace[Integer.valueof(actnum[i - 1])];
                } else {
                    inWords[j] = tensPlace[Integer.valueof(actnum[i])];
                }

            }

            j++;
        }
        // End of For loop

        // Reverse the List
        inWords = reverse(inWords);

        for (Integer i = 0; i < inWords.size(); i++) {
            finalWord += inWords[i];
        }

        return finalWord;
    }


}

thnx in advance
Hi. Can you please keep below trigger into helper class.
 
trigger InvoiceSum on Invoice_Items__c (after insert, after delete, after undelete, after update) {
    set<Id> invIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Invoice_Items__c invItem: Trigger.new){
			if(Trigger.isInsert || Trigger.isUndelete || (invItem.Amount__c != Trigger.oldMap.get(invItem.Id).Amount__c || invItem.InvoiceFK__c != Trigger.oldMap.get(invItem.Id).InvoiceFK__c))
				invIdSet.add(invItem.InvoiceFK__c);            
        }
    }    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Invoice_Items__c invItem: Trigger.old){
            if(Trigger.isDelete || (invItem.Amount__c != Trigger.newMap.get(invItem.Id).Amount__c || invItem.InvoiceFK__c != Trigger.newMap.get(invItem.Id).InvoiceFK__c))
				invIdSet.add(invItem.InvoiceFK__c);
        }
    }       
    List<Invoice__c> invList = [select id, Ammount__c, (Select Id, Amount__c from Invoice_Items__r) from Invoice__c Where ID IN: invIdSet];    
    for(Invoice__c inv : invList){
        
        inv.Ammount__c = 0;
        for(Invoice_Items__c invItem : inv.Invoice_Items__r) {
			inv.Ammount__c += invItem.Amount__c;
        }
    }
    update invList;
}

​​​​​​​
public class testclass5 {
 public list<wrapperclass> wrapclass{get;set;}
   public  testclass5(){
    wrapclass = new list<wrapperclass>();
    string  teststring= ' { "sucess":1,"data": [ {"stateName": "Andrapradesh",  "value": "apx" }, { "stateName": "Telangana",  "value":"tsx"}, {"stateName": "Banglore",  "value": "bngx"} , {"stateName": "Maharastra",  "value":"mhx" }  ] } ';

     Map<String, Object> maptest =   (Map<String, Object>) JSON.deserializeUntyped(teststring);
     
     system.debug(maptest); 
     
      Object ob = (Object)maptest.get('data');    
        System.debug(ob);
          
         String srlze  = System.JSON.serialize(ob); 
      system.debug(srlze);
       
   wrapclass  = (list<wrapperclass>)System.JSON.deserialize(srlze,list<wrapperclass>.class);
   system.debug(wrapclass);
  
  }
  
 public string selectedValue{get;set;}
 
   public pageReference testmethod1(){
    
     system.debug('for Datatable functionality:'+ selectedValue);
     return null;
   
   }
 
 public pageReference testmethod2(){
    
     system.debug('for repeat functionality:'+ selectedValue);
     return null;
   
   }
 

   public class wrapperclass{
   
    public string stateName{get;set;}
    
     public string  value{get;set;}
    
   }
   
   
 
}


Visualforce page:
 
<apex:page controller="testclass5">
 
  <apex:form >
    <apex:dataTable value="{!wrapclass}" var="a" cellpadding="6px">
    
    <apex:column > 
         <apex:actionsupport action="{!testmethod1}" event="onclick">
         {!a.stateName}<apex:param name="selectedValue" value="{!a.value}" assignTo="{!selectedValue}">
          </apex:param>
          </apex:actionsupport>
       </apex:column>
     
    </apex:dataTable>
    
    <br/>
    
      <apex:actionsupport action="{!testmethod2}" event="onclick">
    <apex:repeat value="{!wrapclass}" var="a" >
      <li style="padding:5px;"> 
    
         {!a.stateName}<apex:param name="selectedValue" value="{!a.value}" assignTo="{!selectedValue}">
          </apex:param>
          
      </li>
    </apex:repeat>
    
  </apex:actionsupport>
     
  
  
  </apex:form>
  
</apex:page>


after debugging iam getting the selectedvalue,as  null.., can anybody help to solve the issue. thank you... 

I am a beginner in apex. I have written this kind of test, but it makes some mistakes, someone can tell me what is wrong or how to do it better.
I only have 35% coverage
These are my codes.


***** Code Visualforce ****

<apex:page controller="deleteRowsExample" action="{!onloadmethod}"> <!--- action="{!onloadmethod}"--->
<apex:form >
<apex:pageBlock >
    <apex:commandbutton value="Add Contact" action="{!addContact}" immediate="true"/>
    <apex:commandButton value="Save Changes" action="{!saveChanges}"/>
  <!-- Display some account information -->  
  <apex:pageBlockSection columns="1">
      <apex:outputField value="{!accountRec.Name}"/>
      <apex:outputField value="{!accountRec.OwnerId}"/>
  </apex:pageBlockSection>
  
  <!-- Display the related contacts for the Account -->
  <apex:pageblocktable value="{!Contacts}" var="con"> <apex:variable value="{!0}" var="cnt"/>
      <apex:column headervalue="Action">
          <apex:commandlink value="Remove" action="{!removeContact}" immediate="true">
              <!-- Pass the row number to the controller so that we know which row to remove -->
              <apex:param name="index" value="{!cnt}"/>
          </apex:commandlink> 
          <apex:variable var="cnt" value="{!cnt+1}"/>              
      </apex:column>  
      <apex:column headerValue="first Name">
          <apex:inputfield value="{!con.FirstName}"/>
      </apex:column>    
      <apex:column headerValue="Last Name">
          <apex:inputfield value="{!con.LastName}"/>
      </apex:column>     
  </apex:pageblocktable>
  
</apex:pageBlock>  
</apex:form>    
</apex:page>
 

*****controller******
 

public class deleteRowsExample {

public List<Contact> allContactList = new List<Contact>();
public List<Contact> deleteContactList = new List<Contact>();
    
public Account accountRec {get;set;}

//Called when the page loads initially from the "action" method on the apex:page. Populates the Account record and the releated contact list
public void onloadmethod(){

     String aid = System.currentPageReference().getParameters().get('id');
     accountRec = [Select Id,OwnerId,Name,Type,Phone,Website from Account where Id=:aid]; 
     allContactList = [Select Id,FirstName,LastName from Contact where AccountId=:accountRec.Id];
}
//Send the list of contacts to the visualforce page
public List<Contact> getContacts(){
    return allContactList;
}

//Add a temporary contact to the table. Not saved to the database
public void addContact(){
    Contact c = new Contact();
    allContactList.add(c);
}

//Remove a contact from the table.
public void removeContact(){
    Integer indexVal = Integer.valueof(system.currentpagereference().getparameters().get('index'));
    //If the contact is an existing contact then add it to the list to delete from the database
    if(allContactList[indexVal - 1].Id != null)
        deleteContactList.add(allContactList[indexVal - 1]);
    //Remove the contact from the table    
    allContactList.remove(indexVal - 1);            
}    
public void saveChanges(){
    for(Integer i=0; i<allContactList.size(); i++) {
			upsert allContactList; //insert allContactList;
		} 

    //delete the contacts that were removed
    if(deleteContactList.size() > 0){
        delete deleteContactList;
    }
}    
    
}
 

*****Test Class*****
 

@isTest
private class testdeleteRowsExample_Test {
  @isTest static void agregacuentas(){
   Test.startTest();   
 Account acc = new Account();
        acc.Name = 'TestCuenta';
        insert(acc);   
           
        Contact con = new Contact();
        con.AccountId = acc.Id;
        con.FirstName = 'Pedro';
        con.LastName = 'Lopez';
        con.MailingPostalCode = '45546';
        insert (con);
        
        Contact con2 = new Contact();
        con2.AccountId = acc.Id;
        con2.FirstName = 'Rosa';
        con2.LastName = 'Croy';
        con.MailingPostalCode = '66546';
        insert (con2); 
 
deleteRowsExample Rows = new deleteRowsExample();
            Rows.addContact();
            Rows.onloadmethod(); 
            Rows.getContacts();
            Rows.saveChanges();
            Rows.removeContact();
Test.stopTest();
    }
}
Hi All,
I am getting following error in javascript. Please help me with this error.
 
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}   
 
var newRecords = [];   
 
var coapp = new sforce.SObject("Lead");  
coapp.id ="{!Lead.Id}"; 
coapp.Name="{!Lead.Name}" 
coapp.Rating="Hot";             
 
newRecords.push(coapp); 
result = sforce.connection.update(newRecords); 
window.location.reload();

Error: The Name field is required.

Thanks in Advance
I am new to LWC and cant seem to figure out how to open the source code for LWC. Aura can be opened in the dev console but from what i understand this is not possible with LWC.

Is it possible to open a LWC source code from within the org? I have a LWC that was developed by someone else that needs editing. How can I access the source code?
I have one external Id auto number field in opportunity object.
I am able to perform a global search in a sandbox on this field but the global search functionality is not working in production for this field only.
And I have system administer rights.
where salesforce store lightning web components. like we have apexclass object for all sobject and auradefinationbundle for aura components.
Hi,

As I am creating two maps now  I want to create the third map in which i have to put the values from 1st and 2nd Map.

Thanks
Hello, Can someone tell me what I'm missing in the validation rule: 
AND(
ISPICKVAL( Status, 'Working - Contacted'),
ISPICKVAL( Rating, 'Hot')
)
I'm trying to not let users select save if the Status of Working - Contacted is selected and the picklist Rating field is not selected as Hot and try to save the record, the system should prompt them they will not be able to save this record. 

The other values in the picklist are: none, Cold, Warm. 

If the field is left blank, the user is still able to bypass but I'm trying to prevent that.

Thanks!
 
  • December 16, 2019
  • Like
  • 0
Hey guys,

I have object A.

I have let's say a PDF or a Word file I want to attach automatically. to each record of object A upon creation.

I don't see how process builder could do this, so is there a way to do this? Maybe in apex? Thanks
Requirement: 
Three cities 
First Click on the lightning card
First city should display and continue to display
Second click on the lightning card
Second city should display and continue to display
Third click on the lightning card
Third city should display and continue to display

Ex : Upon first click, Tirupati should display 
Upon second click, Nellore should display
Upon third click, Kanchipuram should display
and finally all three city values shoudl continue to display like that 

I could come up with the below code but it is static. I am new to LWC, please help. Thank you.

JS : 
import { LightningElement,track } from 'lwc';
export default class ConditionalRenderingExample extends LightningElement {
 
 
  city;
  
  @track cityList =  ['Tirupati', 'Nellore', 'Kanchipuram'];
  
  showCityHandler(event){ 
  
   this.city = target.event.value;
   
    }   
  
}

HTML : 
<template>
       <lightning-card onclick={showCityHandler}>
         <template for:each={cityList} for:item="city">
               <p key={city}>{city}</p>
         </template>
       </lightning-card>
</template>
<td>

<select  data-style="" class="selectpicker form-control" name="multipleSelected" id="multipleSelected" multiple="multiple">
                                                                                        
                          <apex:repeat value="{!MedicalAllergies}" var="itm">                                                   
                                 <option  value="{!itm.label}">{!itm.label} </option>
                           </apex:repeat>
  </select>   

 </td>

 
  • December 13, 2019
  • Like
  • 0
I am completely new to Apex and coding.I have a requirement where I need to create Opportunities for Contact objects when a Picklist field on contact object gets updated.
Which means when the picklist filed is having any of the following values then an opportunity should get created for that contact automatically...
My picklist field values are: Service every year, Service every 6 months, Phone call and Send mail.
Now I need some help in writing the batch apex class and test class for this requirement. Any help is much appreciated.
Thanks in advance.
public class test5 {

  public list<string> lststatename{get;set;}
  public list<string> lstrating{get;set;}
  
  public list<string> lstactive{get;set;}
  public map<string, string> statemap{get;set;}

public map<string, string> activestatusmap{get;set;}

 public set<string> mapkey{get;set;}
 
    public list<string> mapvalue{get;set;}
 public test5(){
 
 
    string  jsonexample1 =  ' { "overalldata": [ {"stateName": "Andrapradesh",  "rating": "5.0" , "active": "yes" }, { "stateName": "Telangana",  "rating": "4.0" ,"active": "no" }, {"stateName": "Banglore",  "rating": "5.0" ,"active": "no"} , {"stateName": "Maharastra",  "rating": "4.5" ,"active": "no" }  ] } ';

   
     map<string,object>  metadatamap= (map<string,object>)json.deserializeuntyped(jsonexample1); 
     
      list<object>  values1= (list<object>)metadatamap.get('overalldata');
        
        
         lststatename= new list<string>();
         lstrating= new list<string>();
         statemap= new map<String, string>();
         
          for(object parsed : values1){
          map<string,object>  values = (map<string,object>)parsed;
          string statename = string.valueof(values.get('stateName'));
          
          string rating= string.valueof(values.get('rating'));
          
          lststatename.add(statename);
             
          lstrating.add(rating);
             
             statemap.put(statename,rating);
             
             }
            
 }
}
Visual force page:
 
<apex:page controller="test5" >

 <apex:form >
   <apex:repeat value="{!statemap}" var="a">
    <apex:selectList >   
               <apex:selectOptions value="{!a}">{!a}</apex:selectOptions>
         </apex:selectList>
   
   </apex:repeat>
            
                                          
      
 
 </apex:form>
 
</apex:page>

Hi..! can any body bind data to the selectlist with statename as itemlabel and rating  as the itemvalue in visualforce page
.. Thank you..!
public class jsontest {

  public  loandetails loandetails{get;set;}
  
 public jsontest (){

 string teststring ='{"status":1,"data":[{"$id":"1","type":"A","InterestAmount":"2.90","TotalAmount":"198000.00","year":2018,"Name":"Axis BANK"},{"$id":"2","type":"B","InterestAmount":"3.90","TotalAmount":"158000.00","year":2019,"Name":"ICICI BANK"},{"$id":"3","type":"A","InterestAmount":"2.90","TotalAmount":"258000.00","year":2018,"Name":"HDFC BANK"}]}';
 
           Map<String, Object> mapobj= (Map<String, Object>)JSON.deserializeUntyped(teststring);
           system.debug('the Mapped and deserialized values are:'+ mapobj);
           
            list<Object> objj = (list<Object>)mapobj.get('data');
            system.debug('the data value is :::'+objj);
           
            string SerilizeEmpdata = system.json.serialize(objj);
           system.debug('After Serilization:::'+ SerilizeEmpdata);
           
            loandetails =(loandetails)system.json.deserialize(SerilizeEmpdata,loandetails.class);
             system.debug(loandetails);
             system.debug('binded to loan information is:::'+loandetails.name);     
 
 }
 
  //wrapperclass
 
  public class loandetails{
  
    public string type{get;set;}
    public string InterestAmount{get;set;}
    public string TotalAmount{get;set;}
    public integer year{get;set;}
    public string name{get;set;}
  } 
}

Getting an error: 
System.JSONException: Malformed JSON: Expected '{' at the beginning of object
Hello, 

I try to create test class for convert lead class, but i have an error that is . "System.DmlException: ConvertLead failed. First exception on row 0; first error: INVALID_STATUS, invalid convertedStatus: Creation account PA: [Status]".
Can you help me please ?

Class:
Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Lead> LeadtoConvert)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel, ApiName FROM LeadStatus WHERE IsConverted=true AND ApiName='Creation account PA'];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        
        for(Lead currentlead: LeadtoConvert){
            	system.debug(currentlead.id);
            	system.debug(currentlead.status);
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.id);
                Leadconvert.setConvertedStatus(CLeadStatus.ApiName);
                Leadconvert.setDoNotCreateOpportunity(TRUE);
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

Test class:
@isTest(seealldata = true)
public class TestAutoConvertLeads{
    public static testMethod void convertLead(){
        test.startTest();
        Lead leadtoConvert = new Lead();
        leadtoConvert.FirstName='Trigger1';
        leadtoConvert.LastName='Test1';
        leadtoConvert.Company='Trigger Test1';
        leadtoConvert.Exists_In_PartsAdvisor__c=true;
        insert leadtoConvert;
        List<Lead> listToConvert = new List<Lead>();
        listToConvert.add(leadToConvert);
       
        AutoConvertLeads.LeadAssign(listToConvert);
        
        test.stopTest();   
        
    } 
}

Thanks​​​​​​​
Hello All,

I have a input form for a custom object Employee with three fields name, designation, phone .
on click of save button only name is getting saved, rest phone and designation fields are empty. 
Here is my code-

HTMl
<template>
    <lightning-card title= "Insert Employee Data" icon-name="standard:account">
        <div class="slds-p-around_x-small">
            <lightning-input label="Employee Name" value={rec.Name} onchange={handleNameChange}></lightning-input>
            <lightning-input label="Designation" value={rec.Designation__c} onchange={handleDesChange}></lightning-input>
            <lightning-input label="Phone" value={rec.Primary_Phone__c} onchange={handlePhnChange}></lightning-input><br/>
            <lightning-button label="Save" onclick={handleClick}></lightning-button>
   
        </div>
    </lightning-card>
</template>

JS
import { LightningElement, track } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Employee__c.Name';
import DESIGNATION_FIELD from '@salesforce/schema/Employee__c.Designation__c';
import PHONE_FIELD from '@salesforce/schema/Employee__c.Primary_Phone__c';
import createEmployee from '@salesforce/apex/createEmployee.createEmployee';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class InputFormForCustomObject extends LightningElement {

    @track name = NAME_FIELD;
    @track designation = DESIGNATION_FIELD;
    @track phone = PHONE_FIELD;
    rec = {
        Name : this.name,
        Designation : this.Designation__c,
        Phone : this.Primary_Phone__c
    }

    handleNameChange(event) {
        this.rec.Name = event.target.value;
        console.log("name1", this.rec.Name);
    }
    
    handleDesChange(event) {
        this.rec.Designation = event.target.value;
        console.log("Designation", this.rec.Designation);
    }
    
    handlePhnChange(event) {
        this.rec.Phone = event.target.value;
        console.log("Phone", this.rec.Phone);
    }

    handleClick() {
        createEmployee({ hs : this.rec })
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.rec.Name = '';
                    this.rec.Designation = '';
                    this.rec.Phone = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Employee created',
                            variant: 'success',
                        }),
                    );
                }
                
                console.log(JSON.stringify(result));
                console.log("result", this.message);
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                console.log("error", JSON.stringify(this.error));
            });
    }
}

Meta Xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
   <apiVersion>45.0</apiVersion>
   <isExposed>true</isExposed>
   <targets>
       <target>lightning__AppPage</target>
       <target>lightning__RecordPage</target>
       <target>lightning__HomePage</target>
   </targets>
</LightningComponentBundle>

Apex
public with sharing class createEmployee {
     @AuraEnabled
    public static Employee__c createEmployee(Employee__c hs) {
        
        insert hs;
        return hs;
    }
}

​​​​​​​​​​​​​​
How can we pass multiple parameters from Component to Apex class .For ex I have a custom object ObjectA__c , the component  takes input from user and then I need to process these values in apex class and save to db . There are more than 10 fields which needs which needs to be set in apex. I cant pass these fields as parameters . I am not sure about wrapper class. Please let me know what is the best way to do it .
 
I have 3 fields in design attributes for LWC. These fields are objName, field1 and field2. I'm  passing these fields to the apex method using @wire on a function and with $ on the parametes. When these fields have value, the method returns correct result set. However if any of the parameter is empty, the component is unable to invoke the apex. Is there any way to validate the input parameters before being passed to the Apex method.

pseudo code as below

 @api strObject;
 @api fieldColumn1;
 @api fieldColumn2;

 @wire(retriveRecords, { strObject: '$strObject',fieldColumn1: '$fieldColumn1', fieldColumn2: '$fieldColumn2'})
    contacts(result) {
        if (result.data) {
            this.data = result.data;
            this.error = undefined;
        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }
My Vf Page is 
<apex:page standardController="Class__c" extensions="ManageClassController" >
    <apex:pageBlock > 
        <apex:pageBlockSection >
            <apex:form >
                <apex:pageBlockTable value="{!classList}" var="c" >
                    <apex:column headerValue="class name">
                        <apex:outputText value="{!c.name}"></apex:outputText>
                    </apex:column>
                    <apex:column headerValue="Edit" >
                        <apex:commandLink value="Edit" action="{!editDetails}">
                            <apex:param assignTo="{!classId}" value="{!c.id}" />
                        </apex:commandLink>
                    </apex:column>    
                    <apex:column headerValue="Delete">
                        <apex:commandLink value="Delete">
                            <apex:param assignTo="{!classId}" value="{!c.id}" />
                        </apex:commandLink>
                    </apex:column>   
                </apex:pageBlockTable>
            </apex:form>
        </apex:pageBlockSection>
        <apex:pageBlockSection >
            
            <apex:form rendered="{!flag}">
                <apex:inputField value="{!dummyClass.name}"/>
                <apex:inputField value="{!dummyClass.Fee__c}"/>
                <apex:inputField value="{!dummyClass.Detailed_Description__c}"/>
                <apex:inputField value="{!dummyClass.Max_Size__c}"/>
                <apex:inputField value="{!dummyClass.My_Count__c}"/>
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandLink value=""/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:form>
            
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

My Controller is 
public class ManageClassController {
    public List<Class__c> classList{get;set;}
    public String classId{get;set;}
    public class__c dummyClass{get;set;}
    public boolean flag {get;set;}
    private ApexPages.StandardController controller {get; set;}
    public ManageClassController(ApexPages.StandardController stdController){
        this.controller = stdController;
        this.classList = new List<Class__c>([SELECT id , name from class__c]);
        this.flag=false;
        this.classId = null;
    }
    public void editDetails(){
        System.debug('I came here');
        System.debug('classId = ' + this.classID);
        if(this.classId != null){
            this.dummyClass = [SELECT id , name , fee__c , detailed_description__c , max_size__c , my_count__c FROM class__c where id = :classId];
            this.classId = null;
            this.flag = true;
        }
    }
}

My vf page is running as 
User-added imageand as soon as i press edit link value must get populate in controller but is not going
Debug only logs -
User-added imageThanks in advance
When I am trying to iterate through list in aura:iteration is is not showing values as expected . But if I print list on UI I am able to see list of values.Only iteration not working.
User-added imageIf I write like this the below screen coming:
User-added imageRed color values coming on iteration.Blue color are printing list.
==> But If I modify code like below nothing printing inside iteration:
User-added imageOutput screen like below:
Only list printing no values in Iteration:
User-added image
how to use best pratice for test classes for below code
 
@isTest
Private class TestProductSearchpopupController {
    @isTest
    static void testMethod1() 
    {   
        Account acc = new Account (name='Pencil');
        insert acc;
        Opportunity opp= new Opportunity ();
        opp.name= 'Testopp1';
        Opp.Accountid= acc.id;
        opp.CloseDate= date.today();
        opp.StageName= 'Qualification';
        insert opp;
        
        List <Quotes__c> lstquote = new List<Quotes__c>();
        
        Quotes__c testque = new Quotes__c();
        testque.Name = 'Test PriceBookEntry';
        testque.OpportunityId__c = opp.id;
        testque.AccountId__c = acc.id;
        lstquote.add(testque);
        
        List <Product2__c> lstproduct = new List<Product2__c>();
        Product2__c testProduct = new Product2__c();
        testProduct.Name='Test product';
        lstproduct.add(testProduct);
        
        List <PricebookEntry__c> lstpbe = new List<PricebookEntry__c>();
        
        PricebookEntry__c testpbe = new PricebookEntry__c();
        testpbe.Name='Test PriceBookEntry';
        lstpbe.add(testpbe);
        
        List <QuoteLineitem__c> lstqli = new List<QuoteLineitem__c>();
        QuoteLineitem__c testqli = new QuoteLineitem__c();
        testqli.QuotesId__c = testque.id;
        
        lstqli.add(testqli);
      

        Test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController(lstquote[0]);
        ProductSearchPopupController psp = new ProductSearchPopupController(sc);
        psp.ProceedWithSelectedToNextPage();
        psp.processSelected();
        psp.runQuery();
        psp.saveproduct();
        Test.stopTest();
    }  
}

my class
 
public class ProductSearchPopupController {
   
    public String query {get; set;}
    public List<PricebookEntry__c> products {get; set;}
    public List<wrapProduct> wrapProductList {get; set;}
    public List<PricebookEntry__c> selectedProduct{get;set;}
    public List<QuoteLineitem__c> quoteLineList{get;set;}
    public List<wrapProduct> selectedWrapperList{get;set;}
    public Boolean normalList{get;set;}
    public Boolean selectedList{get;set;}
    public Boolean block{get;set;}
    public Boolean block1{get;set;}
    public Boolean block2{get;set;}
    public String SalesPrice {get; set;}
    public integer Discount {get; set;}
    public String Quantity {get; set;}
    public String ServiceDate {get; set;}
    Id recordId;
    
    public ProductSearchPopupController(ApexPages.StandardController controller){
        recordId = controller.getId();
        system.debug('recordId '+recordId);
        wrapProductList = new List<wrapProduct>();
        selectedWrapperList = new List<wrapProduct>();
        normalList = true;
        selectedList = false;
        block = true;
        block1 = false;
        block2 = false;
    }
    
    public PageReference runQuery(){
        if(query == null || query == ''){
            system.debug('query '+query);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info,'Please enter Product to search for'));
            
            return null;
        }
        system.debug('query '+query);
        List<List<PricebookEntry__c>> searchResults=[FIND :query IN ALL FIELDS RETURNING PricebookEntry__c (id, Name, ProductCode__c, Product2Id__r.Product_Description__c,UnitPrice__c, UseStandardPrice__c)];
        if(searchResults[0]!=null){
            for(PricebookEntry__c a: searchResults[0]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapProductList.add(new wrapProduct(a));
                block = true;
                block1 = true;
                block2 = false;
            }
        }
        return null;
    }
    public PageReference ProceedWithSelectedToNextPage(){
        selectedWrapperList = new List<wrapProduct>();
        normalList = false;
        selectedList = true;
        for(wrapProduct selectedWrapObj: wrapProductList){
            system.debug('selectedWrapObj.selected  ---------'+selectedWrapObj.selected);
            if(selectedWrapObj.selected == true)
                selectedWrapperList.add(selectedWrapObj);
        }
        system.debug('selectedWrapperList size ---------'+selectedWrapperList.size());
        PageReference pageRef = new PageReference('/apex/AccountOpportunityTwoPage');
        pageRef.setRedirect(false);
        return pageRef;
    }
    public void processSelected() {
        selectedProduct = new List<PricebookEntry__c>();
        for(wrapProduct wrapProductObj : wrapProductList) {
            if(wrapProductObj.selected == true) {
                selectedProduct.add(wrapProductObj.acc);
                block = false;
                block1 = false;
                block2 = true;
                
            }
        }
    }
    
    public class wrapProduct{
        public PricebookEntry__c acc {get;set;}
        public Boolean selected {get;set;}
        public wrapProduct(PricebookEntry__c p) {
            this.acc = p;
            this.selected = false;
        }
        
    }
    
    public pagereference saveproduct(){ 
        List<QuoteLineitem__c> quoteLineList = new  List<QuoteLineitem__c>();
        if(!selectedProduct.isEmpty()){
            for(PricebookEntry__c sp:selectedProduct){
                system.debug('sp '+sp);
                QuoteLineitem__c qli = new QuoteLineitem__c();
                qli.QuotesId__c = recordId;
                qli.ListPrice__c = sp.UnitPrice__c;
                qli.UnitPrice__c = sp.UnitPrice__c;
                qli.Product2Id__c = sp.Product2Id__c;    
                if(Discount!=0 || Discount!=null){
                    qli.Discount__c = Discount;
                }
                quoteLineList.add(qli);
            }

            if(quoteLineList.size()>0){
                insert quoteLineList;
                PageReference pageRef = new PageReference('https://proseraa.lightning.force.com/lightning/r/Quotes__c/'+recordId+'/view');
                pageRef.setRedirect(true);
                return pageRef;
            }
        }
        return null;
    }
   
}

​​​​​​​
I am assuming that what I trying to do is pretty basic, I am just fairly new to visual force

I would like an alert to show if a certain condition is met. In this alert I would like to have input fields that can be saved to the record. 

I created this visual force page, but it is not an alert. 
How can I make it into an alert?

<apex:page standardController="Comment__c" rendered="{!if(Comment__c.Care_Management_Related2__c==true,true,false)}">
<apex:form >
        <apex:pageBlock title="Enter Care Management Call Details">
            <apex:pageBlockSection title="Next Suggested Call" columns="1">
                <apex:inputField value="{!Comment__c.Next_Suggested_Call_Date__c}"
                label="next suggested call date"/>
                <apex:inputText value="{!Comment__c.Next_Suggested_Call_Description__c}"
                    label="Next Suggested Call Description"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi i'm lost in a test for a send email, i need to test if the email as sent, how i do that?

Thanks for your attention

Batch Class:
global class EmailCaringSenior implements Schedulable, Database.Batchable<sObject> {
    
    Account estipulante;
    
	global Database.QueryLocator start(Database.BatchableContext BC) {
        try{
        	estipulante = [SELECT Id FROM Account WHERE RecordTypeId IN (SELECT Id FROM RecordType WHERE Name = 'Estipulante' AND SObjectType = 'Account') AND Name = 'Caring Senior'];
        } catch(Exception e) {
             System.debug('The following exception has occurred: ' + e.getMessage());
        }
        return Database.getQueryLocator([SELECT Name, CPF__pc FROM Account WHERE Estipulante__c = :estipulante.Id AND CreatedDate = TODAY]);
	}
    
   	global void execute(Database.BatchableContext BC, List<sObject> scope) {
		List<Account> accounts = (List<Account>) scope;
        String listaPaciente = '';
        Integer contagem = 0;
		for(Account paciente : accounts){
			contagem++;
            listaPaciente +=  contagem + '. ' + paciente.Name + ' (CPF: ' + paciente.CPF__pc + ') <br>';
		}
        
		String dataOntem = DateTime.now().addDays(-1).format('dd-MM-yyyy');
        
		Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.toAddresses = new String[] { 'gabrielmocelin@unochapeco.edu.br' };
        message.subject = 'Ace - Novos Pacientes (' + dataOntem +  ')';
        message.setHtmlBody('Olá Gestor, <br> Abaixo uma lista de pacientes carregados no Health Cloud ontem (' + dataOntem + '): <br><br> ' + listaPaciente);
        for(OrgWideEmailAddress owa : [SELECT Id, Address, DisplayName FROM OrgWideEmailAddress]) 
        {
           if(owa.DisplayName.contains('Caring Senior'))
           { 
            message.setOrgWideEmailAddressId(owa.Id); 
           } 
        }
        Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
        Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        
        if (results[0].success) 
        {
            System.debug('The email was sent successfully.');
        } else 
        {
            System.debug('The email failed to send: ' + results[0].errors[0].message);
        }
    }

	global void execute(SchedulableContext sc) {
		EmailCaringSenior b = new EmailCaringSenior();
		Database.executebatch(b);
	}
	
	global void finish(Database.BatchableContext BC) {
		
	}
}
Test Class:
@isTest
public class Test_EmailCaringSenior {
    
    static testMethod void testInsertDetecta()
    {   
        Integer contasAntes = [SELECT COUNT() FROM Account];
        System.assertEquals(contasAntes, 0);
        
        RecordType estipulanteRecordType = [SELECT Id FROM RecordType WHERE Name = 'Estipulante' AND SObjectType = 'Account'];
        Account estipulante = new Account();
        estipulante.RecordTypeId = estipulanteRecordType.Id;             
        estipulante.Name = 'Caring Senior';
        insert estipulante;
        
        Datetime dataAnteOntem = Datetime.now().addDays(-2);
        Test.setCreatedDate(estipulante.Id, dataAnteOntem);
 
        RecordType personAccountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Paciente' AND SObjectType = 'Account'];
        Account paciente = new Account();
        paciente.RecordType = personAccountRecordType;             
        paciente.FirstName = 'Teste';
        paciente.LastName = 'Sobrenome';
        paciente.CPF__pc = '133.173.513-06';
        paciente.Estipulante__c = estipulante.id;
        insert paciente;
        
        Datetime dataOntem = Datetime.now().addDays(-1);
        Test.setCreatedDate(paciente.Id, dataOntem);

        Test.startTest();
			Account myAccount = [SELECT Id, Name, CreatedDate FROM Account WHERE Name ='Teste Sobrenome' LIMIT 1];
        	System.assertEquals(myAccount.CreatedDate, dataOntem);	
      		
           	Account estipulanteTest = [SELECT Id, CreatedDate FROM Account WHERE Name = 'Caring Senior' AND RecordTypeId = :estipulanteRecordType.Id];
			System.assertEquals(estipulanteTest.Id, estipulante.id);
        	System.assertEquals(estipulanteTest.CreatedDate, dataAnteOntem);
        
            EmailCaringSenior b = new EmailCaringSenior();
			Database.executebatch(b);
        
        Test.stopTest();
    }
}

 
I need help in writing a trigger, I have two objects

1) Opportunity
2) Opportunity_ Program__c

both are having lookup relationship, Opportunity is Parent and Opportunity Program is child.

Opportunity program has Status field.

I need to write a trigger on Opportunity Program object, for a given Opportunity if any of the child records contains status as "MATR" then Opportunity.StageName = 'Closed Won', if any of the child record for a given opportunity does not contain "MATR" then Opportunity.StageName = 'Closed Lost'

Can anyone helps me out in this issue please.
I am new to LWC and cant seem to figure out how to open the source code for LWC. Aura can be opened in the dev console but from what i understand this is not possible with LWC.

Is it possible to open a LWC source code from within the org? I have a LWC that was developed by someone else that needs editing. How can I access the source code?