• Deepak Pandey 13
  • NEWBIE
  • 365 Points
  • Member since 2015
  • CCC Infotech


  • Chatter
    Feed
  • 11
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 140
    Replies
Hello Developers,
Below is my code to find total number of contacts for an account. Everything works fine here. I need to write a test class for this code. Can anyone help me with this....
trigger TriggerCntact on Contact (after insert, after delete) {
	set<ID> accSet = new Set<Id>();
    if(trigger.isinsert){
        for(Contact Con : Trigger.new){
            accSet.add(con.AccountId);
        }
    }
        if(trigger.isDelete){
        for(Contact Con : Trigger.old){
            accSet.add(con.AccountId);
        }
    }
    List<Account> acclist = [SELECT Id from Account WHERE ID IN :accSet];
    List<Contact> conlist = [SELECT AccountId FROM Contact WHERE AccountId IN :accSet];
    list<Contact> listCon = new List<Contact>();
    list<Account> listacc = new List<Account>();
    map<String, Integer> conMap = new Map<String, Integer>();
    for(Account acnt : acclist){
        listCon.clear();
        for(contact cont : conlist){
            if(cont.AccountId == acnt.Id){
                listcon.add(cont);
            ConMap.put(cont.AccountId, listCon.size());
            }
        }
    }
    if(acclist.size()>0){
        for(account a : acclist){
            if(conMap.get(a.Id)==NULL){
                a.Total_Contacts__c	= 0;
            }
            else{
                a.Total_Contacts__c	= ConMap.get(a.Id);
                listacc.add(a);
            }
        }
        if(listacc.size()>0){
            update Listacc;
        }
    }
}

Thanks in Advance!!​
Can you please help me out on this..? I am trying to write a test class for a simple trigger. But some of the lines (italics) are not covered under the code coverage. Can anyone please guide me... Also i have not written any test classes for this trigger but it is showing coverage without a test class..?

trigger AccountDuplicateTrigger on Account (before insert)
{        
    for(Account a:Trigger.new)    
    {
        if(Trigger.isInsert)
        {                   
            if(a.Name !='') 
            {       
                string dupItem = '';
                List<Account> acc= new List<Account>();                   
                if((a.BillingStreet != null) && (acc.isEmpty())) 
                {
                    acc=[select ID from account where Name=:a.Name and BillingStreet=:a.BillingStreet]; 
                    if(acc.isEmpty()==False)                                                              
                        dupItem='Name \''+ String.escapeSingleQuotes(a.Name)+'\' and Billing street \''+
                        String.escapeSingleQuotes(a.BillingStreet)+'\'';

                }
                if((a.BillingCity != null) && (acc.isEmpty())) 
                {
                    acc=[select ID from account where Name=:a.Name and BillingCity=:a.BillingCity];    
                    if(acc.isEmpty()==False) 
                        dupItem='Name \''+ String.escapeSingleQuotes(a.Name)+'\' and Billing city \''+
                        String.escapeSingleQuotes(a.BillingCity)+'\'';

                }                                      
                else{                
                }
                
                //Alerts the user                    
                if(acc.isEmpty()==False) {
                    a.adderror('You cannot create a duplicate account here as the '+dupItem+' already belongs to a different account.');     
                }

            }
        }
    }
}
When a Preservation Activity (child) gets deleted, I need the Preservation Object (parent) to recalculate the Max Date.
(also, I'm not a coder so I tried to annotate what I thought was happening in the code that's why those notes are there.)
trigger RollUpRecentActivity on Preservation_Activities__c (after insert, after update, after delete) {
    set<Id>setPreserveId = new set<Id>(); //set new variable "setPreserveID"
    list<Preservation_Object__c>lstPreserve = new list<Preservation_Object__c>(); //set a new Preservation Object list called "lstPreserve"
    if(trigger.isAfter){ //if it's afterUpdate
        system.debug('@Developer --> isAfter:'); //debug statement
        if(trigger.isInsert || trigger.isUpdate){ //if it's on insert OR update
            for(Preservation_Activities__c oActivities:trigger.new){ //set oActivities which equals the activity/ies that are trigger.new
                setPreserveId.add(oActivities.Preservation_Object__c);//to the setPreserveId variable, add the PReservation objects of the activities in the trigger
            }
        }
        system.debug('@developer-->setPreserveId: '+setPreserveId);  //debug statement
        if(setPreserveId.size()>0){ //if there's actually an id
        for(Preservation_Activities__c oActivities:[
            	Select Preservation_Object__c,id,Name,Activity_Type__c,Activity_Date__c  
            	from Preservation_Activities__c 
            	where Preservation_Object__c In:setPreserveId and Activity_Date__c != null and isDeleted = FALSE
            	order by Activity_Date__c desc limit 1]){
            Preservation_Object__c oPreserve = new Preservation_Object__c();
            oPreserve.Id = oActivities.Preservation_Object__c;
            oPreserve.Last_Activity_Type__c = oActivities.Activity_Type__c;
            lstPreserve.add(oPreserve);
        }
        system.debug('@developer-->lstPreserve: '+lstPreserve);
        if(lstPreserve.size()>0){
            update lstPreserve;
        }
        }
    }
 }

 
Hi, 
I am newbie here and pretty new to SFDC. I would like to achieve following
1. On opportunity stage - when I select "Opp Lost" - I need it to auto change all records in related list (custom object) picklist field to "Opp Lost"
2. But if I select opportunity stage "Opp Won" - I need it to change the records to "Opp Won" that are currently "In Progress" stage. Any records that are selected "Opp Lost" are not changed.
FYI - In Opportunity stage - we have 7 stage including "Opp Lost" & "Opp Won" however in the related list custom object picklist field - we have 3 stages "Opp Won", "In Progress" & "Opp Lost" 
How can I achieve this? Coding is not an option since I am a rookie.
Thanks / Ram
 
