• Jayant
  • SMARTIE
  • 794 Points
  • Member since 2010


  • Chatter
    Feed
  • 24
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 274
    Replies
Hello!

Please could you help me to get the correct code to the below  issue and if it possible?

We have a custom object for requesting new users in Salesforce. If manager wants to request for create new user he needs to create new record (User Request) and provide all infomrations like name, email, profile etc. For now I create users manually using infomration on this record.
I would like to add a buton with apex code to create new user based on the infomration from this record, it si possible?

Thanks in advance!
L.
Hello, when setting USD as the currency for a line item of an opportunity, after setting the PriceBookEntry currency to USD, I get this error:

"Unable to create/update fields: CurrencyIsoCode. Please check the security settings of this field and verify that it is read/write for your profile or permission set."

What do I need to check?

The product has the active price in USD.

One thing took my attention is that when I am using Salesforce webpage, I get that the Price Book entry has the ID 01u400000044tqC, however, when I use the following query:
 
Select Id From PricebookEntry WHERE CurrencyIsoCode = '%s' AND PriceBook2.Id = '%s' AND Product2.SKU__c = '%s' AND IsActive = true AND Product2.IsActive = true
I get this Price Book entry Id 01u400000044tqCAAQ.

Is it normal to have AAQ added to the real ID?

Thanks
Jaime

trigger WBSAttachment on Project__c (before insert, before update) 
{
    
    
    Project__c[] lstProject = [SELECT Id, WBS_Attached__c, (SELECT Id, Name, ContentType FROM Attachments)  FROM Project__c where id IN :Trigger.newMap.keySet()];
    for(Project__c objProject : lstProject)
    {
        Attachment[] lstAttc = objProject.Attachments;
        if(lstAttc.size()>0 && objProject.Attachments.Name.contains('WBS'))
        {
            System.debug('Need to set Syllabus Attached to true for Opportunity Id: ' + objProject.id);
            System.debug('just testing this: ' + Trigger.newMap.get(objProject.Id).Id);
            
            Trigger.newMap.get(objProject.Id).WBS_Attached__c = true;
        }
        else
        {
            Trigger.newMap.get(objProject.Id).WBS_Attached__c = false;
        }                  
    }
    
}
I am new to Service cloud and trying to work out few examples. I created a queue with just filling the mandatory fields. I stated creating the case assginment rules with criteria and trying to find the queue which I created when selecting the dropdown "Queue". why? where am I going wrong?
I understand that you cannot add fields to the recycle bin page for a specific tab. 

I would like to retrieve deleted records from the CASE object which have a specific recordtype. 

I tried to do this in the Developer Console with SOQL but this still does not work.

I read that you need to de an SOQL All Query, I am an administrator.
Can somebody help me out here? 

Thanks,

Dave
Hi,

I have defined Object A (master) and Object B (detail) in  a master-detail relationship. I have also defined Object A.field-x inside Object B as Object B.field-x.

When Object B.field-y is populated, I would like to auto-populate Object B.field-x where ObjectB.field-y is the controlling field? Unfortunately, the standard auto-populate fields update using a workflow rule does not work as Object B.field-x is not one of the fields available for auto-population.

Thanks,
Maythil
Hi,

I have two objects called object1, object2(Master) and having lookup relationship among them, In object1 having a field called test1 and in Object2 having fields test2(piclist values are A,B), test3(picklist values x,y).
Now i am creating a validation rule on object1 to make test1 field mandatory while test2 is 'A' and test3 is 'x'

AND(ISPICKVAL(object1__r.test2__c='A'),ISPICKVAL(object2__r.test3__c='x') )

Getting below error:

 Field test2__c is a picklist field. Picklist fields are only supported in certain functions.

