• Shree K
  • NEWBIE
  • 125 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 59
    Questions
  • 22
    Replies
Hi All, I picked up trigger 1 from trailhead (believing effeciently written ) where Map is used at point in the trigger but I was able to achieve what trigger 1 is doing by using list in trigger 2 (written by me) now what I wonder is I don't see any necessity of using Map in trigger 1.

I am curious to know if both the triggers are effeciently written or only one of them, if so why ?

Trigger - 1
 
trigger AddRelatedRecord1 on Account(after insert) {

    List<Opportunity> oppsToInsrt = new List<Opportunity>();
    // Get the related opportunities for the accounts in this trigger

    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
        [SELECT Id,Name,(SELECT Id,StageName,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
    
    // Add an opportunity for each account if it doesn't already have one.
    // Iterate through each account.
    for(Account a : Trigger.New) {
        System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
        // Check if the account already has a related opportunity.
        if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
        
            // If it doesn't, add a default opportunity
            oppsToInsrt.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       AccountId=a.Id));
        }           
    }
    if (oppsToInsrt.size() > 0) {
        insert oppsToInsrt;
    }
}

Trigger - 2
 
trigger AddRelatedRecord2 on Account(after insert) {
   
    List<Opportunity> oppList = new List<Opportunity>();  
    
    List<Account> acctsWithOpps = new List<Account>(
        [SELECT Id,Name,city__c,(SELECT Id,stageName,closeDate,city__c FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

    for(Account a : acctsWithOpps) {
           
        if (a.Opportunities.size() == 0) {
          
            oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       City__c = a.city__c,
                                       AccountId=a.Id));
        }           
    }
    if (oppList.size() > 0) {
        insert oppList;
    }
}

 
Hi All, I am aware that trigger can process or perform DML operations on 10000 per transaction but I am still not clear if trigger does all 10000 records at a time or in sepearate chunks similar to batch apex procesing.

Below is my understanding so far about how records are processed in SF, Please feel free to provide your inputs if I am wrong.

For Example, If 1 Million records are inserted through Dataloader. It will push 10000 records in one go and if this leads to any trigger fire in order to update records , trigger will be able to update 10000 records per transaction(no such concept as chunks/batch size like in batch apex). am I correct?

Finally is there any way to perform DML operation on more than 10000 records in a transaction using sysnchronous apex(triggers) other than Aynchronous apex(batch apex)? 
Hi Devs, I would like to try custom lightning components challenges(other than trailhead) as many as possible to have more insight into SLDS.
Could you please post any interesting,real time scenarios or challenges from your experience which required tricky solutions?
Hi All,
Is there any way to make a field editable based on the Picklist value of another field through configuration (without any apex or Vf code)?
Ex: "Primary" and "Secondary" are picklist values of field SGT request, if Primary is selected Comments(text) field should become editable so that users can enter text and save.

Thanks
Shree
Hi All,
Can somone please explain the differences between implementing pagination with standardSetController and StandardListController? in another words when is it ideal to use a list controller and a set controller to implement pagination, Pros and cons for each? all i need is few points because i get to see the code and examples of implementing pagination in both ways and have a clear understading of implementing pagination using list controller but my interest is to about the differences between both ways.

My humble request to not post the blogspots online, I have been there already and couldn't find the differences.

Thanks,
Shree
Hi All,
after a bit of reading about to have the total count of the records which were processed in the Batch class, I came across both Database.Stateful and Database.Saveresult online, but both seems to be doing pretty much samething one itself and by combining both.

1) If we have to have the total count the records which were processed  in the batch apex, should we use both Database.stateful and Database.saveResult, if not ,can someone please explain me the difference between these two and their explicit usage ? 

2) In the 1st link below some of them suggesting database.stateful alone and some database.saveresult alone but in the 2nd link both were used to get the count of the records which were processd, actually this caused me the confusion.
https://salesforce.stackexchange.com/questions/82969/count-of-records-processed-during-batch
https://developer.salesforce.com/forums/?id=906F0000000kGqFIAU
3) once the batch is complete, where would i be able to see the results?
help will be appreciated,

Thanks,
Shree
Hi All,
Trying to write few triggers while learning but facing few issues to make them work as expected, below is the trigger code and the issues/errors Please feel free to provide your inputs as comments.

Trigger 1:

 /* Challenge: whenever a contact is either inserted or updated with an account,
 the Primary_Account__c (Text field on contact) has to be updated with account name(text formate),
 I am unable to convert AccountId to Account Name (as text). */ 

Trigger2:

 /* Challege is to query only Accounts which have Opportunities and 
 whenever an account is either inserted or updated with its Primary_Account__c(checkbox field)=True then its related 
 Opportunity which has a Primary_Account__c(Text field) has to be updated as 'Yes'.
    
 I am Trying to query and Iterate over only accounts which have Opps in this trigger,
 Please feel free to better up the query if it is not properly written,
 but in a way that it retrieves only accounts which have Opps. */
//Trigger 1

