• @anilbathula@
  • PRO
  • 2960 Points
  • Member since 2011

  • Chatter
    Feed
  • 99
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 519
    Replies
Can I have help writing a query for permission set license holder in Salesforce. I am trying to find all the users who are assigned the permission set license named: Sales Cloud Einstein. 
 for(Lead l: scope)
        {
            
            if(l.State!=''){ //State is not empty
                l.State__c =l.State__c;
            }else{    //State is empty
                l.State__c ='Default';}
            
            
            l.Age__c = l.Current_Age__c;
            
        }
        update scope;
    }

Hi all,

In platform developer II there are 65 questions and 5 of them do not account for the exam percentage they have zero marks. Can somebody tell me if they are the last 5 questions? or they appear randomly.

Thanks,

A

  • March 04, 2020
  • Like
  • 0
Hello,

What is the SOQL query to check the list of thins a user is following.
The user can click Follow on Account, Opportunity etc
but is there any limit on thiings to follow
  • January 30, 2020
  • Like
  • 0
I need to put validation on Task so that Task cannot be created for Accounts other than "Sold to Customer" and "Prospect Customer". Currently Task can be created even for "Bill to Customer". There is no option to create a validation rule with task hence I need to have Before insert and before update Trigger. (Type is a picklist in Account that has value: Sold to Customer, Prospect Customer, Bill to Customer)

trigger TaskCanbeCreatedforSoldtoOnly on Task (before insert, before update) {
    for (Task t: Trigger.new){
         if(t.Account.Type== 'Bill To Customer') {
                     t.addError ('Please select the Sold to Customer');
        }
    }
}

Thank you
We have object Recommend__c which has a formula field pointed to the parent object Application:

Adm_Status__c = TEXT(App__r.App_Adm_Status__c)

Can the ProcessBuilder be defined starting on the Recommend__c object, looking for changes to Adm_Status__c ?  So far is not working in PB or Workflow.
Hi Guys,

The functionality i'm trying to perform here is to update the parent object status to complete when all related child object records have a status complete. But i'm receiving the error "Error: Compile Error: Variable does not exist: id at line 11"

I'm pasting the code below. Can you please help me out here. Thanks!!

trigger updateParentStatus on Child_Object__c (after insert, after update) {

    Set<Id> parentIds = new Set<Id>();
    Integer count = 0;

        for(Child_Object__c wd: Trigger.new) {
            parentIds.add(wd.Parent_Object__c);
        }
    
    List<Parent_Object__c> parentList = [Select id, Status__c from Parent_Object__c where id =: parentIds];
    List<Child_Object__c> childList = [Select id, Status__c from Parent_Object__c Where parentIds =: parentList.id];
    
    for(Child_Object__c wd: Trigger.new) {
        if(wd.Status__c != 'Completed') {
            count++;
        }
    }
    
    for(Parent_Object__c wo: parentList) {
        wo.Status__c = 'Completed';    
    }
    
    if(count==0) {
        update parentList;
    }
}
 
I am trying to optimize my working code. When i tried to convert a set into a Map, I am getting an error -  
Line: 10, Column: 22
Method does not exist or incorrect signature: void add(Id, String) from the type Map<Id,String>

 
Map<ID, String>  mapAccountBillingAddress = new Map<ID, String>();
for (AggregateResult aggregate : [Select count(Id),BillingStreet str,BillingCity ct, BillingState stt, BillingPostalCode pc 
From Account                                                                Group By BillingStreet,BillingCity,BillingState,BillingPostalCode
HAVING (count(BillingStreet) > 1  AND count(BillingPostalCode) > 1 )
] )
{
mapAccountBillingAddress .add(aggregate.id, ((String)aggregate.get('str')+(String)aggregate.get('ct')+(String)aggregate.get('stt')+(String)aggregate.get('pc')));
	
   
}



 

Hello all,

I am still getting my feet wet with Apex but have come a good way, but still would be very gracilous for this awesome community's input please:)

I have a Trigger on Task after activities are either inserted or updated that performs a rollup for touchpoints on open activities.

The issue is if a user deletes an activity, the rollup is unaffected resulting in an erroneus count for the touchpoints.

This is my code:

trigger TaskRollupSummaryTrigger on Task (after insert, after update) {
    Set<ID> contactIdSet = new Set<ID>();

    for (Task t : trigger.new) {
        if (t.whoId != NULL) {
            contactIdSet.add(t.whoId);
        }
    }
    
    if (contactIdSet.size() > 0) {
        AggregateResult[] groupedResults = [SELECT WhoId, Type, Count(ID) FROM Task WHERE WhoId IN :contactIdSet AND Type IN ('Call','Email','In-Person Meeting') GROUP BY WhoId, Type];
        
        Map<ID, Contact> contactMap = new Map<ID, Contact>([SELECT Id, Total_Call_Touchpoints__c FROM Contact WHERE Id IN :contactIdSet]);
    
        for (AggregateResult g : groupedResults) {    
            System.debug('####' + g.get('WhoId') + ' : ' + g.get('expr0'));
            Contact c = contactMap.get((String)g.get('WhoId'));
            
            if ((String)g.get('Type') == 'Call') {
                c.Total_Call_Touchpoints__c = (Decimal)g.get('expr0');
            } else if ((String)g.get('Type') == 'Email') {
                c.Total_Email_Touchpoints__c = (Decimal)g.get('expr0');
            } else if ((String)g.get('Type') == 'In-Person Meeting') {
                c.Total_Meeting_Touchpoints__c = (Decimal)g.get('expr0');
            }
        }
        update contactMap.values();
    }
}

First question is why isn't the SELECT counting acxtivities that have been deleted?

Is there a way to get the trigger to see when activities are deleted and refelct that in the ttouchpoint rollups?

Hi Salesforce fellas,

I am still a beginner with Case Triggers and I would like to create an Apex Trigger that would update the children cases everytime the parent case is updated (any update on any field of the Parent).
* To make the parent-child relationship, I just use the standard method and enter the Parent Case number in "Parent Case" field of the Child Case.

The Children Cases would have their following fields updated with the value in the Parent Case:
Status, ClosedDate, Category, SubCategory, SubCategory2, Category_Bank, SubCategory_Bank

I made this Case Trigger  but it just does not work, and it is only when Parent Case ' Status' field is updated to "Closed"
 
trigger updateChildCases on Case (after update) {
  

        List<Case> childrenToUpdate = new List<Case>();
        Set<Id> parentIds = new Set<Id>();
        for(Case p:trigger.new) {
        
            if(p.IsClosed == TRUE) {
                parentIds.add(p.Id);
            }
        }
        if(parentIds.size() > 0) {
            for(Case ch : [SELECT Id, 
            Parent.Status,
            Parent.ClosedDate,
            
            Parent.Category__c,
            Parent.SubCategory_2__c, 
            Parent.SubCategory__c,
            
            Parent.Category_Bank__c,
            Parent.SubCategory_Bank__c  
            
            FROM Case WHERE Parent.Id IN :parentIds
            AND Parent.Status <> NULL
            AND PArent.ClosedDate <> NULL
            
            AND Parent.Category__c <> NULL
            AND Parent.SubCategory__c <> NULL
            AND Parent.SubCategory_2__c <> NULL
            
            AND Parent.Category_Bank__c <> NULL
            AND Parent.SubCategory_Bank__c <> NULL
            ]) {
 
                ch.Status = ch.Parent.Status;                 ch.ClosedDate = ch.Parent.ClosedDate;                 ch.Category__c = ch.Parent.Category__c;                 ch.SubCategory__c = ch.Parent.SubCategory__c;                 ch.SubCategory_2__c = ch.Parent.SubCategory_2__c;                ch.Category_Bank__c = ch.Parent.Category_Bank__c;                ch.SubCategory_Bank__c = ch.Parent.SubCategory_Bank__c;
 
                childrenToUpdate.add(ch);
            } 
Update childrenToUpdate;
            }
        }