and also changed my expression with TEXT but still i am not able to sove it.
AND(TEXT(ISPICKVAL(object1__r.test2__c='A'))


Any suggestions from community.

Thanks in advance.



  • May 07, 2015
  • Like
  • 0
Here's an example of a section I'm replicating in Visualforce. I feel like I've travelled the Seven Kingdoms trying to find an answer to this question. Visualforce will evenly distribute the fields between two columns; however, the client would like it to replicate the native page layout, and that means certain fields exist in a certain order and in specific columns. I've tried Style attributes but they only seem to effect the formatting of the field itself and not which column to associate said field. 

<apex:pageBlockSection title="Special Request Tracking" columns="2" rendered="{!Case.Request_Type2__c== 'Special Requests'}">
                   <apex:inputField value="{!Case.Origin}"/>
                   <apex:inputField value="{!Case.ServicingData__c}"/>
                   <apex:inputField value="{!Case.Type_of_Communication__c}"/>
                   <apex:inputText value="{!Case.Contact}"/>
                   <apex:inputField value="{!Case.Requestor_Role__c}"/>
                   <apex:inputField value="{!Case.Exclude_from_CPI_Reporting__c}"/>
             </apex:pageBlockSection>

Any help would be greatly appreciated!
public List<ProfileSkillUser> searchResult{get;set;} 

function(){
public List<ProfileSkillUser> temp;
for (5 times){
	temp = [SELECT User.FirstName, User.LastName, ProfileSkill.Name, EFX_Type__C, ProfileSkill.EFX_Category__c, EFX_Skill_assessment__c
                        FROM ProfileSkillUser];

}

}


temp will populate value 5 times
searchResult should be addition/summation of temp
Hi 

Please suggest me  how to display  picklist  field  and textbox  on selection of  values in muti-picklist field
and if I selected two values at at a time  in mutlpicklist field then how  could be displayed both fields(picklist and textbox) in visualforce page 


Please post sample code if you have
its very urgent 

Thanks

 
Trying to write a trigger that fires when a contact is created/updated.  The trigger would update a lookup field on the account (Account.Primary_Contact__c).  The correct ID comes from a contact record that has Contact.Primary_Contact__c = true.  

Why won't this work?

trigger fillPrimaryonAcct on Contact (before insert, before update) {
    //Collect IDs to update
    List<Id> cIdList = new list<Id>();
    List<Id> aIdList = new list<Id>();

    //Loop
    for(contact c: trigger.new) {
        aIdList.add(c.Id);
    
    }
    //List that grabs the Id of the primary contact
    List<Contact> pContact = [SELECT Id FROM Contact WHERE Primary_Contact__c = true, Id = :id];

}

Any better ways to do this would be appreciated!
Hi All,
I have been given this code however I am not a developer and received an error that my test coverage was only 73%.
I have searched a ton of test code but I'm still lost and need to get this deployed as soon as possible.
Any help would be much appreciated.
Thank you in advance!

Class
public class SubmitCaseController {

private final Case c;
  
    
    
     public SubmitCaseController(ApexPages.StandardController stdcontroller) {
     this.c = (Case)stdcontroller.getRecord();
     }

public PageReference redirectByProfile()

Id profileId = userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;

string mystring1 = 'Portal';
if (profileName.contains(myString1)==false)


String prefix = Case.SObjectType.getDescribe().getKeyPrefix(); 
String param = getParameters() + '&(your field id)=(your field value)';
return new PageReference('/'+prefix+'/e?nooverride=1&'+param); 
}
else 
return null; 

}

private String getParameters(){
string param = '';
Map <String, String> strMap = ApexPages.currentPage().getParameters();
String[] keys = new String[]{'RecordType', 'retURL', 'cancelURL'};
for(String s : keys){
if(strMap.containsKey(S)) param += s + '=' + strMap.get(s) + '&';
}
if(param.length() > 0) param = param.substring(0, param.length()-1);
return param;
}

    public SubmitCaseController() {

        AssignmentRule AR = new AssignmentRule();

        AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];

        Database.DMLOptions dmlOpts = new Database.DMLOptions();

        dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;


        c.setOptions(dmlOpts);

 
    }      

    public static list<SelectOption> getFieldValues(SObject obj, String fld) {

        List<SelectOption> options = new List<SelectOption>();

        map<String, Schema.SObjectField>fieldMap = obj.getSObjectType().getDescribe().fields.getMap();  

        list<Schema.PicklistEntry> values =

        fieldMap.get(fld).getDescribe().getPickListValues();

        options.add(new SelectOption('', '--None--'));

        for (Schema.PicklistEntry a : values) {

            options.add(new SelectOption(a.getLabel(), a.getValue()));

        }       

        return options;

    }   

    public PageReference submitCase() {       

        try {

            c.Origin = 'Communities';

            INSERT c;

            PageReference casePage = new ApexPages.StandardController(c).view();

            casePage.setRedirect(true);

            return casePage;

        } catch (Exception e) {

            ApexPages.addMessages(e);

            return null;

        }       

    }  

}

 
I am trying to write an soql that queries owners in opportunities as well as including the opportunities that have those split owners.

For example if I want Opportunities that Angela and Bob own I write:
SELECT Id from Opportunity where OwnerId in (:AngelaId, :BobId);
but I also want to include opportunities that Angela and Bob own as split owners. How do I do this?

a bad example to try to show what I want:
SELECT Id from Opportunity where OwnerId in (:AngelaId, :BobId) or OpportunitySplit.SplitOwnerId in (:AngelaId, :BobId);
Hi All,

I'm trying to increment a counter if a user tries to add the same merchandise item to the shopcart. If its a new merchandise item, add the item with it's correct total.
 
public class StoreFront2 {


