• suji srinivasan
  • NEWBIE
  • 215 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 38
    Questions
  • 44
    Replies
I have two profiles,in profile 1 user should have read access to account and opportunity , only owner should  edit the record they own.

In profile 2 account and opportunity should be private.how to achiev this?

Thanks in advance
All users have create,read,edit,delete access. I need to modify it by providing  read access alone  to all users. Only record owner should have edit access.How to achieve it?

Thanks in advance
i tried in process builder and flows but its not updating instantly lead status field .
condition used:
Emailbouncedreason isnull =false
Leadstatus=disqualified
when i edit the record that time only it updating lead status.
class:
public class EmailToHR {         
    //@InvocableMethod
    public static list<Candiate__c> Candidates(){
        list<Candiate__c> CanList = new list<Candiate__c>();
        list<String> IntStatus = new string[] {'L1 Selected','Selected'};
            list<Candiate__c> SelectedCandidates =  [Select First_name__c, Interview_Status__c 
                                                     FROM Candiate__c
                                                     WHERE Interview_Status__c IN :IntStatus ];  
        for(Candiate__c can : SelectedCandidates){
            CanList.add(can);
        }
        return CanList;
    }  
    @InvocableMethod
    Public static void HREmail(){
        //list<IndividualEmail__c> em = IndividualEmail__c.getall().values();
        EmailTemplate tempId = [Select id, name, body,HTMLvalue From EmailTemplate Where name='EmailtoHR'];
        String emailBody = tempId.HTMLValue;
        integer NoCandidates = Candidates().size();
        emailbody = emailbody.replace('Selected_Candidates', string.valueof(NoCandidates));
        IndividualEmail__c InEmail = IndividualEmail__c.getInstance('VenolinTalent Acquisition Group');
        
        //IndividualEmail__c InEmail = IndividualEmail__c.getvalues('VenolinTalent Acquisition Group');
        system.debug(InEmail);
        string hrEmail = string.valueOf(InEmail.Email__c);
        //string hrEmail = InEmail.Email__c;
        if (hrEmail != Null){
            String[] toAddresses = new String[] {hrEmail,'hr@venolin.com'};
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTemplateID(tempId.id);
            mail.setToAddresses(toAddresses);
            mail.setSubject('selected candidates');
            mail.setPlainTextBody(NoCandidates + 'Candidates are selected');
            mail.setHtmlBody(emailbody);
            messaging.sendEmail(new Messaging.SingleEmailMessage [] {mail});           
        }
    }
}

testclass:
@isTest
public class TestEmailToHR {
    @isTest public static void testMail (){
         IndividualEmail__c cust = new IndividualEmail__c();
         cust.Email__c = 'sacgaze@gmail.com';
         cust.Name = 'VenolinTalent Acquisition Group';
         insert cust;
        Position__c pos2 = new Position__c();
            pos2.TechnicalSkils__c = 'Salesforce';
            pos2.YearsOfExperience__c = '1 Year';
            pos2.NumberOfPositions__c = 2;
            pos2.SkillSet__c = 'Sales Cloud';
            pos2.SubSetOfSkills__c = 'Admin';
            pos2.Role__c = 'Developer';
            //pos1.RelatedCandidate__c = canp.id;
            insert pos2;
       list<Candiate__c> Candidates = new list<Candiate__c>();
        for (integer i=0; i<5; i++){
            Candidates.add(new Candiate__c(First_Name__c = 'Nikhil',
                                           Last_Name__c = 'Rao',
                                           Mobile_No__c = '98773339402',
                                           Current_Employer__c = 'TCS',
                                           Current_Employment__c = 'permanent',
                                           CTC__c = 30000,    
                                           Position_Object__c = pos2.id,
                                           Status__c = 'Scheduled',
                                           Email_ID__c = 'test@gmail.com',
                                           Ready_for_Contract__c = 'Yes',
                                           Communication__c = '8',
                                           Hands_on_JD__c = '7',
                                           Knowledge__c     = '7',
                                           Expected_CTC__c = 40000,
                                           Interview_Status__c = 'L1 Selected'));
        }
        insert Candidates;
    }
    @isTest 
    static void testEmail(){
        Test.startTest();
        IndividualEmail__c cust = new IndividualEmail__c();
         cust.Email__c = 'sacgaze@gmail.com';
         cust.Name = 'VenolinTalent Acquisition Group';
         insert cust;
        EmailToHR.HREmail();
        Test.stopTest();
    }
}

thanks in advance
I included process builder .but when i try to deploy its email templates are not included . how to include email templates in unmanaged package.

Thanks in advance.
I queried Tasks
SELECT accountid FROM Task WHERE What.Type = 'Account 'AND CreatedDate = LAST_N_MONTHS:24
I queried Account and Opportunity
SELECT Id, Name FROM account WHERE Rating = 'Prospect 'AND Id NOT IN (SELECT accountid FROM Opportunity WHERE CreatedDate = LAST_N_MONTHS:24) 
how to connect this withmy Account and opportunity.

Thanksin Advance
I got error  like First error: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, ID is invalid or you do not have access to the record.: [toAddresses, rid.Owner.Email]