my test class is probably incomplete:
@isTest
private class UpdateChildCases_Test {
 
  static testMethod void Test(){
            
    Case curCase = new Case(Status = 'Closed',
    Category__c ='Registration',
    SubCategory__c = 'Open/Reopen Account',
    SubCategory_2__c = 'Create Profile',
    Category_Bank__c = '1',
    SubCategory_Bank__c = '2' );
    insert curCase;
    
    Case curCase2 = new Case(Status='New',ParentId=curCase.Id);
    insert curCase2;

       Test.StartTest(); 
 
    Test.StopTest();
  }
}
(sorry if the code burns your eyes )

I get some code coverage and no error when I save the trigger and the test class, but then when I go back to my cases and try to close a Parent Case it just does not update the Child Case.

Any good soul who could help me with that please?

Thank you very much :)
trigger autoCreateTaskAgent on Agent__c (after insert) {
List <Task> autoTask = new List <Task>();
    List <Agent__c> agentList = new List <Agent__c>();
    //Date today1 = Date.today();
    if(Agent__c.End_Date__c < Date.today())
    {
        System.debug('Hello');
    }
}
Hello and thank you in advance,

I have this trigger: 
 
trigger preventSigAccDeletion on Account (before delete) {
        for(Account acc : trigger.old){
            if( acc.Contact_type__c.contains ('Signatory')
             &&  acc.Status__c == 'Approved'){
           
            
            

acc.adderror('Signatory Accounts cannot be deleted. Please contact administrator if you need it to be deleted or merged');
}}}
Contact_type__c is a multi picklist
Status__c is a standard picklist

When I try to delete record where Contact_type__c is blank then the code throws following error: 
Apex trigger preventSigAccDeletion caused an unexpected exception, contact your administrator: preventSigAccDeletion: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.preventSigAccDeletion: line 3, column 1

Thank you all.

I am trying to exclude an Opportunity Type picklist value when calculating a commission.
My formula is:
IF (NOT(ISPICKVAL(Type, 'Flooring')))
   Total_Amount_Invoiced__c >= 5000.00,
   500.00,
    0.00)
If the Total Amount Invoiced >= 5000.00 for all Opportunity types EXCEPT 'Flooring', return 500.00, if not >=5000.00, return 0.00.


IF ( 
Total_Amount_Invoiced__c >= 5000.00, 
500.00, 
0.00) 
works but need to exclude 'Flooring' and I am stuck. 
 
Hi, 

  In pick list Oppty_Reg_Extension_Request__c  there are two values 

  1. 1st 90 Days Extension
  2. 2nd 90 Days Extension

 User should be able to select first 1st 90 Days Extension and save  only after than he should be able to select 2nd 90 Days Extension

Please let me know how to add this condition in formula. 

Thanks
Sudhir
  • January 25, 2018
  • Like
  • 0
trigger UpdateAEContactActivities on Task (after update) {

set<ID> ContactIds= new Set<ID>();
for(Task tt:trigger.new){
if(UserInfo.getProfileId()=='Standard Sales User'){
    if(tt.Subject.containsIgnoreCase('Call (Completed)') || tt.Subject.containsIgnoreCase('Call (Left Message)') || tt.Subject.containsIgnoreCase('Call (No Answer)') || tt.Subject.containsIgnoreCase('Call (Incoming)') || tt.Subject.containsIgnoreCase('Email - &') || tt.Subject.containsIgnoreCase('LinkedIn') || tt.Subject.containsIgnoreCase('[Sendbloom]')){
        if(tt.Status.equals('Completed')){
            ContactIDs.add(tt.whoID);
        }
    }
}
}

if(ContactIds.isEmpty())
return;

 if(stoprecurssionupdate.runonce()){
List<Contact> cnts= new List<Contact>();
Integer number1=1;
for(Contact ct:[select id, name, AE_Activities_Counter__c  from Contact where id in:Contactids])
{

if(ct.AE_Activities_Counter__c ==null)
ct.AE_Activities_Counter__c=0;
ct.AE_Activities_Counter__c=ct.AE_Activities_Counter__c+number1;
cnts.add(ct);
}

if(cnts.size()>0)
{
update cnts;
}
}}

The code keeps returning an error on line 5...  I know I don't have the syntax correct....
Hii,
    could we able convert lead to oppurtunity,if we have no access to oppurtunity objects?Please clarify my doubt.

Thanks in advance,
Varshitha
When deploying from sandbox to prod, my custom fields in my change set are coming through hidden.  Even if I make the fields accessible to all profiles in sandbox, even an admin cannot see them by default in prod.  I then have to go and change the settings in prod for each individual field for them to show.  I have not been exporting the profile settings from sandbox.  Is it best practice to do so when you deploy?

Thanks
Hi all,

I have a Parent (Contact) and Child ( Program Enrollments).  A Contact can have multiple Program Enrollments and Each of them can have a different Program Name. I want to filter the contacts that have Program Enrollments with Program Name = "VWISE" but not have Program Enrollments with Program Name= "EBV".

How can I achieve this??

I appreciate your time and help!

Best,
Amrutha
Hi,
I have completed the challenge,i got Compass of Wisdom badge, but the Cloak of Adventure badge hasn't appeared and no information about the sweatshirt.

What do I need to do?

Thanks
Anil.B

Hi guys,

 

I had a validation rule which throughs error when the previous value in a field  is 2012 and the new value is 2013.

And Stage Name is withdrawn.it work fines with my validation rule. but i want to simplify it .

here is my validation rule:-

 

AND($Profile.Name = "Custom System Admin",
ISPICKVAL(StageName,"Prospecting"),
OR(AND(ISPICKVAL(PRIORVALUE(DeliveryInstallationStatus__c),"Jan 2012"), ISPICKVAL(DeliveryInstallationStatus__c,"Jan 2013")),
AND(ISPICKVAL(PRIORVALUE(DeliveryInstallationStatus__c),"Jan 2012"), ISPICKVAL(DeliveryInstallationStatus__c,"sep 2013")),
AND(ISPICKVAL(PRIORVALUE(DeliveryInstallationStatus__c),"sep 2012"), ISPICKVAL(DeliveryInstallationStatus__c,"Jan 2013")),
AND(ISPICKVAL(PRIORVALUE(DeliveryInstallationStatus__c),"Sep 2012"), ISPICKVAL(DeliveryInstallationStatus__c,"sep 2013"))))

 