Trigger ContactTrigger on Contact (before insert,before update){

list <Contact> Cons = New List<Contact>();

list <Contact> ConsWithAccts = [select Id,Name,AccountId from Contact where Id IN:trigger.New AND AccountId!=Null];
for (contact c:ConsWithAccts){
    if (ConsWithAccts.size()>0){
  
      //I am stuck here.
}
}
}

// Trigger 2:

trigger UpdateRelatedOpp on Account(after insert,after update) {
     
    List<Opportunity> oppList = new List<Opportunity>();
    for (Account a : [SELECT Id,Name,(select Id,AccountId from Opportunities) FROM Account WHERE Primary_Account__c = True AND Id IN :Trigger.New ]) {
        
        //I'm Stuck here.
    }
    
    if (oppList.size() > 0) {
        update oppList;
    }
 }
Hi All,

Could someone please give me an exclusive case where Trigger.NewMap/OldMap could be the ultimate solution when compared to using trigger.new/trigger.Old? I am here after spending lot of time reading about trigger context variables and getting familier with the difference between them but when i started using them my self in the code I have noticed things are getting done even when interchangeably used Trigger.New in place Trigger.NewMap or trigger.Old in place Trigger.OldMap.

1) if i have to compare old and new values field values of a record or its related record , wouldn't just Trigger.New/Trigger.Old be enough?

Note: I am aware that, here I am talking about a list(Trigger.New/Ol) and a Map(Trigger.NewMap/oldMap) and I can't use Trigger.NewMap in the event of before insert event.
Hi All,
I have a custom object Interests (with only 2 Record types Primary and Secondary) which is a child to Account (lookup relationship) and Account has a Related List to create child records.

1) Standard Process : The standard "New" button lets the users to redirect and select the record type of their choice to create Child records(Interests).
what i am looking for is a customized solution (Probably URL hacking) with a custom list button which should redirect the users straight away to the edit mode and Prepopulate the Account (Parent ID) and the Primary (record type) on the  child record that is going to be created,in other words when the users are redirected from the Parent Record(Account) the child record that is going to be created should have the Parent Id in the lookup field and be with its record type as Primary.
I am thinking of 2 ideas:
1) Having a custom button, upon click the users would be on edit mode by auto populating Record type (in the standad field) and the parent ID.
2) Having a custom button which lets the users to a custom VF Page where there would be only a button, upon click of the button the record type will be populated as Primary and auto populating the Parent id when creating the child record.

Now all i need is a URL to make the things work, Please let me know if anyone has a better idea or with the possible apex work around for the URl part.

Thanks.  
  • September 16, 2018
  • Like
  • 0
I am aware of manually restricting a record type access to a profile but i have over 100 profiles which should have restriction to a specific record type, I wonder, is there any other way like eclipse etc to do this?
Hi All,
Can someone help me on how to make use of Record Types in formulas instead of using their Ids? so that the formula would be working for records created by that particular Record Type,

For Example how can i avoid using Ids in the below formula
IF( 

AND( 
ISNULL(Request_Date__c) 
,	
( 
RecordTypeId = '01234567Abcdefg' 
|| 
AND( 
NOT(ISBLANK(Text(Process_Type__c))) 
, 
RecordTypeId = '7654321Abcdefgh' 
) 
) 
)

 
Hi All,
I have an Apex class Class1 with method1,method2 and method3 in it, i would like to set a static variable V1=True initially and have below trigger to be run when the Static variable V1 is false.
trigger Trigger1 on Account (before insert, before update) {


    if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isBefore){
        Class1.Method1(Trigger.new);
        Class1.Method2(Trigger.new);
    }
    if((Trigger.isInsert || Trigger.isupdate) && Trigger.isAfter){
    
        Class1.Method3(Trigger.new,trigger.old);
    }  

}
Help will be appreiated,

Thanks
CvK
I have a VR that makes a field required , I would like to have this to be excluded while cloning(custom button), Please let me know if this possible through configuration, currently cloning process is handling by an Apex class in my Org,if apex is the way to resolve this issue, sample piece of code would be much appreciated.
Either bypassing the VR or making the Product__c field empty upon cloning works for me.
VR as follows:
AND(RecordType.Name = 'Global', 
ISBLANK(Product__c), 
OR(IsPickVal(Confirmed__c,"Yes")))

Thanks
CK
Hi Everyone,
I need to use a condition , when ever  an Opportunity is created with its stage as 'Won' and recordtype name as 'Global' a record in custom Object has to be created ,i am good till here , what I wonder is , Is there any way that i can use Opportunity Object's record type name without querying RecordType Object, all i am looking for is a condition like below to be built without querying another Object coz i already have a list Opp,

If (Opp.StageName='Confirmed' && RecordTypeName(would like to use this as a string )= 'Global') 

