• Naveen Ila
  • NEWBIE
  • 219 Points
  • Member since 2015


  • Chatter
    Feed
  • 8
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 1
    Questions
  • 59
    Replies
Hi and thanks in advance for your help! I've been working on an apex trigger for a junction object that has two custom master-detail fields, but I'm stuck and could use some help.

I have created a junction object to create a connection between two Accounts (1st: Account object; 2nd: Connected_Account custom object). Connected_Account__c functions as a one-to-one relationship with Account (every Account has itself as a Connected_Account)

junction object:
Connection__c
- Connection__c.Name : auto number {0}
- Account1__c : master-detail(Account)
- Account2__c : master-detail(Connected_Account__c)

Connected_Account__c
- Connected_Account__c : lookup(Account)

User creates a new Connection__c on the Account Page Layout for Account X:

Connection__c.Name = 1
// Account1 autopopulated, Account1 = X
Account1__c = X
// User selects Account2, Connected_Account = Y
Account2__c = Y

Now, what I'm trying to accomplish is a trigger such that after a User creates Connection__c.Name=1, the trigger creates a second Connection__c.Name=2 where the field values are inverted:

Connection__c.Name = 2
Account1__c = Y
Account2__c = X
 
ConnectionHandler.apxc :

public with sharing class ConnectionHandler {
    public static void CreateNewConnection(List<Connection__c> connects) {
        for(Connection__c c : connects) {
            Connection__c connect = new Connection__c();
            connect.Account1__c = c.Account2__c;
            connect.Account2__c = c.Account1__c;
            connects.add(connect);
        }
        if(connects.size() > 0) {
            insert connects;
        }
    }
}


ConnectionTrigger.apxt :

trigger ConnectionTrigger on Connection__c (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
	if(Trigger.isAfter && Trigger.isInsert) {
        ConnectionHandler.CreateNewConnection(Trigger.New);
    }
}

Any advice and/or suggestions would be greatly appreciated. Thanks again!
  • August 21, 2018
  • Like
  • 0
I am adding a button that opens a modal window to add a task to a specific "Objective".  There is an add Task button next to every "Objective" that is displayed, but I'm not sure how I can pull the record Id of the specific objective the button sits next to so I can set the WhatId field of the task to that specific objective... Any ideas here? 

Thanks in advance.
 
<aura:iteration items="{!v.objectives}" var="obj" >


        	<div class="blacklink slds-col slds-size_11-of-12 slds-text-body_regular slds-m-bottom_small slds-box">
                	<a class ="blacklink" href="{!'/lightning/r/Task/'+ obj.Id + '/view'}" target="_blank">	{!obj.Description__c} </a>
            </div>
            <div id ="obj.Id" class="slds-size_1-of-12 slds-m-top_x-small slds-p-left_large">
                	<lightning:button label="+Task" class="slds-button slds-text-body_regular" onclick="{!c.taskopenmodal}" name="obj.Id"/>
                
			</div>
            
            	
                        <aura:if isTrue="{!obj.Tasks}">
                    	<div class="slds-col slds-size_3-of-5 slds-p-left_xx-large slds-m-bottom_small slds-text-heading_small slds-border_bottom" >
                            Task Subject
						</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small slds-text-heading_small slds-border_bottom">
                			Status
                		</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small slds-text-heading_small slds-border_bottom">
                			Owner
                		</div>
          				</aura:if>
                    
            <aura:iteration items="{!obj.Tasks}" var="t" >
                       	<div class="slds-col slds-size_3-of-5 slds-p-left_xx-large slds-m-bottom_small" >
                            <a href="{!'/lightning/r/Task/'+ t.Id + '/view'}" target="_blank">
                            {!t.Subject} 
                            </a>
						</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small">
                			{!t.Status}
                		</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small">
                			{!t.Owner.Name}
                		</div>
            </aura:iteration> 
            
         </aura:iteration>

 

Hey guys,

Here is a fun one, I am working on disabling a button unless a checkbox disclaimer is checked. I wrote a little controller that should check the checkbox value and depending on whether it's true or false, update the disabled boolean to the inverse. It works on the first change when I check the box the diabled flag goes to false. However when I uncheck the box it doesn't update that boolean. What am I doing wrong? Thanks!

Examples screenshots
This is correct. 

User-added image
This is correct. 
User-added image
This is not, the button value should be true
User-added image

Cmp code 
 

<aura:component access="global" implements="lightning:availableForFlowScreens">
    <aura:attribute name="proofSelection" type="String"/>
    <aura:attribute name="Changes" type="String"/>
    <aura:attribute name="Encoded_ID" type="String" />
    <aura:attribute name="DisclaimerValue" type="Boolean" default="false"/>
    <aura:attribute name="ButtonDisabled" type="Boolean" default="true"/>
    <aura:attribute name="UploadFiles" type="Boolean" default="false"/>
	<aura:attribute name="radioOptions" type="List" default="[
      {'label': 'Yes', 'value': 'true'},
      {'label': 'No', 'value': 'false'} ]"/>

    <div style="width:400px;">
    <div class="slds-p-around_medium slds-p-bottom_medium" >
        
        <div class="slds-form slds-form_stacked">
			<lightning:select name="selectItem" label="How's the proof look?:" value="{!v.proofSelection}" class="slds-p-top_small"  >
        		<option value="-Select One-">-Select One-</option>
        		<option value="I approve my proof. Please proceed to print!">I approve my proof. Please proceed to print!</option>
        		<option value="I would like changes made to my proof.">I would like changes made to my proof.</option>
        	</lightning:select>           
            
    		<!-- If proof is not approved, also ask customer for changes. -->
        	<aura:if isTrue="{!v.proofSelection == 'I would like changes made to my proof.'}">
       			
					<div class="slds-form-element">
                	<lightning:textarea name="ChangesText" value="{!v.Changes}" label="Tell us what you'd like changed:" class="slds-p-top_small"/>
					<div class="slds-p-top_small"></div>
					<lightning:radioGroup aura:id="UploadFiles" name="UploadFiles"
                     label="Would you like to upload new content? (logos, images, etc)"
					options="{! v.radioOptions }" value="{! v.UploadFiles }" />
					<div class="slds-p-top_small"></div>
					</div>
                
                <!-- If customer clicks yes to upload files show the file upload iframe. -->
            	<aura:if isTrue="{! v.UploadFiles }" >      
            		<iframe src="{!'/TVA_CFB__RequestFile?'+v.Encoded_ID}" height="325px" width="325px" frameborder="0" class="slds-p-bottom_small"/>                                                                                                                             
            	</aura:if>
       		</aura:if>
            

          <div class="slds-p-top_small"></div>
        	<!-- If proof is  approved, askes customer for check box. -->
			<aura:if isTrue="{!v.proofSelection == 'I approve my proof. Please proceed to print!'}">
                       
        			<lightning:input aura:id="DisclaimerCheckBox" type="checkbox"
					label="I have proofread my artwork and am aware that Taradel is not responsible 
                    for any graphic, text, pricing, color variation or format issues after I submit 
                    the approval for print." 
                    name="DisclaimerCheckBox" value="DisclaimerCheckBox" onchange="{!c.handleCheck}" />
            </aura:if>  
          </div>
       <div class="slds-p-top_small"></div>    
       <lightning:button label="Finish and Save" aura:id="Finish_and_Save" 
       variant="neutral" onclick="{!c.handleChange}" disabled="{! v.ButtonDisabled}"/>
		<div class="slds-p-top_small"></div>
      <ui:outputText value="{!'Discalimer Value: ' + v.DisclaimerValue}" />
        <div class="slds-p-top_small"></div>
      <ui:outputText value="{!'ButtonDisabled Value: ' + v.ButtonDisabled}" />

    </div>
    </div>    