What i need instead of using  (ISPICKVAL(PRIORVALUE(DeliveryInstallationStatus__c),"Jan 2012")

like this can i using like this (ISPICKVAL(Contains(PRIORVALUE(DeliveryInstallationStatus__c),"2012"), ISPICKVAL(DeliveryInstallationStatus__c,"2013")) .

 

The Above code has 4 conditions if i use include or contains then it can be of 2 condition.

 

Thanks

Anil.B

 

Hi guys,

 

I have a custom object which have five fields mandatory.

And a picklist field with six values .

when i select the value in this picklist then the record type with that name should open up.

is it possible in the standard functionality.

 

 

Thanks

Anil.B

Hi guys,

 

I have written a trigger to insert a custom objects record which are linked with lead to attch contact and opportunity on lead conversion.

But it is hitting soql limit on bulk Conversion.

Due to soql in for loop.

Please help from this problem.

 

 

trigger Commentsonconvert on Lead (after update,after insert) {
 Lead ld;
  List<Comments__c> Com = new List<Comments__c>();
 
  for(Lead l: Trigger.New){
      ld=l;
  
  if(ld.isConverted == true){  
   list <Comments__c>cs=[Select id,Contact__c, Opportunity__c from Comments__c where Lead__c=:ld.id];               
      for (Comments__c comTemp :cs ){
          comTemp.Opportunity__c = ld.ConvertedOpportunityId;
          if(ld.lastname!=null){
              comTemp.Contact__c=ld.ConvertedContactId;
          }
          Com.add(comTemp);
      }
  }
}
  if(Com !=null) update Com;
  
}

 

Thanks

Anil.B

Hi guys.

 

I have batch calss name:Del_leads

and a Schedule Class bulkdelleads.

 

When i am writing test method for batch class it is not covering the execute method i am calling this execute from schedule class.Can any body help to figure out the problem.

 

Batch Class:-

=====================

global class Del_leads implements Database.Batchable<sobject>
{

public String query;
public date d=System.today();
public integer i=7;
Public Date z=d-i;
Public String s;
public integer j;
Public string k='Name'+','+'Company'+','+'phone'+','+'Email';

global Database.QueryLocator start(Database.BatchableContext BC){
system.debug(query);
return Database.getQueryLocator(query);

}

global void execute(Database.BatchableContext BC,List<Lead> Lds){
for( j=0;j<lds.size();j++){
if(j==0){
s +=k+'\n'+ lds[j].Name+','+lds[j].Company+','+lds[j].phone+','+lds[j].Email;
} else{
s +=+'\n'+ lds[j].Name+','+lds[j].Company+','+lds[j].phone+','+lds[j].Email;
}
}

Blob b=Blob.valueOf(s);
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('attachment.csv');
efa.setBody(b);

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {'franktoanil@gmail.com'});
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Please find the attachment of deleted records');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
delete Lds;
}

global void finish(Database.BatchableContext BC){
System.debug(LoggingLevel.WARN,'Deleting Leads Finished');
}

=====================================================
/*-----------------Test Method-----------------Only 47 % test coverage*/

=====================================================
public static testMethod void Del_leads (){
List <Lead> lds = new List<Lead>();
for(integer i = 0; i<200; i++){
Lead l = new Lead(LastName='Anil',Company='ef');
lds.add(l);
}
insert lds;

test.startTest();
Del_leads dl = new Del_Leads();
dl.query='select id,Name,Company,Phone,Email from lead where createddate<=:z and date_opened__c=null ';
ID batchprocessid = Database.executeBatch(dl);
test.stoptest();
System.AssertEquals(
database.countquery('SELECT COUNT()'+' FROM Lead '),200);
}
}

============================

Schedule Class

============================

global class bulkdelleads Implements Schedulable{
public static String CRON_EXP = '0 0 0 3 9 ? 2022';
global void Execute(SchedulableContext SC){

Del_leads ld=new Del_leads();
ld.query='select id,Name,Company,Phone,Email from lead where createddate<=:z and date_opened__c=null ';
database.executebatch(ld);

}

==================================

/*----------Test Method------------------ 100% test Coverage-*/

==================================
static testmethod void bulkdelleads () {
Test.startTest();

Lead l = new Lead ();
l.LastName = 'Raghu ';
l.company='eg';
insert l;

// Schedule the test job

String jobId = System.schedule('bulkdelleads ',bulkdelleads.CRON_EXP,new bulkdelleads ());
// Get the information from the CronTrigger API object

CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
NextFireTime
FROM CronTrigger WHERE id = :jobId];

// Verify the expressions are the same

System.assertEquals(bulkdelleads.CRON_EXP,ct.CronExpression);

// Verify the job has not run

System.assertEquals(0, ct.TimesTriggered);

// Verify the next time the job will run

System.assertEquals('2022-09-03 00:00:00',
String.valueOf(ct.NextFireTime));

Test.stopTest(); 

}

}

 

Thanks

Anil.B

 

Hi guys,

 

I have a batch class which delete records from lead.

Before deleting these records i want all the query records should be send as a attchment to a email.

Is it possible.

-----Batch Class---

global class Del_leads implements Database.Batchable<sobject>
{
  
   public String query;  
   public date d=System.today();
   public integer i=7;
   Public Date z=d-i;
   String email;
  
   global Database.QueryLocator start(Database.BatchableContext BC){
      system.debug(query);
      return Database.getQueryLocator(query);
   }
   
   global void execute(Database.BatchableContext BC,List<Lead> Lds){
       delete Lds;       
   }  
   
   global void finish(Database.BatchableContext BC){
   
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();        
        mail.setToAddresses(new String[] {'anil@gmail.com'});
        mail.setReplyTo('batch@acme.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');        
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        System.debug(LoggingLevel.WARN,'Deleting leads Finished');
   }
}

---------------------------------------------------------------Schedule class----------------

global class bulkdelleads Implements Schedulable{
global void Execute(SchedulableContext SC){

Del_leads ld=new Del_leads();
ld.query='select id,name from lead where createddate<=:z and date_opened__c=null limit 10';
database.executebatch(ld);


}
}

 

Before Delete operation iwant to send All the ld.query records as attachment to a email.

 

 

 

Thanks
Anil.B

 

 

 

 

Hi guys,

 

can u help me in the query.

-----Batch Class---------

 

global class Del_leads implements Database.Batchable<sobject>
{

date d=system.today();
integer i=7;
date z=d-i;
global Database.QueryLocator start(Database.BatchableContext BC)
{

return Database.getQueryLocator('select id,name from lead where createddate<=\'z\' and date_opened__c=null');
}

global void execute(Database.BatchableContext BC,List<Lead> Lds)
{
delete Lds;
}
global void finish(Database.BatchableContext BC)
{
System.debug(LoggingLevel.WARN,'Deleting leads Finished');
}
}

-----------Schedule class-------------------------------

global class bulkdelleads Implements Schedulable{
     global void Execute(SchedulableContext SC){      
        
        Del_leads ld=new Del_leads();
       database.executebatch(ld);     
           
     }
}

 

Thanks

Anil.B

hi guys ,

 

i am using a page block section for creating new and edit when creating new it works fine.

when editing the record its creating another record .Iam using upsert on the save button .

-------------Controller-------------------------

Public Class lComments{
public lead l {get;set;}
public list<Comments__c> Com{get; set;}
public Comments__c c{get;set;}
public Boolean property {get; set;}
public Boolean showblock{get;set;}
public Boolean hidebutton{get;set;}
public String SelId { get; set; }
public String delid{get;set;}
id str{get;set;}
public map<id,comments__c> mpid{get;set;}

public LComments(ApexPages.StandardController controller) {
l=(Lead)controller.getRecord();
str=Apexpages.currentpage().getparameters().get('id');
property=false;
hidebutton=true;
c=new Comments__c();
loaddata();
}
public void loaddata(){
com=[select id,name,lead__c,Contact__c,Opportunity__c,Finance__c,Comments_text__c,lead__r.Name ,Role__c ,CreatedDate from comments__c  where lead__c=:str order by CreatedDate desc limit 1000];
mpid=new map<id,Comments__c>([Select id, name from comments__c where id =:selid ]);
for(comments__c d:com){
mpid.put(d.id,d);

}
}

public PageReference save1(){
Comments__c c=new Comments__c(Name=c.Name,Comments_text__c=c.Comments_text__c,Lead__c=str);
upsert c;
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
pageRef.setRedirect(true);
return pageRef;
}

public Comments__c getc(){
property=true;
hidebutton=false;
c=new comments__c();
return null;
}

Public void edit1(){
Property=true;
c=New Comments__c();
if(mpid.containsKey(SelId)){
c.Name=mpid.get(SelId).Name;
c.Comments_text__c=mpid.get(SelId ).Comments_text__c;
}

}

public Comments__c del1(){
Com=[select id from comments__c where id=:delid];
if(com.size()>0){
delete com;
}
loaddata();
return null;

}
}