Thanks
Ck


 
Hi All,
Need help on bulding a formula for process builder, 
During the life cycle of an Opportunity the stage field would be updated as 'Confirmed'  i.e either at the time of creation or when edited later,then the process builder action(creating child record) has to be triggered only for the first time, My current criteria in PB acting as evaluation criteria in WFR like 'Created or every time edited' instead it should act like 'created, and any time it’s edited to subsequently meet criteria', To keep this short, even if the Stage Field is updated as 'Confirmed' many times PB action should fire and create child record only once, that is for the first time.

Help will be appreciated,

Thanks
Hi ,
need help with the trigger to send emails upon Account owner change,
below is my trigger code,which is not working,
help will be appreciated,
 
trigger EmailSend on Account (after insert,after update) {

List<account> acclist  = new set<account>();
For(account a:trigger.new){
If (a.ownerid != oldmap.get (a.id).ownerid)
acclist.add (a.id);
}
Messaging.SingleEmailMessage mails = new Messaging.SingleEmailMessage(); 
for(account acc:acclist) { 
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  mail.setTargetObjectId(acc.ownerid); 
mail.setTemplateId('templateid'); mail.setWhatId(acc.id); mail.setBccSender(false); mail.setUseSignature(false);  mail.setSaveAsActivity(false); 
mails.add(mail);
 } Messaging.sendEmail(mails);
}
Thanks


 
Unable to save case record with attachment, code as follows,help will be appreciated.
 
<apex:page standardController="Case" Extensions="CaseHandlerExtn" ShowHeader="False">
<apex:form >
<apex:pageBlock Title="Submit a Case" >
<apex:PageBlockSection Title="Section 1" columns="1">
<apex:PageblockSectionItem >
<apex:outputLabel >Contact Name</apex:outputLabel>
<apex:InputField Id="Id1" value="{!Case.ContactId}"/>
</apex:PageblockSectionItem>
<apex:PageblockSectionItem >
<apex:outputLabel >Email</apex:outputLabel>
<apex:inputField Id="Id2" value="{!Case.ContactEmail}" />
</apex:PageblockSectionItem>
<apex:PageblockSectionItem >
<apex:outputLabel >Subject</apex:outputLabel>
<apex:inputField Id="Id2" value="{!Case.subject}" />
</apex:PageblockSectionItem>
<apex:PageblockSectionItem >
<apex:outputLabel >Description</apex:outputLabel>
<apex:inputField Id="Id2" value="{!Case.Description}" />
</apex:PageblockSectionItem>
</apex:PageBlockSection>
<apex:pageBlockButtons >

<apex:commandButton Id="Cancel" action="{!Cancel}" Value="Cancel" />

</apex:pageBlockButtons>
<apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
            <apex:commandButton Id="save" action="{!Save}" value="Save" />
       </apex:pageBlock>
</apex:pageBlock>
</apex:form>  
</apex:page>
 