public class AccountRatingBatchClass implements  Database.Batchable<sObject> {
    public List<Account> start(Database.BatchableContext bc){
        Integer year = Date.today().year() - 1;
        
       List<Account> aq = [SELECT Id,Rating,CreatedDate FROM Account 
                        WHERE CALENDAR_YEAR(CreatedDate) =:year AND CreatedDate < LAST_N_DAYS:365 AND Rating = 'Client' AND OpportunityCount__c=0];
        return aq;
    }
    public void execute(Database.BatchableContext bc,List<Account> accList){
        for(Account acc : accList){
            acc.Rating='Prospect';
        }
        
        
        List<Messaging.SingleEmailMessage> atm = new List<Messaging.SingleEmailMessage>();  
            EmailTemplate et=[Select id from EmailTemplate where Name='AccountProspectGetOpp'];
                for(Account al : accList){
        
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();       
                        List<AccountTeamMember> recips = new List<AccountTeamMember>(
                                [SELECT UserId,User.isActive,User.Email FROM AccountTeamMember 
                                    WHERE AccountId =: al.Id AND User.isActive=true]);
            
            for(AccountTeamMember rid : recips){
                mail.settoAddresses(new string[]{'rid.Owner.Email'});
                mail.setTargetObjectId(rid.UserId);
                mail.setSenderDisplayName('Salesforce System');
                mail.setUseSignature(false);
                mail.setBccSender(false);
                mail.setSaveAsActivity(false);
                mail.setTemplateId(et.Id);
            }
                
        atm.add(mail);
    } 
        for(Account acl : accList){
        
                    Messaging.SingleEmailMessage mails = new Messaging.SingleEmailMessage();       
                        List<Account> recip = new List<Account>(
                                [SELECT ownerId,owner.Email FROM Account WHERE Id =: acl.Id]);
            
            for(Account rrid : recip){
                mails.settoAddresses(new string[]{'rid.Owner.Email'});
                mails.setTargetObjectId(rrid.ownerid);
                mails.setSenderDisplayName('Salesforce System');
                mails.setUseSignature(false);
                mails.setBccSender(false);
                mails.setSaveAsActivity(false);
                mails.setTemplateId(et.Id);
            }
                
        atm.add(mails);
            
    } 
     update accList;  
        System.debug(accList);
    Messaging.sendEmail(atm);
    }
public void finish(Database.BatchableContext bc){
     
}
}

thanks in advance
I couldnt see debug statements aswell. its not showing error got 100% coverage. when i use database.execute batch totalbatch processed it shows 1 and zero failures. only after schedule it shows  total batch zero in apex jobs.can anyone guide me to resolve this issue?

global class UpdateAccountRating implements Database.Batchable<sObject> {
   
 global  Database.QueryLocator start(Database.BatchableContext bc) {
     set<string> strlist = new set<string>{'workInprogress','Delivered','ClosedWon'};
      string query='select id, stageName,AccountId, Account.Rating from opportunity where stageName IN :strlist AND AccountId !=Null';
     system.debug('query=='+query);
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<opportunity> Scope){
      
        for(opportunity o :Scope){
            o.Account.Rating='client';  
          system.debug('Rating'+o.Account.Rating);
           
        }
         update Scope;}
         global void finish(Database.BatchableContext bc){
       
        AsyncApexJob job = [SELECT Id, Status,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];  
    }   
     } 

testclass
@isTest
public class UpdateAccountRatingTest {
    @isTest
    public static void unit_test(){
      
        Account acc =new Account();
        acc.Name = 'test';
        acc.Rating='prospect';
        insert acc;
        
        
        Opportunity opp = new opportunity();
        opp.Name = 'test opp';
        opp.Accountid = acc.Id;
        opp.stageName = 'workInprogress';
        opp.CloseDate = system.today()+5;
        insert opp;
         
       
        
        Test.startTest();
      
        UpdateAccountRating uar  = new UpdateAccountRating();
        Database.executeBatch(uar);
      String sch = '0 0 0 1 * ? *';
      string JobID = system.schedule('BatchJob',sch, new UpdateAccountRatingSchedular());
        Test.stopTest();
       

 }
    }
schedular
global class UpdateAccountRatingSchedular implements Schedulable {
global void execute(SchedulableContext sc){
        UpdateAccountRating uar = new UpdateAccountRating();
        database.executebatch(uar);
    }
}


Thanks in advance
global class UpdateAccountRating implements Database.Batchable<sObject> {
   
 global  Database.QueryLocator start(Database.BatchableContext bc) {
     set<string> strlist = new set<string>{'workInprogress','Delivered','ClosedWon'};
      string query='select id, stageName,AccountId, Account.Rating from opportunity where stageName IN :strlist AND AccountId !=Null';
     system.debug('query=='+query);
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<opportunity> Scope){
      
        for(opportunity o :Scope){
            o.Account.Rating='client';  
          system.debug('Rating'+o.Account.Rating);
           
        }
         update Scope;}
         global void finish(Database.BatchableContext bc){
       
        AsyncApexJob job = [SELECT Id, Status,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];  
    }   
     }

testclass
@isTest
public class UpdateAccountRatingTest {
    @isTest
    public static void unit_test(){
      
        Account acc =new Account();
        acc.Name = 'test';
        acc.Rating='prospect';
        insert acc;
        
        
        Opportunity opp = new opportunity();
        opp.Name = 'test opp';
        opp.Accountid = acc.Id;
        opp.stageName = 'workInprogress';
        opp.CloseDate = system.today()+5;
        insert opp;
         
       
        
        Test.startTest();
      
        UpdateAccountRating uar  = new UpdateAccountRating();
        Database.executeBatch(uar);
      String sch = '0 0 0 1 * ? *';
      string JobID = system.schedule('BatchJob',sch, new UpdateAccountRatingSchedular());
        Test.stopTest();
       

 }
    }
schedular
global class UpdateAccountRatingSchedular implements Schedulable {
global void execute(SchedulableContext sc){
        UpdateAccountRating uar = new UpdateAccountRating();
        database.executebatch(uar);
    }
}