----------------------Vf page----------------------------------------

--------
<apex:page standardController="Lead" extensions="lComments" >
<apex:form id="main" >
<table border="5">
<tr><td>
<div style="overflow: auto; height: 250px; width:500px;">
<apex:outputText value="{!Lead.Name}" style="font-size:12px;"/>
</div>
</td><td>
<div style="overflow: auto; height: 250px; width:500px;" >

<div id="parentdiv" style="text-align:center;width:30px;margin:auto;">
<apex:commandButton value="New" action="{!getc}" reRender="main,ref" rendered="{!hidebutton}" />
</div>

<apex:pageBlock rendered="{!Property}" id="ref" >
<apex:pageBlockSection columns="1" >
<apex:inputField value="{!c.Name}" required="true" />
<apex:inputField value="{!c.Comments_text__c}" style="width:380px;height:100px" />
</apex:pageBlockSection>
<apex:pageBlockButtons location="Bottom">
<apex:commandbutton action="{!Save1}" title="Save" value="Save" />
<apex:commandbutton action="{!cancel}" title="cancel" value="Cancel" onclick="window.history.previous()" />
</apex:pageBlockButtons>
</apex:pageBlock>

<apex:pageBlock >
<apex:pageBlockTable value="{!Com}" var="p" style="table-layout:fixed;" >

<apex:column width="100px" >
<apex:commandLink value="Edit" action="{!edit1}" reRender="main,ref" >
<apex:param name="cid" value="{!p.id}" assignTo="{!selid}"/>
</apex:commandlink>
&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandLink value="Del" action="{!del1}" reRender="main">
<apex:param name="cid" value="{!p.id}" assignTo="{!delid}"/>
</apex:commandLink>
</apex:column>

<apex:column style="overflow: hidden;">
<apex:facet name="header">Name</apex:facet>
{!If(LEN(p.Name)<25,p.Name,LEFT(p.Name,25))}
</apex:column>

<apex:column style="overflow: hidden;height:20px; ">
<apex:facet name="header">Comments</apex:facet>
{!If(LEN(p.Comments_text__c)<100,p.Comments_text__c,LEFT(p.Comments_text__c,100))}
</apex:column>
<apex:column value="{!p.Role__c}" />
<apex:column value="{!p.Lead__c}" />
<apex:column value="{!p.CreatedDate}" />
</apex:pageBlockTable>
</apex:pageBlock>
</div>
</td></tr>
</table>
</apex:form>
</apex:page>

------------------

Thanks

Anil.B

 

 

Hi guys,

I am using  a Vf page on lead.

in that iam using a page block section which opens two input fields when u click new button.

when we enter values and save it stores in a data table in the same page .

For ever record iam using edit and del option in the page block table.

when i click edit  i want use the new button( page block section) but the value should be populated from the selected record.

how to do this.

------------------------------------------------------------

on  new button:- this page block will open

<apex:pageBlock rendered="{!Property}" id="ref" >

           <apex:pageBlockSection columns="1" >

               <apex:inputField value="{!c.Name}" required="true" />

               <apex:inputField value="{!c.Comments__c}" style="width:380px;height:100px" />

           </apex:pageBlockSection>

           <apex:pageBlockButtons location="Bottom">

               <apex:commandbutton action="{!Save1}" title="Save" value="Save" />

               <apex:commandbutton action="{!cancel}" title="cancel" value="Cancel" onclick="window.history.previous()" />            </apex:pageBlockButtons>

        </apex:pageBlock>

-----------------------------------------------------

After entering values it stores the record in this section.

<apex:pageBlock >
<apex:pageBlockTable value="{!Com}" var="p" style="table-layout:fixed;" >

<apex:column width="100px" >
<apex:commandLink value="Edit" action="{!edit1}" reRender="main,ref" >
<apex:param name="cid" value="{!p.id}" assignTo="{!selid}"/>
</apex:commandlink>
&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandLink value="Del" action="{!del1}" reRender="main">
<apex:param name="cid" value="{!p.id}" assignTo="{!delid}"/>
</apex:commandLink>
</apex:column>

<apex:column style="overflow: hidden;">
<apex:facet name="header">Name</apex:facet>
{!If(LEN(p.Name)<25,p.Name,LEFT(p.Name,25))}
</apex:column>

<apex:column style="overflow: hidden;height:20px; ">
<apex:facet name="header">Comments</apex:facet>
{!If(LEN(p.Comments__c)<100,p.Comments__c,LEFT(p.Comments__c,100))}
</apex:column>

<apex:column value="{!p.Role__c}" />
<apex:column value="{!p.Lead__c}" />
<apex:column value="{!p.CreatedDate}" />

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

 

When i click edit command link it should open up the top section with the selected record values.and when i save it should update the record.

------------------------------------------------------------------------------------------------------------------------------

My controller:-

 

Public Class lComments{
public lead l {get;set;}
public list<Comments__c> Com{get; set;}
public Comments__c c{get;set;}
public Boolean property {get; set;}
public Boolean hidebutton{get;set;}
public string SelId { get; set; }
public String delid{get;set;}
id str{get;set;}
map<id,String>mpid=new map<id,String>();

public LComments(ApexPages.StandardController controller) {
l=(Lead)controller.getRecord();
str=Apexpages.currentpage().getparameters().get('id');
property=false;
hidebutton=true;
c=new Comments__c();
loaddata();

}
public void loaddata(){
com=[select id,name,lead__c
,Contact__c
,Application__c
,Finance__c
,Comments__c
,lead__r.Name
,Role__c
,CreatedDate
from comments__c
where lead__c=:str order by CreatedDate desc limit 1000];

}
public PageReference save1(){
Comments__c c=new Comments__c(Name=c.Name,Comments__c=c.comments__c,Lead__c=str);
insert c;
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
pageRef.setRedirect(true);
return pageRef;
}

public Comments__c getc(){
property=true;
hidebutton=false;
c=new comments__c();
return null;
}
Public comments__c edit1(){
com=[select id,Name,Comments__c,Role__c,Lead__c,createddate from Comments__c where id=:selid];

return null;


}

public Comments__c del1(){
Com=[select id from comments__c where id=:delid];
if(com.size()>0){
delete com;
}
loaddata();
return null;
}

}

 

 

 

Thanks

Anil.B

hi guys,

This trigger has 100% test coverage before after adding one condition it decreased .