Public Class CaseHandlerExtn {

Public attachment Atchmnt {get;set;}
Public Case Cs{get;set;}
Public Blob Filebody{get;set;}
Public String FileName{get;set;}
Public Id RecId {get;set;}

//Public Contact Con{get;set;}

Public CaseHandlerExtn (Apexpages.StandardController StndCntlr){
      Atchmnt = New attachment();
       RecId = StndCntlr.getRecord().Id; 
      Cs = New Case(status='New',Origin='Web');    
         }
         
 Public Void SaveCase(){
  insert Cs;
  Atchmnt.ParentId=Cs.Id;
  Insert Atchmnt ;
   
  }
  
  public PageReference UploadFile()
    {
        PageReference pr;
        if(fileBody != null && fileName != null)
        {
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }      
}


 
I did run lightning experience readiness check report and while going through this report I found that there are couple of button/ links which are not assigned to page layout,  where in when I went through each of these links I found these button/ links are related to one or many page layout as well these layouts are assigned to profile,  as well when I preview my org in LE I  can see these buttion/links available to me,  can somebody explain or guide me as to why report is saying that these buttons are not assigned to page layout?
Hi Everyone,
Can someone help me finding if there are any references or docs that have prerequisites and step by step process to build force.com authenticated sites from scratch.

Thanks
Ckrdy
Hi
It makes sense to me that, Too many dml rows:10001 because of more than 10000 records being inserted,
Note: I have a soql query in my batch apex which is currently not limited by (Limit keyword in the query).i dont think i can do this because there is a possibility of some millions of records to be processed.
Currently there is no batch size set,I am not sure if limiting or decreasing my batch size is going to solve this problem o.
Help will be appreciated.

Here is my batch apex code and scheduler,
 
global class batchLogBookManagementV2 implements Database.Batchable<sObject>, Database.Stateful {

global List<Log_Book__c> logToBeContinued = new List<Log_Book__c> ();
global List<Log_Book__c> logToBeInserted = new List<Log_Book__c> ();    
global List<Subject_Registered__c> sbsr = new List<Subject_Registered__c> ();
    
    global List<Weeks__c> weekList = Weeks__c.getAll().values();
    global Map<Integer, Weeks__c> weekMap = new Map<Integer, Weeks__c>();
    global Map<String, Integer> weekMapGetIntWithWeek = new Map<String, Integer>();    
    global Map<String, Subjects_and_Levels__c> subjectLevelMap =  Subjects_and_Levels__c.getAll();
    global List<Subjects_and_Levels__c> subjectLevelList = subjectLevelMap.values();
    global Map<String, Subjects_and_Levels__c> levelMap = new Map<String, Subjects_and_Levels__c>();
    

        
global final String query = 'SELECT id,Last_Schedule__c, Level__c, Student__c, Subject__c, Week__c, (SELECT Student__c, Subjects_Registered__c, Subject__c, Class_Scheduled_Date__c, Level__c, Week__c FROM Log_Books__r ORDER By Class_Scheduled_Date__c DESC NULLS FIRST LIMIT 1 ) FROM Subject_Registered__c WHERE Deactivated__c = false AND Last_Schedule__c != null';
 
 
global Iterable<sObject> start(Database.BatchableContext BC){
     sbsr = Database.query(query);
     for(Subject_Registered__c s: sbsr)
     {
         logToBeContinued.add(s.log_Books__r[0]);         
     }
    
    return logToBeContinued;
    }
 
global void execute(Database.BatchableContext BC,List<Log_Book__c> scope){
     for(Subjects_and_Levels__c level: subjectLevelList)
     {
     system.debug('level : '+level);
         if(level !=null)
         levelMap.put(level.subject__c+Integer.valueof(level.Order__c), level);
         else
             system.debug('error as level null');
     }
    for(Weeks__c week : weekList)
    {
    system.debug('week : '+week);
        if(week != null){
            weekMap.put((Integer)week.Order__c, week);
            weekMapGetIntWithWeek.put(week.Name, (Integer)week.Order__c);
        }
    }
     System.debug('++++++++++++++++++++++++   : ' + scope);
     for(Log_Book__c s: scope)
     {
         
         System.debug('logToBeInserted--------------------------------   : ' + logToBeInserted.size());
         System.debug('--------------------------------   : ' + s);
         Integer totalLevels = 0;
          if(s.Subject__c == 'English')
            totalLevels = 15;
          else if(s.Subject__c == 'Abacus')
            totalLevels = 11;
          else if(s.Subject__c == 'Math')
            totalLevels = 14;
          else if(s.Subject__c == 'G.K')
            totalLevels = 4;
         System.debug('xxxxxxxxxxxxxxxx  : ' + subjectLevelMap);
          
         System.debug('@@Subject@@@@@@@'+subjectLevelMap.get(s.Subject__c+s.level__c) );
          
            if(subjectLevelMap.containsKey(s.Subject__c+':'+s.Level__c) && (s.Class_Scheduled_Date__c != null))
            {
                
            Integer levelOrder = Integer.valueof(subjectLevelMap.get(s.Subject__c +':'+s.Level__c).Order__c);
             system.debug('level order: '+levelOrder);
            Integer weekOrder = Integer.ValueOf(weekMapGetIntWithWeek.get(s.Week__c));
             system.debug('week order: '+weekOrder);
             Log_Book__c l = new Log_Book__c (); 
         l.Student__c = s.Student__c;
         l.Subject__c = s.Subject__c;
         l.Subjects_Registered__c = s.Subjects_Registered__c;
         l.Class_Scheduled_Date__c = s.Class_Scheduled_Date__c.addDays(7);
                System.debug('class schedule date is--->'+l.Class_Scheduled_Date__c);
           
         if(s.Week__c == '26-Z')
         {
             if(levelOrder != null && levelOrder < totalLevels)
             {
                 levelOrder = levelOrder +1;
                 System.Debug('lb.Subject__c+levelOrder : '+ l.Subject__c+levelOrder);
                 l.level__c = levelMap.get(l.Subject__c+levelOrder).Level__c;
                 l.Week__c = '1-A';
                 logToBeInserted.add(l);
             }
             
         }
         else
          if(s.Subject__c == 'Math' && s.Level__c == 'Level 5B' && s.Week__c == '17-Q')
            {
              if(levelOrder != null && levelOrder < totalLevels)
             {
                 levelOrder = levelOrder +1;
                 System.Debug('lb.Subject__c+levelOrder : '+ l.Subject__c+levelOrder);
                 l.level__c = levelMap.get(l.Subject__c+levelOrder).Level__c;
                 l.Week__c = '1-A';
                 logToBeInserted.add(l);
             }
       
            }
         else
         {
                weekOrder = weekOrder+1;
                l.Week__c = weekMap.get(weekOrder).Name;
                l.Level__c = s.Level__c;
                logToBeInserted.add(l);
                    
         }
    }  
     }//for
    if(logToBeInserted.size()>0)
    {
               
        Database.UpsertResult[] srList = Database.upsert(logToBeInserted, false);
        
        // Iterate through each returned result
        for (Database.UpsertResult  sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('Successfully inserted LogBook. LogBook ID: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                }
            }    
        
        }
        
    }
     //System.debug('###############################  :' + ((Subject_Registered__c)scope.get(0)).log_Book__r.Class_Scheduled_Date__c);
     System.debug('Scope of the record is'+scope.size());
    // scope variable now has the records received from QueryLocator.
  //  delete scope;    
   // Database.emptyRecycleBin(scope);
    }
 
global void finish(Database.BatchableContext BC){
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id =:BC.getJobId()];
 
    // Send an email to the Apex job's submitter
    // notifying of job completion.
  
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BAtch: ' + a.Status);
 //mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures.');
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures and Status'+a.status);
 
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
  }
}