    public String message { get; set; }
 	DisplayMerchandise[] products;
    DisplayMerchandise[] cart;

	
                           
    public PageReference shop(){
        
        for(DisplayMerchandise c :products){
            if(c.id == cart.merchandise.id){
                cart.count++;
            }
            else{
                cart.add(c);
            }
            
        }
        message = 'You bought: ';
        for (DisplayMerchandise p:products){
            if(p.count > 0){
               message += p.merchandise.name + ' (' + p.count + ') ' ;
                
                
               }
 
            
            }
        
    
      
        return null;
    }


    
 public DisplayMerchandise[] getCart() {
    if(cart == null){
        cart = new DisplayMerchandise[]{};
    }
    
    return cart;
}
    
        public class DisplayMerchandise {
        public Merchandise__c merchandise{get; set;}
        public Decimal count{get; set;}
        public DisplayMerchandise(Merchandise__c item){
            this.merchandise = item;
        }
       }
    
    public DisplayMerchandise[] getProducts() {
        
        if (products == null){
            products = new DisplayMerchandise[]{};
            for (Merchandise__c item : 
            [SELECT id, name, description__c, price__c
            FROM Merchandise__c
            WHERE Total_Inventory__c > 0]) {
            
            products.add(new DisplayMerchandise(item));
         	
            }
    
    }
        
    return products;
    }

}

 
I'm trying to add my products from my DisplayMerchandise[] List to a shopping cart called "cart". How can I accomplish this? Every time I hit "Add to Cart" it throws a null pointer exception.

Apex
public class StoreFront2 {


    public String message { get; set; }
 	DisplayMerchandise[] products;
    DisplayMerchandise[] cart;

	
                           
    public PageReference shop(){
        
        message = 'You bought: ';
        for (DisplayMerchandise p:products){
            
            if(p.count > 0){
               message += p.merchandise.name + ' (' + p.count + ') ' ;
                Decimal counts = p.count;            
               }
            cart.addAll(p);
            }    
    
      
        return null;
    }
    
    



    
    public DisplayMerchandise[] getcart(){
        if(cart != null){
            cart = new DisplayMerchandise[]{};
            
        }
        return cart;
    }
    
        public class DisplayMerchandise {
        public Merchandise__c merchandise{get; set;}
        public Decimal count{get; set;}
        public DisplayMerchandise(Merchandise__c item){
            this.merchandise = item;
        }
       }
    
    public DisplayMerchandise[] getProducts() {
        
        if (products == null){
            products = new DisplayMerchandise[]{};
            for (Merchandise__c item : 
            [SELECT id, name, description__c, price__c
            FROM Merchandise__c
            WHERE Total_Inventory__c > 0]) {
            
            products.add(new DisplayMerchandise(item));
         	
            }
    
    }
        
    return products;
    }

}

Visualforce
<apex:page standardStylesheets="false" showHeader="false" sidebar="false" controller="StoreFront2">
  <apex:stylesheet value="{!URLFOR($Resource.styles)}"/>
  <h1>Store Front</h1>
  
  <apex:form >
      <apex:dataTable value="{!products}" var="pitem" rowClasses="odd,even">
          
          <apex:column headerValue="Product">
              <apex:outputText value="{!pitem.merchandise.name}" />
          </apex:column>
          <apex:column headervalue="Price">
              <apex:outputText value="{!pitem.merchandise.Price__c}" />
          </apex:column>
          <apex:column headerValue="#Items">
              <apex:inputText value="{!pitem.count}"/>
          </apex:column>
   
      </apex:dataTable>
      
      <br/>
      <apex:commandButton action="{!shop}" value="Add to Cart" reRender="msg,cart" />
  </apex:form>
  
    <apex:outputPanel id="msg">{!message}</apex:outputPanel><br/>    
    <h1>Your Basket</h1>
<form>    
     <apex:dataTable id='cart' value="{!cart}" var="carti" rowClasses="odd,even">
          
          <apex:column headerValue="Product">
              <apex:outputText value="{!carti.merchandise.name}" />
          </apex:column>
          <apex:column headervalue="Price">
              <apex:outputText value="{!carti.merchandise.Price__c}" />
          </apex:column>
          <apex:column headerValue="#Items">
              <apex:outputText value="{!carti.count}"/>
          </apex:column>
   
      </apex:dataTable>
    </form>
    
  
</apex:page>

 
Hi,

Anybody suggest me a simple process to copy a record from one custom object to another custom object on button click. 


 
Hi, trying to modify below apex trigget to generate contact role name instead of ID
I would appreciate suggestions what I'm doing wrong here
 