help me in increasing the test coverage.

 
trigger Updtcon on comments__c (before insert) {
Set<Id> sobjectSetOfIds = new Set<Id>();
Set<Id> sobjectSetOfctctIds = new Set<Id>();
Set<Id> sobjectSetOffinIds = new Set<Id>();

Comments__c cms;
opportunity opp;
UserRole ur = [ select Id, Name FROM UserRole where Id =:Userinfo.getUserroleid()];


for(Comments__c cs:trigger.New){
cms=cs;
if(cms.Opportunity__c!=null && cms.Contact__c==null && cms.finance__c==null){
sobjectSetOfIds.add(cms.Opportunity__c);
}
if(cms.Opportunity__c==null && cms.Contact__c!=null && cms.finance__c==null){
sobjectSetOfctctIds.add(cms.Contact__c);
}
if(cms.Opportunity__c==null && cms.Contact__c==null && cms.finance__c!=null){
sobjectSetOffinIds.add(cms.Finance__c);
}
}
/* updating contact and finance from opportunity object comments related list*/
if(!sobjectSetOfIds.ISEmpty())
{
Map<Id,Opportunity>smap= new Map<Id, Opportunity>([Select id,Name,Borrower__c,(Select id,name from Finances__r) from Opportunity where Borrower__r.RecordType.name=:'Applicant' AND Id in : sobjectSetOfIds ]);

for(Comments__c s: trigger.new){
if(smap.containsKey(s.Opportunity__c)){ 
s.Contact__c=smap.get(s.Opportunity__c).Borrower__c;
if(smap.get(s.Opportunity__c).finances__r.size()>0){
s.Finance__c=smap.get(s.Opportunity__c).finances__r[0].id;
}
s.Comment_Created_from__c ='Opportunity ::'+ ' '+smap.get(s.Opportunity__c).Name;
s.written_by__c='Opportunity';//UserInfo.getName();
s.Written_date__c=system.Today();
s.Role__c=ur.name;
}
}
}

/* updating opportunity and finance from contact object comments related list*/
if(!sobjectSetOfctctIds.ISEmpty()){
List<Opportunity> opportunities = [select Id,Borrower__c, Name,Borrower__r.Name,(Select id,name,contact__c from Finances__r )from Opportunity where Borrower__r.RecordType.name=:'Applicant' AND Borrower__c in:sobjectSetOfctctIds ];
map<string,string> mpcopid=new map<string,string>();
map<string,string> mpcopname=new map<string,string>();
map<string,string> mpfinid=new map<string,string>();
for(Opportunity oppn:opportunities){
mpcopid.put(oppn.Borrower__c,oppn.Id);
mpcopname.put(oppn.Borrower__c,oppn.Borrower__r.Name);
if(oppn.finances__r.size()>0){mpfinid.put(oppn.Borrower__c,oppn.Finances__r[0].Id);}


}
for(Comments__c s: trigger.new){
if(mpcopid.containsKey(s.Contact__c))
{
s.Opportunity__c=mpcopid.get(s.Contact__c);
if(mpfinid.ContainsKey(s.Contact__c)){s.Finance__c=mpfinid.get(s.Contact__c);}
s.Comment_Created_from__c ='Contact :: '+mpcopname.get(s.Contact__c);
s.written_by__c='Contact';//UserInfo.getName();
s.Written_date__c=system.Today();
s.Role__c=ur.name;
}
}
}



/* updating opportunity and contact from finance */
if(!sobjectSetOffinIds.ISEmpty()){
Map<id,Finance__c> fc =new Map<id, Finance__c>([select id,Name,Opportunity__r.id,Opportunity__r.Borrower__r.id from Finance__c where id in:sobjectSetOffinIds]);
for(Comments__c cs:trigger.New){
if(fc.containsKey(cs.Finance__c)){
cs.Opportunity__c=fc.get(cs.Finance__c).opportunity__r.id;
cs.Contact__c=fc.get(cs.Finance__c).Opportunity__r.Borrower__r.id;
cs.Comment_Created_from__c='Finance::'+''+fc.get(cs.Finance__c).Name;
cs.written_by__c='Finance';//UserInfo.getName();
cs.Written_date__c=system.Today();
cs.Role__c=ur.Name;

}
}
}
}

After adding the condition in red line then the code is not getting covered which is in brown,

test Method:-

-----------------------------------------------

@isTest
private class Updtcon {
static testMethod void Updtcon () {



Contact C= new contact(LastName='Anil');
insert c;

Opportunity o=new opportunity(name='Anil',StageName='prospecting',CloseDate=system.today(),Borrower__c=c.id);
insert o;

Finance__c f=new finance__c(Name='payment',opportunity__c=o.id,Contact__c=o.Borrower__r.id);
insert f;

Comments__c cm=new comments__c(Name='Raghu',Contact__c=c.id);
insert cm;

comments__c cms=new comments__c(Name='Anil',opportunity__c=o.id);
insert cms;

Comments__c cs=new comments__c(Name='Anil',Finance__c=f.id);
insert cs;

}
}

 

Thanks

Anil.B

Hi guys,

 

can u plz help me to increase my test coverage from 59 to 100%

The code in red lines are not  covered in the test class

 

trigger code:-

=======================================================================================

 