User-added image
global class opptask implements Database.Batchable <sobject>{
      List <Account> acc = new List<Account>();
      
global Database.QueryLocator start(Database.BatchableContext bc) {
     List <Task> taskList = new List<Task>();
    string query = 'SELECT accountid FROM Task WHERE What.Type = Account AND CreatedDate = LAST_N_MONTHS:48';
      
     return Database.getQueryLocator(query);
      }
global void execute(Database.BatchableContext bc, List<Account> acclist) {
  acclist ='SELECT Id, Name FROM account WHERE Rating = Prospect AND Id NOT IN (SELECT accountid FROM Opportunity WHERE CreatedDate = LAST_N_MONTHS:48) AND Id NOT IN (taskList)';
         
  for (Account a : acclist) {
        a.Rating = dormant;
        }
   Update acc;
    }
    
    global void finish(Database.BatchableContext bc) {
        
    }
}
how to enable row count in  summary reports?
HTML
<template>
<lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="standard:timesheet" alternative-text="Event" size="small"></lightning-icon>
            &nbsp;Add Products
        </h3>
        <template for:each={itemList} for:item="item" for:index="index">
             
                <lightning-layout multiple-rows key={item.id}>        
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-combobox  name="Product Family" data-id={item.data.id} label="Product Family" placeholder="Select Product Family"
                         options={items}  onchange={handleChange} value={item.data.selectedProductFamily} required="true"></lightning-combobox>
                    </lightning-layout-item>
                    <lightning-layout-item  size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                    padding="around-small">
                    <lightning-combobox  name="Product" data-id={item.data.id} label="Product"  placeholder="Select Product "
                     options={item.productNames}  onchange={handleChange} value={item.data.selectedProductId} required="true"></lightning-combobox>
                </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-input name="CGST" data-id={item.data.id} label="CGST" value={item.data.selectedCGST} variant="label-stacked" type="number" onchange={handleChange} required>
                        </lightning-input>
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-input name="SGST" data-id={item.data.id} label="SGST" value={item.data.selectedSGST} variant="label-stacked" type="number" onchange={handleChange} required>
                        </lightning-input>
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-input name="IGST" data-id={item.data.id} label="IGST" value={item.data.selectedIGST} variant="label-stacked" onchange={handleChange} type="number">
                        </lightning-input>
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                    padding="around-small">
                    <lightning-input name="Quantity" data-id={item.data.id} label="Quantity" value={item.data.selectedQuantity} variant="label-stacked" onchange={handleChange} type="number" required >
                    </lightning-input>
                </lightning-layout-item>
                <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                padding="around-small">
                <lightning-input name="BasePrice" data-id={item.data.id} label="Base Price" value={item.data.selectedBasePrice} variant="label-stacked" onchange={handleChange} type="number" required >
                </lightning-input>
            </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <div class="slds-p-top_medium">
                            <lightning-icon icon-name="action:new" access-key={item.id} id={index}
                                alternative-text="Add Row" size="small" title="Add Row" onclick={addRow}>
                            </lightning-icon>
                            <lightning-icon icon-name="action:delete" access-key={item.id} id={index}
                                alternative-text="Delete Row" size="small" title="Delete Row" onclick={removeRow}>
                            </lightning-icon>
                        </div>
                    </lightning-layout-item>
                </lightning-layout>
 
        </template>
       
        <lightning-layout>
            <div class="slds-align_absolute-center">
                <lightning-button variant="success" onclick={handleSubmit} name="submit" label="Submit">
                </lightning-button>
                <lightning-button icon-name="utility:delete" class="slds-p-around_large" variant="destructive" padding="around-large" type="submit" label="cancel" onclick={handleClose}></lightning-button>
            </div>
        </lightning-layout>
    </lightning-card>  