trigger PrimaryContactRole on Opportunity (before update) {

   for (Opportunity o : Trigger.new) {

       Integer i = [select count() from OpportunityContactRole where OpportunityId = :o.id and IsPrimary = true];
      
       if(i==1) {
       OpportunityContactRole contactRole =
            [select Contact.Name from OpportunityContactRole where OpportunityId = :o.id and IsPrimary = true];

       o.Primary_Contact_Role__c = contactRole.ContactID;
       } 

      }

   }

thanks
  • April 30, 2015
  • Like
  • 0
hi iam trying to built a list where i want to make to fields as unique . how can i achieve this .  iam trying pair numbers but giving error to me. is any other method is there ?
Hi All,

I have a requirement where in i have to show a picklist of record types on VF page based on the logged in user.The pick list should only display the case record types that the current user has permission to create cases.When user change the value in the picklist, then change the case record type field and refresh the entire page.Need help on the approach and any sample code reference.    
I have created a visualforce page that displays both opportunity and contact fields that I want users to be able to edit and save. I am using the opporutnity standard controller and added the following extension so as to be able to override (or add to) the standard save functionality with the 'SaveBoth' method (below). I have managed to be able to query the correct contact and populate the contact ID, but upon 'Save' none of the contact fields on the Visualforce page are updating.

Here is the Controller Extention
public with sharing class NewLeadControllerExtension 
{
    ApexPages.StandardController controller;
    public Opportunity oppt {get; set;}
    public Account acct {get; set;}
    public Contact cont {get; set;}

    public NewLeadControllerExtension(ApexPages.StandardController controller)
    {
        this.controller = controller;
        oppt = (Opportunity)controller.getRecord();
        acct = new Account();
        cont = new Contact();
        acct.Name = oppt.Account.Name;
        cont.Id = [SELECT Id FROM Contact WHERE Name =: acct.Name LIMIT 1].Id;
    }
    public String getTitle()
    {
        return 'The Contact ID is '+ cont.Id;
    }
    public PageReference SaveBoth()
   {
        update cont; 
        controller.Save(); 
        return null;
   }
}
Here is my visualforce page
<apex:page standardController="Opportunity" extensions="NewLeadControllerExtension">
   <p>{!title}</p>
   <apex:form >  
   <apex:pageBlock title="New Sales Leads">
   
       <apex:pageBlockButtons location="bottom">
          <apex:commandButton action="{!SaveBoth}" value="Save" rerender="section1"/>
          <apex:commandButton action="{!QuickSave}" value="QuickSave"/>
       </apex:pageBlockButtons>
   
       <apex:pageBlockSection title="Opportunity Fields" columns="2" >
          <apex:repeat value="{!$ObjectType.Opportunity.FieldSets.Opportunity_Fields}" var="field">
             <apex:inputField value="{!Opportunity[field]}"/>  
          </apex:repeat>
          <apex:outputField value="{!Opportunity.Id}"/>     
       </apex:pageBlockSection>
       
       <apex:pageBlockSection title="Contact Fields" columns="2" id="section1">
          <apex:inputField value="{!Opportunity.Account.Id}"/>
          <apex:inputField value="{!Opportunity.Account.Name}"/>
          <apex:inputField value="{!Opportunity.Account.Contact__r.Rating__c}"/>
          <apex:inputField value="{!Opportunity.Account.Contact__r.Name}"/>
          <apex:inputField value="{!Opportunity.Account.Contact__r.Id}"/>
          <apex:inputField value="{!Opportunity.Account.Contact__r.Lead_Source__c}"/>
          <apex:inputField value="{!Opportunity.Account.Contact__r.MobilePhone}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Email}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Do_you_own_an_investment_property__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Level_of_Investment__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Project_of_Interest__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Life_Cycle_Stage__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Purchase_Type__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.No_of_Bedrooms__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.First_Home_Buyer__c}"/>
          <apex:outputField value="{!Opportunity.Account.Contact__r.Call_Details__c}"/>  
       </apex:pageBlockSection>
      </apex:pageBlock>
    </apex:form>
       <apex:pageBlock title="Activity Blah">
       <apex:pageBlockSection title="Call and Email Hitory" columns="1" >
             <apex:relatedList subject="{!opportunity.account.contact__r}" list="ActivityHistories" /> 
       </apex:pageBlockSection>
       </apex:pageBlock>
       <apex:pageMessages /> 
</apex:page>
Many thanks for your help

 
Hi All,

I am experiencing the following behavior on Salesforce Knowledge and would like to know if this is specific to me or everyone has this issue ?

I have Articles that are exposed on Internal App, Customer and PKB channels. I have a Customer community (that acts as an authenticated site) and several public force.com sites which all expose the articles for perusal by Customers.
Community and Force.com sites are entirely developed using VisualForce and no standard functionality is included.
When I view an article inside the Internal App using Article detail page or Article Management tab, the view statistics (in standard object - KnowledgeArticleViewStat) gets updated to reflect the same. But when I view the same articles on Community or PKB using custom VF solution, even though the Articles are shown as expected, the associated view stats do not get updated.