trigger Updtcon on comments__c (before insert) {
 Set<Id> sobjectSetOfIds = new Set<Id>();

    Comments__c cms;
    opportunity opp;   
        
 
    for(Comments__c cs:trigger.New){
        cms=cs;    
        if(cms.Opportunity__c!=null && cms.Contact__c==null && cms.Finance__c==null){
            sobjectSetOfIds.add(cms.Opportunity__c);           
        }
    } 
    Map<Id,Opportunity>smap= new Map<Id, Opportunity>([Select id,Name,Borrower__c,(Select id,name from Finances__r)  from Opportunity where Id in : sobjectSetOfIds]);
                
    for(Comments__c s: trigger.new){
        if(smap.containsKey(s.Opportunity__c)){        
            s.Contact__c=smap.get(s.Opportunity__c).Borrower__c;  
            if(smap.get(s.Opportunity__c).finances__r.size()>0&&smap.get(s.Opportunity__c).finances__r!=null){            
            s.Finance__c=smap.get(s.Opportunity__c).finances__r[0].id; 
            }
            s.Comment_Created_from__c ='Opportunity  ::'+ '  '+smap.get(s.Opportunity__c).Name;
            s.written_by__c=UserInfo.getName();
            s.Written_date__c=system.Today();
        }
    }
    
    /* updating opportunity from contact object comments related list*/  

   for(Comments__c cs:trigger.New){
        cms=cs;    
        if(cms.Opportunity__c==null && cms.Contact__c!=null && cms.Finance__c==null){
           List<Opportunity> opportunities = [select Id, Name,Borrower__r.Name,(Select id,name,contact__c from Finances__r )from Opportunity where Borrower__r.Id  = :cms.Contact__c];         
        
           for(Opportunity oppn:opportunities){                        
               cs.Opportunity__c = oppn.id;
               if(oppn.finances__r.size()>0){           
               cs.Finance__c=oppn.finances__r[0].id;
               }
               cs.Comment_Created_from__c ='Contact ::'+'  '+ oppn.Borrower__r.Name;
               cs.written_by__c=UserInfo.getName();
               cs.Written_date__c=system.Today();
             
            }
        }
     }  
     
   /* updating opportunity and contact from finance */
   
   for(Comments__c cs:trigger.New){
        cms=cs; 
        if(cms.Finance__c!=null & cms.Contact__c==null&& cms.Opportunity__c==null){
            List<Finance__c> fc=[select id,Name,Opportunity__r.id,Opportunity__r.Borrower__r.id from Finance__c where id=:cms.Finance__c];
            for(finance__c f:fc){
                cs.Opportunity__c=f.opportunity__r.id;
                cs.Contact__c=f.Opportunity__r.Borrower__r.id;
                cs.Comment_Created_from__c ='Finance  ::'+'  '+ f.Name;
                cs.written_by__c=UserInfo.getName();
                cs.Written_date__c=system.Today();
            }
        }
   }

=======================================================================================

test class:-

=======================================================================================

@isTest
private class Updtcon {
static testMethod void Updtcon () {

Contact C= new contact(LastName='Anil');
insert c;

list<opportunity> o=new list <opportunity>();
for(integer i=0;i<200;i++){
Opportunity oppn=new opportunity(name='Anil',StageName='prospecting',CloseDate=system.today(),Borrower__c=c.id);
o.add(oppn);
}
insert o;

// System.assertEquals(1,o.size());

Finance__c f=new finance__c(Name='payment',opportunity__c=o[0].id,Contact__c=o[0].Borrower__r.id);
insert f;

comments__c cms=new comments__c(Name='Anil',opportunity__c=o[0].id,Contact__c=o[0].Borrower__r.id);
insert cms;

}
}

============================================================================================

 

Thanks

Anil.B

 

Hi guys,

 

please help me to come out of this error.

 

for(Comments__c cs:trigger.New){
cms=cs;
if(cms.Opportunity__c==null && cms.Contact__c!=null ){
sobjectSetOfIds.add(cms.Contact__c);
}
}

Map<Id,Contact>smap1= new Map<Id, Contact>([Select id
,Name
,(select id ,Name from opportunities limit1)
from Contact
where Id in : sobjectSetOfIds]);

for(Comments__c s: trigger.new){
if(smap1.containsKey(s.Contact__c)){
s.Opportunity__c=smap1.get(s.Contact__c).Opportunities__r[0].id;  //Error
}
}

 

Thanks

Anil.B

hi guys,

 

Please help me in with the query.

My contact will have only one opportunity  1-1 relation ship:-1 account ,1 contact 1, opportunity.

 

  for(Comments__c cs:trigger.New){
        cms=cs;    
        if(cms.Opportunity__c==null && cms.Contact__c!=null ){
            sobjectSetOfIds.add(cms.Contact__c);           
        }
    }   
    
    Map<Id,Contact>smap1= new Map<Id, Contact>([Select id
                                                        ,Name
                                                        ,Opportunities__r.id // error  
                                                         from Contact 
                                                         where Id in : sobjectSetOfIds]);
                
    for(Comments__c s: trigger.new){
        if(smap1.containsKey(s.Contact__c)){        
            s.Opportunity__c=smap1.get(s.Contact__c).Opportunities.id;    //error
                
        }
    }

 

Thanks

Anil.B

 

Hi Guys

 

I like to have print option on schema builder.

 

who ever thinks so its a gud option. please support by voting.

 

Vote for this option by click the link

 

https://sites.secure.force.com/success/ideaView?id=08730000000iHEZAA2

 

 

Thanks 

Anil.B

 

 

Hi guys,

 

please help me in this case.

 

I am working with contact object .There is a lookup field called spouse on to contact.(self lookup). 

Here if a contact record name='Daniel'.

And spouse in the record of daniel is 'Mary'.

if i click mary lookup feild the daniel should be the spouse in the mary record.

it means the lookup value should change vice versa.

 

How can i achieve this with trigger plz help me with the trigger.

 

 

Thanks

Anil.B

Hi all,

 

iam facing problem using visual force page in my lead there a re four record types

one,two,three,four.

if i click new button->then it shows the record type selection page->then i select one ->it redirects to a visual force page name leadTest. because i over ridden new button with visual force page.

 

if i click two it should go to a standard page record type for two and a page layout is also assigned for it.

 

if i click three it should go to a standard page record type for three and a page layout is also assigned for it.

 

same like for four.

 

but here it is not redirecting to the standard page when iam passing the url in my controller .

 

can any help me. my code is:-

 

visualforce page  

<apex:page StandardController="Lead" tabStyle="Lead" extensions="LeadController" action="{!redirectToPage}" >

 

Controller Method

 public PageReference redirectToPage() {
     
        String selectedRecordType = ApexPages.currentPage().getParameters().get('RecordType');
        if (selectedRecordType == 'One')// id will be there
            return Page.LeadTest.setRedirect(True);        
        else if(selectedRecordType == 'Two')
            return  new PageReference('/00Q/e?retURL=%2F00Q%2Fo&RecordType=012O00000000Acd&ent=Lead');
          else if(selectedRecordType == 'Three')
            return  new PageReference('/00Q/e?retURL=%2F00Q%2Fo&RecordType=012O00000000Acn&ent=Lead');

         else if(selectedRecordType == 'four')
            return  new PageReference('/00Q/e?retURL=%2F00Q%2Fo&RecordType=012O000000003ds&ent=Lead');   
        else
            return null;
    }

Hi all,

 

iam facing problem using visual force page in my lead there a re four record types

one,two,three,four.

if i click new button->then it shows the record type selection page->then i select one ->it redirects to a visual force page name leadTest. because i over ridden new button with visual force page.

 

if i click two it should go to a standard page record type for two and a page layout is also assigned for it.

 

if i click three it should go to a standard page record type for three and a page layout is also assigned for it.

 

same like for four.

 

but here it is not redirecting to the standard page when iam passing the url in my controller .

 

can any help me. my code is:-

 

visualforce page  

<apex:page StandardController="Lead" tabStyle="Lead" extensions="LeadController" action="{!redirectToPage}" >

 

Controller Method

 public PageReference redirectToPage() {
     
        String selectedRecordType = ApexPages.currentPage().getParameters().get('RecordType');
        if (selectedRecordType == 'One')// id will be there
            return Page.LeadTest.setRedirect(True);        
        else if(selectedRecordType == 'Two')
            return  new PageReference('/00Q/e?retURL=%2F00Q%2Fo&RecordType=012O00000000Acd&ent=Lead');
          else if(selectedRecordType == 'Three')
            return  new PageReference('/00Q/e?retURL=%2F00Q%2Fo&RecordType=012O00000000Acn&ent=Lead');

         else if(selectedRecordType == 'four')
            return  new PageReference('/00Q/e?retURL=%2F00Q%2Fo&RecordType=012O000000003ds&ent=Lead');   
        else
            return null;
    }

Hi friends

 

            iam creating a record in custom object name loan from opportunity.when the opportunity stage is sourcing it should create a record in loan but its creating duplicate records.please help me in this.

 


 

 trigger lol on Opportunity (after update) {
    List<loans__c>ln=new List<loans__c>();
    
    for(opportunity o:Trigger.New){
        
        if(((Trigger.IsInsert)||(Trigger.isUpdate)&& (Trigger.oldmap.get(o.id).StageName!='Sourcing'))&& (o.StageName=='Sourcing'))
        {
        loans__c l=new loans__c(Name=o.Name,Approval_Status__c=o.StageName,Opportunity__c=o.Id);
        ln.add(l);
        }
        try{
        insert ln;
        }
        catch(system.DmlException e){
        System.debug(e);
        }
        }


}


 

Thanks

 

Anil

List<Account> acc = New List<Account>;

 

In this case salesforce allocated how much memory to <new list>

How to get the memory allocated for the new list;

 

public class NewBankController {

    public List<Bank_Rates__c> brSearchOutput { get; set; }
    public List<Bank_Rates__c> brEmailSearchOutput { get; set; }
    public Bank_Rates__c bank {get; set;}
    String leadId;
    public String[] inputBanks;
    public Lead thisLead{get; set;}
    public DisplaySearch displayOptions {get; set;}
    Datetime dt = system.today();
    string dtFrmt = dt.format('dd MMM yyyy');
     
    //Email variables
    
    public String subject{ get; set; }
    public String emailBody { get; set; }
    private String myErrMessage;
    private String fileName='';
    

    public NewBankController(){
        bank = new Bank_Rates__c();       
        displayOptions = new DisplaySearch();
        leadId = ApexPages.currentPage().getParameters().get('leadId');
        setSearchResults();
    }
    
    public Bank_Rates__c getBank() {
        if(bank == null) bank = new Bank_Rates__c();
        return bank;    
    }
    
    /*
    Method used to fetch search results
    of the given query
    */
    public PageReference search(){
        searchOutput();             
        return Page.NextStep;
    }
    
    public void setSearchResults(){
        leadId = ApexPages.currentPage().getParameters().get('leadId');
        thisLead=[Select id, Email, Name, Property_use__c, Employment__c, Product_Name__c, City_of_work__c,
            City_of_property__c, Residency_Status__c, Loan_Requested_SAL__c, Company_type__c, Loan_Tenure_Requested__c,                                                                             
            Depriciation_co_y1__c, Gross_Profit_co_y1__c, itr_co_y1__c, Prop_total_Cost__c, Prop_Const_Stage__c,
            Prop_Purchase_from__c, Prop_Purchase_Through__c, Prop_Location__c, Prop_occupancy__c, Prop_Age__c,
            type_of_industry__c, Salary_gross__c, Banking_individual__c, Bank_company__c,
            Rented_to1__c, Lessee_name1__c, Lease_amount1__c, Lease_Term__c, Lease_due_term1__c, Prop_Type__c      
        from lead where
        id=:leadId];
        
        setSearchInput(thisLead);
    }
    
    public void setSearchInput(Lead thisLead){
        bank.Product_Name__c = thisLead.Product_Name__c;
        bank.Property_use__c = thisLead.Property_use__c;
        bank.City_of_work__c = thisLead.City_of_work__c;
        bank.City_of_property__c = thisLead.City_of_property__c;
      
    }     
    
    public void searchOutput(){
        String[] inputtypeOfLoan;
        String[] inputBanks;
        if(bank.Type_of_Loan__c!=null)
            inputtypeOfLoan=bank.Type_of_Loan__c.Split(';');  
           
        if(bank.Banks_list__c!=null)       
            inputBanks = bank.Banks_list__c.Split(';');
            
        fileName = thisLead.Name + '-' + dtFrmt + '';
            subject ='ACC__c;
            emailBody = 'Dear ' + thisLead.Name + ',\n\n' +
                        'Please find enclosed our proposal for your kind perusal.' + '\n' +
                        'Do let us know if you require any further information or assistance in this context,' + '\n' +
                        'we would be more than happy to be at your service' + '\n\n\n' +
                        'Yours truly, \n'+ UserInfo.getName();      
            
                
        brSearchOutput =  [ Select id, Name, Max_Loan_Amount__c, Min_Loan_Amount__c, Max_Tenure__c,
            Min_Tenure__c, Type_of_Loan__c, Employment__c, Slab_Rates__c, ADF__c, Bank_Name__c, Product_Name__c,
            ANCIL_CHG__c, Base_Rate__c, Franking_Fee__c, Funding_Upto__c, Mort__c,Teaser_Fixed__c,
            Insurance__c, P__c, PreClosure__c, Proc_Fee_incl_tax__c, Project_Approved__c, Prop_Type__c,
            Rate_Std__c, Rate_OD_Loan__c, Bank_Selection__c, Display_Banks__c
            
            from Bank_Rates__c
            
            where      
            ((Max_Loan_Amount__c<=:bank.Loan_Requested_SAL__c
            or Min_Loan_Amount__c>=:bank.Loan_Requested_SAL__c )
            and Type_of_Loan__c in :inputtypeOfLoan
            and Bank_Name__c  in :inputBanks )
            and ((Employment__c in  (:bank.Employment__c))
            or (Employment__c='General'))                          
            ];
    }
    
    public PageReference emailStep(){
        setEmailDataTable();         
        return Page.AnilTest;    
       
    }
    
    public void setEmailDataTable(){
        brEmailSearchOutput = new List<Bank_Rates__c>();
        for(Bank_Rates__c br:brSearchOutput)
            if(br.Bank_Selection__c==true){
                brEmailSearchOutput.add(br);
            }  
        }
        
     //function used to send the proposal email
    public PageReference send() {
        
        // Define the email  
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        // Reference the attachment page and pass in the Meeting Fee ID
        PageReference pdf =  Page.SearchCriteriaProposal;
        pdf.getParameters().put('leadId',thisLead.Id);
        pdf.setRedirect(true);
        
        // Take the PDF content
        Blob b ;
        try {
            b= pdf.getContent();
        }catch(VisualforceException e){
            b=Blob.valueOf('Error occured while Generating PDF');
        
        }
        // Create the email attachment
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName(fileName);
        efa.setBody(b);
        efa.setInline(false);
        efa.setContentType('application/pdf');
        // Sets the paramaters of the email  
        String addresses;
        if (thisLead.Email != null){
            addresses = thisLead.Email ;        
        }
        
        String []toAddresses = addresses.split(':', 0);
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody(emailBody);
        email.setUseSignature(false);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
        
        // Sends the email  
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
        
        /* create the attachment against the quote */
        Attachment a = new Attachment(parentId = thisLead.id, name=thisLead.Name + '.pdf', body = b);
          
        /* insert the attachment */
        insert a;        
        return new PageReference('/'+thisLead.Id);
    }   
      //Test Method
    public static testMethod void testNewBankController(){
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'rii1', email='standarduser@testorg.com',        
        emailencodingkey='UTF-8', lastname='RII', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,timezonesidkey='America/Los_Angeles', username='rixyncsindiainc@testorg.com');
        insert u;  
      
        Bank_Rates__c br=new Bank_Rates__c();
        ApexPages.StandardController sc = new ApexPages.standardController(br);
        NewBankController myPageCon = new NewBankController( );
       
         
     }     
 }