</aura:component>

Controller
({
   handleChange : function(component, event, helper) {
      // When an option is selected, navigate to the next screen
      var response = event.getSource().getLocalId();
      component.set("v.value", response);
      var navigate = component.get("v.navigateFlow");
      navigate("NEXT");
   },

    handleCheck : function(component, event, helper) {
        var isChecked = component.find("DisclaimerCheckBox").get("v.checked");
        component.set("v.DisclaimerValue", isChecked);
		      
		var disabled;
        	var boxvalue = component.find("DisclaimerCheckBox").get("v.checked");
        	if (boxvalue = true){
            	disabled = false;
        	} else {
            	boxvalue = true;
        	}
        	component.set("v.ButtonDisabled", disabled);
    }
 })

 
Hello all,

I wrote a trigger which performs the following operation. Whenever data is uploaded into Customer object, it checks for existing records, and if found any, updates the fields with new record. In Production, I need to upload around 400,00 records. Now when I am trying to load the data, It's throwing me the following error "System.LimitException: Too many query rows: 50001".

My trigger handler class:
public class AccountInsertTriggerHandler {
    private List<Account> trgOldList = new List<Account> ();
    private List<Account> trgNewList = new List<Account> ();
    private Map<id,Account> trgOldMap = new Map<id,Account>();
    private Map<id,Account> trgNewMap = new Map<id,Account>();
    public Map<String,Account> leadsMap = new Map<String,Account>();
    private List<String> LeadList = new List<String> ();
    