</template>
JS
import { LightningElement,api,wire,track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import fetchproducts from '@salesforce/apex/purchaseOrderLWCController.fetchproducts';
import fetchproductname from '@salesforce/apex/purchaseOrderLWCController.fetchproductname';
import createOrderRecord from '@salesforce/apex/purchaseOrderLWCController.createOrderRecord';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class PurchaseOrderProductCreatePage extends LightningElement {
    @api purchaseOrderId;
    keyIndex = 0;
    @track itemList = [
       {data: {
            id: 0,
            selectedCGST:0,
            selectedSGST:0,
            selectedIGST:0,
            selectedQuantity:0,
            selectedBasePrice:0,
            selectedProductId:'',
            selectedProductFamily:'',
        },
        productNames:[]}
    ];
    @track  productnames =[];
    @track  productnamelist
    @track  items =[];
    value = '';
    currentIndex=0;
    @wire(fetchproducts) wiredProducts ({ error, data }) {
        if (data) {
           
            console.log('products',data)
            for( var i = 0; i < data.length; i++){
              // if (this.items["value"]!=data[i].family)
                this.items = [...this.items ,{value: data[i] , label: data[i]} ];    
            };
            console.log('options',this.items)
       } else if (error) {
          // this.error = error;  
           console.log('error in LWC', error)
      }   }
    addRow() {
        ++this.keyIndex;
        var newItem = [  {data: {
            id: this.keyIndex,
            selectedCGST:0,
            selectedSGST:0,
            selectedIGST:0,
            selectedQuantity:0,
            selectedBasePrice:0,
            selectedProductId:'',
            selectedProductFamily:'',
        },
        productNames:[]} ];
        this.itemList = this.itemList.concat(newItem);
    }
    removeRow(event) {
        if (this.itemList.length >= 1) {
            this.itemList.splice(event.target.accessKey, 1);
            this.keyIndex-1;
            }
            }
    handleChange(event) {
        // Get the string of the "valueselectedBasePrice" attribute on the selected option
        let selectedValue = event.detail.value;
        console.log('selected value=' + selectedValue);
       
        console.log('purchaseOrderId-------' + this.purchaseOrderId);
        let selectedIndex=parseInt(event.target.dataset.id);
        let selectedName=event.target.name;
        if(selectedName=='Product Family'){
            fetchproductname({productFamily:selectedValue})
         .then((result) => {
            let productNames=[]
            console.log('result value=' ,result);
            for( var i = 0; i < result.length; i++){
                // if (this.items["value"]!=data[i].family)
                productNames = [...productNames ,{value: result[i].Id , label: result[i].Name} ];    
              };
            this.error = undefined;
            this.itemList[selectedIndex].productNames=productNames;
            this.itemList[selectedIndex].data.selectedProductFamily=selectedValue;
           
            console.log('filter products', this.itemList);
        })
        .catch((error) => {
            this.error = error;
          console.log('error')
        });
        console.log('filter products', this.productFamily)
        }else if(selectedName=='Product') {
           
        this.itemList[selectedIndex].data.selectedProductId=selectedValue;
        }else if(selectedName=='CGST') {
        this.itemList[selectedIndex].data.selectedCGST=selectedValue;
        }else if(selectedName=='SGST') {
            this.itemList[selectedIndex].data.selectedSGST=selectedValue;
        }
        else if(selectedName=='IGST') {
            this.itemList[selectedIndex].data.selectedIGST=selectedValue;
            }
        else if(selectedName=='Quantity') {
            this.itemList[selectedIndex].data.selectedQuantity=selectedValue;
            }
            else if(selectedName=='BasePrice') {
                this.itemList[selectedIndex].data.selectedBasePrice=selectedValue;
                }
             
                     
        console.log('selectedIndex Id' , event.target.dataset.id);
        console.log('selectedIndex Name' , event.target.name);
         
    }
    handleClose(){
        window.location.reload();
    }
    handleSubmit(event){  
        console.log(JSON.stringify(this.itemList));
        console.log(this.purchaseOrderId);
        let PurchaseorderItemList=[]
        let validtion=false;
        this.itemList.forEach(element => {
            if(element.data.selectedBasePrice ==0 || element.data.selectedQuantity==0 || !element.data.selectedProductId || !element.data.selectedProductFamily){
               
               
                validtion=true;
            }
            purchaseOrderItemList.push({
                Product2Id:element.data.selectedProductId,
                Quantity:element.data.selectedQuantity,
               
                UnitPrice:element.data.selectedBasePrice,
                CGST__c:element.data.selectedCGST,
                SGST__c:element.data.selectedSGST,
                IGST__c:element.data.selectedIGST,
                purchaseOrderId:this.purchaseOrderId,
                PricebookEntryId:'01u2y000001jcN9AAI'
            })
        });
        console.log(PurchaseorderItemList);
        if(!validtion){
            createOrderRecord({newPurchaseOrderItemList:PurchaseorderItemList})
            .then((result) => {
                const event = new ShowToastEvent({
                    title: "Success",
                    message: "Products Added Successfullly ",
                    variant:"Success"
                });
                this.dispatchEvent(event);
             
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: this.purchaseOrderId,
                        objectApiName: 'ObjectApiName',
                        actionName: 'view'
                    }
                });
               
           })
           .catch((error) => {
               this.error = error;
             console.log(error)
           });
           
        }else{
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Value Missing',
                    message: 'Please enter required values for product',
                    variant: 'error',
                }),
            );
        }
       
     }

}
metaxml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
In this above component submit button is not working
thanks in advance
Batch
global class UpdateAccountRating implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsProcessed = 0;
 global  Database.QueryLocator start(Database.BatchableContext bc) {
      string query='select id, stageName,AccountId, Account.Rating from opportunity where stageName IN (\'workInprogress,Delivered,closedwon\') AND AccountId !=Null';
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<opportunity> Scope){
      
        for(opportunity o :Scope){
            o.Account.Rating='client';  
          system.debug('Rating'+o.Account.Rating);
            recordsProcessed = recordsProcessed + 1;
        }
         update Scope;}
         global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + 'records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];  
    }   
     }

test class
@isTest
public class UpdateAccountRatingTest {
    @isTest
    public static void unit_test(){
       //insert All mandatory fields
        Account acc =new Account();
        acc.Name = 'test';
        acc.Rating='prospect';
        insert acc;
        
        //insert All mandatory fields
        Opportunity opp = new opportunity();
        opp.Name = 'test opp';
        opp.Account.Rating='prospect'; 
        opp.Accountid = acc.Id;
        opp.stageName = 'workInprogress';
        opp.CloseDate = system.today()+5;
        insert opp;
         
       
        
        Test.startTest();
      
        UpdateAccountRating uar  = new UpdateAccountRating();
        Database.executeBatch(uar);
      String sch = '0 0 0 1 * ? *';
      string JobID = system.schedule('BatchJob',sch, new UpdateAccountRatingSchedular());
        Test.stopTest();
       

 }
    }

thanks in advance
select Id,Rating,(select Id,StageName from Opportunities where StageName=\'WorkInprogress,Delivered,closedwon\') From account

This is my query. its querying all accounts. i need only accounts related to Opportunities where StageName=\'WorkInprogress,Delivered,closedwon\')

Thanks in advance
select id, Name, (Select Id, Name from contacts), (Select Id, Name From Opportunities where Id='Your Opportunity Id') from Account

Thanks in advance
global class UpdateRating implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsProcessed = 0;
 global  Database.QueryLocator  start(Database.BatchableContext bc) {
    string query='select Rating,(select StageName from Opportunities where StageName=\''+String.escapeSingleQuotes('Inprogress,Delivered,closedwon')+ '\') From account where Rating <> \''+String.escapeSingleQuotes('client') + '\'';
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<Account> Scope){
      
        for(Account a :Scope){
            a.Rating='client';        
            recordsProcessed = recordsProcessed + 1;
        }
         update Scope; }
         global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + 'records processed. Shazam!');
            
    }   
     }

test class

@isTest public class UpdateAccountRatingTest {
@testSetup static void setup() {

Account ac =new Account();
ac.Name = 'test';
ac.rating='prospect';
insert ac;
ac.Name = 'test';
ac.rating='client';
update ac; }
@isTest static void test() {
Test.startTest();
UpdateAccountRating uar = new UpdateAccountRating();
Id batchId = Database.executeBatch(uar);
Test.stopTest(); } }
Thanks in advance
I am getting error for my batch apex in soql as'illegal assignment of list to string'
how to resolve this?
global class UpdateAccountRating implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsProcessed = 0;
 global  Database.QueryLocator  start(Database.BatchableContext bc) {
    string query=[select Id,Rating,(select Id,StageName from Opportunities where StageName='Inprogress,Delivered,closedwon') From account where Rating!='client'];
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<Account> Scope){
      
        for(Account a :Scope){
            a.Rating='client';        
            recordsProcessed = recordsProcessed + 1;
        }
         update Scope; }
         global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + 'records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];
     
    }   
     }
    thanks in advance