Hi

I'm trying to deploy 1 Pagelayout + 4 Custom Fields + 3 Apex Classes with test classes + 1Workflow Rule with 1 Field Update for Case Object.

But every time it gives error of CODE COVERAGE FAILURE or CODE COVERAGE IS 0 %.

Please help as it is very urgent for me to deploy it to Production Org.
Hello,

I want to execute a test function in test class.

Before executing fucntion i want to create a user with a licence "partner community", how is it posible to achieve ?

thanks for suggestion !
User-added image

Hello,

When i click "change log levels" i get this exceoption.*

I am not able to add the users ..it gives error like below

User-added image
 
Hello,

I am overriding a button.

 get below error message
"|EXCEPTION_THROWN|[EXTERNAL]|System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: CustomObject__c.Name"

I making no query

What can be the reason ?
Hi everyone,
How to create a custom vfpage as PDF page. I have the component reanderedAS="PDF", but i was to see the field values in the genenrated PDF. Can anyone help me over here.

Regards,
Bhargav.
trigger Deleteres on Restintegration__c(after update) {
 List<Id> lstId = new List<Id>();

if(trigger.isupdate)
{
for(Restintegration__c res : trigger.new)
{
if(res.id != null)
{
lstId.add(res.id) ;
}
}
 }

for(Restintegration__c res: Trigger.old){
        List<Restintegration__c > existoppList =  [Select Id from Restintegration__c where  id in = lstId];
        delete existoppList;
    }
 
}
Trigger deloldrecords on Restintegration__c(before update)
{
list<Restintegration__c> newlist= new list<Restintegration__c>();

for(Restintegration__c oldacc:Trigger.old)
{
newlist.add(oldacc);
}
delete newlist;
}
Hi 
  I am trying to get day name from date type data type.

<aura:component>
  <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
 <aura:attribute name="today" type="Date" default=""/>
 
    <ui:inputDate aura:id="expdate" label="Today's Date" class="field" value="{!v.today}" displayDatePicker="true" />      
    <ui:button class="btn" label="Submit" press="{!c.setOutput}"/> 

 <div aura:id="msg" class="hide">
  You entered: <ui:outputDate aura:id="oDate" value="" />
 </div>
     
</aura:component>

Controller is-

({
    doInit : function(component, event, helper) {
        var today = new Date();
        component.set('v.today', today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate());
    },

    setOutput : function(component, event, helper) {
        var cmpMsg = component.find("msg");
        $A.util.removeClass(cmpMsg, 'hide');
        var expdate = component.find("expdate").get("v.value");

        var oDate = component.find("oDate");
        oDate.set("v.value", expdate);

    }
  
})  

This code retrive all day which you given. I want this code only show Day name like sunday , monday ETC
hi my batchclass test not working.
@isTest
private class TesttaskAssignBatch {
    static testmethod void test(){
           
            List<User> lstUser = new List<User>([SELECT Username,ContactId ,Email,profile.name from USER where profile.name = 'Custom Partner Community Login']);

            if(!lstUser.isEmpty())
            {
             tast t = new task();
   t.Subject  = 'Weekly Status Report & Meeting - '+date.today();
            t.Description = 'Test';
            t.OwnerId = lstUser[0].id;
            t.ActivityDate=date.today();
            t.priority = 'High';
            t.Type = 'Email';
            t.Status = 'In Progress';  
            t.WhoID = lstUser[0].ContactId ;
            Database.DMLOptions dmlOptions = new Database.DMLOptions();
            dmlOptions.EmailHeader.TriggerUserEmail = TRUE;
            Database.Insert(t,dmlOptions);
            insert t;          
            }  
   
        Test.startTest();
       
        Database.executeBatch(new taskAssignBatch(), 1);

        Test.stopTest();      
    }
}
 this code not working ?

Hi all,
      my requirment to find greatest integer in the list. In below code map have a size of integer. I want to take maximum integer value in the list(map1 contain integer list) and show on the page.

public class sizeorder 
{
public list<Ordered__c> lstorder {get;set;}

    public sizeorder()
    {
        lstorder = [select id,Name, Customer__c, Email__c from Ordered__c];
    map<string,list<Ordered__c>> map1 = new map<string,list<Ordered__c>>();
    
        for(Ordered__c ord : lstorder)
        {
            if(map1.get(ord.Customer__c )==null)
            {
             map1.put(ord.Customer__c ,  new list<Ordered__c >());
            }
           map1.get(ord.Customer__c).add(ord);
        }
     for(string str : map1.keyset())
     {
     list<Ordered__c> lst = map1.get(str);
     integer inte = lst.size();
     System.debug('@@@@@inte' + inte );
     integer i;
     integer j;
     integer k;
     integer l ;
     for(i=0; i<inte ; i++)
      {
     j = i++ ; 
     l= j ;
     system.debug('####j' +j); 
     system.debug('####l' +l); 
     system.debug('####i++' +i++); 
      }
      for (i = 1; i < inte ; i++)
      {
        if ( i > j)
        {
           j = k ; 
           system.debug('####j' +j); 
        }
      }
    }
  }
}
public class stagesize 
{
    public stagesize() 
    {
    lstOpp = new List<Opp>();
  stages = new list<string>();
        Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe();
        System.debug(fieldResult);
        List<Schema.PicklistEntry> pichlstval = fieldResult.getPicklistValues(); 
        system.debug('--pichlstval -->>'+pichlstval );              
        for( Schema.PicklistEntry f : pichlstval )
        {
           stages.add(f.getLabel());
          System.debug('@@@@@stages' +stages);
        }
        
        map < string , list<opportunity>> lststage = new map < string , list<opportunity>>();
          for(Opportunity opp : [select id,Name,StageName from Opportunity])
          {
           if(lststage.get(opp.StageName)== null)
            {
             lststage.put(opp.StageName , new list<Opportunity>());
            }
           lststage.get(opp.StageName).add(opp);    
          System.debug('@@@@@lststage.size()' +lststage.size());
          }     
     for(string opp : stages)
     {
     integer i = lststage.size();
    String prefix = String.getCommonPrefix(stages);
     System.debug('@@@@@i' +i );
      System.debug('@@@@@prefix' +prefix );

    Opp o = new opp(prefix , i);
    lstOpp.add(o);
   //     lstOpp.add((prefix),(i));
     }
     
      }
     public List<Opp> lstOpp {get;set;} 
    public List<string> stages {get;set;}
    