While deploying Workflow Email alert showing error as User doesn;t exist in target Org. How to resolve this error?
I need to tweak the code to any Task that contains the word Pardot will be deleted. I'm not a developer so any assistance will be appreciated. Thanks so much. 

Apex Class
public class TaskDeleteBatch implements Database.Batchable<sObject>{
    public Database.QueryLocator start(Database.BatchableContext bc){
      String query ='select id from task where createdby.Name =\'B2BMA Integration\' AND Subject LIKE \'Pardot List Email%\'';
        return Database.getQueryLocator(query);
    }
    public void execute(Database.BatchableContext bc, list<Task> scope){
        Database.delete(scope);  }
     public void finish(Database.BatchableContext bc)   }}

TaskDeleteBatchTest
@isTest public class TaskDeleteBatchTest {
    @isTest static void testMethod1(){
       Lead l = new lead();
        l.LastName = 'Test';
        l.Company = 'Test Company';
        l.How_did_lead_hear_about_us__c='Email Campaign';
        Insert l;
        
        Profile p = [SELECT Id FROM Profile WHERE Name='B2BMA Integration User']; 

        User u = new User(Alias = 'standt', Email='standarduser@leopardsolutions.com', 
                          EmailEncodingKey='UTF-8', LastName='B2BMA Integration', LanguageLocaleKey='en_US', 
                          LocaleSidKey='en_US', ProfileId = p.Id, 
                          TimeZoneSidKey='America/Los_Angeles', UserName='b2bmaintegration@leopardsolutions.com');
        
        system.runAs(u){
            Task t = new Task();
            t.Subject = 'Pardot List Email';
            t.whoId = l.Id;
            Insert t;   
            
            system.debug([select id,createdBy.Name from task][0].createdBy.Name);
        }
        
        Test.startTest();
          Database.executeBatch(new TaskDeleteBatch());
    Test.stopTest();

    }
}
global class TeacherBonusClass implements database.Batchable<sObject>, Database.Stateful{
    
    
    global Integer recordsProcessed = 0;
    
    
    global static Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('Select Name, Salary__c from Teacher__c');
    }
    
    global static void execute(Database.BatchableContext bc, List<Teacher__c> teaList){
        
        List<Teacher__c> teaNewList = new List<Teacher__c>();
        for(Teacher__c tea: teaList){
            if(tea.Salary__c< 300000){
                tea.Salary__c = tea.Salary__c + (0.002 * tea.Salary__c);
                teaNewList.add(tea);
                
            }
            recordsProcessed = recordsProcessed + 1;
        }
        insert teaNewList;
        
    }
    
    global static void finish(Database.BatchableContext bc){
        
        Messaging.SingleEmailMessage  mail = new Messaging.SingleEmailMessage();
        string[] toAddresses = new String[] {'akshattiwari489@gmail.com'};
        mail.setSubject('Salary Bonus Alert');
        mail.setToAddresses(toAddresses);
        mail.setPlainTextBody('Your Salary Has been Incremented  by 0.2% and your new salary is');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
        
        
        
    }

}