I mentioned reportfoldername/reportname .still unable to retrieve. 
<?
xml version="1.0" encoding="UTF-8" standalone="yes"?>

<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
        <members>Sales & Marketing Dashboards Reports/Win Ratio</members>
        <name>Report</name>
    </types>
    <types>
        <members>Sales and Marketing Dashboards/Sales Manager Dashboard</members>
        <name>Dashboard</name>
    </types>
    <version>54.0</version>
</Package>
Thanks in advance
LWC- Use Lightning Data Service to Work with Data
HTML
<template>
    <lightning-card>
        <lightning-record-form
            object-api-name={contact}
            fields={fields}
            onsuccess={handleSuccess}>
        </lightning-record-form>
    </lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CONTACT_OBJECT from '@salesforce/schema/contact';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import NAME_FIELD from '@salesforce/schema/contact.Name';
import EMAIL_FIELD from '@salesforce/schema/contact.Email';
export default class ContactCreator extends LightningElement {
    objectApiName = CONTACT_OBJECT;
    fields = [NAME_FIELD, EMAIL_FIELD];
    handleSuccess(event) {
        const toastEvent = new ShowToastEvent({
            title: "Contact created",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(toastEvent);
    }
}

meta XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Thanks in Advance
I have two profiles,in profile 1 user should have read access to account and opportunity , only owner should  edit the record they own.

In profile 2 account and opportunity should be private.how to achiev this?

Thanks in advance
I couldnt see debug statements aswell. its not showing error got 100% coverage. when i use database.execute batch totalbatch processed it shows 1 and zero failures. only after schedule it shows  total batch zero in apex jobs.can anyone guide me to resolve this issue?

global class UpdateAccountRating implements Database.Batchable<sObject> {
   
 global  Database.QueryLocator start(Database.BatchableContext bc) {
     set<string> strlist = new set<string>{'workInprogress','Delivered','ClosedWon'};
      string query='select id, stageName,AccountId, Account.Rating from opportunity where stageName IN :strlist AND AccountId !=Null';
     system.debug('query=='+query);
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<opportunity> Scope){
      
        for(opportunity o :Scope){
            o.Account.Rating='client';  
          system.debug('Rating'+o.Account.Rating);
           
        }
         update Scope;}
         global void finish(Database.BatchableContext bc){
       
        AsyncApexJob job = [SELECT Id, Status,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];  
    }   
     } 

testclass
@isTest
public class UpdateAccountRatingTest {
    @isTest
    public static void unit_test(){
      
        Account acc =new Account();
        acc.Name = 'test';
        acc.Rating='prospect';
        insert acc;
        
        
        Opportunity opp = new opportunity();
        opp.Name = 'test opp';
        opp.Accountid = acc.Id;
        opp.stageName = 'workInprogress';
        opp.CloseDate = system.today()+5;
        insert opp;
         
       
        
        Test.startTest();
      
        UpdateAccountRating uar  = new UpdateAccountRating();
        Database.executeBatch(uar);
      String sch = '0 0 0 1 * ? *';
      string JobID = system.schedule('BatchJob',sch, new UpdateAccountRatingSchedular());
        Test.stopTest();
       

 }
    }
schedular
global class UpdateAccountRatingSchedular implements Schedulable {
global void execute(SchedulableContext sc){
        UpdateAccountRating uar = new UpdateAccountRating();
        database.executebatch(uar);
    }
}


Thanks in advance
global class UpdateAccountRating implements Database.Batchable<sObject> {
   
 global  Database.QueryLocator start(Database.BatchableContext bc) {
     set<string> strlist = new set<string>{'workInprogress','Delivered','ClosedWon'};
      string query='select id, stageName,AccountId, Account.Rating from opportunity where stageName IN :strlist AND AccountId !=Null';
     system.debug('query=='+query);
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<opportunity> Scope){
      
        for(opportunity o :Scope){
            o.Account.Rating='client';  
          system.debug('Rating'+o.Account.Rating);
           
        }
         update Scope;}
         global void finish(Database.BatchableContext bc){
       
        AsyncApexJob job = [SELECT Id, Status,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];  
    }   
     }

testclass
@isTest
public class UpdateAccountRatingTest {
    @isTest
    public static void unit_test(){
      
        Account acc =new Account();
        acc.Name = 'test';
        acc.Rating='prospect';
        insert acc;
        
        
        Opportunity opp = new opportunity();
        opp.Name = 'test opp';
        opp.Accountid = acc.Id;
        opp.stageName = 'workInprogress';
        opp.CloseDate = system.today()+5;
        insert opp;
         
       
        
        Test.startTest();
      
        UpdateAccountRating uar  = new UpdateAccountRating();
        Database.executeBatch(uar);
      String sch = '0 0 0 1 * ? *';
      string JobID = system.schedule('BatchJob',sch, new UpdateAccountRatingSchedular());
        Test.stopTest();
       

 }
    }
schedular
global class UpdateAccountRatingSchedular implements Schedulable {
global void execute(SchedulableContext sc){
        UpdateAccountRating uar = new UpdateAccountRating();
        database.executebatch(uar);
    }
}

User-added image
Batch
global class UpdateAccountRating implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsProcessed = 0;
 global  Database.QueryLocator start(Database.BatchableContext bc) {
      string query='select id, stageName,AccountId, Account.Rating from opportunity where stageName IN (\'workInprogress,Delivered,closedwon\') AND AccountId !=Null';
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<opportunity> Scope){
      
        for(opportunity o :Scope){
            o.Account.Rating='client';  
          system.debug('Rating'+o.Account.Rating);
            recordsProcessed = recordsProcessed + 1;
        }
         update Scope;}
         global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + 'records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];  
    }   
     }

