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


  • Chatter
    Feed
  • 25
    Best Answers
  • 0
    Likes Received
  • 5
    Likes Given
  • 4
    Questions
  • 89
    Replies
I have a VF page that displays a live count of selected rows of a VF page. I'd like to also show a sum of a currency field for the selected records. Let's say the field is Total_Amount__c. 

How could I include this live sum in my page.

here is the code:
Vf page:
<apex:page controller="CountLiveController">
    <script>
        function test()
      {
          console.log('>>yes');
          methodOneInJavascript();
      }
        
        </script>
    <apex:form id="frm" >
        
        <apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="frm"/>

           <apex:pageBlock title="Accounts">

            <apex:pageBlockTable value="{!wrapList}" var="a">
                <apex:column headerValue="Select Account">
                    <apex:inputCheckbox value="{!a.selected}" onchange="test();"/> 
                    
                </apex:column>
                <apex:column headervalue="Account Name" value="{!a.acc.name}"/>
            </apex:pageBlockTable>
             <apex:pageBlockSection>
          Live Count::: {!Count}
            </apex:pageBlockSection>
        </apex:pageBlock> 
    </apex:form>
</apex:page>
Controller:
public class CountLiveController {
    public List<Account> acList{get;set;}
    public List<AccountWrapper> wrapList{get;set;} 
    public List<AccountWrapper> selectedWrap{get;set;}
    public Integer Count{get;set;}
    public CountLiveController()
    {
        acList=new List<Account>();
        selectedWrap = new List<AccountWrapper>();
        acList=[Select name from Account limit 10];// Show number of accounts as per requirement
        wrapList=new List<AccountWrapper>();
        for(Account a:acList)
        {
           AccountWrapper aw=new AccountWrapper(a);
           wrapList.add(aw); 
        }
        System.debug('>>wrapList'+wrapList);
    }

    public class AccountWrapper{
        public Boolean selected{get;set;}
        public Account acc{get;set;}
      public AccountWrapper(Account a)
      {
          acc=a;
          selected=false;
      }
    }
     
   public void methodOne()
   {
       selectedWrap.clear();
       for(AccountWrapper wrap:wrapList)
       {
          if(wrap.selected==true)
          {
             selectedWrap.add(wrap);
          }
          Count=selectedWrap.size(); 
         system.debug('::::'+selectedWrap);
       }  
   }
}

 
I am trying to create a lookup to Territory on the Account object. But while creating a lookup field, I am not able to see the Territory object in "Related To" dropdown box. I am not able to see this on custom objects as well.

Am I missing something here or Salesforce not allows us to add Territory as lookup to other objects?

 
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>
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... 
User-added image

Please suggest me something to resolve this error, I am using visualforce email template with without sharing class, and I am not using any attachments.
Only absolute URLs are supported, getting this error for my org in vs code while retrieving the data from the sandbox.
Even I tried login with my domain and test.salesforce.com as well, even facing the same issue, and for other orgs everything is working fine.User-added image
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.
User-added image

Please suggest me something to resolve this error, I am using visualforce email template with without sharing class, and I am not using any attachments.
I have a VF page that displays a live count of selected rows of a VF page. I'd like to also show a sum of a currency field for the selected records. Let's say the field is Total_Amount__c. 

How could I include this live sum in my page.

here is the code:
Vf page:
<apex:page controller="CountLiveController">
    <script>
        function test()
      {
          console.log('>>yes');
          methodOneInJavascript();
      }
        
        </script>
    <apex:form id="frm" >
        
        <apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="frm"/>

           <apex:pageBlock title="Accounts">

            <apex:pageBlockTable value="{!wrapList}" var="a">
                <apex:column headerValue="Select Account">
                    <apex:inputCheckbox value="{!a.selected}" onchange="test();"/> 
                    
                </apex:column>
                <apex:column headervalue="Account Name" value="{!a.acc.name}"/>
            </apex:pageBlockTable>
             <apex:pageBlockSection>
          Live Count::: {!Count}
            </apex:pageBlockSection>
        </apex:pageBlock> 
    </apex:form>
</apex:page>
Controller:
public class CountLiveController {
    public List<Account> acList{get;set;}
    public List<AccountWrapper> wrapList{get;set;} 
    public List<AccountWrapper> selectedWrap{get;set;}
    public Integer Count{get;set;}
    public CountLiveController()
    {
        acList=new List<Account>();
        selectedWrap = new List<AccountWrapper>();
        acList=[Select name from Account limit 10];// Show number of accounts as per requirement
        wrapList=new List<AccountWrapper>();
        for(Account a:acList)
        {
           AccountWrapper aw=new AccountWrapper(a);
           wrapList.add(aw); 
        }
        System.debug('>>wrapList'+wrapList);
    }

    public class AccountWrapper{
        public Boolean selected{get;set;}
        public Account acc{get;set;}
      public AccountWrapper(Account a)
      {
          acc=a;
          selected=false;
      }
    }
     
   public void methodOne()
   {
       selectedWrap.clear();
       for(AccountWrapper wrap:wrapList)
       {
          if(wrap.selected==true)
          {
             selectedWrap.add(wrap);
          }
          Count=selectedWrap.size(); 
         system.debug('::::'+selectedWrap);
       }  
   }
}

 
I am trying to create a lookup to Territory on the Account object. But while creating a lookup field, I am not able to see the Territory object in "Related To" dropdown box. I am not able to see this on custom objects as well.

Am I missing something here or Salesforce not allows us to add Territory as lookup to other objects?

 
Hi,

I want to create a record triggered flow for renewal opportunity so that the it will be closed one year from close date when an opportunity is closed won.
I need to consider the leap year too. Also, the opportunity name should be like this: [opportunity name] - Renewal [renewal count] - year.
For example,
Ford - Renewal 1 - 2024
Ford - Renewal 2 - 2025
Etc.
 
I created a VF page to edit two fields on the Quote object. I need to make this page publically visible to customers and allow them to edit the two fields and submit the form. 
So far, the page and all fields are showing up publically, but when I try to add an ID to the URL and pull a specific record, I get an "Authorization Required" error message.
The guest profile has access to all fields for the Quote object, so I'm not sure what I'm missing
 
write a trigger that when a country(custom field) of account(standard object) is updated, the country(custom field) of contact(standard object) should be copied
Hi,

The LWC lightning input components does not contain onpaste functionality. Any pointers on how this cna be achieved.

Thnak you
public class  customerUpdate {
public  void updatecustomer(){
        Set<Id> ParentIds = New Set<Id>();
        for(customer__c newissuer :(List< customer__c>) Trigger.New)
        {
            if(newissuer.Id != null)
                ParentIds.add(newissuer.Id);
        }
        List<customer__c> ParentList = [SELECT Id, Name,Status__c, RevQ0__c, RevQ1__c, RevQ2__c, RevQ3__c, RevQ4__c 
                                FROM customer__c where id =: ParentIds];
         For(customer__c CO : ParentList)    
        {
            system.debug('ParentList12'+co.id);
            system.debug('ParentList123'+co.Status__c);
            for(customer__c rc :(List<customer__c>) Trigger.New){
         if(rc.Status__c=='Approved'){
                   rc.RevQ1__c= CO.RevQ0__c;
                   rc.RevQ0__c = null;
                    rc.RevQ2__c= CO.RevQ1__c;
                    rc.RevQ3__c= CO.RevQ2__c;
                    rc.RevQ4__c= CO.RevQ3__c;
                    
                 
                }
            }
            
        }    
    }
    
}
  • January 24, 2020
  • Like
  • 0
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..!
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?