    public AccountInsertTriggerHandler(List<Account> trgOldList,List<Account> trgNewList,Map<id,Account> trgOldMap,Map<id,Account> trgNewMap){
        this.trgOldList = trgOldList;
        this.trgNewList = trgNewList;
        this.trgOldMap = trgOldMap;
        this.trgNewMap = trgNewMap;
        
        for(Account acct: trgNewList){
            String UniqueCustID = acct.Region__pc + '-' + acct.PersonEmail;
            LeadList.add(UniqueCustID);
        }
        List<Account> allLeads = [select AP_21_Per_IDX__c, AP21_perIDx__pc, AP21_Code__pc, Salutation, AP21_Initials__pc, 
                                    FirstName, LastName, Gender__pc, PersonBirthdate, AP21_StartDate__pc, PersonTitle, AP21_Password__pc,
                                     AP21_UpdateTimestamp__pc, AP21_Privacy__pc, AP21_Reference_Sales_rep__pc, BillingStreet, 
                                     AP21_Billing_AddressLine2__pc, BillingCity, BillingState, BillingPostalCode, BillingCountry, 
                                     ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, 
                                     ShippingCountry, PersonEmail, Home_Phone__pc, PersonMobilePhone, Business_Phone__pc, 
                                     AP21_Loyalty_ID__pc, AP21_LoyaltyTypeID__pc, AP21_LoyaltyType__pc, AP21_Loyalty_CardNo__pc, 
                                     AP21_Loyalty_CardExpiry__pc, AP21_Loyalty_Balance__pc, AP21_Loyalty_CreditStatus__pc, 
                                     AP21_Loyalty_Message__pc, AP21_Loyalty_JoinDate__pc, AP21_LoyaltyStatusID__pc, 
                                     AP21_Loyalty_Currency__pc, AP21_Loyalty_Code__pc, AP21_Loyalty_Format__pc, Store__pc, Region__pc
                                     from Account where AP_21_Per_IDX__c = null and UniqueID__pc IN : LeadList limit 50000];
        for (Account accLeads: allLeads){
            String UniqueLeadsID = accLeads.Region__pc + '-' + accLeads.PersonEmail;
            leadsMap.put(UniqueLeadsId,accLeads);
           // System.debug(leadsMap);
        }
    }
    public void OnAfterInsert(){
        CompareCustomersToLeads(trgNewList,null);
    }
    /*public void OnBeforeInsert(){
        CompareCustomersToLeads(trgNewList,null);
    }*/
    public void CompareCustomersToLeads(List<Account> trgNewList,Map<id,Account> trgOldMap){
        //Add to map using Region and emailAddress as Key and Account record as value.Only add records from Flow User
        ////Retrieve all leads (where PerIdx is blank and created by not Flow) and create map
        ////compare similiar records in the maps i.e for each customer record in customer map, find lead record
        //compare values and update lead with PerIdx and other values
        Map<String,Account> customerMap = new Map<String,Account>();
       // Map<String,Account> leadsMap = new Map<String,Account>();
        List<Account> leadsToUpdate = new List<Account>();
        List<Account> customersToDelete = new List<Account>();
        for(Account acc: trgNewList){
            String UniqueID = acc.Region__pc + '-' + acc.PersonEmail;
            if(leadsMap.containsKey(UniqueID)){
                customerMap.put(UniqueID,acc);
                //acc.addError('No Match to Lead hence cannot Insert');
            }
            
            //System.debug(customerMap);
            
        }
        for(String key:customerMap.keySet()){
           // System.debug('********KEY ' + key);
            if(leadsMap.containsKey(key)){
                Account customerRecord = customerMap.get(key);
                Account leadsRecord = leadsMap.get(key);
              //  System.debug(customerRecord);
             //   System.debug(leadsRecord);

                if(customerRecord.AP_21_Per_IDX__c!=null &&leadsRecord.AP_21_Per_IDX__c==null){
                 //   System.debug('*********** Met Conditions');
                    leadsRecord.AP_21_Per_IDX__c = customerRecord.AP_21_Per_IDX__c;
                    leadsRecord.AP21_perIDx__pc = customerRecord.AP21_perIDx__pc;
                    leadsRecord.FirstName = customerRecord.FirstName;
                    leadsRecord.LastName = customerRecord.LastName;
                    leadsRecord.PersonMobilePhone = customerRecord.PersonMobilePhone;
                    if(leadsRecord.Gender__pc==null)
                        leadsRecord.Gender__pc = customerRecord.Gender__pc;
                    if(leadsRecord.PersonBirthdate==null)
                        leadsRecord.PersonBirthdate = customerRecord.PersonBirthdate;
                    if(leadsRecord.Store__pc==null)
                        leadsRecord.Store__pc = customerRecord.Store__pc;
                    leadsRecord.AP21_Code__pc = customerRecord.AP21_Code__pc;
                    leadsRecord.Salutation = customerRecord.Salutation;
                    leadsRecord.AP21_Initials__pc = customerRecord.AP21_Initials__pc;
                    leadsRecord.AP21_StartDate__pc = customerRecord.AP21_StartDate__pc;

                    leadsRecord.PersonTitle = customerRecord.PersonTitle;
                    leadsRecord.AP21_Password__pc = customerRecord.AP21_Password__pc;
                    leadsRecord.AP21_UpdateTimestamp__pc = customerRecord.AP21_UpdateTimestamp__pc;
                    leadsRecord.AP21_Privacy__pc = customerRecord.AP21_Privacy__pc;
                    leadsRecord.AP21_Reference_Sales_rep__pc = customerRecord.AP21_Reference_Sales_rep__pc;
                    leadsRecord.BillingStreet = customerRecord.BillingStreet;
                    leadsRecord.AP21_Billing_AddressLine2__pc = customerRecord.AP21_Billing_AddressLine2__pc;

                    leadsRecord.BillingCity = customerRecord.BillingCity;
                    leadsRecord.BillingState = customerRecord.BillingState;
                    leadsRecord.BillingPostalCode = customerRecord.BillingPostalCode;
                    leadsRecord.BillingCountry = customerRecord.BillingCountry;

                    leadsRecord.ShippingStreet = customerRecord.ShippingStreet;
                    leadsRecord.ShippingCity = customerRecord.ShippingCity;
                    leadsRecord.ShippingState = customerRecord.ShippingState;
                    leadsRecord.ShippingPostalCode = customerRecord.ShippingPostalCode;
                    leadsRecord.ShippingCountry = customerRecord.ShippingCountry;
                    leadsRecord.PersonEmail = customerRecord.PersonEmail;
                    if(leadsRecord.Home_Phone__pc==null)
                     leadsRecord.Home_Phone__pc = customerRecord.Home_Phone__pc;
                    if(leadsRecord.PersonMobilePhone==null)
                     leadsRecord.PersonMobilePhone = customerRecord.PersonMobilePhone;
                    if(leadsRecord.Business_Phone__pc==null)
                     leadsRecord.Business_Phone__pc = customerRecord.Business_Phone__pc;

 

                    leadsRecord.AP21_Loyalty_ID__pc = customerRecord.AP21_Loyalty_ID__pc;
                    leadsRecord.AP21_LoyaltyTypeID__pc = customerRecord.AP21_LoyaltyTypeID__pc;
                    leadsRecord.AP21_LoyaltyType__pc = customerRecord.AP21_LoyaltyType__pc;
                    leadsRecord.AP21_Loyalty_CardNo__pc = customerRecord.AP21_Loyalty_CardNo__pc;
                    leadsRecord.AP21_Loyalty_CardExpiry__pc = customerRecord.AP21_Loyalty_CardExpiry__pc;
                    leadsRecord.AP21_Loyalty_Balance__pc = customerRecord.AP21_Loyalty_Balance__pc;
                    leadsRecord.AP21_Loyalty_CreditStatus__pc = customerRecord.AP21_Loyalty_CreditStatus__pc;

                    leadsRecord.AP21_Loyalty_Message__pc = customerRecord.AP21_Loyalty_Message__pc;
                    leadsRecord.AP21_Loyalty_JoinDate__pc = customerRecord.AP21_Loyalty_JoinDate__pc;
                    leadsRecord.AP21_LoyaltyStatusID__pc = customerRecord.AP21_LoyaltyStatusID__pc;
                    leadsRecord.AP21_Loyalty_Currency__pc = customerRecord.AP21_Loyalty_Currency__pc;
                    leadsRecord.AP21_Loyalty_Code__pc = customerRecord.AP21_Loyalty_Code__pc;
                    leadsRecord.AP21_Loyalty_Format__pc = customerRecord.AP21_Loyalty_Format__pc;
                    leadsRecord.Region__pc = customerRecord.Region__pc;



                   
                    leadsToUpdate.add(leadsRecord);
                   
                    customersToDelete.add(customerRecord);
                }

            }
        }
        update leadsToUpdate;
        List<Account> deleteCustomers = [select id from Account where id IN: customersToDelete limit 50000];
        delete deleteCustomers;
        
    }

My Trigger:
 
trigger AccountTrigger on Account (after insert) {
    AccountInsertTriggerHandler accInsTriggerHandler = new AccountInsertTriggerHandler(Trigger.old,Trigger.new,Trigger.oldmap,Trigger.newmap);
    if(Trigger.isInsert)
        accInsTriggerHandler.OnAfterInsert();
    //if(Trigger.isInsert)
        //accInsTriggerHandler.OnBeforeInsert();

}

Debug log:
 
10:09:58.714 (18562455772)|SOQL_EXECUTE_BEGIN|[152]|Aggregations:0|SELECT id FROM Account WHERE id IN :tmpVar1 LIMIT 50000
10:09:58.714 (18569696442)|SOQL_EXECUTE_END|[152]|Rows:1
10:09:58.714 (18569734502)|EXCEPTION_THROWN|[152]|System.LimitException: Too many query rows: 50001
10:09:58.714 (18569853312)|HEAP_ALLOCATE|[152]|Bytes:30
10:09:58.714 (18569880194)|METHOD_EXIT|[47]|01p7F00000O4xqM|AccountInsertTriggerHandler.CompareCustomersToLeads(List<Account>, Map<Id,Account>)
10:09:58.714 (18569890597)|METHOD_EXIT|[4]|01p7F00000O4xqM|AccountInsertTriggerHandler.OnAfterInsert()
10:09:58.714 (18569947597)|FATAL_ERROR|System.LimitException: Too many query rows: 50001

Class.AccountInsertTriggerHandler.CompareCustomersToLeads: line 152, column 1
Class.AccountInsertTriggerHandler.OnAfterInsert: line 47, column 1
Trigger.AccountTrigger: line 4, column 1
10:09:58.714 (18569960836)|FATAL_ERROR|System.LimitException: Too many query rows: 50001

Class.AccountInsertTriggerHandler.CompareCustomersToLeads: line 152, column 1
Class.AccountInsertTriggerHandler.OnAfterInsert: line 47, column 1
Trigger.AccountTrigger: line 4, column 1
10:09:59.570 (18570083066)|CUMULATIVE_LIMIT_USAGE
10:09:59.570 (18570083066)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 2 out of 100
  Number of query rows: 50001 out of 50000 ******* CLOSE TO LIMIT
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 1 out of 150
  Number of DML rows: 3 out of 10000
  Maximum CPU time: 5296 out of 10000 ******* CLOSE TO LIMIT
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

10:09:59.570 (18570083066)|CUMULATIVE_LIMIT_USAGE_END

10:09:58.714 (18571196926)|CODE_UNIT_FINISHED|AccountTrigger on Account trigger event AfterInsert|__sfdc_trigger/AccountTrigger
10:09:58.714 (18572303315)|EXECUTION_FINISHED

Please help with me some pointers in resolving the issue​​
Hello,
This is my first post in developer forum since I am mainly a declarative guy :) I hope someone will be able to point me at the right direction here.
I created a flow using the flow designer to accept user input and then create a record. I also wanted the users to be able to attach documents so I added a lightning component.When I run the flow, I get the user input screen and then the file attachment screen. The issue is when I upload the file, I get the file can't be uploaded error. I have attached screenshots of my screens. This is my first time tryig to work witha lightning component so there is a fair chance I am missing something trivial here :) Please help.
PS - We are not using any record types for files.