    public class Opp  
    {
        public String stage {get;set;}    
        public Integer size {get; set;}
        
      public  opp(string s , Integer I)  
      {
        stage = s;
        size = i ;
      }
    }
}
hello my 

apex class-
public class wrapperleadClassController {
public lead led {get;set;}
public List<lead> AccountsOrigList {get;set;}
public List<wraplead> listlead {get; set;}

public ApexPages.StandardSetController setCon {
 get {
 setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
 [SELECT Name,Status, ID FROM Lead  ]));
 return setCon;
}
set;
}


public wrapperleadClassController()
{

}
public List<wraplead> getleads() 
{
if(AccountsOrigList == null)

AccountsOrigList = setCon.getRecords();
listlead = new List<wraplead>();

for (lead l: AccountsOrigList)
{
listlead.add(new wraplead(l));
system.debug('lead list display'+listlead);
}
}
return listlead;

    
    public Pagereference deletes()
     {
        List<lead> leadsToDelete = new List<lead>();
        
        for (wraplead avar : listlead)
        {
            if (avar.selected == True)
                {
                 if (avar.ld.id != null)   
                    {                
                    leadsToDelete.add(avar.ld);
                    }               
                }
        }
       delete leadsToDelete;
       return null;
     }
 
    

public PageReference updt() 
{
        List<lead> leadsToUpsert = new List<lead>();         
        for(wraplead ldup : listlead) 
        {

            if(ldup.selected == true) 
            {
           if (ldup.ld.id != null)   
           {
            ldup.ld.id=led.id;
          ldup.ld.Status=led.Status;
                leadsToUpsert.add(ldup.ld);
               }
            }
           } 
        update leadsToUpsert ;

        return null;
    }

                     


public class wraplead {
public lead ld {get; set;}
public Boolean selected {get; set;}
public Boolean Checked {get; set;}
public wraplead(lead l) {
ld = l;
selected = false;
Checked =true;
}
}
}

page-
<apex:page controller="wrapperleadClassController" sidebar="false" showHeader="false">
 
<apex:form >
    <apex:pageBlock id="table" >
       <apex:pageBlockTable value="{!leads}" var="aa" id="table">


             <apex:column >
           <apex:inputcheckbox value="{!aa.selected }"/>
         </apex:column>
        
          <apex:column value="{!aa.ld.Name}" />
         <apex:column value="{!aa.ld.Status}" />  
         
         
    <apex:column >
           <apex:selectRadio value="{!aa.Checked}" />
         </apex:column>    
       </apex:pageBlockTable>   
     </apex:pageBlock>
   
     
     <apex:pageBlock >
       <apex:pageBlockSection >
          <apex:pageblockSectionItem >
         Status    
           <apex:inputField value="{!led.Status}"/>
          </apex:pageblockSectionItem>
          <apex:commandButton value="Update" action="{!updt}" />
          <apex:commandButton value="Delete" action="{!deletes}" />
           </apex:pageBlockSection>
    </apex:pageBlock>
           
 </apex:form>

</apex:page>
hello.  i have wrapper class want to update status field.
Apex class-
public class wrapperleadClassController {
public lead led {get;set;}
public List<wraplead> listlead {get; set;}
public wrapperleadClassController()
{

}
public List<wraplead> getleads() 
{
listlead = new List<wraplead>();
  
for(lead l : [select Name,Status from lead limit 10]) 
{
listlead.add(new wraplead(l));
system.debug('lead list display'+listlead);
}
return listlead;
}
public PageReference updt() 
{
        List<lead> selectedlead = new List<lead>();
       
        
        for(wraplead ldup : getleads()) 
        {

            if(ldup.selected == true) 
            {
            lead ll = new lead();
           ll.Status=led.Status;
                selectedlead.add(ll);
                system.debug('lead list display'+selectedlead);
               }
            }
        update selectedlead;

        return null;
    }

vf pages-

<apex:page controller="wrapperleadClassController" sidebar="false" showHeader="false">
 
<apex:form >
    <apex:pageBlock id="table" >
       <apex:pageBlockTable value="{!leads}" var="aa" id="table">
             <apex:column >
           <apex:inputcheckbox value="{!aa.selected }"/>
         </apex:column>
          <apex:column value="{!aa.ld.Name}" />
         <apex:column value="{!aa.ld.Status}" />           
       </apex:pageBlockTable>   
     </apex:pageBlock>
   
     
     <apex:pageBlock >
       <apex:pageBlockSection >
          <apex:pageblockSectionItem >
         Status    
           <apex:inputField value="{!led.Status}"/>
          </apex:pageblockSectionItem>
          <apex:commandButton value="Update" action="{!updt}" />
           </apex:pageBlockSection>
    </apex:pageBlock>
           