Also, if a user copies over the Article Id and browses to it by pasting the Id directly in address bar of browser, the user is still presented the article in standard community/force.com site styling and the view stats do get updated as expected.

I want to know why the stats don't get updated while interacting with Articles using VF ? and what could be done so that the stats start getting updated based on views from custom PKB or Community ?

Also, does everyone face this issue or its specific to my Org ?

Note - We don't use Knowledge specific VF components but the usual ones as its a completely customized look and feel.
Hi All,

While exploring our Customer community, I had the following observations and I am not sure whether every org faces these or we are the only ones or if we are doing something wrongly here.

Background -  We have a Customer community and we use the Overage High Volume Customer Portal license for providing access to Customers.

The observations - 

1. External OWD seems to affect the High-Volume users while its a general belief that none of the sharing settings apply to HV users as they neither have a Role nor can be part of Public Groups.

2. Our Community has several VF pages exposed on it and the entire look and feel is customized (no standard stylesheets). We have just exposed the Home tab on Community and no other tabs. All standard tabs like Account, Contact, Case etc. are hidden on the profile associated with these HV users. Still if an authenticated community user types in the standard Salesforce URL patterns, they are able to view these tabs along with the data (as per the external OWD, if their profile provides them at least Read permission on the object). For e.g. typing "/500/o" would take him to the Cases tab, "/001/o" would take him to the Accounts tab and so on. They can also type in the Id of any record and reach the detail page (if they don't have access, insufficient privileges page). All these standard URLs display the pages with standard community styling.

The issue is why are the users able to access tabs by typing in the URLs when their profile has those tabs as hidden ?

It seems to be a very serious issue and I expect that I am not the only one who's facing it (please do not assume you don't have it unless you have explicitly checked/tried to reproduce). What is the use of having a custom styling when such behavior destroys the uniform experience that a Customer is supposed to have and there are chances of exposing data that they are not supposed to see (they should see what has been exposed via VF pages on Community).

If you faced the same issue, how did you work-around this ? or if you are facing the same issue, how do you plan to mitigate it ?

I am trying to render the VF page as XML using contentType="application/xml#export.xml".

The issue is when the number of records I am converting to XML is small (<1000), the file is generated in 15-20 seconds but when the number of records increase to more than 1000, it simply can't load the document and I get the following messages - 

 

In Firefox - Firefox can't find the file at https://xxxxxx.visual.force.com/apex/DummyName?pId=a1BM0000000ApZ1.

 

In Chrome - No webpage was found for the web address: https://xxxxxxx.visual.force.com/apex/DummyName?pId=a1BM0000000ApZ1

 

I am not yet hitting the heap size or statements governor, still this message.

 

Has anyone tried a similar scenario before or has faced something like this ?

 

Your suggestions on a work around to create xml file out of SFDC data are most welcome.

 

Quick replies are most appreciated :).

How  can I use the QueryAll() API call in an Apex Trigger ?

Is this possible ?

Is their any out-of-the-box class that provides an equivalent method to achieve this ???

  • August 05, 2010
  • Like
  • 0

Hi All,

I have trigger on after insert and after update, below is my handler class.

If i create a task from contact(is a required field on page layout) it fails because whatID is null. So I'm trying to query to get the whatID based on whoID.

If i create a task from account, works fine because whoid and whatid are not null.