test class
@isTest
public class UpdateAccountRatingTest {
    @isTest
    public static void unit_test(){
       //insert All mandatory fields
        Account acc =new Account();
        acc.Name = 'test';
        acc.Rating='prospect';
        insert acc;
        
        //insert All mandatory fields
        Opportunity opp = new opportunity();
        opp.Name = 'test opp';
        opp.Account.Rating='prospect'; 
        opp.Accountid = acc.Id;
        opp.stageName = 'workInprogress';
        opp.CloseDate = system.today()+5;
        insert opp;
         
       
        
        Test.startTest();
      
        UpdateAccountRating uar  = new UpdateAccountRating();
        Database.executeBatch(uar);
      String sch = '0 0 0 1 * ? *';
      string JobID = system.schedule('BatchJob',sch, new UpdateAccountRatingSchedular());
        Test.stopTest();
       

 }
    }

thanks in advance
select id, Name, (Select Id, Name from contacts), (Select Id, Name From Opportunities where Id='Your Opportunity Id') from Account

Thanks in advance
global class UpdateRating implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsProcessed = 0;
 global  Database.QueryLocator  start(Database.BatchableContext bc) {
    string query='select Rating,(select StageName from Opportunities where StageName=\''+String.escapeSingleQuotes('Inprogress,Delivered,closedwon')+ '\') From account where Rating <> \''+String.escapeSingleQuotes('client') + '\'';
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<Account> Scope){
      
        for(Account a :Scope){
            a.Rating='client';        
            recordsProcessed = recordsProcessed + 1;
        }
         update Scope; }
         global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + 'records processed. Shazam!');
            
    }   
     }

test class

@isTest public class UpdateAccountRatingTest {
@testSetup static void setup() {

Account ac =new Account();
ac.Name = 'test';
ac.rating='prospect';
insert ac;
ac.Name = 'test';
ac.rating='client';
update ac; }
@isTest static void test() {
Test.startTest();
UpdateAccountRating uar = new UpdateAccountRating();
Id batchId = Database.executeBatch(uar);
Test.stopTest(); } }
Thanks in advance
I am getting error for my batch apex in soql as'illegal assignment of list to string'
how to resolve this?
global class UpdateAccountRating implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsProcessed = 0;
 global  Database.QueryLocator  start(Database.BatchableContext bc) {
    string query=[select Id,Rating,(select Id,StageName from Opportunities where StageName='Inprogress,Delivered,closedwon') From account where Rating!='client'];
     return Database.getQueryLocator(query); 
    }
     global Void execute(Database.BatchableContext bc, List<Account> Scope){
      
        for(Account a :Scope){
            a.Rating='client';        
            recordsProcessed = recordsProcessed + 1;
        }
         update Scope; }
         global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + 'records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];
     
    }   
     }
    thanks in advance
I mentioned reportfoldername/reportname .still unable to retrieve. 
<?
xml version="1.0" encoding="UTF-8" standalone="yes"?>

<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
        <members>Sales & Marketing Dashboards Reports/Win Ratio</members>
        <name>Report</name>
    </types>
    <types>
        <members>Sales and Marketing Dashboards/Sales Manager Dashboard</members>
        <name>Dashboard</name>
    </types>
    <version>54.0</version>
</Package>
Thanks in advance
LWC- Use Lightning Data Service to Work with Data
HTML
<template>
    <lightning-card>
        <lightning-record-form
            object-api-name={contact}
            fields={fields}
            onsuccess={handleSuccess}>
        </lightning-record-form>
    </lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CONTACT_OBJECT from '@salesforce/schema/contact';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import NAME_FIELD from '@salesforce/schema/contact.Name';