I am trying to maintain states accross the transaction and I am getting error " Variable Does Not Exist: recordsProcessed " when I am tring to store values inside the recordsProcessed inside for loop. What modifications should I make in the code?
Hi,
I'm new in apex and need some help,


I write a trigger that creates a new account every time that I created an account:
trigger AccountParent on Account (after insert) {
    
    List<Account> acc = new List<Account>();
    
    for (Account a : Trigger.new) {
        Account ac = new Account();
        ac.Name = a.Description;
        ac.Parent__c = a.Name;
        acc.add(ac);
    }
    
    if (acc.size()>0) {
        insert acc;
    }
}

but when i create account i get an error:
AccountParent: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountParent: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name] Trigger.AccountParent: line 13, column 1: [] Trigger.AccountParent: line 13, column 1

why?? 
 

Hello everyone,

i have two objects name doctor and Appointment Doctor is parent object and Appointment is Child (Master Detail Relationship) in doctor object there is available Field(checkbox) ,when i create appointment if doctor is not availabel then appointment with that doctor Should not be schedule  so how can i validate Appointment Object Using Admin Knowledge.

 

 

Can I have help writing a query for permission set license holder in Salesforce. I am trying to find all the users who are assigned the permission set license named: Sales Cloud Einstein. 
Can someone tell me what am I doing wrong with the following formula? The formula hasn´t a sintaxis error, but, I´m not getting a percentage as answer,, Im getting 0.

if( text(Status)="Baja",0,

if(and(text(Ciclo__c )= "Fall 2020", (OwnerId)="Brenda Monzalvo"),1/35,

0))
SOQL Query:
SELECT ClaimNumber__c, Program__c, ProgramDesc__C , ClaimStartDate__c, ClaimEndDate__c
FROM ClaimHeader__x WHERE (ClaimNumber__c = '13128E' AND  ProgramDesc__c = 'STAR') OR (ClaimNumber__c = '13128E' AND ProgramDesc__c = 'CHIP')  ORDER BY ClaimStartDate__c DESC LIMIT 11 OFFSET 0
                
We are expecting only one record for this query with claim number '13128E', but it is returning more records.
 
Hi,
I've inherited a Sales Cloud org, that until recently had the following trigger working. Now the Original Total Cost is no longer populated at the trigger points.
However the Error at deletion is still being sucessfuly fired.
 
trigger OLITrigger on OpportunityLineItem (before insert, before update, before delete) {
    
 //Code block to enable bypassing of triggers using field off users record  
    String currentUserId = UserInfo.getUserId();
    User currentUser = [SELECT Bypass_Triggers__c FROM User WHERE Id = :currentUserId LIMIT 1];
    if (currentUser.Bypass_Triggers__c) return;
        
    If(System.Trigger.isInsert){
    
      For(OpportunityLineItem oli: Trigger.New){
    
        oli.Original_Total_Cost__c = oli.TotalPrice;
        
      }
  }
    
  If(System.Trigger.isUpdate){

       For(OpportunityLineItem oli : [SELECT TotalPrice,Original_Total_Cost__c,Opportunity.StageName FROM OpportunityLineItem Where Id IN: Trigger.New]){
           
      if(oli.Opportunity.StageName == 'Closed Won')
     {
         //Do Nothing
     }
           
      else  if(Trigger.oldmap.get(oli.id).TotalPrice == Trigger.newmap.get(oli.id).TotalPrice)
           {
               // Do nothing  
            }
                  
     else if(Trigger.oldmap.get(oli.id).TotalPrice != Trigger.newmap.get(oli.id).TotalPrice)
     {
          oli.Original_Total_Cost__c = Trigger.oldmap.get(oli.id).TotalPrice;
     }
       }
  }
       
  If(System.Trigger.isBefore &&System.Trigger.isDelete){
    
  For(OpportunityLineItem oli : Trigger.old)
    {
        if(oli.number_of_invoice_lines__c == 0 || oli.number_of_invoice_lines__c == null){

        list<Line_Item_Details__c> LineItemDetailsId=[Select Id FROM Line_Item_Details__c Where id =:oli.Line_Item_Details__c];     
        delete LineItemDetailsId;
        }
        
        else if(oli.number_of_invoice_lines__c >= 1) 
        {
            oli.addError('You can not delete this Product as it has Invoiced Schedules');
        }
       
    }
    }

}

 
 for(Lead l: scope)
        {
            
            if(l.State!=''){ //State is not empty
                l.State__c =l.State__c;
            }else{    //State is empty
                l.State__c ='Default';}
            
            
            l.Age__c = l.Current_Age__c;
            
        }
        update scope;
    }

Hi all,

In platform developer II there are 65 questions and 5 of them do not account for the exam percentage they have zero marks. Can somebody tell me if they are the last 5 questions? or they appear randomly.

Thanks,

A

  • March 04, 2020
  • Like
  • 0
Hello,

I am wondering exactly what happens when you 'cancel' a DX command run in VSCode using the button in the UI, e.g.:

Screenshot of SFDX in VSCode

If it is DEPLOYING changes - will it revert any changes already made? Could it be possible that some of the changes may have already been applied to an org?


Hoping someone can answer for me. Cheers
 
Hello,

What is the SOQL query to check the list of thins a user is following.
The user can click Follow on Account, Opportunity etc
but is there any limit on thiings to follow
  • January 30, 2020
  • Like
  • 0
Hi friends,
I'm trying to deploy source to org with Visual Studio Code, but I get this error: Invalid version specified:47.0
How Can I fix it?
INFO:
1. my org is a developer edition
2. my apex api version is 46.0
3. I already run sfdx force:config:set apiVersion=46.0 --global (in VS Code)
4. my VS Code plugins versions is:
salesforcedx 47.0.7 (pre-release)
├─ force-language-services 47.0.2
└─ salesforce-alm 47.0.7
Please, help me. Thank you.
I have an excellent trigger (inherited from the previous SFDC Admin) that pulls in values from a custom object that manages my territories by zip code. I'm rolling out Salesforce for my European team and unfortunately the zip codes in Germany are duplicates to zip codes in the US. 

How do I update the trigger to prevent it from firing if the Country is not USA? I am using standard country and state picklists.