//////////////////////////////////////////

global class scheduledLogBookBatch implements Schedulable
{
   global void execute(SchedulableContext SC) {
   
       batchLogBookManagementV2 p = new batchLogBookManagementV2(); 
       if(!Test.isRunningTest())
       Database.executeBatch(p);
       
   }
}

 
Hi, 
Most of the procedural languages like SQL have locking,blocking and deadlocking issues,wondering if apex has blocking issues,coz i have seen posts about locking and deadlocking but not blocking relating to apex, could some one eloborate each of those with an example if possible and any statements that helps to troublshoot, like FOR UPDATE statement for locking records
  • September 30, 2015
  • Like
  • 2
Hi All, I picked up trigger 1 from trailhead (believing effeciently written ) where Map is used at point in the trigger but I was able to achieve what trigger 1 is doing by using list in trigger 2 (written by me) now what I wonder is I don't see any necessity of using Map in trigger 1.

I am curious to know if both the triggers are effeciently written or only one of them, if so why ?

Trigger - 1
 
trigger AddRelatedRecord1 on Account(after insert) {

    List<Opportunity> oppsToInsrt = new List<Opportunity>();
    // Get the related opportunities for the accounts in this trigger

    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
        [SELECT Id,Name,(SELECT Id,StageName,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
    
    // Add an opportunity for each account if it doesn't already have one.
    // Iterate through each account.
    for(Account a : Trigger.New) {
        System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
        // Check if the account already has a related opportunity.
        if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
        
            // If it doesn't, add a default opportunity
            oppsToInsrt.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       AccountId=a.Id));
        }           
    }
    if (oppsToInsrt.size() > 0) {
        insert oppsToInsrt;
    }
}

Trigger - 2
 
trigger AddRelatedRecord2 on Account(after insert) {
   
    List<Opportunity> oppList = new List<Opportunity>();  
    
    List<Account> acctsWithOpps = new List<Account>(
        [SELECT Id,Name,city__c,(SELECT Id,stageName,closeDate,city__c FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

    for(Account a : acctsWithOpps) {
           
        if (a.Opportunities.size() == 0) {
          
            oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       City__c = a.city__c,
                                       AccountId=a.Id));
        }           
    }
    if (oppList.size() > 0) {
        insert oppList;
    }
}

 
Hi All, I am aware that trigger can process or perform DML operations on 10000 per transaction but I am still not clear if trigger does all 10000 records at a time or in sepearate chunks similar to batch apex procesing.

Below is my understanding so far about how records are processed in SF, Please feel free to provide your inputs if I am wrong.

For Example, If 1 Million records are inserted through Dataloader. It will push 10000 records in one go and if this leads to any trigger fire in order to update records , trigger will be able to update 10000 records per transaction(no such concept as chunks/batch size like in batch apex). am I correct?

Finally is there any way to perform DML operation on more than 10000 records in a transaction using sysnchronous apex(triggers) other than Aynchronous apex(batch apex)? 
Hi All,
Can somone please explain the differences between implementing pagination with standardSetController and StandardListController? in another words when is it ideal to use a list controller and a set controller to implement pagination, Pros and cons for each? all i need is few points because i get to see the code and examples of implementing pagination in both ways and have a clear understading of implementing pagination using list controller but my interest is to about the differences between both ways.

My humble request to not post the blogspots online, I have been there already and couldn't find the differences.

Thanks,
Shree
Hi All,
after a bit of reading about to have the total count of the records which were processed in the Batch class, I came across both Database.Stateful and Database.Saveresult online, but both seems to be doing pretty much samething one itself and by combining both.

1) If we have to have the total count the records which were processed  in the batch apex, should we use both Database.stateful and Database.saveResult, if not ,can someone please explain me the difference between these two and their explicit usage ? 

2) In the 1st link below some of them suggesting database.stateful alone and some database.saveresult alone but in the 2nd link both were used to get the count of the records which were processd, actually this caused me the confusion.
https://salesforce.stackexchange.com/questions/82969/count-of-records-processed-during-batch
https://developer.salesforce.com/forums/?id=906F0000000kGqFIAU
3) once the batch is complete, where would i be able to see the results?
help will be appreciated,

Thanks,
Shree
Hi All,
Trying to write few triggers while learning but facing few issues to make them work as expected, below is the trigger code and the issues/errors Please feel free to provide your inputs as comments.