Regards
Raghunath


User-added image
User-added image
User-added image
User-added image
User-added image
                              string ffdate = program.ffExpireDate;  
                              system.debug('ffexpirydate'+ffdate);
                               date dt = date.parse(ffdate);
                               FF.Expiry_Date__c = dt; 
Getting Error :-   |FATAL_ERROR|System.TypeException: Invalid date: 30-Sep-2018

Log: 
|USER_DEBUG|[49]|DEBUG|ffexpirydate30-Sep-2018 
|FATAL_ERROR|System.TypeException: Invalid date: 30-Sep-2018
                               
I have build a lightning component to list all the open cases and inserted in a page layout. But I want to hyperlink the case number, if someone clicks on that, it should take the user to the corresponding case for view/edit etc. can you pls let me know how to do this. thanks.
  • August 17, 2018
  • Like
  • 0
Hi All,

I'm trying to do Pagination in my VFpage.  I have the below code. When I preview the page all my buttons are Disabled. Can someone tell me why is it dispabled? Attendance__C had When I load the page it displays 10 records. 

Thanks for your help!!

public class PaginationAttendance{ 
 public String acctlist { get; set; }

    private integer totalRecs = 0;
    private integer OffsetSize = 0;
    private integer LimitSize= 10;
    
    public integer Pagination() {
        totalRecs = [select count() from attendance__c];
        return totalRecs;
    }
    
    public List<attendance__c> getacclist() {
        List<attendance__c> acc =[SELECT contact__c, Manager__c, Manager_s_Manager__c,
               Approved__c,Attendance_Date__c, Hours__C,
              Is_Eligible_for_compensatory_off__c, AttendanceType__c FROM Attendance__c LIMIT :LimitSize OFFSET :OffsetSize];
    return acc;
    }
    
    public void FirstPage() {
        OffsetSize = 0;
    }
    
    public void previous(){
        OffsetSize = OffsetSize - LimitSize;
    }
    
    public void next(){
        OffsetSize = OffsetSize + LimitSize;
    }
    
    public void LastPage()  {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
    }
    
    public boolean getprev() {
        if(OffsetSize == 0)
        return true;
        else
        return false;
    }
    public boolean getnxt(){
        if((OffsetSize + LimitSize) > totalRecs)
        return true;
        else
        return false;
    }
}
===============================================================================

<apex:page controller="PaginationAttendance" sidebar="false" showHeader="false">
<apex:form > 
<apex:pageBlock id="details">
<apex:pageblockTable value="{!acclist}" var="acc">    
<apex:column value="{!acc.Contact__c}"/>
<apex:column value="{!acc.Manager__c}"/>
            <apex:column value="{!acc.Manager_s_Manager__c}"/>
            <apex:column value="{!acc.Approved__c}"/>
            <apex:column value="{!acc.Attendance_Date__c}"/>
            <apex:column value="{!acc.Hours__c}"/>            
            <apex:column value="{!acc.Is_Eligible_for_compensatory_off__c}"/>
            <apex:column value="{!acc.AttendanceType__c}"/>
</apex:pageblockTable>
<apex:pageblockButtons >
<apex:commandButton value="First Page" rerender="details" action="{!FirstPage}" disabled="{!prev}"/>
<apex:commandButton value="Previous" rerender="details" action="{!previous}" disabled="{!prev}"/>
<apex:commandButton value="Next" rerender="details" action="{!next}" disabled="{!nxt}"/>
<apex:commandButton value="Last Page" rerender="details" action="{!LastPage}" disabled="{!nxt}"/>
</apex:pageblockButtons>
</apex:pageBlock>
</apex:form></apex:page>
Challenge Not yet complete... here's what's wrong: 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: LQBWGHOD

User-added image

I do creatged new org for this challenge and working on the same. 

 
Hello, 
I'm trying to create a trigger to update a field based on the value of another field. The field I'm trying to update is a picklist and the values I'm trying to update it to are active picklist values. There are various HS_Original_Source__c values that if they are populated, I want the standard leadsource field to have it's equivilant value. Ex. HS_Original_Source__c is ORGANIC SEARCH and would map to leadsource of Organic Search.
 