import EMAIL_FIELD from '@salesforce/schema/contact.Email';
export default class ContactCreator extends LightningElement {
    objectApiName = CONTACT_OBJECT;
    fields = [NAME_FIELD, EMAIL_FIELD];
    handleSuccess(event) {
        const toastEvent = new ShowToastEvent({
            title: "Contact created",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(toastEvent);
    }
}

meta XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Thanks in Advance
HTML
<template>
<lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="standard:timesheet" alternative-text="Event" size="small"></lightning-icon>
            &nbsp;Add Products
        </h3>
        <template for:each={itemList} for:item="item" for:index="index">
             
                <lightning-layout multiple-rows key={item.id}>        
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-combobox  name="Product Family" data-id={item.data.id} label="Product Family" placeholder="Select Product Family"
                         options={items}  onchange={handleChange} value={item.data.selectedProductFamily} required="true"></lightning-combobox>
                    </lightning-layout-item>
                    <lightning-layout-item  size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                    padding="around-small">
                    <lightning-combobox  name="Product" data-id={item.data.id} label="Product"  placeholder="Select Product "
                     options={item.productNames}  onchange={handleChange} value={item.data.selectedProductId} required="true"></lightning-combobox>
                </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-input name="CGST" data-id={item.data.id} label="CGST" value={item.data.selectedCGST} variant="label-stacked" type="number" onchange={handleChange} required>
                        </lightning-input>
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-input name="SGST" data-id={item.data.id} label="SGST" value={item.data.selectedSGST} variant="label-stacked" type="number" onchange={handleChange} required>
                        </lightning-input>
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <lightning-input name="IGST" data-id={item.data.id} label="IGST" value={item.data.selectedIGST} variant="label-stacked" onchange={handleChange} type="number">
                        </lightning-input>
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                    padding="around-small">
                    <lightning-input name="Quantity" data-id={item.data.id} label="Quantity" value={item.data.selectedQuantity} variant="label-stacked" onchange={handleChange} type="number" required >
                    </lightning-input>
                </lightning-layout-item>
                <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                padding="around-small">
                <lightning-input name="BasePrice" data-id={item.data.id} label="Base Price" value={item.data.selectedBasePrice} variant="label-stacked" onchange={handleChange} type="number" required >
                </lightning-input>
            </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="2" large-device-size="2"
                        padding="around-small">
                        <div class="slds-p-top_medium">
                            <lightning-icon icon-name="action:new" access-key={item.id} id={index}
                                alternative-text="Add Row" size="small" title="Add Row" onclick={addRow}>
                            </lightning-icon>
                            <lightning-icon icon-name="action:delete" access-key={item.id} id={index}
                                alternative-text="Delete Row" size="small" title="Delete Row" onclick={removeRow}>
                            </lightning-icon>
                        </div>
                    </lightning-layout-item>
                </lightning-layout>
 
        </template>
       
        <lightning-layout>
            <div class="slds-align_absolute-center">
                <lightning-button variant="success" onclick={handleSubmit} name="submit" label="Submit">
                </lightning-button>
                <lightning-button icon-name="utility:delete" class="slds-p-around_large" variant="destructive" padding="around-large" type="submit" label="cancel" onclick={handleClose}></lightning-button>
            </div>
        </lightning-layout>
    </lightning-card>  
</template>

JS
import { LightningElement,api,wire,track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import fetchproducts from '@salesforce/apex/Purchaseorder.fetchproducts';
import fetchproductname from '@salesforce/apex/Purchaseorder.fetchproductname';
import createOrderRecord from '@salesforce/apex/Purchaseorder.createOrderRecord';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class PurchaseOrderProductCreatePage extends LightningElement {
    @api PurchaseOrderId;
    keyIndex = 0;
    @track itemList = [
       {data: {
            id: 0,
            selectedCGST:0,
            selectedSGST:0,
            selectedIGST:0,
            selectedQuantity:0,
            selectedListPrice:0,
            selectedProductId:'',
            selectedProductFamily:'',
        },
        productNames:[]}
    ];
    @track  productnames =[];
    @track  productnamelist
    @track  items =[];
    value = '';
    currentIndex=0;
    @wire(fetchproducts) wiredProducts ({ error, data }) {
        if (data) {
           
            console.log('products',data)
            for( var i = 0; i < data.length; i++){
              // if (this.items["value"]!=data[i].family)
                this.items = [...this.items ,{value: data[i] , label: data[i]} ];    
            };
            console.log('options',this.items)
       } else if (error) {
          // this.error = error;  
           console.log('error in LWC', error)
      }   }
    addRow() {
        ++this.keyIndex;
        var newItem = [  {data: {
            id: this.keyIndex,
            selectedCGST:0,
            selectedSGST:0,
            selectedIGST:0,
            selectedQuantity:0,
            selectedListPrice:0,
            selectedProductId:'',
            selectedProductFamily:'',
        },
        productNames:[]} ];
        this.itemList = this.itemList.concat(newItem);
    }
    removeRow(event) {
        if (this.itemList.length >= 1) {
            this.itemList.splice(event.target.accessKey, 1);
            this.keyIndex-1;
            }
            }
    handleChange(event) {
        // Get the string of the "value" attribute on the selected option
        let selectedValue = event.detail.value;
        console.log('selected value=' + selectedValue);
       
        console.log('PurchaseorderId-------' + this.PurchaseorderId);
        let selectedIndex=parseInt(event.target.dataset.id);
        let selectedName=event.target.name;
        if(selectedName=='Product Family'){
            fetchproductname({productFamily:selectedValue})
         .then((result) => {
            let productNames=[]
            console.log('result value=' ,result);
            for( var i = 0; i < result.length; i++){
                // if (this.items["value"]!=data[i].family)
                productNames = [...productNames ,{value: result[i].Id , label: result[i].Name} ];    
              };
            this.error = undefined;
            this.itemList[selectedIndex].productNames=productNames;
            this.itemList[selectedIndex].data.selectedProductFamily=selectedValue;
           
            console.log('filter products', this.itemList);
        })
        .catch((error) => {
            this.error = error;
          console.log('error')
        });
        console.log('filter products', this.productFamily)
        }else if(selectedName=='Product') {
           
        this.itemList[selectedIndex].data.selectedProductId=selectedValue;
        }else if(selectedName=='CGST') {
        this.itemList[selectedIndex].data.selectedCGST=selectedValue;
        }else if(selectedName=='SGST') {
            this.itemList[selectedIndex].data.selectedSGST=selectedValue;
        }
        else if(selectedName=='IGST') {
            this.itemList[selectedIndex].data.selectedIGST=selectedValue;
            }
        else if(selectedName=='Quantity') {
            this.itemList[selectedIndex].data.selectedQuantity=selectedValue;
            }
            else if(selectedName=='BasePrice') {
                this.itemList[selectedIndex].data.selectedBasePrice=selectedValue;
                }
             
                     
        console.log('selectedIndex Id' , event.target.dataset.id);
        console.log('selectedIndex Name' , event.target.name);
         
    }
    handleClose(){
        window.location.reload();
    }
    handleSubmit(event){  
        console.log(JSON.stringify(this.itemList));
        console.log(this.PurchaseorderId);
        let PurchaseorderItemList=[]
        let validtion=false;
        this.itemList.forEach(element => {
            if(element.data.selectedBasePrice ==0 || element.data.selectedQuantity==0 || !element.data.selectedProductId || !element.data.selectedProductFamily){
               
               
                validtion=true;
             

            }
            PurchaseorderItemList.push({
                Product2Id:element.data.selectedProductId,
                Quantity:element.data.selectedQuantity,
               
                UnitPrice:element.data.selectedListPrice,
                CGST__c:element.data.selectedCGST,
                SGST__c:element.data.selectedSGST,
                IGST__c:element.data.selectedIGST,
                purchaseorderId:this.purchaseorderId,
                PricebookEntryId:'01u2y000001jcN9AAI'
            })
        });
        console.log(PurchaseorderItemList);
        if(!validtion){
            createOrderRecord({newPurchaseOrderItemList:PurchaseorderItemList})
            .then((result) => {
                const event = new ShowToastEvent({
                    title: "Success",
                    message: "Products Added Successfullly ",
                    variant:"Success"
                });
                this.dispatchEvent(event);
             
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: this.PurchaseorderId,
                        objectApiName: 'ObjectApiName',
                        actionName: 'view'
                    }
                });
               
           })
           .catch((error) => {
               this.error = error;
             console.log(error)
           });
           
        }else{
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Value Missing',
                    message: 'Please enter required values for product',
                    variant: 'error',
                }),
            );
        }
       
     }

}