Trigger 1:

 /* Challenge: whenever a contact is either inserted or updated with an account,
 the Primary_Account__c (Text field on contact) has to be updated with account name(text formate),
 I am unable to convert AccountId to Account Name (as text). */ 

Trigger2:

 /* Challege is to query only Accounts which have Opportunities and 
 whenever an account is either inserted or updated with its Primary_Account__c(checkbox field)=True then its related 
 Opportunity which has a Primary_Account__c(Text field) has to be updated as 'Yes'.
    
 I am Trying to query and Iterate over only accounts which have Opps in this trigger,
 Please feel free to better up the query if it is not properly written,
 but in a way that it retrieves only accounts which have Opps. */
//Trigger 1

Trigger ContactTrigger on Contact (before insert,before update){

list <Contact> Cons = New List<Contact>();

list <Contact> ConsWithAccts = [select Id,Name,AccountId from Contact where Id IN:trigger.New AND AccountId!=Null];
for (contact c:ConsWithAccts){
    if (ConsWithAccts.size()>0){
  
      //I am stuck here.
}
}
}

// Trigger 2:

trigger UpdateRelatedOpp on Account(after insert,after update) {
     
    List<Opportunity> oppList = new List<Opportunity>();
    for (Account a : [SELECT Id,Name,(select Id,AccountId from Opportunities) FROM Account WHERE Primary_Account__c = True AND Id IN :Trigger.New ]) {
        
        //I'm Stuck here.
    }
    
    if (oppList.size() > 0) {
        update oppList;
    }
 }
Hi All,

Could someone please give me an exclusive case where Trigger.NewMap/OldMap could be the ultimate solution when compared to using trigger.new/trigger.Old? I am here after spending lot of time reading about trigger context variables and getting familier with the difference between them but when i started using them my self in the code I have noticed things are getting done even when interchangeably used Trigger.New in place Trigger.NewMap or trigger.Old in place Trigger.OldMap.

1) if i have to compare old and new values field values of a record or its related record , wouldn't just Trigger.New/Trigger.Old be enough?

Note: I am aware that, here I am talking about a list(Trigger.New/Ol) and a Map(Trigger.NewMap/oldMap) and I can't use Trigger.NewMap in the event of before insert event.
Hi All,
Can someone help me on how to make use of Record Types in formulas instead of using their Ids? so that the formula would be working for records created by that particular Record Type,