 </apex:form>

</apex:page>                     


 
public with sharing class Backup_ExtensionController {
    public Backup__c  bkup{get;set;}
    public List<string> splitString {get;set;}
    
    public Backup_ExtensionController(ApexPages.StandardController controller) 
    {
    list<Backup__c> bk= new list<Backup__c>();
    
      controller.addFields(new List<string>{'splitemail__c'});
        Backup__c record = (Backup__c)controller.getRecord();

        splitString = new List<string>();

        if(!String.IsBlank(record.splitemail__c))
            splitString = record.splitemail__c.split(','); 
    }

}

pages-

<apex:inputfield value={!bkup.splitfield}/>
<apex:commanndutton action={!save} value="save"/>
public class spltedinputemail 
{
  public List<string> splitString {get;set;}
  public Backup__c back{get;set;}
  
    public spltedinputemail(ApexPages.StandardController controller) 
    {
       controller.addFields(new List<string>{'splitemail__c'});
       this.back= (Backup__c)controller.getRecord();
        splitString = new List<string>();

        if(!String.IsBlank(back.splitemail__c))
            splitString = back.splitemail__c.split(';');
       system.debug('!!!!splitString' +splitString );
    }

  List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
  public pagereference splitemail()
  {
  if(splitString != null)
  {
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   List<String> sendTo = new List<String>();
    sendTo.add('splitString ');
      mail.setToAddresses(sendTo);
      mail.setSenderDisplayName('CCC Infotech');
     List<String> ccTo = new List<String>();
      ccTo.add('splitString ');
    mail.setCcAddresses(ccTo);
      mail.setSubject('URGENT BUSINESS PROPOSAL');
      String body = 'Dear '  + ', ';
      body += 'I confess this will come as a surprise to you.';
      body += 'I am John Alliston CEO of the Bank of Nigeria.';
      body += 'I write to request your cooperation in this ';
      body += 'urgent matter as I need a foreign partner ';
      body += 'in the assistance of transferring $47,110,000 ';
      body += 'to a US bank account. Please respond with ';
      body += 'your bank account # so I may deposit these funds.';
      mail.setHtmlBody(body);
      mails.add(mail);
  } 
 Messaging.sendEmail(mails); 
  return page.spltsendingmail;
 }
}

what is the problem?
help of picklist uptate owner of case.
1st picklst of user or queue  after come list of user or queue and commond button update update owner.


public class roleexten 
{
        public Case cse {get; set;}
        public String selectedId {get;set;}
        public List<selectoption> UserOptionList{get;set;}
        public list<Case> caselist{get; set;}
         public Id ownerid {get;set;}
        
        public roleexten(ApexPages.StandardController controller)
        {
        
       ownerid = ApexPages.currentPage().getParameters().get('id') ;
            caselist=[select id,ownerid from case where id=: ownerid ];
            cse  =new Case();
            system.debug('cse.ownerId:::::'+cse.ownerId);
            selected();
        }
        public pagereference assignowner()
        {
            return page.vfpageownerassign ;
        }
        
        
        public void selected()
        {
          system.debug('run:::::::::::::::');
            UserOptionList = new List<selectoption>();

            UserOptionList.add(new selectoption('','--None--'));
            system.debug('select :::::'+cse.ownerId);
            if(cse.assign__c == 'User')
       {
            for(User u :[select id ,name from user ])
            {
                system.debug('@@@@u' +u);
                UserOptionList.add(new SelectOption(u.Id , u.Name));
            }
        }
            //system.debug('@@@@UserOptionList' +UserOptionList );
      else if (cse.assign__c == 'Queue')
       {
      for(Group gp :[Select Name, Id From Group where Type = 'Queue'])
       { 
     UserOptionList.add(new SelectOption(gp.Id , gp.name));
       }    
  }
 }
 public void saveassign()
     {
        for(case c : caselist)
         {
             c.ownerid=selectedId;
         }
         update caselist;
     }
}

Page----
<apex:page standardController="Case" extensions="roleexten" sidebar="false">
 <apex:form >
  <apex:pageblock mode="edit" >
  <apex:commandButton value="save" action="{!saveassign}" />
   <apex:pageBlockSection >
    <apex:pageBlockSectionItem >
     <apex:inputField value="{!cse.assign__c}">
     <apex:actionSupport action="{!selected}" event="onchange" reRender="cont"/> 
     </apex:inputField>
    </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
   
            <apex:outputPanel id="cont">
           <apex:pageblockSection title="Owner" >
                  <apex:selectList size="1" value="{!selectedId }">
                      <apex:selectOptions value="{!UserOptionList }"></apex:selectOptions>
                  </apex:selectList>
        
           </apex:pageBlockSection>
           </apex:outputPanel>
 

  </apex:pageblock>
 </apex:form>
</apex:page>
hi everyone.
shortout my problem ?
i have a two picklis
1st- custom picklist field (user and queue)
2nd- picklist(show list of user and queue)

my requirement after click select user then come user another picklist after select them click on command button case owner will be ssigned.

apex class---
public class roleexten 
{
        public Case cse {get; set;}
        public String selectedId {get;set;}
        public List<selectoption> UserOptionList{get;set;}
        public list<Case> caselist{get; set;}
        