trigger LeadSourceTrigger on Opportunity (before update, before insert) {
 List<Opportunity> oppList = new List<Opportunity>();
    
    //Go through the updated records coming into the database and update their custom fields 
    //according to the updated lead source 
    for(Opportunity opp : Trigger.new)
    {
        if(opp.LeadSource == '' && opp.HS_Original_Source__c != '' && opp.HS_Original_Source__c != 'OFFLINE')
        {
          if(opp.HS_Original_Source__c == 'ORGANIC SEARCH')
          {
               opp.LeadSource = 'Organic Search';
               System.debug('organic search');
           }
           /*
              if(opp.HS_Original_Source__c == 'next value')
          {
               opp.LeadSource = 'next value';
               System.debug('next value');
           }
           
           
            */
          
          //Put each updated record in the list created
          oppList.add(opp);  
        }
        
 }
 }

Any help would be much appreciated.
Hello,

I've been looking into created a custom lightning componenet for related records. My use case is I have an object called Checklist, on checklist there is a lookup to an object called Submittal and on submittal there is a lookup to an object called Listing.

I want to display the listing details when on the checklist object. I've looked into recordViewForms but they don't support displaying this relationship and was hoping someone could point me in the right direction as I can't find anything online for where to get started.
Inside the Developer Console, I am receiving the error:
Unexpected Token '<' on Line 2

I believe my syntax defining my List<AggregateResult> is correct.
 
trigger CaseHandlerCountAlert on SOBJECT (after insert) {
    List<AggregateResult> AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co,  Milestone1_Project__c.id,
                                    Milestone1_Project__c.Implementation_status__c, Milestone1_Project__c.Client_Advisor_Email__c
                                    FROM Case
                                    WHERE CreatedDate = LAST_N_DAYS:5
                                    GROUP BY AccountId, Account.Name
                                    HAVING COUNT(Id)  >= 8
                                    WHERE Id IN :Trigger.New];
                                    

                for(AggregateResult aggr:AggregateResultList){ 
                        system.debug(aggr);

                        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                        
                            if(Milestone1_Project__c.Implementation_status__c == 'LIVE - TRANSITION'){    
                                // Set Outgoing Email to Implementation Coordinator
                                //message.toAddresses = new String[] { test@test.com }; 
                            }
                            else if (Milestone1_Project__c.Implementation_status__c == 'Live'){  
                                // Private method *** getAddresses() *** retrieves email address from Customer_Success_Managers Public Group
                                
                                //message.toAddresses = new String[] { "test@test.com" };
                            } 
                        message.setSubject = 'Subject Test Message';
                        message.setPlainTextBody = 'Account name: ' + aggr.get('name') + ' has ' + (Integer)aggr.get('co') + ' cases opened in the last 8 days.';
                        Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
                        Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
                    System.debug('Account Name: ' + aggr.get('name'));   
                }            
                  
 

private List<String> getAddresses(){
    List<User> UserList =
            [SELECT id, name, email
            FROM User 
            WHERE id 
            IN (SELECT userorgroupid 
                FROM groupmember
                WHERE group.name = 'Customer Success Managers')];

    Set<String> emailString = new Set<String>();

    for(User u: UserList){
        emailstring.add(u.email);
    }   
    return (emailString);
    }    
}

 
I'm trying to use a image inside a table, and when I click on it, should call a function an pass a parameter. But when I use the tag<img> inside the tag<a> the parameter is set as null. 

Could anyone help me?
!--- comp
 <a  data-ex="{!contSubIndex}" onclick="{!c.expandTVSubTable}">
                                                                                            <img src="{!$Resource.v360IconeMais}"/>
 
                                                                                       </a>
Controller

 
var index = event.target.getAttribute('data-ex');
        alert(index);
Challenge Not yet complete... here's what's wrong: 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: LQBWGHOD

User-added image

I do creatged new org for this challenge and working on the same. 

 
Hi all,
 I need to check and uncheck the checkbox in salesforce lighting. anyone, please guide me. below code doesn't work properly.