For Example how can i avoid using Ids in the below formula
IF( 

AND( 
ISNULL(Request_Date__c) 
,	
( 
RecordTypeId = '01234567Abcdefg' 
|| 
AND( 
NOT(ISBLANK(Text(Process_Type__c))) 
, 
RecordTypeId = '7654321Abcdefgh' 
) 
) 
)

 
Hi
It makes sense to me that, Too many dml rows:10001 because of more than 10000 records being inserted,
Note: I have a soql query in my batch apex which is currently not limited by (Limit keyword in the query).i dont think i can do this because there is a possibility of some millions of records to be processed.
Currently there is no batch size set,I am not sure if limiting or decreasing my batch size is going to solve this problem o.
Help will be appreciated.

Here is my batch apex code and scheduler,
 
global class batchLogBookManagementV2 implements Database.Batchable<sObject>, Database.Stateful {

global List<Log_Book__c> logToBeContinued = new List<Log_Book__c> ();
global List<Log_Book__c> logToBeInserted = new List<Log_Book__c> ();    
global List<Subject_Registered__c> sbsr = new List<Subject_Registered__c> ();
    
    global List<Weeks__c> weekList = Weeks__c.getAll().values();
    global Map<Integer, Weeks__c> weekMap = new Map<Integer, Weeks__c>();
    global Map<String, Integer> weekMapGetIntWithWeek = new Map<String, Integer>();    
    global Map<String, Subjects_and_Levels__c> subjectLevelMap =  Subjects_and_Levels__c.getAll();
    global List<Subjects_and_Levels__c> subjectLevelList = subjectLevelMap.values();
    global Map<String, Subjects_and_Levels__c> levelMap = new Map<String, Subjects_and_Levels__c>();
    

        
global final String query = 'SELECT id,Last_Schedule__c, Level__c, Student__c, Subject__c, Week__c, (SELECT Student__c, Subjects_Registered__c, Subject__c, Class_Scheduled_Date__c, Level__c, Week__c FROM Log_Books__r ORDER By Class_Scheduled_Date__c DESC NULLS FIRST LIMIT 1 ) FROM Subject_Registered__c WHERE Deactivated__c = false AND Last_Schedule__c != null';
 
 
global Iterable<sObject> start(Database.BatchableContext BC){
     sbsr = Database.query(query);
     for(Subject_Registered__c s: sbsr)
     {
         logToBeContinued.add(s.log_Books__r[0]);         
     }
    
    return logToBeContinued;
    }
 
global void execute(Database.BatchableContext BC,List<Log_Book__c> scope){
     for(Subjects_and_Levels__c level: subjectLevelList)
     {
     system.debug('level : '+level);
         if(level !=null)
         levelMap.put(level.subject__c+Integer.valueof(level.Order__c), level);
         else
             system.debug('error as level null');
     }
    for(Weeks__c week : weekList)
    {
    system.debug('week : '+week);
        if(week != null){
            weekMap.put((Integer)week.Order__c, week);
            weekMapGetIntWithWeek.put(week.Name, (Integer)week.Order__c);
        }
    }
     System.debug('++++++++++++++++++++++++   : ' + scope);
     for(Log_Book__c s: scope)
     {
         
         System.debug('logToBeInserted--------------------------------   : ' + logToBeInserted.size());
         System.debug('--------------------------------   : ' + s);
         Integer totalLevels = 0;
          if(s.Subject__c == 'English')
            totalLevels = 15;
          else if(s.Subject__c == 'Abacus')
            totalLevels = 11;
          else if(s.Subject__c == 'Math')
            totalLevels = 14;
          else if(s.Subject__c == 'G.K')
            totalLevels = 4;
         System.debug('xxxxxxxxxxxxxxxx  : ' + subjectLevelMap);
          
         System.debug('@@Subject@@@@@@@'+subjectLevelMap.get(s.Subject__c+s.level__c) );
          
            if(subjectLevelMap.containsKey(s.Subject__c+':'+s.Level__c) && (s.Class_Scheduled_Date__c != null))
            {
                
            Integer levelOrder = Integer.valueof(subjectLevelMap.get(s.Subject__c +':'+s.Level__c).Order__c);
             system.debug('level order: '+levelOrder);
            Integer weekOrder = Integer.ValueOf(weekMapGetIntWithWeek.get(s.Week__c));
             system.debug('week order: '+weekOrder);
             Log_Book__c l = new Log_Book__c (); 
         l.Student__c = s.Student__c;
         l.Subject__c = s.Subject__c;
         l.Subjects_Registered__c = s.Subjects_Registered__c;
         l.Class_Scheduled_Date__c = s.Class_Scheduled_Date__c.addDays(7);
                System.debug('class schedule date is--->'+l.Class_Scheduled_Date__c);
           
         if(s.Week__c == '26-Z')
         {
             if(levelOrder != null && levelOrder < totalLevels)
             {
                 levelOrder = levelOrder +1;
                 System.Debug('lb.Subject__c+levelOrder : '+ l.Subject__c+levelOrder);
                 l.level__c = levelMap.get(l.Subject__c+levelOrder).Level__c;
                 l.Week__c = '1-A';
                 logToBeInserted.add(l);
             }
             
         }
         else
          if(s.Subject__c == 'Math' && s.Level__c == 'Level 5B' && s.Week__c == '17-Q')
            {
              if(levelOrder != null && levelOrder < totalLevels)
             {
                 levelOrder = levelOrder +1;
                 System.Debug('lb.Subject__c+levelOrder : '+ l.Subject__c+levelOrder);
                 l.level__c = levelMap.get(l.Subject__c+levelOrder).Level__c;
                 l.Week__c = '1-A';
                 logToBeInserted.add(l);
             }
       
            }
         else
         {
                weekOrder = weekOrder+1;
                l.Week__c = weekMap.get(weekOrder).Name;
                l.Level__c = s.Level__c;
                logToBeInserted.add(l);
                    
         }
    }  
     }//for
    if(logToBeInserted.size()>0)
    {
               
        Database.UpsertResult[] srList = Database.upsert(logToBeInserted, false);
        
        // Iterate through each returned result
        for (Database.UpsertResult  sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('Successfully inserted LogBook. LogBook ID: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                }
            }    
        
        }
        
    }
     //System.debug('###############################  :' + ((Subject_Registered__c)scope.get(0)).log_Book__r.Class_Scheduled_Date__c);
     System.debug('Scope of the record is'+scope.size());
    // scope variable now has the records received from QueryLocator.
  //  delete scope;    
   // Database.emptyRecycleBin(scope);
    }
 
global void finish(Database.BatchableContext BC){
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id =:BC.getJobId()];
 
    // Send an email to the Apex job's submitter
    // notifying of job completion.
  
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BAtch: ' + a.Status);
 //mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures.');
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures and Status'+a.status);
 
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
  }
}

//////////////////////////////////////////

global class scheduledLogBookBatch implements Schedulable
{
   global void execute(SchedulableContext SC) {
   
       batchLogBookManagementV2 p = new batchLogBookManagementV2(); 
       if(!Test.isRunningTest())
       Database.executeBatch(p);
       
   }
}

 
Hi All,
Can some provide me a sample before insert trigger code or references to limit a user (Logged in user) to create only 100 cases in a month,