public with sharing class TaskTriggerHandler {
    
    private boolean trigger_isExecuting = false;
    
    public TaskTriggerHandler(){
        
    }
    
    public void OnAfterInsert(Task[] newObjects){
        // EXECUTE AFTER INSERT LOGIC       updateAccountActivityFields(newObjects);
    }
    
    public void OnAfterUpdate(Task[] oldObjects, Task[] updatedObjects, Map<ID, Task> ObjectMap){
        //EXECUTE AFTER UPDATE LOGIC
        updateAccountActivityFields(updatedObjects);
    }
    

     public void updateAccountActivityFields(Task[] taskRecords){
      
        // find task record type 
        RecordType taskRec = [SELECT Id FROM RecordType WHERE SobjectType ='Task' AND DeveloperName ='Task_Record_Type'];
        
        List<Account> accountsToUpdate = new List<Account>();
        Account a;
       
        //Get all the contactIds and accountIds of the task being inserted/updated
        for(Task tk : [SELECT Id, LastModifiedBy.name, type, LastModifiedDate, CreatedDate, RecordTypeId, whoid, whatid FROM task WHERE id in :taskRecords]){
            if(tk.RecordTypeId == taskRec.Id  && tk.Whoid!=null){
                
                // query to get account ID from contact:whoID 
                a = new Account(Id = [SELECT AccountId FROM Contact WHERE Id =: tk.WhoId]);
                              
                //convert task's CreatedDate, datetime to date
                Date createdDateJustDate = date.newinstance(tk.CreatedDate.year(), tk.CreatedDate.month(), tk.CreatedDate.day());
        
                //update the activity fields on account with Task's lastModifiedDate and LastModifiedBy based on Task Type
                if(tk.type=='Face 2 Face Meeting' || tk.type=='Lunch'){
                    a.Last_Face_to_Face_Activity__c = createdDateJustDate;
                    a.Last_Visited_By__c = tk.LastModifiedBy.name;
      
                }
                else{
                    a.Last_Call_Activity__c =  createdDateJustDate;
                    
                }
                
                accountsToUpdate.add(a);
               
            }
        }
        
       if(!accountsToUpdate.isEmpty())
            Update accountsToUpdate;

Please help!!

Can anyone please help writing a test class?
global class LoanOfficerBatch implements Database.Batchable<sObject> {
    public String query = 'SELECT Loan_Officer_1a__c,Loan_Officer_1a__r.Email, ConvertedOpportunityId, Name, Phone,' 
                          +  'Status, Est_Re_Pull_Date__c, Realtor_Name__c ' 
                          +   ' FROM Lead'; 
    public EmailTemplate templateId = [Select Id,HtmlValue,Subject from EmailTemplate where name = 'LoanOfficerRecord' LIMIT 1];

    global Database.QueryLocator start(Database.BatchableContext bc) {

        query += ' WHERE CreatedDate = THIS_MONTH  AND Loan_Officer_1a__c != null';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Lead> allLeads) {
        
        
         
        List<String> convertedOppId = new List<String>();
         for(Lead l: allLeads){
	         convertedOppId.add(l.ConvertedOpportunityId); 
             }

         Map<Id, Opportunity> opptyMap = new Map<Id, Opportunity>();  
         for(Opportunity o : [SELECT Id,Name,Contact__r.Name,Contact__r.Phone,Starting_Credit_Score__c,Enrolled_On__c,Est_Re_Pull_Date__c,StageName FROM Opportunity WHERE Id IN: convertedOppId]){
	      opptyMap.put(o.Id, o);
          }
        
        
        
        Map<Id,List<Lead>> leadMap = new Map<Id,List<Lead>>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMEssage>();
        if(allLeads != null && allLeads.size() > 0){
            for(Lead l: allLeads){
                if(!leadMap.containsKey(l.Loan_Officer_1a__c)){
                    leadMap.put(l.Loan_Officer_1a__c, new List<lead>());
                }
                leadMap.get(l.Loan_Officer_1a__c).add(l);
            }
        }
        if(leadMap.keySet().size() > 0){
            Map<Id,Contact> officers = new Map<Id,Contact>([SELECT Id,Email,Name FROM Contact WHERE Id IN: leadMap.keySet()]);
            for(Id i: leadMap.keySet()){
                Contact con = officers.get(i);
                System.debug(con);
                if(String.isnOtBlank(con.Email)){
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(new String[]{con.EMail});
                    mail.setSubject(templateId.Subject);
                    String html = templateId.HtmlValue;
                    html = html.replace('||OfficerName||',con.Name);
                    String leadsTable = '<table cellpadding="3" cellspacing="3" width="100%" align="center" border="1" style="border-collapse:collapse;">'+
                        '<tr style="font-weight:bold;"><td>Name</td><td>Phone</td><td>Status</td><td>Est. Re Pull Date</td><td>Realtor Name</td></tr>';
                    
                    for(Lead l: leadMap.get(i))  
                    if(l.ConvertedOpportunityId==null)
                    {                    {
                        
                        
                        leadsTable += '<tr><td>'+l.Name+'</td>'+
                            '<td>'+l.Phone+'</td><td>'+l.Status+'</td>'+
                            '<td>'+l.Est_Re_Pull_Date__c+'</td><td>'+l.Realtor_Name__c+'</td></tr>';
                    }
                                               }
                    leadsTable += '</table>';
                    
                     String opptyTable = '<table cellpadding="3" cellspacing="3" width="100%" align="center" border="1" style="border-collapse:collapse;">'+
                        '<tr style="font-weight:bold;"><td>Name</td><td>Phone</td><td>Starting Credit Score</td><td>Enrolled On</td><td>Estimated Pull Date</td><td>StageName</td></tr>';
                    
                    for(Id idKey: opptyMap.keySet()){
                        Opportunity o = opptyMap.get(idKey);
                        
                        
                        opptyTable += '<tr><td>'+o.Contact__r.Name+'</td><td>'+o.Contact__r.Phone+'</td><td>'+o.Starting_Credit_Score__c+'</td><td>'+o.Enrolled_On__c+'</td>'
                            +'<td>'+o.Est_Re_Pull_Date__c+'</td><td>'+o.StageName+'</td></tr>';
                    }
                    opptyTable += '</table>';
                    html = html.replace('||Leads||',leadsTable);
                    html = html.replace('||Opportunity||',opptyTable);
                    html = html.replace('null',' ');
                    mail.setHTMLBody(html);
                    mails.add(mail);
                }
            }
        }
        if(mails.size() > 0){
            Messaging.sendEmail(mails);
        }
    }

    global void finish(Database.BatchableContext BC) {

    }
   
}
Hello!

Please could you help me to get the correct code to the below  issue and if it possible?

We have a custom object for requesting new users in Salesforce. If manager wants to request for create new user he needs to create new record (User Request) and provide all infomrations like name, email, profile etc. For now I create users manually using infomration on this record.
I would like to add a buton with apex code to create new user based on the infomration from this record, it si possible?

Thanks in advance!
L.
I have the following SOQL query in my custom controller.  I would like to build a page that shows all the parent (case) records and related child (RMA) records in one single table.  I've been able to do this with a single case, but can't seem to figure out how to do it when I want to display all cases.

How would one go about doing this?
 
string searchquery = 'SELECT ID, '
                   + 'casenumber, '
                   + 'subject, '
                   + 'Severity__c, '
                   + 'Case_Type__c, '
                   + 'CreatedDate, '
                   + 'ClosedDate, '
            	   + 'Status, '
                   + 'Status_Comment__c, '
                    + '(select  '
                         + 'Customer_Asset_Type__c, '
                         + ' RMA_Customer_Reported_PO__c, '
                         + ' Date_Received__c, '
                         + 'PO_Contract_Date__c, '
                         + 'RMA_Actual_SN_Returned__c, '
                         + 'RMA_Customer_Reported_Failure_Inform__c, '
                         + 'RMA_Customer_Reported_Part_Number__c, '
                         + 'RMA_Customer_Reported_Qty__c, '
                         + 'RMA_Customer_Reported_SN__c, '
                         + 'Warranty_Status__c '
                         + 'from RMA_Products__r) '
                   + 'FROM Case  '
                   + 'WHERE OwnerId= \'' + UserInfo.getUserID() + '\''
                   + 'ORDER BY casenumber DESC '
                   ;

        caseResults = Database.query(searchquery);

 
global class LoanOfficerBatch implements Database.Batchable<sObject> {
    public String query = 'SELECT Loan_Officer_1a__c,Loan_Officer_1a__r.Email, ConvertedOpportunityId, Name, Phone,' 
                          +  'Status, Est_Re_Pull_Date__c, Realtor_Name__c ' 
                          +   ' FROM Lead'; /*JMA:: add  ConvertedOpportunityId field*/ 
    public EmailTemplate templateId = [Select Id,HtmlValue,Subject from EmailTemplate where name = 'LoanOfficerRecord' LIMIT 1];

    global Database.QueryLocator start(Database.BatchableContext bc) {

        query += ' WHERE CreatedDate = LAST_MONTH  AND Loan_Officer_1a__c != null';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Lead> allLeads) {
        
        //JMA:: Create a map of <Id, Opportunity>
        //JMA:: Query Opportunities by using Lead.ConvertedOpportunityId. You need to first create a set of Id from Lead.ConvertedOpportunityId
        //JMA:: populate the map <Id, Opportunity>
         
        List<String> convertedOppId = new List<String>();
         for(Lead l: allLeads){
             convertedOppId.add(l.ConvertedOpportunityId); 
             }

         Map<Id, Opportunity> opptyMap = new Map<Id, Opportunity>();  
         for(Opportunity o : [SELECT Id,Name,Contact__r.Name,Contact__r.Phone,Starting_Credit_Score__c,Enrolled_On__c,Est_Re_Pull_Date__c,StageName FROM Opportunity WHERE Id IN: convertedOppId]){
          opptyMap.put(o.Id, o);
          }
        
        
        
        Map<Id,List<Lead>> leadMap = new Map<Id,List<Lead>>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMEssage>();
        if(allLeads != null && allLeads.size() > 0){
            for(Lead l: allLeads){
                if(!leadMap.containsKey(l.Loan_Officer_1a__c)){
                    leadMap.put(l.Loan_Officer_1a__c, new List<lead>());
                }
                leadMap.get(l.Loan_Officer_1a__c).add(l);
            }
        }
        if(leadMap.keySet().size() > 0){
            Map<Id,Contact> officers = new Map<Id,Contact>([SELECT Id,Email,Name FROM Contact WHERE Id IN: leadMap.keySet()]);
            for(Id i: leadMap.keySet()){
                Contact con = officers.get(i);
                System.debug(con);
                if(String.isnOtBlank(con.Email)){
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(new String[]{con.EMail});
                    mail.setSubject(templateId.Subject);
                    String html = templateId.HtmlValue;
                    html = html.replace('||OfficerName||',con.Name);
                    String leadsTable = '<table cellpadding="3" cellspacing="3" width="100%" align="center" border="1" style="border-collapse:collapse;">'+
                        '<tr style="font-weight:bold;"><td>Name</td><td>Phone</td><td>Status</td><td>Est. Re Pull Date</td><td>Realtor Name</td></tr>';
                    
                    for(Lead l: leadMap.get(i)){
                        //JMA:: for each lead you can get the associated Opportunity from map <Id, Opportunity>
                        
                        leadsTable += '<tr><td>'+l.Name+'</td>'+
                            '<td>'+l.Phone+'</td><td>'+l.Status+'</td>'+
                            '<td>'+l.Est_Re_Pull_Date__c+'</td><td>'+l.Realtor_Name__c+'</td></tr>';
                    }
                    leadsTable += '</table>';
                    
                     String opptyTable = '<table cellpadding="3" cellspacing="3" width="100%" align="center" border="1" style="border-collapse:collapse;">'+
                        '<tr style="font-weight:bold;"><td>Name</td><td>Phone</td><td>Starting Credit Score</td><td>Enrolled On</td><td>Estimated Pull Date</td><td>StageName</td></tr>';
                    
                    for(Id idKey: opptyMap.keySet()){
                        Opportunity o = opptyMap.get(idKey);
                        
                        
                        opptyTable += '<tr><td>'+o.Contact__r.Name+'</td><td>'+o.Contact__r.Phone+'</td><td>'+o.Starting_Credit_Score__c+'</td><td>'+o.Enrolled_On__c+'</td>'
                            +'<td>'+o.Est_Re_Pull_Date__c+'</td><td>'+o.StageName+'</td></tr>';
                    }
                    opptyTable += '</table>';
                    html = html.replace('||Leads||',leadsTable);
                    html = html.replace('||Opportunity||',opptyTable);
                    html = html.replace('null',' ');
                    mail.setHTMLBody(html);
                    mails.add;
                }
            }
        }
        if(mails.size() > 0){
            Messaging.sendEmail(mails);
        }
    }

    global void finish(Database.BatchableContext BC) {

    }
   
}
AND(NOT(ISBLANK(Component__c)),AND(OR(AND(Component__r.Product__r.yes__c = FALSE,NOT(ISPICKVAL(Component__r.type__c,"exhausted"))),NOT(ISPICKVAL( Component__r.Status__c,"install"))),Service__c = FALSE),$RecordType.Name='supportive', 
$Setup.settings__c.Validate__c = FALSE, 
ISBLANK(source__c),ISPICKVAL(Categories__c,"fields"),OR(ISPICKVAL(Reasons__c,"appear"), ISPICKVAL(Reasons__c,"Maintenance")),NOT(ISPICKVAL(Origin,"Portal")),Component__r.Product__r.source__c = "RT")
Hi everyone-

I scheduled an apex job to run daily at midnight but noticed that the job failed due to the Apex CPU time limit exceeded error. The code works in my developer sandbox but not in production. I'm wondering if it is because of something in my SOQL query, but unclear on where the culprit would be. The query only returns about 500 results. Any help is appreciated- here is my class:
 
global without sharing class UnassignAccountsDueToInactivity implements Schedulable {
    global void execute(SchedulableContext ctx) {
        List<Account> acctList = [SELECT Id, Name, OwnerId 
                                  FROM Account 
                                  WHERE (OwnerProfileName__c LIKE '%AE%' OR OwnerProfileName__c LIKE '%SDR%') AND 
                                  (Current_Customer__c != 'Current Customer A' AND Current_Customer__c != 'Current Customer B' AND Current_Customer__c != 'Current Customer C') AND
                                  Number_of_Open_Opportunities__c <= 0 AND
                                  DaysSinceLastActivity__c >= 30 AND
                                  DaysSinceLastOwnerChangeDate__c >= 7];
        
        if(!acctList.isEmpty()){
            for(Account acc : acctList){
                acc.DisqualifiedReason__c = 'No response';
                acc.OwnerId = '000000000000000';
            }
            update acctList;
        }
    }
}
I understand that you cannot add fields to the recycle bin page for a specific tab. 

I would like to retrieve deleted records from the CASE object which have a specific recordtype. 

I tried to do this in the Developer Console with SOQL but this still does not work.

I read that you need to de an SOQL All Query, I am an administrator.
Can somebody help me out here? 

Thanks,

Dave