Thanks in advance
I have updated SFDX.I need to install local dev server . Its getting failed ad got error message 
'Failed to setup Red Hat XML extension
Activating extension 'redhat.vscode-xml' failed: Connection to server got closed. Server will not be restarted..
Starting SFDX: Start Local Development Server'
How to preview LWC component locally. Thanks in advance.
 
I need to display calender field for industry picklist field value 1.
<aura:component controller="DynamicPicklist" implements="flexipage:availableForAllPageTypes,force:appHostable">
     
   <!--<aura:attribute name='flag' type="boolen" default="false"/>-->
    <aura:attribute name="fieldMap" type="Map"/>
    <aura:attribute name="lead" type="Lead" default="{'sobjectType':'Lead', 
                                                       'LastName': '',
                                                       'Company': '',
                                                       'Email': '',
                                                       'Phone': '', 
                                                       'Industry': ''}"/>
    
 <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="Name" type="text" label="Lead Name" value="{!v.lead.LastName}" />
            </div>
            <div class="form-group">
                <lightning:input name="Company" type="text" label="Company" value="{!v.lead.Company}" />
            </div>
            <div class="form-group">
                <lightning:input name="Email" type="email" label="Email" value="{!v.lead.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="Phone" type="phone" label="Phone" value="{!v.lead.Phone}" />
            </div>
            <div class="form-group">
                <lightning:select aura:id="industryPicklist" value="{!v.lead.Industry}" onchange="{!c.handleOnChange}" name="Industry" label="Industry" required="true">
                    <option value="">--None--</option>
                    <option value="1">Re engagement</option>
                   
                    <option value="2">Inadequate Data</option>
             </lightning:select>
                </div>
             <aura:if isTrue="{!v.lead.Industry=='Reengagement'}">
             <lightning:input type="date" name="input1" label="Enter a date" value="{! v.date }" />
                </aura:if>
       </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.LeadSave}" />              
    </div>
   </aura:component>
controller:
({
    
    doInit: function(component, event, helper) {        
        helper.getPicklistValues(component, event);
    },
     
    
    LeadSave : function(component, event, helper) {
        helper.saveLead(component, event);
    },
     
    //handle Industry Picklist Selection
    handleOnChange : function(component, event, helper) {
       if(event.target.value == 'Reengagement'){
        component.set("v.flag", "true")
       
       }else{
       component.set("v.flag", "false")
       }
        
    }

})
Helper:
({
    
    getPicklistValues: function(component, event) {
        var action = component.get("c.getIndustryFieldValue");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var fieldMap = [];
                for(var key in result){
                    fieldMap.push({key: key, value: result[key]});
                }
                component.set("v.fieldMap", fieldMap);
            }
        });
        $A.enqueueAction(action);
    },
     
    
    saveLead : function(component, event) {
        var lead = component.get("v.lead");
        var action = component.get("c.createLead");
        action.setParams({
            leadobj : lead
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                alert('Record Created Successfully!!');
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert(errors[0].message);
                    }
                }
            }
        });       
        $A.enqueueAction(action);
    }
})
Apex:
public class DynamicPicklist {
        @AuraEnabled 
    Public static void createLead(Lead leadobj){
        try{
            
            insert leadobj; 
             
        }catch(Exception e){
            System.debug(e.getMessage());
            System.debug(e.getLineNumber());
        }
        
    }
     
    @AuraEnabled 
    public static Map<String, String> getIndustryFieldValue(){
        Map<String, String> options = new Map<String, String>();
        
        Schema.DescribeFieldResult fieldResult = Lead.Industry.getDescribe();
        
        List<Schema.PicklistEntry> pValues = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pValues) {
            
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
}
hi, how to enable input calendar field for picklist option1-Reengagement
and disable the same input calendar field for picklist option 2-Inadeqautedata  in aura.

<lightning:select aura:id="industryPicklist" value="{!v.lead.Industry}" onchange="{!c.handleOnChange}" name="industryPicklist" label="Industry" required="true">
                    <option value="">--None--</option>
                    <option value="1">Re engagement</option>
                   
                    <option value="2">Inadequate Data</option>
                   <lightning:input type="date" name="input1" label="Re engagement" /> 
Thanks in advance
Hi,

I want to show the 'SuppliedEmail' field on the form when the picklist value of 'Investigation_Email_Preference__c' is either "abc" or "def".

How do i do that with lightning:recordForm ?

Component:
<aura:component implements="flexipage:availableForAllPageTypes,force:lightningQuickActionWithoutHeader,force:hasRecordId">
<aura:attribute name="myFields" type="List" default="['Case_Investigation__c','Investigation_Subject__c','Investigation_Email_Preference__c','Tier2_Agent__c','SuppliedEmail']"/>
<lightning:recordForm
        recordId="{!v.recordId}"
        objectApiName="Case"       
        columns="2"
        fields="{!v.myFields}"
        mode="edit"
        onsubmit="{!c.handleSubmit}"/>

</aura:component>
I want to show/hide a div that contains an input field, based on the picklist value in lightning:

CMP: 
<div class="slds-col">
            <lightning:select class="select-auto-width" name="selectEmailPreference" aura:id="selectEmailPreference" label="Current Email Preference" required="true" onchange="{!c.setEmailPreference}">
            <option value="1">No Email Updates</option>
            <option value="2">Send all Email Updates</option>
            <option value="3">Send Critical Updates and Fixes Only</option>
        </lightning:select>

Show this div only when the value is either option 2 or option 3
 <div class="slds-col">
                   <lightning:layoutItem size="4">
                    <lightning:input type="email" label="Current Email"/>
                       </lightning:layoutItem>
                   </div>