Controller:
 confirm :function(component, event, helper) {
        if(event.target.title =='false'){
           component.find("PaymentCleared").set('v.value',false);  
            component.set('v.simpleRecord.Payment_Cleared__c',false);
        }
        else{
             component.find("PaymentCleared").set('v.value',true); 
             component.set('v.simpleRecord.Payment_Cleared__c',true);
        }
In Opportunity, I have a field called Status__c. I want to pull a list of records in which Status__c specifically has not been updated in the last 21 days. History tracking has been turned on for that field over a year ago. What's the SOQL query to do so?
I created with a lot of help a trigger with its Apex Class in a sandbox. Now I would like to have it in my production to really use it. 
How can I do that ? 

Please help me, I spend a lot of time creating these, I cannot have done it for nothing. Thank you in advance.
Hi and thanks in advance for your help! I've been working on an apex trigger for a junction object that has two custom master-detail fields, but I'm stuck and could use some help.

I have created a junction object to create a connection between two Accounts (1st: Account object; 2nd: Connected_Account custom object). Connected_Account__c functions as a one-to-one relationship with Account (every Account has itself as a Connected_Account)

junction object:
Connection__c
- Connection__c.Name : auto number {0}
- Account1__c : master-detail(Account)
- Account2__c : master-detail(Connected_Account__c)

Connected_Account__c
- Connected_Account__c : lookup(Account)

User creates a new Connection__c on the Account Page Layout for Account X:

Connection__c.Name = 1
// Account1 autopopulated, Account1 = X
Account1__c = X
// User selects Account2, Connected_Account = Y
Account2__c = Y

Now, what I'm trying to accomplish is a trigger such that after a User creates Connection__c.Name=1, the trigger creates a second Connection__c.Name=2 where the field values are inverted:

Connection__c.Name = 2
Account1__c = Y
Account2__c = X
 
ConnectionHandler.apxc :

public with sharing class ConnectionHandler {
    public static void CreateNewConnection(List<Connection__c> connects) {
        for(Connection__c c : connects) {
            Connection__c connect = new Connection__c();
            connect.Account1__c = c.Account2__c;
            connect.Account2__c = c.Account1__c;
            connects.add(connect);
        }
        if(connects.size() > 0) {
            insert connects;
        }
    }
}


ConnectionTrigger.apxt :

trigger ConnectionTrigger on Connection__c (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
	if(Trigger.isAfter && Trigger.isInsert) {
        ConnectionHandler.CreateNewConnection(Trigger.New);
    }
}

Any advice and/or suggestions would be greatly appreciated. Thanks again!
  • August 21, 2018
  • Like
  • 0
We have a workflow setup to create a completed task when a date is entered on an object.This works perfectly, however, there is a custom picklist field on the task that we want to update when the auto-task is created. I've setup a second workflow to update the field, but it does not work on the auto-created tasks, it only works on my manually entered tasks. The second workflow is setup with the criteria of the task subject being equal to what we have specified for the auto-created task. I'm not sure if I'm missing something... Any advice?
I have build a lightning component to list all the open cases and inserted in a page layout. But I want to hyperlink the case number, if someone clicks on that, it should take the user to the corresponding case for view/edit etc. can you pls let me know how to do this. thanks.
  • August 17, 2018
  • Like
  • 0
Hello,

Has anyone ever experienced this? When running a batch class, the query fetches 9200 rows (sometimes over 10000 so this is why I'm using batch). I then proceed to loop and insert in a custom object. But everytime the insert is missing 200 rows (size of scope) so 9000 rows are inserted instead of 9200. If I put the scope to 500, then 500 rows are missing. When I debug, I notice that the first SerialBatchApexRangeChunkHandler is always empty as if the execute doesn't happen until the 2nd pass. Another thing that I noticed is that for lower row counts like 2000, this behavior doesn't happen and all iterations are there. I've tried to schedule the batch and also ran it manually but both have same behavior. Why is this happening? Thanks.  Here is the code:
 
global class ScheduledOpportunityTrend_Batch implements Database.Batchable<sObject> {
	String query;
   
    global ScheduledOpportunityTrend_Batch() {
        if(Test.isRunningTest()){
             query ='Select id,Name, Opportunity.Account.name, Opportunity.amount, Opportunity.CloseDate,Opportunity.CreatedDate, Opportunity.DateClosed__c, Opportunity.Name, ProductCode, Product_Code_Entry__c, Opportunity.Account.Territory__c, convertCurrency(TotalPrice), Opportunity.currencyisocode,Opportunity.id, OpportunityLineItem.Product2.Business_Unit__c from OpportunityLineItem where InQuote__c = true and OpportunityLineItem.Product2.Business_Unit__c = \'Optical\' and Opportunity.IsClosed = false ORDER BY Opportunity.Name limit 100'; 
        } else{
             query ='Select id,Name, Opportunity.Account.name, Opportunity.amount, Opportunity.CloseDate,Opportunity.CreatedDate, Opportunity.DateClosed__c, Opportunity.Name, ProductCode, Product_Code_Entry__c, Opportunity.Account.Territory__c, convertCurrency(TotalPrice), Opportunity.currencyisocode,Opportunity.id, OpportunityLineItem.Product2.Business_Unit__c from OpportunityLineItem where InQuote__c = true and OpportunityLineItem.Product2.Business_Unit__c = \'Optical\' and Opportunity.IsClosed = false ORDER BY Opportunity.Name'; 
        }
   }

    
    global Database.querylocator start(Database.BatchableContext BC){
        //Get the opportunities for Simulator that are open. We don't take into account any dates. We fetch everything.
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<OpportunityLineItem> scope){
  		
         List<SnapshotOpportunityTrend__c> ObjecttoInsert = new List<SnapshotOpportunityTrend__c>();
       
        for(OpportunityLineItem s :  scope){
            //create object and set all the fields in object
                SnapshotOpportunityTrend__c SnapObject = new SnapshotOpportunityTrend__c();
                
                snapObject.Business_Unit__c = s.Product2.Business_Unit__c;
                snapObject.Opportunity_Id__c = s.Opportunity.id;
                snapObject.Opportunity__c = s.Opportunity.id;
                SnapObject.Account_Name__c = s.Opportunity.Account.name;
                SnapObject.Amount__c = s.Opportunity.amount;
                SnapObject.Amount_Currency__c = s.Opportunity.amount;
                SnapObject.Closed_Date__c = s.Opportunity.CloseDate;
                SnapObject.Created_Date__c = s.Opportunity.CreatedDate.date();
                SnapObject.Date_Closed__c = s.Opportunity.DateClosed__c;
                SnapObject.Opportunity_Name__c = s.Opportunity.Name;
                SnapObject.Product_Code__c = s.ProductCode;
                SnapObject.Product_Code_Entry__c = s.Product_Code_Entry__c;
                SnapObject.Territory__c = s.Opportunity.Account.Territory__c;
                SnapObject.Total_Price__c = s.TotalPrice;
                SnapObject.Total_Price_Currency__c = s.TotalPrice;
                    
                    ObjecttoInsert.add(SnapObject);

            system.debug('aaaaaaaa: ' + ObjecttoInsert.size());
           		
       }
 				
 			try{
                //insert list containing all lines
                insert ObjecttoInsert;
            }catch(Exception e) {
                System.debug('An exception occurred: ' + e.getMessage());
            }

    }
     
    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('SnapObject: ' + a.Status);
       mail.setPlainTextBody
       (query + ' : ' + a.TotalJobItems +
       ' batches with '+ a.NumberOfErrors + ' failures.' );
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 
I wrote a couple of triggers that duplicate opportunities when we set their stage to closed won, and then automatically create revenue schedules based on the products those opportunities have. They have been working well, but I started getting a weird error whenever I try to close an opp with more than one product. Here's a screenshot of the error:

User-added image

For some reason, when it tries to duplicate this opp, if I only have one product on it, it will work, but once I add a second, it throws and error. I'll also attach the code for the "Create_Followup" trigger. I can upload the "EditSchedule" trigger too if that turns out to be part of the problem. Thanks for the help.

here's create_Followup. It's throwing an error when it tries to insert the opp product list.

trigger Create_followup on Opportunity (before update, after insert) {
    List<Pricebook2> standardBook = [SELECT Id FROM Pricebook2 WHERE Name = :'Ambition'];//Create an instance of the standard pricebook
    
    if(Trigger.isUpdate){
        List<Opportunity> listOppor = new List<Opportunity>();
        for (Opportunity o: Trigger.new){
            if (o.StageName == 'Closed Won' && o.Stage_Change__c == false){

                Opportunity oppNew = o.clone();
                oppNew.Name = oppNew.Name  + ' - Annual ' + o.CloseDate.year();
                
                if(o.Renewal_Date__c != null){
                oppNew.Renewal_Date__c = o.Renewal_Date__c.addYears(1);
                oppNew.CloseDate = o.Renewal_Date__c;
                oppNew.Contract_Start_Date__c = o.Renewal_Date__c;}
                
                oppNew.StageName = 'Discovery';
                oppNew.Probability = 25;
                oppNew.Parent_Opportunity__c = o.Id;
                
                
                oppNew.Pricebook2Id = standardBook[0].Id;//associate the standard pricebook with this opportunity
                
                oppNew.Is_Clone__c = true;
                listOppor.add(oppNew);
                o.Stage_Change__c = true;
                
            }

        }//end of for loop

        if(listOppor.size() > 0){
            insert listOppor;
            
            List<OpportunityContactRole> ocrList = [SELECT OpportunityId, ContactId, Role FROM OpportunityContactRole WHERE OpportunityId IN :Trigger.New];
            List<OpportunityContactRole> newOcrList = new List<OpportunityContactRole>();

            if(!ocrList.isEmpty()) {
                Map<Id, Id> oldOpNewOpIdMap = new Map<Id, Id>();
                for(Opportunity opNew : listOppor) {
                    oldOpNewOpIdMap.put(opNew.Parent_Opportunity__c, opNew.Id);
                }   
                for(OpportunityContactRole ocr : ocrList) {
                    OpportunityContactRole newOcr = new OpportunityContactRole();
                    newOcr.ContactId = ocr.ContactId;
                    newOcr.Role = ocr.Role;
                    newOcr.OpportunityId = oldOpNewOpIdMap.get(ocr.OpportunityId);
                    newOcrList.add(newOcr);
                }
                insert newOcrList;
            }
            
          List<OpportunityLineItem> oliList = [SELECT OpportunityId, PricebookEntryId, UnitPrice, Quantity, Duration__c, Payment_Terms__c, Discount FROM OpportunityLineItem WHERE OpportunityId IN :Trigger.New];
          List<OpportunityLineItem> newoliList = new List<OpportunityLineItem>();
          
          if(!oliList.isEmpty()) {
                Map<Id, Id> oldOpNewOpIdMap2 = new Map<Id, Id>();
                for(Opportunity opNew : listOppor) {
                    oldOpNewOpIdMap2.put(opNew.Parent_Opportunity__c, opNew.Id);
                }   
                for(OpportunityLineItem oli : oliList) {
                    OpportunityLineItem newOli = new OpportunityLineItem();
                    newOli.UnitPrice = oli.UnitPrice;
                    
                    newOli.PricebookEntryId = oli.PricebookEntryId;
                    newOli.Quantity = oli.Quantity;
                    newOli.Duration__c = 12;
                   
                    newOli.Payment_Terms__c = oli.Payment_Terms__c;
                    newOli.Discount = oli.Discount;
                    newOli.OpportunityId = oldOpNewOpIdMap2.get(oli.OpportunityId);
                    
                    
                    newoliList.add(newOli);
                }
                insert newoliList;
            }

            
        }
        
        

    }

    if(trigger.isInsert){
        try{
            //OpportunityLineItem[] lines = new OpportunityLineItem[0];
            //PricebookEntry entry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = 'ENTERPRISE_ANNUAL_UPFRONT'];
            List<Event> eventList = new List<Event>();
            //List<Note> noteList = new List<Note>();


            for(Opportunity o: Trigger.new){
                if(o.Is_Clone__c == true){

                    //noteList.add(new Note(ParentId=o.id,Title='Matt is the Apex_God',Body='Matt is the Apex_God',isPrivate=false));

                    //lines.add(new OpportunityLineItem(PricebookEntryId=entry.Id, OpportunityId=o.Id, UnitPrice=entry.UnitPrice, Quantity=1));

                    if(o.Renewal_Date__c != null){

                        DateTime myDateTime = o.Renewal_Date__c.addMonths(-10);
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime,subject='Account Management Follow-Up', EndDateTime=myDateTime, IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(2),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(2), IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(4),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(4), IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(6),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(6), IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(8),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(8), IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(10),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(10), IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(10),subject='Renewal',EndDateTime=myDateTime.addMonths(10), IsAllDayEvent=true));
                        eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(9),subject='Sales Contract Follow-Up',EndDateTime=myDateTime.addMonths(9), IsAllDayEvent=true));

                    }//end of if

                }
            }
            //insert lines;
            insert eventList;
            //insert noteList;

        }
        catch(Exception e){

        }
    }
}