        public roleexten(ApexPages.StandardController controller)
        {
            caselist=[select id,ownerid from case];
            cse  =new Case();
            system.debug('cse.ownerId:::::'+cse.ownerId);
            selected();
        }
        public pagereference assignowner()
        {
            return page.vfpageownerassign ;
        }
        
        
        public void selected()
        {
          system.debug('run:::::::::::::::');
            UserOptionList = new List<selectoption>();

            UserOptionList.add(new selectoption('','--None--'));
            system.debug('select :::::'+cse.ownerId);
            if(cse.assign__c == 'User')
       {
            for(User u :[select id ,name from user ])
            {
                system.debug('@@@@u' +u);
                UserOptionList.add(new SelectOption(u.Id , u.Name));
            }
        }
            //system.debug('@@@@UserOptionList' +UserOptionList );
      else if (cse.assign__c == 'Queue')
       {
      for(Group gp :[Select Name, Id From Group where Type = 'Queue'])
       { 
     UserOptionList.add(new SelectOption(gp.Id , gp.name));
       }    
  }
 }
 public void saveassign()
     {
        for(case c : caselist)
         {
         
         }
     }
}public class roleexten 
{
        public Case cse {get; set;}
        public String selectedId {get;set;}
        public List<selectoption> UserOptionList{get;set;}
        public list<Case> caselist{get; set;}
        
        public roleexten(ApexPages.StandardController controller)
        {
            caselist=[select id,ownerid from case];
            cse  =new Case();
            system.debug('cse.ownerId:::::'+cse.ownerId);
            selected();
        }
        public pagereference assignowner()
        {
            return page.vfpageownerassign ;
        }
        
        
        public void selected()
        {
          system.debug('run:::::::::::::::');
            UserOptionList = new List<selectoption>();

            UserOptionList.add(new selectoption('','--None--'));
            system.debug('select :::::'+cse.ownerId);
            if(cse.assign__c == 'User')
       {
            for(User u :[select id ,name from user ])
            {
                system.debug('@@@@u' +u);
                UserOptionList.add(new SelectOption(u.Id , u.Name));
            }
        }
            //system.debug('@@@@UserOptionList' +UserOptionList );
      else if (cse.assign__c == 'Queue')
       {
      for(Group gp :[Select Name, Id From Group where Type = 'Queue'])
       { 
     UserOptionList.add(new SelectOption(gp.Id , gp.name));
       }    
  }
 }
 public void saveassign()
     {
        for(case c : caselist)
         {
         
         }
     }
}

pages-
<apex:page standardController="Case" extensions="roleexten" sidebar="false">
 <apex:form >
  <apex:pageblock >
   <apex:pageBlockSection >
    <apex:pageBlockSectionItem >
     <apex:inputField value="{!cse.assign__c}">
     <apex:actionSupport action="{!selected}" event="onchange" reRender="cont"/> 
     </apex:inputField>
    </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
   
            <apex:outputPanel id="cont">
           <apex:pageblockSection title="Owner" >
                  <apex:selectList size="1" value="{!selectedId }">
                      <apex:selectOptions value="{!UserOptionList }"></apex:selectOptions>
                  </apex:selectList>
        <apex:commandButton value="save" action="{!saveassign}" />
           </apex:pageBlockSection>
           </apex:outputPanel>
 

  </apex:pageblock>
 </apex:form>
</apex:page>
apex class---
public class roleexten {
public Case cse {get; set;}
public String selectedId {get;set;}
public List<selectoption> UserOptionList{get;set;}
    
    public roleexten(ApexPages.StandardController controller)
     {
       cse  =new Case ();
     }
  public pagereference assignowner()
  {
  return page.vfpageownerassign ;
  }
  public void selected()
    
    {
       UserOptionList = new List<selectoption>();
       UserOptionList.add(new selectoption('','--None--'));
        
       for(User u :[select id ,name from user ])
            {
            system.debug('@@@@u' +u);
                  UserOptionList .add(new SelectOption(u.Id , u.Name));
                  
                }
                system.debug('@@@@UserOptionList' +UserOptionList );
           }
  
}

vf pages-

<apex:page standardController="Case" extensions="roleexten" sidebar="false">
 <apex:form >
  <apex:pageblock >
   <apex:pageBlockSection >
    <apex:pageBlockSectionItem >
     <apex:inputField value="{!cse.ownerId}"/>
     <apex:actionSupport action="{!selected}" event="onchange" reRender="cont"/> 
    </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
   
            <apex:outputPanel id="cont">
           <apex:pageblockSection title="Owner" >
                  <apex:selectList value="{!selectedId }">
                      <apex:selectOptions value="{!UserOptionList }"></apex:selectOptions>
                  </apex:selectList>
           </apex:pageBlockSection>
           </apex:outputPanel>
 

  </apex:pageblock>
 </apex:form>
</apex:page>
code---
public class acctestsample
{
public Backup__c acc{get;set;}

    public void savedata() 
  {
  acc=new Backup__c();
    insert acc;
  }
}

vf page--

<apex:page controller="acctestsample" sidebar="false">
 