Thanks
Ckrdy
Hi, 
i have a command button in one outputpanel,when user clicks on that button a fieldset has to be dispalyed in another outputpanel(even the outputpanel has to be displayed only after onclick of that button,
help will be appreciated,

Thanks
chhakri
 
Hi, 
Based on the picklist values its asssigned fieldsets has to be displayed on the visualforce page,where the fields in the fieldset are required fields,so when i made them required either by using  the flag required="{!OR(f.DBRequired, f.required)}" or <apex:inputField value="{!Dom[f]}" required="{!i.DBRequired}", my page is not rerendering untill i fill the fields and click on save button it is not allowing me to select another value even if i select another option its related fieldset is not being displayed onthe page.on the other hand if remove those dbrequired/required parameters everything works fine but the fields in the fieldset are acting as, not required.
help will be appreciated in resolving this problem.

All that i need is when a picklist value is selected a fieldset assigned to it should be displayed and the fields should be madatory fields for the user
if there there any change of selection it has to do the same thing as it did for the previous selection.

Note: I trying to do this on a Webform for a custom object,not using any particular pageblock.

For Eg:
                                    <apex:selectOption itemLabel="Bio" itemValue="Bio"></apex:selectOption>
                                     <apex:selectOption itemLabel="Pharma" itemValue="Pharma"></apex:selectOption>

                    <apex:outputPanel id="fieldSet">
                    <apex:repeat value="{!$ObjectType.Domain_Obj__c.FieldSets[RequestValue]}" var="f">             
                    <apex:outputText value="*" style="float:left; position:relative; color:red;" rendered="{!OR(f.DBRequired, f.required)}"/>
                       <div class="row margin">
                        <div class="small-12 columns">
                           <legend> {!f.label}</legend>
                           <br/>
                            <apex:inputField value="{!Myextn[f]}"/>
                            <br/>
                        </div>
                      </div>
                    </apex:repeat>
                    </apex:outputPanel>

Thanks
CkRdy
Hi,

how to call a fieldset on visualforce page based on the selected option of the picklist field value in salesforce?if npossible An example Apex code will be highly appreciated.

Thanks
CKrdY
Hi
I have a requirement to displays records in pageblock based on "OnClick" event on the pageblock button with render attribute,
That mean when ever the pageblock button is clicked records should be displayed within that pageblock, i am failing to acheive this,
help will be appreciated,

Below is my controller and Vf page code for the reference:

Controller:

public with sharing class DisplayQueryList{ 
public List<Account> Records {get; set;}
public DisplayQueryList(){ 
Records = 
[select Name, AccountNumber, CleanStatus from Account where CleanStatus='Pending']; 

}

VF Page:

<apex:page controller="TestDisplayQueryList">
  <apex:form > 
    <apex:pageBlock title="Tabular display with facet"> 
        <apex:pageBlockTable value="{!Records}" var="Record"> 
            <apex:column > 
                <apex:facet name="header">Account Name</apex:facet> 
                <apex:outputText value="{!Record.Name}"/> 
            </apex:column> 
            <apex:column > 
                <apex:facet name="header">Account Number</apex:facet> 
                <apex:outputText value="{!Record.AccountNumber}"/> 
            </apex:column> 
            <apex:column > 
                <apex:facet name="header">Clean Status</apex:facet> 
                <apex:outputText value="{!Record.CleanStatus}"/> 
            </apex:column> 
        </apex:pageBlockTable> 
    </apex:pageBlock> 
    <apex:pageBlock title="Tabular Display without facet">
    <apex:pageBlockTable value="{!records}" var="record">
        
        <apex:column value="{!record.Name}"/>
        <apex:column value="{!record.AccountNumber}"/>
        <apex:column value="{!record.CleanStatus}"/> 
              
      </apex:pageBlockTable>
    </apex:pageBlock>
   </apex:form>     
</apex:page>

Hi everyone,
what are the most often and important use cases of inline vf page other than adding them to page layouts and displaying them on the detail page?
i mean in what type of situations we can use inline vf pages as a solution?
Hi all,
In first VF page I am getting basic Lead information and I want to pass that information to another VF page which will have detailed information about the Lead. Now after click on Save button I need to pass that record information and then add more info and save that Lead.

I am facing problem with the controller

Below is my VF page code and Controller

VFpage Code:

<apex:page controller="myLeadController">
    <apex:sectionHeader title="New Lead Page" />
    <apex:form >
        <apex:pageBlock title="Create a New Lead">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>        
            <apex:pageBlockSection title="Lead Information">
                <apex:inputField id="firstName" value="{!Lead.FirstName}"/>
                <apex:inputField id="lastName" value="{!Lead.LastName}"/>
                <apex:inputField id="companyName" value="{!Lead.Company}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public class myLeadController {
    
    Lead lead;

    public Lead getLead() {
        if(lead == null) lead = new Lead();
        return lead;
    }
    
    public PageReference save() {
        // Add the lead to the database. 
        insert lead;
        // Send the user to the detail page for the new lead.
       // need to pass the record id to Thankyou Page
        PageReference leadPage = new ApexPages.Thankyou
        leadPage.setRedirect(true);
        return leadPage;
    }

}