We have an VF Apex Class called opportunityButtons that controls the behavior of a pane of buttons on our renewal Opportunities layout. Currently, an error message is generated when the user selects the button to create a .pdf of the sales agreement (or selects the other button to create through DocuSign) and the Primary/Contact Role has no mailing address.

We would like to implement a similar error message when the opportunity is a renewal and the Original Agreement Date has not been entered in the record.

If this is something you think you can help with, we can either chat here or do a hangout. I can also share the code through GitHub gist.

Any guidance will be greatly appreciated.

Thanks,

Julien

Hi,

I've overridden the standard "New" button functionality on the Lead object using a visualforce page and custom controller.

The purpose of this override is to allow for a dynamic dependent picklist when creating a new lead.  Specifically, the requirement is: when a user selects a value from the standard lead picklist field called "Lead Source"...then...show a second custom field picklist called "Lead Source Detail".  The values that the user sees in this second picklist must only be the names of Campaigns in SFDC that have a value in their Type field equal to the value the user selected in the Lead Source field.

Here's an example.

User clicks "New" button on the lead tab to create a new lead in the ui.

User sees the Lead Source picklist field.  Let's say it has values of A,B,C.  User selects A.

The user should then have the option of selecting a value in a second picklist field called Lead Source Detail.  The options the user should see are only the campaigns in SFDC that have a Type field value of "A".  So for example, say there are 2 campaigns in SFDC with a Type field value of "A".  These would therefore be the only 2 selectable options in the Lead Source Detail field for the user.

The following code works for setting up a couple of dependent picklists on a lead New override screen, but, it's not quite there.  I'm not sure how to modify it to get what I want above.

If you create a couple custom objects Category__c, Feature__c, and put a picklist field on Lead object called "Category__c", and put in the following 2 classes and VF page, and use the vf page to override the New button on Lead object, you'll see where I am.  This all works to override the lead new button with a couple dyamic dependent picklists, but I need to modify this code so that, basically, the dependent picklist fields are:

1. the controlling field should be the lead.leadsource field and
2. the dependent picklist field should display a list of campaigns where the campaign type = the lead source value selected in option 1

the vf page: 

<apex:page standardController="Lead" extensions="LeadNew_ControllerExtension2" title="Lead Edit" tabStyle="Lead">

   <apex:form id="form">
        <apex:pageBlock title="Lead Edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!doSave}" value="Save" />
                <apex:commandButton action="{!cancel}" value="Cancel" />
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Lead Information">
                
                <apex:pageBlockSectionItem >
                <apex:outputlabel value="First Name"></apex:outputlabel>
                <apex:inputfield value="{!Lead.FirstName}"/>               
                </apex:pageBlockSectionItem>                
                
                <apex:pageBlockSectionItem >
                <apex:outputlabel value="Last Name"></apex:outputlabel>
                <apex:inputfield value="{!Lead.LastName}"/>               
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem >
                <apex:outputlabel value="Company"></apex:outputlabel>
                <apex:inputfield value="{!Lead.Company}"/>               
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem >
                <apex:outputlabel value="Email"></apex:outputlabel>
                <apex:inputfield value="{!Lead.Email}"/>               
                </apex:pageBlockSectionItem>              
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel for="productList" value="{!$ObjectType.Lead.fields.Product__c.label}" />
                    <apex:actionRegion >
                        <apex:selectList value="{!product}" title="Product" size="1" id="products">
                            <apex:selectOptions value="{!productList}" />
                            <apex:actionSupport event="onchange" rerender="versions" />
                        </apex:selectList>
                    </apex:actionRegion>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel for="versions" value="{!$ObjectType.Lead.fields.Version__c.label}" />
                    <apex:actionRegion >
                        <apex:selectList value="{!version}" title="Version" size="1" id="versions">
                            <apex:selectOptions value="{!versionList}" />
                        </apex:selectList>
                    </apex:actionRegion>
                </apex:pageBlockSectionItem>
                
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>

</apex:page>
the controller:

global with sharing class LeadNew_ControllerExtension2 {
    private final Id recordId;
    private final Lead record;
    private final ApexPages.StandardController controller;
 
    public LeadNew_ControllerExtension2(ApexPages.StandardController stdController) {
        this.controller = stdController;
        this.recordId = this.controller.getId();
        this.record = [
            select Id, ProductText__c,Product__c,Version__c,Product__r.Name,LeadSource,Lead_Source_Detail_Text__c,
                LastName,Email,Company,
                VersionText__c
            from Lead WHERE Product__c = null
         //   where Id = :this.recordId
            limit 1
        ];
        
    }
 
    public List<SelectOption> getProductList() {
        List<SelectOption> products = new List<SelectOption>();
        products.add(new SelectOption('', '--None--'));
 
        for (Product__c p: ProductUtils2.getAllProducts()) {
            products.add(new SelectOption(p.Id, p.Name));
        }
 
        return products;
    }
 
    public Id getProduct() {
        return this.record.Product__c;
    }
 
    public void setProduct(Id productId) {
        this.record.Product__c = productId;
    }
 
    public List<SelectOption> getVersionList() {
        List<SelectOption> versions = new List<SelectOption>();
        versions.add(new SelectOption('', '--None--'));
 
        if (record.Product__c != null) {
            for (Version__c v: ProductUtils2.getAllVersions(getProduct())) {
                versions.add(new SelectOption(v.Id, v.Name));
            }
        }
 
        return versions;
    }
 
    public Id getVersion() {
        return this.record.Version__c;
    }
 
    public void setVersion(Id versionId) {
        this.record.Version__c= versionId;
    }
 
    public PageReference doSave() {
        Lead c = (Lead) controller.getRecord();

        c.Product__c = this.record.Product__c;
        c.Lead_Source_Detail_Text__c = this.record.Version__c;
        
        upsert c;
 
        return new PageReference('/'+c.Id);
    }
}

util class used in the controller:

public with sharing class ProductUtils2 {
    
    static public List<Product__c> getAllProducts(Boolean includeEOL) { 
        return [
            select Name
            from Product__c
            order by Name
        ];
    }
 
    public static List<Product__c> getAllProducts() {
        return getAllProducts(false);
    }
 
    public static List<Version__c> getAllVersions(Id productId, Boolean test) {
 
        return [
            select Name,
                Product__c
            from Version__c
            WHERE Product__c =: productId
            order by Name
        ];
    }
 
    public static List<Version__c> getAllVersions(Id productId) {
        return getAllVersions(productId, false);
    }
}



  • May 23, 2014
  • Like
  • 0
I am adding a button that opens a modal window to add a task to a specific "Objective".  There is an add Task button next to every "Objective" that is displayed, but I'm not sure how I can pull the record Id of the specific objective the button sits next to so I can set the WhatId field of the task to that specific objective... Any ideas here? 

Thanks in advance.
 
<aura:iteration items="{!v.objectives}" var="obj" >


        	<div class="blacklink slds-col slds-size_11-of-12 slds-text-body_regular slds-m-bottom_small slds-box">
                	<a class ="blacklink" href="{!'/lightning/r/Task/'+ obj.Id + '/view'}" target="_blank">	{!obj.Description__c} </a>
            </div>
            <div id ="obj.Id" class="slds-size_1-of-12 slds-m-top_x-small slds-p-left_large">
                	<lightning:button label="+Task" class="slds-button slds-text-body_regular" onclick="{!c.taskopenmodal}" name="obj.Id"/>
                
			</div>
            
            	
                        <aura:if isTrue="{!obj.Tasks}">
                    	<div class="slds-col slds-size_3-of-5 slds-p-left_xx-large slds-m-bottom_small slds-text-heading_small slds-border_bottom" >
                            Task Subject
						</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small slds-text-heading_small slds-border_bottom">
                			Status
                		</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small slds-text-heading_small slds-border_bottom">
                			Owner
                		</div>
          				</aura:if>
                    
            <aura:iteration items="{!obj.Tasks}" var="t" >
                       	<div class="slds-col slds-size_3-of-5 slds-p-left_xx-large slds-m-bottom_small" >
                            <a href="{!'/lightning/r/Task/'+ t.Id + '/view'}" target="_blank">
                            {!t.Subject} 
                            </a>
						</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small">
                			{!t.Status}
                		</div>
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small">
                			{!t.Owner.Name}
                		</div>
            </aura:iteration> 
            
         </aura:iteration>