 <apex:form >

<apex:pageblock >
 <apex:pageBlockSection columns="1">
   <apex:inputField value="{!acc.name}"/>
 </apex:pageBlockSection> 
<apex:pageBlockButtons >
          <apex:commandButton value="Save" action="{!savedata}"/>
      </apex:pageBlockButtons>
 </apex:pageBlock>
 </apex:form>
</apex:page>

test class-

@istest
public class testvfpage
{
static Backup__c acc;
Private Static testmethod void Testacc()
{
acc=new Backup__c();
acc.name = 'vftest';
insert acc;
}
}
trigger to insert and update cutom field user on account . 
1- insert time hard coded value fill in accountteammember.
2-update time user (look up of user) change than accountteammember user will be same.

trigger-

trigger atm on account(after insert,after update)
{

  list<AccountTeamMember> accountTeamList=new list<AccountTeamMember>();
 
  
   if(Trigger.isInsert)
     for(account a:trigger.new)
     {
    
        AccountTeamMember acctTM = new AccountTeamMember();
                    AccountShare acctShare = new AccountShare();
                    acctTM.AccountId = a.id;
                    acctTM.userId = a.user__c;
                    acctTM.TeamMemberRole = 'Account Manager';
                    accountTeamList.add(acctTM);   
   }
       for(account acc:trigger.new)
    {
     Account oldAccount = Trigger.oldMap.get(acc.ID);
 if(acc.user__c != oldAccount.user__c)
         
        {       
                AccountTeamMember acctTM = new AccountTeamMember();
                    AccountShare acctShare = new AccountShare();
                    acctTM.AccountId = acc.id;
                    acctTM.userId = acc.user__c;
                    //acctTM.TeamMemberRole = 'Account Manager';
                    accountTeamList.add(acctTM);   
        } 
     
     }       
           
insert accountTeamList;
}
If account checkbox is checked than contact will not inserted show error?
trigger avoid on contact (before insert,before update)
{
   set<id> setcheck = new set<id>();
   set<id> setExistingid = new set<id>();

   //Add alll email in set to fetch related existing records
   list<account> lst=[select id ,name,checkcontact__c from account where checkcontact__c=true];
   system.debug('$$$$lst' +lst);
   for(Account acc : lst)
   {
          setcheck.add(acc.id);
          system.debug('$$$$setcheck' +setcheck);
   }

   if(Trigger.isInsert||Trigger.isUpdate)
     for(contact a:trigger.new)
     {
         if(setExistingid.contains(a.account.id))
        {
                 a.adderror('This checkcontact ');
        }
     }
}
trigger countingof on lead (after insert,after update,after delete)
    {
    set<id>  conId = new set<id>();
    map<id,list<lead>> countle= new map<id,list<lead>>();
    
  
 
    
         if(trigger.isafter && trigger.isinsert || trigger.isUpdate )
             {
              for(lead c: trigger.new)
                  {
                   if(c.owner_type__c!=null)
                       {
                       conId.add(c.owner_type__c);
                       }
                  }
             }
         if(trigger.isafter && trigger.isDelete)
             {
             for(lead c:trigger.old)
                 {
                  if(c.owner_type__c!=null)
                    {
                  conId.add(c.owner_type__c);
                    }
                 }
             }
 
list<lead> leadlist= [select id ,owner_type__c  , no_of_lead__c  from lead where owner_type__c In :conId];
      for(lead a :leadlist)
         {
          countle.put(a.owner_type__c, leadlist);
         }
 
     list<lead> lst=new list<lead>();
     list<lead> countlist = [select id, no_of_lead__c,owner_type__c  from lead where owner_type__c in :conId];
        for(lead a : countlist)
          { 
          list<lead> lstt=countle.get(a.owner_type__c);
           a.no_of_lead__c= lstt.size();
           system.debug('@@@a' +a);  
           if(a.owner_type__c!=null)
           {   
           lst.add(a);
          }
        update lst;
        }
    } 


Error:Apex trigger countingof caused an unexpected exception, contact your administrator: countingof: execution of AfterUpdate caused by: System.DmlException: Update failed.
User-added image


in this pic i have a lookup of project ! can i change it in picklist?
my requirement is-
1-Account is drop-down 
2-Contact is checkbox
3-Sendind email to Contact
When select accountname all thier related contact(name,phone,email) come to checkbox. Select the checkbox of contact and a commond botton click send a mail of their contact email. 
wrapper class
 
i wanna a code which is firring when opportunity has been created than opportunitylineitem also filled... using trigger
sir i have a question that if any record has been deleted than deleted record will be save in another custom object. using trigger. anybody help me?. 
public class spltedinputemail 
{
  public List<string> splitString {get;set;}
  public Backup__c back{get;set;}
  
    public spltedinputemail(ApexPages.StandardController controller) 
    {
       controller.addFields(new List<string>{'splitemail__c'});
       this.back= (Backup__c)controller.getRecord();
        splitString = new List<string>();

        if(!String.IsBlank(back.splitemail__c))
            splitString = back.splitemail__c.split(';');
       system.debug('!!!!splitString' +splitString );
    }

  List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
  public pagereference splitemail()
  {
  if(splitString != null)
  {
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   List<String> sendTo = new List<String>();
    sendTo.add('splitString ');
      mail.setToAddresses(sendTo);
      mail.setSenderDisplayName('CCC Infotech');
     List<String> ccTo = new List<String>();
      ccTo.add('splitString ');
    mail.setCcAddresses(ccTo);
      mail.setSubject('URGENT BUSINESS PROPOSAL');
      String body = 'Dear '  + ', ';
      body += 'I confess this will come as a surprise to you.';
      body += 'I am John Alliston CEO of the Bank of Nigeria.';
      body += 'I write to request your cooperation in this ';
      body += 'urgent matter as I need a foreign partner ';
      body += 'in the assistance of transferring $47,110,000 ';
      body += 'to a US bank account. Please respond with ';
      body += 'your bank account # so I may deposit these funds.';
      mail.setHtmlBody(body);
      mails.add(mail);
  } 
 Messaging.sendEmail(mails); 
  return page.spltsendingmail;
 }
}

what is the problem?
Hi Developers,
I'm new to salesforce. Below is my Trigger to Update lead Owner when Account owner field on Lead is updated. Can anyone help me with writing the test class for this code. 
trigger UpdateLeadOwner on Lead (before insert, before update) {
List<String> AccOwnerPicklist =  new List<String>();
    for(Lead L : Trigger.New){
        if(L.Account_Onwer__c != Null){  
            AccOwnerPicklist.add(L.Account_Onwer__c);
        } 
    }
    List<User> UserList = [select id, name from user where name IN :AccOwnerPicklist];
    
    if(UserList != NULL && UserList.size()>0){
        for(Lead L : Trigger.New){
            for(User U : UserList){
                if(L.Account_Onwer__c == U.Name){
                    L.OwnerId = U.Id;
                }
            }
        }
    }
}

Any help will be highly appriciated.

Thank you in advance
Ravi
We are creating a note against a custom object.  We are inserting a ContentDocumentLink record usinmg the following code:

              ContentDocumentLink cdl = new ContentDocumentLink();

              // link the link object to the note
              cdl.ContentDocumentId = cn.Id;

              // link to sObjects by Id
              cdl.LinkedEntityId = caseId;

              // set visibility
              cdl.Visibility = 'InternalUsers';

              // set ShareType
              cdl.ShareType = 'I';

I have tried using both a system admin and the normal user. This code works fin in our development environment but fails in our test environment.

I can only think that there is a setting in our test environment for which the sharing type and visibility combination is invalid, but I have no idea what that could be.  I have turned the content feature setting on for both users and that made no difference.  I have also cheked the OWD (Private) and it is the same in both environments.  

Has anyone seen this issue before?
 
Hi,
I have a requirement to make to make a file private and be available to only the user whose role name consists the name of the file for a specific custom object. For this I am trying to retrieve from Content Document Link with the custom object name LinkedEntity.Type and ContentDocumentid as filters, when I hard code the ContentDocumentid it is working fine but when I try to dynamically provide the ContentDocumentId then the query is not returning any result. I am adding a snippet of my code. Please Help!!. Thanks
List<Id> listOfConDocuId = new List<Id>();

    
    for(ContentVersion cv: Trigger.new){
        if((!cv.Title.contains('product proposal')) || (!cv.Title.contains('final')) || (!cv.Title.contains('packet')))
            listOfConDocuId.add(cv.ContentDocumentId);
    }
    
    Map<Id, Project__c> mapOfProjectId = new Map<Id, Project__c>([SELECT Id FROM Project__c]);
    
    Set<Id> setOfProjectId = mapOfProjectId.keySet();
       
    List<ContentDocumentLink> LinkedProject = [SELECT ContentDocumentId, LinkedEntityId, ContentDocument.Title FROM ContentDocumentLink where LinkedEntityId in :setOfProjectId and LinkedEntity.Type='Project__c' and ContentDocumentId IN :listOfConDocuId];

 
Hi,

I am getting following error  while writting Test class

User-added image
In Tasks..  Owner is a mandatory field.

But I am getting this error.  Field is not writeable: Task.Owner 

Assigner to is the field. Owner is the technical Name. its a lookup to User.

Can anybody suggest way

How do I get it corrected
Hi,
 
I have a strange problem..
 
I have a class where I'm inserting the records to an object from that class.
Lets say the object is Data__c..
 
I have all records in one list variable. Suppose i have 5 records in that list..
 
so., if i wrote
 insert data;(data is a list variable) all 5 records are inserted successfuly.. But I have a trigger on that object(before insert)..
 
For five records trigger is firing only once.. That trigger is firing only for the last record..
 
How to do an insert in which for all the records trigger will fire one by one..
 
Thanks
Raj
Hi all,

I have the following query :

Select id, (Select Name , email from contacts where email != null), (Select name,stagename from Opportunities where stagename = 'Closed Won') from Account where id in (select accountid from contact where email!=null) and id in(select accountid from opportunity where stagename = 'Closed Won') 

I wish to know if the governor limit for fetched records includes only accounts, child contacts and child opportunities or will it include the All contacts and opportunities mentioned in the where clause as well.

Thanks.
I have a trigger that looks to see if the lookup field AVSFQB__Primary_Contact__c (looks up to Contact) has changed on an Opportunity and if so, deletes all Contact Roles and adds the value from the AVSFQB__Primary_Contact__c field.

Everything works perfectly except when I try to fire the trigger via DataLoader.  I've handled null pointer issues before, but in this example, I'm checking for null on both the list of Opportunities as well as the field AVSFQB__Primary_Contact__c just to be sure.  When executing via the ui, it works great.  When trying to upload a set of records it fails.  

Can someone point me in the right direction?
 
trigger opportunityMaintenance on Opportunity (after insert, after update) {

    if(Trigger.isAfter){
        if(Trigger.isUpdate || Trigger.isInsert){
            set<Id> setOpportunityIds = new set<Id>() ;
            for(Opportunity opp : Trigger.new){
                if(opp != null){
                    //Error on the next line: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object
                    if((opp.AVSFQB__Primary_Contact__c != null) && (Trigger.oldMap.get(opp.Id).AVSFQB__Primary_Contact__c != Trigger.newMap.get(opp.Id).AVSFQB__Primary_Contact__c))
                    {
                    setOpportunityIds.add(opp.Id) ;
                    }
                }    
            }
            if(!setOpportunityIds.isEmpty())
            delete([SELECT Id from opportunityContactRole WHERE OpportunityID IN: setOpportunityIds]) ;

        List<Opportunity> oppList = new List<Opportunity>();
        oppList = [select Id, Name, AVSFQB__Primary_Contact__c from Opportunity where Id in :Trigger.New];
            for(Opportunity opp : oppList) {
                if (oppList.size()>0){
                    if(opp.AVSFQB__Primary_Contact__c != NULL){
                        opportunityContactRole ocr = new opportunityContactRole(
                        ContactId = opp.AVSFQB__Primary_Contact__c,
                        OpportunityId = opp.Id,
                        Role = 'Decision Maker',
                        IsPrimary = TRUE);
                        insert ocr;    
                    }    
                }
            }
        }   
    }
}

 
i covered 62%  help me


public class mySecondController {
    Account account;

    public Account getAccount() {
        if(account == null) account = new Account();
        return account;
    }

    public PageReference save() {
        // Add the account to the database. 
        insert account;
        // Send the user to the detail page for the new account.
        PageReference acctPage = new ApexPages.StandardController(account).view();
        acctPage.setRedirect(true);
        return acctPage;
    }
}
=======================
@isTest
private class mySecondController_Test{
  static testMethod void test_getAccount_UseCase1(){
    mySecondController obj01 = new mySecondController();
    obj01.getAccount();
  }
  static testMethod void test_save_UseCase1(){
    mySecondController obj01 = new mySecondController();
    obj01.save();
  }
}


Thanks in Advance

 
  • October 10, 2017
  • Like
  • 0
I have a question.

When users get new permissions, I want a checkbox(custom field) to be ON.
And then daily I want emails to be sent out to those who have the checkbox on and have never received this email.

How can I do this? I'd much appreciate if anyone could help me out.
A BIG THANK YOU in advance :)
Hi, 

  I have a trigger below which is on opporunity which is working without any issue now I have a problem there is a process builder which update a custom date based on a stage change when this process fires  I am getting below error 

Error element myRule_1_A1 (FlowRecordUpdate).
The flow tried to update these records: null. This error occurred: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: convertToUSD: System.LimitException: Too many query rows: 50001. For details, see API Exceptions.​
rigger convertToUSD on Opportunity (before update){
     
  Try 
   {
   List<String> oppiso = new List<String>();   
   List<Id> oppid = new List<Id>(); 
   List<date> cdate = new List<date>();
      
   List<DatedConversionRate> DatedConversion = [SELECT isocode,startdate,ConversionRate FROM DatedConversionRate] ;
   
   Opportunity conopp = [select  CurrencyIsoCode,amount,closedate  from opportunity where id = :trigger.newmap.keyset() ];  
   
    for(Opportunity o : trigger.new) 
    {
     oppid.add(o.id);
     oppiso.add(o.CurrencyIsoCode);
     cdate.add(o.closedate);
    }
    
   Double cts = [SELECT ConversionRate FROM DatedConversionRate 
                 where isocode IN :oppiso and 
                       startdate <= :cdate 
                 order by startdate desc limit 1].conversionRate;
                 
                  
   for(Opportunity ops : trigger.new) 
   {
    ops.CURRENCY_RATE__c = cts;
    }
    
    }
    
  catch (Exception e)
{
  system.debug(e);
     for(Opportunity ops : trigger.new) 
   {
    ops.CURRENCY_RATE__c = null;
    }
  }  
}

Please suggest me how to fix this issue in code or process builder
  • October 10, 2017
  • Like
  • 0
Hello Developers,
Below is my code to find total number of contacts for an account. Everything works fine here. I need to write a test class for this code. Can anyone help me with this....
trigger TriggerCntact on Contact (after insert, after delete) {
	set<ID> accSet = new Set<Id>();
    if(trigger.isinsert){
        for(Contact Con : Trigger.new){
            accSet.add(con.AccountId);
        }
    }
        if(trigger.isDelete){
        for(Contact Con : Trigger.old){
            accSet.add(con.AccountId);
        }
    }
    List<Account> acclist = [SELECT Id from Account WHERE ID IN :accSet];
    List<Contact> conlist = [SELECT AccountId FROM Contact WHERE AccountId IN :accSet];
    list<Contact> listCon = new List<Contact>();
    list<Account> listacc = new List<Account>();
    map<String, Integer> conMap = new Map<String, Integer>();
    for(Account acnt : acclist){
        listCon.clear();
        for(contact cont : conlist){
            if(cont.AccountId == acnt.Id){
                listcon.add(cont);
            ConMap.put(cont.AccountId, listCon.size());
            }
        }
    }
    if(acclist.size()>0){
        for(account a : acclist){
            if(conMap.get(a.Id)==NULL){
                a.Total_Contacts__c	= 0;
            }
            else{
                a.Total_Contacts__c	= ConMap.get(a.Id);
                listacc.add(a);
            }
        }
        if(listacc.size()>0){
            update Listacc;
        }
    }
}

Thanks in Advance!!​
Have a Trigger on task to populate the DUE DATE field to a new custom field. It's populating value in sandbox but not in production Environment. didn't understand why, please give any suggestions/resolution???
Thanks in advance
Hi, 
I am newbie here and pretty new to SFDC. I would like to achieve following
1. On opportunity stage - when I select "Opp Lost" - I need it to auto change all records in related list (custom object) picklist field to "Opp Lost"
2. But if I select opportunity stage "Opp Won" - I need it to change the records to "Opp Won" that are currently "In Progress" stage. Any records that are selected "Opp Lost" are not changed.
FYI - In Opportunity stage - we have 7 stage including "Opp Lost" & "Opp Won" however in the related list custom object picklist field - we have 3 stages "Opp Won", "In Progress" & "Opp Lost" 
How can I achieve this? Coding is not an option since I am a rookie.
Thanks / Ram