• Sudipta Deb
  • NEWBIE
  • 163 Points
  • Member since 2014
  • Salesforce Architect
  • Cognizant Technology Solutions


  • Chatter
    Feed
  • 3
    Best Answers
  • 1
    Likes Received
  • 4
    Likes Given
  • 12
    Questions
  • 48
    Replies
Hi Can someone explain how to set the lookup (from account name value) to conatct name when creating contact from anonymous window.

List<contact> contactToSave = new List<contact> ();
Contact cont = new Contact();
Account acctRef = new Account(name='University of Arizona'); // need to set this name to contact which I'm creating below. Account name already available on org 
cont.FirstName='Test1';
cont.LastName='Test2';
cont.Department='Finance';
cont.name=actRef;
contactToSave.add(cont);
insert contactToSave;

please explain how this works...

I have created an action in process builder to Create a new contract once the Opportunity stage = Closed Won.

This is occurs when a record is created or edited, and I have unchecked the checkbox asking whether to Allow process to evaluate a record multiple times.

So the criteria to be met is Opportunity Stage = Closed Won

The first action I have written is to create a new contract, with the fields as follows:

 

User-added image
However, similar to how there is a lookup field on Contract Stage to link back to Account and (in this case, I have created another custom lookup field to link to Opportunity) Opportunity as well, I would like to have a lookup field on Opportunity stage to link to Accounts.

This Contract field on Opportunity object is just the mirror image of the Opportunity lookup on Contract object.

What I want to do is be able to, upon marking the Opportunity as Closed Won,

1) Create a new contract (all good this works already)

2) Update the previously empty Contract lookup field on Opportunity object with the Contract ID of the newly created contract.

I am having trouble completing step 2. 

I tried adding another action to Update the contract lookup field on Opportunity object 

User-added image
But upon marking an opportunity as closed won, I get the following error

 

An error occurred at element myRule_1_A3 (FlowRecordUpdate).
The flow failed to access the value for myVariable_current.Contract.Id because it hasn't been set or assigned.

Any ideas on how to automate this? Ideally, I would want users to be able to access the corresponding Contract immediately upon marking the Opportunity as Closed Won, as opposed to having to go to Contract object and searching for that contract.

I swear I'm somewhere close to the answer as I can successfully import the ID of the opportunity when creating a new contract (see first photo I inserted above)

Thanks!
I have an encrypted field NRIC_NEW__C, after saving the record, I would like to copy the content of this field into another text field, how can I do this
  • December 14, 2016
  • Like
  • 0
Hi Folks,

I would like to understand one use case - "Is it a valid scenario to have multiple active entitlements associated with Single Contact/Single Account?
From the below document about "Automatically add entitlements to the case", I can see the code is written such a way that it may possible to have multiple active entitlements against a contact or account. In that case, trigger will link the first entitlements to the case and break the loop.

Also don't you think so that while considering entitlements for Accounts only(Cases without Contacts, but having Accounts), it should consider only those entitlements which are associated with Account, but not with Contacts. May be create a roll-up summary field in Entitlements with counts of EntitlementContacts. Query(To Fetch Active Entitlements for Accounts) will only consider those entitlements for which the roll-up summary field value is zero. 
Hi All,

I am facing problem in completing the challenge for the Lightning module - Connect Components with Events. Below are the code I have written:
campingList.cmp
<aura:component controller="sudipta.CampingListController" implements="force:appHostable,flexipage:availableForAllPageTypes" >
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:handler name="addItem" action="{!c.handleAdditem}" event="c:addItemEvent"/>

    <aura:attribute name="newItem" type="Camping_Item__c" description="Single Camping Item" required="true" 
                                                        default="{'sObjectType':'sudipta__Camping_Item__c',
                                                                'Name':'Item1',
                                                                'sudipta__Quantity__c':10,
                                                                'sudipta__Price__c':100,
                                                                'sudipta__Packed__c':false}"/>
    <aura:attribute name="items" type="Camping_Item__c[]" description="All Camping Item" />
    
    <!-- PAGE HEADER -->
    <div class="slds-page-header" role="banner">
        <div class="slds-grid">
            <div class="slds-col">
                <p class="slds-text-heading--label">Campings</p>
                <h1 class="slds-text-heading--medium">My Campings</h1>
            </div>
        </div>
    </div>
    <!-- PAGE HEADER -->
	
	<!-- NEW CAMPING FORM -->
    <div class="slds-grid">
        <div class="slds-col slds-col--padded sls-p-top--large">
            <c:campingListForm />
        </div>
        
        <div class="slds-col slds-col--padded sls-p-top--large">
            <div area-labelledby="allcamping">
                <fieldset class="slds-box slds-theme--default slds-container--small">
                	<legend id="allcamping" class="slds-text-heading--small slds-p-vertical--medium">All Campings</legend>
                    
                    <aura:iteration items="{!v.items}" var="singleItem">
                        <div class="slds-box slds-theme--default slds-container--small">
                        	<c:campingListItem item="{!singleItem}" />
                        </div>
                    </aura:iteration>
                </fieldset>
            </div>
        </div>
    </div>
    
    
</aura:component>
campingListController:
({
	doInit : function(component, event, helper){
    	var action =  component.get("c.getItems");
        action.setCallback(this,function(response){
        	var state = response.getState();
        	if(component.isValid() && state === "SUCCESS"){
            	component.set("v.items", response.getReturnValue());
            }else if(state === "ERROR"){
                console.log('Failed with below state: ' + state);
                var errors = response.getError();
                if (errors) {
                	if (errors[0] && errors[0].message) {
                    	console.log("Error message: " + errors[0].message);
                    }else{
                        console.log("Unknown Error");
                    }
                }
            }
        });
    
   		$A.enqueueAction(action); 
	},

    handleAdditem : function(component, event, helper){
        helper.createCampings(component, event.getParam("item"));
    }
})
campingListHelper:
({
    createCampings : function(component,camping) {
        var allCampings = component.get("v.items");
        var newCamping = JSON.parse(JSON.stringify(camping));
        
        // set the sobjectType!
        camping.sobjectType='sudipta__Camping_Item__c';
        
        var action = component.get("c.saveItem");
        action.setParams({"item" : camping});
        
        action.setCallback(this, function(response){
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS"){
                allCampings.push(newCamping);
                component.set("v.items",allCampings);
            }else if(state === "ERROR"){
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                    }else{
                        console.log("Unknown Error");
                    }
                }
            }
        });        
        
        $A.enqueueAction(action);
    }
})

Now the other component:
campingListForm.cmp:
<aura:component controller="sudipta.CampingListController" implements="force:appHostable,flexipage:availableForAllPageTypes">
    <aura:attribute name="newItem" type="Camping_Item__c" description="Single Camping Item" required="true" 
                                                        default="{'sObjectType':'sudipta__Camping_Item__c',
                                                                'Name':'Item1',
                                                                'sudipta__Quantity__c':10,
                                                                'sudipta__Price__c':100,
                                                                'sudipta__Packed__c':false}"/>
    <aura:registerEvent name="addItem" type="c:addItemEvent"/>
                                                              
    <div area-labelledby="newcampingform">
        <fieldset class="slds-box slds-theme--default slds-container--small">
            <legend id="newcampingform" class="slds-text-heading--small slds-p-vertical--medium">Add Camping</legend>
            
            <form class="slds-form--stacked">
                <div class="slds-form-element slds-is-required">
                    <div class="slds-form-element__control">
                        <ui:inputText aura:id="campName" label="Campingn Name" class="slds-input" labelClass="slds-form-element__label"
                                      value="{!v.newItem.Name}" required="true"/>
                    </div>
                </div>
                
                <div class="slds-form-element slds-is-required">
                    <div class="slds-form-element__control">
                        <ui:inputNumber aura:id="campQuantity" label="Quantity" class="slds-input" labelClass="slds-form-element__label"
                                        value="{!v.newItem.sudipta__Quantity__c}" required="true"/>
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputCurrency aura:id="campPrice" label="Price" class="slds-input" labelClass="slds-form-element__label"
                                          value="{!v.newItem.sudipta__Price__c}"/>
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputCheckbox aura:id="campPacked" label="Packed?" class="slds-checkbox" labelClass="slds-form-element__label"
                                          value="{!v.newItem.sudipta__Packed__c}"/>
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:button label="Create Camping" class="slds-button slds-button--destructive" press="{!c.submitForm}"/>
                </div>
            </form>
        </fieldset>
    </div>
</aura:component>

campingListForm Controller:
({
	submitForm : function(component, event, helper) {
		console.log('Enterred the saveCamping');
		var validCamping = true;
        var campingName = component.find("campName").get("v.value");
        var campingQuantity = component.find("campQuantity").get("v.value");
        var campingPrice = component.find("campPrice").get("v.value");
        
        if($A.util.isEmpty(campingName)){
            validCamping = false;
            component.find("campName").set("v.errors",[{message: "Name can't be blank"}]);
        }else{
            component.find("campName").set("v.errors",null);
        }
        if($A.util.isEmpty(campingQuantity)){
            validCamping = false;
            component.find("campQuantity").set("v.errors",[{message: "Quantity can't be blank"}]);
        }else{
            component.find("campName").set("v.errors",null);
        }
        if($A.util.isEmpty(campingPrice)){
            validCamping = false;
            component.find("campPrice").set("v.errors",[{message: "Price can't be blank"}]);
        }else{
            component.find("campName").set("v.errors",null);
        }
        
        if(validCamping){
            var newCamping = component.get("v.newItem");
            helper.createItem(component,newCamping);
        }
	}
})

campingListForm Helper:
 
({
	createItem : function(component,item) {
		console.log("Inside the helper function");
		var addEvent = component.getEvent("addItem");
		addEvent.setParams({"item" : item});
		addEvent.fire();
		component.set("v.newItem",{'sObjectType':'sudipta__Camping_Item__c',
                                           'Name': '',
                                           'sudipta__Quantity__c': 0,
                                           'sudipta__Price__c': 0,
                                           'sudipta__Packed__c': false});
	}
})

Controller: CampingListController
public with sharing class CampingListController {
	@AuraEnabled
    public static List<sudipta__Camping_Item__c> getItems(){
        return [SELECT	ID,
               			NAME,
                		sudipta__Quantity__c,
                		sudipta__Price__c,
                		sudipta__Packed__c
                FROM sudipta__Camping_Item__c];
    }
    
    @AuraEnabled
    public static sudipta__Camping_Item__c saveItem(sudipta__Camping_Item__c item){
        System.Debug('Inside saveCamping Method');
        Database.SaveResult[] result = Database.insert(new List<sudipta__Camping_Item__c>{item}, false);
        for (Database.SaveResult sr : result) {
            if(sr.isSuccess()){
                System.Debug('Operation is successful');
            }else{
                for(Database.Error err : sr.getErrors()) {
                	System.Debug('Error message: ' + err.getMessage());
                    System.Debug('Failed for below fields: ' + err.getFields());
                }
            }
        }
        return item;
    }
}
Event: addItemEvent
<aura:event type="COMPONENT" description="Event template" >
	<aura:attribute name="item" type="sudipta__Camping_Item__c"/>
</aura:event>

What is happening is that:
Data is getting saved in Salesforce.
New Data is also inserted into the "items" variable and thus getting displayed in the UI.

But Trailhead is giving me the below error:
User-added image

I really would like to know what is the issue or  bad programming I did so that Trailhead is not allowing me to complete the module. 
I will really appreciate if you can help me here. Thanks.
Hi All -

I am getting the below error when I am testing the my block of code(Trigger helper method) with test data > 200. Any amount of test data which is < 200, my block of code is working fine. Do you have any idea or anybody faced the similar issue earlier
System.DmlException: Update failed. First exception on row 200 with id 50036000003SZd8AAG; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MaintenanceRequest: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id 50036000003SZd9AAG; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Class.MaintenanceRequestHelper.createFollowUpMaintenanceRequest: line 52, column 1
Class.MaintenanceRequestHelper.updateAfterUpdateActivity: line 15, column 1
Trigger.MaintenanceRequest: line 3, column 1: []

 
Hi All -

I have the below code for which I am trying to write the test method to test the bulkify of my code (with 300 Maintenance Requests)

Maintenance Request Helper:
public class MaintenanceRequestHelper {
    private static List<Case> closedCases = new List<Case>();
    private static List<Case> newlyCreatedCases = new List<Case>();
    private static List<Work_Part__c> allWorkParts = new List<Work_Part__c>();
    

    public static void updateAfterUpdateActivity(List<Case> newCases, Map<Id, Case> oldCases){
    	System.Debug('SUDIPTA- CALLED FOR: ' + newCases.size());
    	for(Case singleCase : newCases){
	    	if(singleCase.status == 'Closed' && oldCases.get(singleCase.ID).status != singleCase.status){
	    		if(singleCase.Type == 'Repair' || singleCase.Type == 'Routine Maintenance'){
	    			closedCases.add(singleCase);
	       		}
	    	}
	    }
	    createFollowUpMaintenanceRequest();
    }

    private static void createFollowUpMaintenanceRequest(){
    	Set<ID> caseIds = new Set<ID>();
    	for(Case singleCase : closedCases){
    		caseIds.add(singleCase.Id);
    	}
    	Integer shortestMaintCycle;
    	
    	Map<Id, List<Work_Part__c>> maintWorkPartMap = createMaintWorkPartMap(caseIds);

    	for(Case singleCase : closedCases){
    		List<Work_Part__c> workParts = maintWorkPartMap.get(singleCase.Id);
    		if(workParts != null){
    			shortestMaintCycle = Integer.valueOf(findShortestMaintCycle(workParts));	
    		}else{
    			shortestMaintCycle = Integer.valueOf(0.0);
    		}
    		

    		Case newCase = new Case();
    		newCase.Vehicle__c = singleCase.Vehicle__c;
    		newCase.Type = 'Routine Maintenance';
    		newCase.status = 'New';
    		newCase.Origin = singleCase.Origin;
    		newCase.Reason = singleCase.Reason;
    		newCase.Subject = String.isBlank(singleCase.Subject) ? 'Routine Maintenance Request' :
    			singleCase.Subject;
    		newCase.Date_Reported__c = Date.today();
    		newCase.Date_Due__c = Date.today().addDays(shortestMaintCycle);
    		newCase.Equipment__c = singleCase.Equipment__c;
    		//newCase.Old_Case__c = 'OldCase-'+String.valueOf(singleCase.Id);
    		//newCase.Old_Case__c = singleCase.Case_Id_String__c;
    		newlyCreatedCases.add(newCase);
    	}

    	if(newlyCreatedCases.size() > 0){
    		insert newlyCreatedCases;
    		//updateRelatedWorkOrders(newlyCreatedCases);
    	}
    }
    
    private static void updateRelatedWorkOrders(List<Case> cases){
    	Map<String, Id> oldToNewCaseMap = new Map<String, Id>();
    	for(Case singleCase : cases){
    		oldToNewCaseMap.put(singleCase.Old_Case__c,singleCase.Id);
    	}

    	if(allWorkParts != null){
    		for(Work_Part__c singleWorkPart : allWorkParts){
    			//String key = 'OldCase-'+String.valueOf(singleWorkPart.Maintenance_Request__c);
    			String key = String.valueOf(singleWorkPart.Maintenance_Request__c);
    			Id newCaseId = oldToNewCaseMap.get(singleWorkPart.Maintenance_Request__c);
    			singleWorkPart.Maintenance_Request__c = newCaseId;
    		}
    	}

    	if(allWorkParts != null && allWorkParts.size() > 0){
    		update allWorkParts;
    	}
    }

    private static Decimal findShortestMaintCycle(List<Work_Part__c> workParts){
    	Decimal shortestValue;
    	if(workParts.size()>0){
    		shortestValue = workParts.get(0).Equipment__r.Maintenance_Cycle__c;
    	}
    	for(Work_Part__c singleWorkPart : workParts){
    		if(singleWorkPart.Equipment__r.Maintenance_Cycle__c < shortestValue){
    			shortestValue = singleWorkPart.Equipment__r.Maintenance_Cycle__c;
    		}
    	}
    	return shortestValue;
    }

    private static Map<Id, List<Work_Part__c>> createMaintWorkPartMap(Set<ID> caseIds){
    	//Fetch all WorkPart details
    	allWorkParts = [SELECT ID, Equipment__c, Maintenance_Request__c, 
    			Quantity__c, Equipment__r.Maintenance_Cycle__c FROM Work_Part__c 
    			WHERE Maintenance_Request__c in: caseIds];
    	Map<Id, List<Work_Part__c>> maintWorkPartMap = new Map<Id, List<Work_Part__c>>();
    	for(Work_Part__c singleWorkPart : allWorkParts){
    		List<Work_Part__c> tempList;
    		if(maintWorkPartMap.get(singleWorkPart.Maintenance_Request__c) == null){
    			tempList = new List<Work_Part__c>();
    		}else{
    			tempList = maintWorkPartMap.get(singleWorkPart.Maintenance_Request__c);
    		}
    		tempList.add(singleWorkPart);
    		maintWorkPartMap.put(singleWorkPart.Maintenance_Request__c, tempList);
    	}

    	return maintWorkPartMap;
    }
    
}

And here is my test method-
@isTest
    static void test_Closing_300_Routine_Maintenance_should_create_300_New_Maint(){
    	//Arrange
    	Vehicle__c singleVehicle = TestDataFactory.createVehicle();
    	List<Product2> equipments = TestDataFactory.createEquipments();
    	List<Case> allMaintRequests = TestDataFactory.createMultipleMainRequestWith(
    					201,
    					singleVehicle,
    					'Routine Maintenance',
    					'Open',
    					'Email',
    					'Not Working',
    					'Not Working',
    					Date.today(),
    					Date.today().addDays(10),
    					equipments);
    	
    	//Act
    	Test.startTest();
    	for(Case singleMaintRequest : allMaintRequests){
    		singleMaintRequest.status = 'Closed';
    	}
    	update allMaintRequests;
    	Test.stopTest();			
    	
    	//Assert
    	//List<Case> allCases = [SELECT ID,Date_Due__c FROM Case WHERE Vehicle__c =: singleVehicle.Id and status = 'New'];
    	List<Case> allCases = [SELECT ID,Date_Due__c FROM Case WHERE status = 'New'];
    	System.assertEquals(201,allCases.size());	
    	
    }

Below is the error message I am getting -
System.DmlException: Update failed. First exception on row 200 with id 50036000003SeKQAA0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MaintenanceRequest: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id 50036000003SeKRAA0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Class.MaintenanceRequestHelper.createFollowUpMaintenanceRequest: line 54, column 1
Class.MaintenanceRequestHelper.updateAfterUpdateActivity: line 16, column 1
Trigger.MaintenanceRequest: line 3, column 1: []

Strange thing is that if I test with 200 Maintenance Requests, test method is getting passed, but the moment I make it 201, it started failing. Any idea why this is behaving like this?
Hi,

I have a requirement where I need to run a batch class (Frequency: Weekly) which will generate a csv file and put the file to a ftp server. Do you have any idea how can I achieve the same? Thanks.

With regards,
Sudipta Deb
Hi All,

I am setting up service console. In the right side, I am displaying "Associated Account" with the case. Attached is the screenshot. Currently only below four fields are getting displayed -
  • Account Name
  • Rating
  • Employees
  • Annual Revenie
I would like to understand how can I can add more feilds from account object to be displayed here. Which page layout from Account object I need to update to add more fields? Any help is highly appreciated. Thanks.
User-added image
Hi Team -

I would like to enable Apex Debugger option in my developer org. I tried calling the Salesforce support desk and they suggested me to put the question here. They can't enable and from developer org, I can't create any case also.
Can someone help me to understand how I can enable this option in developer org?

Regards,
Sudipta Deb
I have implemented email-to-case. The new case can be opened in Service Console tab. Now when i am trying to email from the service console, I would like to have To field auto populated with the email address from where the initial email came and case got created.

Do you have any idea how can I auto populate the To field? Any help here is highly appreciated? Thanks.

Regards,
Sudipta Deb
Hi All -

I have created one flow and calling the flow from Custom button inside Contact Page Layout. Once the flow is done, I would like to return to the contact page. Below is the code from Custom Button -

/flow/sudipta/Customer_Issue_Troubleshoot?varEmailAddressPassed={!Contact.Email}&retURL=/{!Contact.Id}

Now what is happening is that once the flow is done, page is returning to the contact page only, but I can see one inner window below the outer window. Screenshot attached. Do you know is there anything I am missing? Thanks,User-added image
I would like to understand how to automate the process of attaching entitlements to a newly created cases. Say for example - If I have two entitlements for Account A. First entitlement is for High Priority Cases and Second entitlement is for Low Priority Cases. I have different milestones setup accordingly. Now when a new case will be logged into the system, how to make sure proper entitlement will be associated with the case automatically. For example - if the new case is having priority high, first entitlement should be associated, whereas if the new case is having priority low, second entitlement should be associated.

Now I know that I can write a trigger to do that. But the problem that I am facing how to compare the conditions setup on Entitlement process with the case properties. If you have done anything like that before, any help will be highly appreciated. Thanks.
Hi,

I have installed two custom lightning components from -
  • https://login.salesforce.com/packaging/installPackage.apexp?p0=04tj0000001mMYP
  • https://login.salesforce.com/packaging/installPackage.apexp?p0=04tj0000001mMYj
But in Lightning App Builder, custom componets are not coming. Any idea why? Thanks
Hi Team-

I would like to refer VisualForce Ids in jQuery using partial ID selector. Below is the code -
<apex:page id="page">
    <apex:form id="form">
        What is your name?
        <br/>
        <apex:inputText id="name" onfocus="myFunc()"/>
        <br/>
        What is your age?
        <br/>
        <apex:inputText id="ageText" onfocus="myFunc()"/>
    </apex:form>
    <apex:includeScript value="{!URLFOR($Resource.jQuery1_11, '/js/jquery-1.11.2.min.js')}"/>
    <script>
        function myFunc() {
            var j$ = jQuery.noConflict();
            var inputTextNameCatched = j$( 'input[id$=name]' ); //Find element with ID ending with name
            inputTextNameCatched.val('Sudipta Deb');
            var inputTextAgeCatched = j$('input[id$=Text]');
            inputTextAgeCatched.val('30');
        }
    </script>
</apex:page>
The above code is working perfectly fine. But when I am trying to get IDs starts with "age" with the below code - 
var inputTextAgeCatched = j$('input[id^=age]');
it is not working. Can anyone please help me to understand what is the problem? Thanks in advance.
Hi,

I have installed two custom lightning components from -
  • https://login.salesforce.com/packaging/installPackage.apexp?p0=04tj0000001mMYP
  • https://login.salesforce.com/packaging/installPackage.apexp?p0=04tj0000001mMYj
But in Lightning App Builder, custom componets are not coming. Any idea why? Thanks
global class inboundEmailattachment implements messaging.inboundemailhandler {
    global messaging.inboundemailresult handleinboundemail(messaging.inboundemail email,messaging.inboundEnvelope evn){
        messaging.inboundemailresult res=new messaging.inboundemailresult();
        contact con=[select lastname,email from contact where email=:email.fromaddress];
        case c=new case();
        c.Subject=email.subject;
        c.Description=email.plaintextbody;
        c.origin='web';
        c.status='new';
        c.priority='high';
        c.contactid=con.id;
        insert c;
        messaging.inboundemail.binaryattachment[] attach=email.binaryattachments;
        list<attachment> mylist=new list<attachment>();
        for(messaging.inboundemail.binaryattachment b:attach){
            attachment a=new attachment();
            a.name=b.filename;
            a.Body=b.body;
            a.parentid=c.id;
            mylist.add(a);
        }
        insert mylist;
        return res;
    }
}
for this i write test class but it not cover all lines of code
test class:
@istest
public class inboundemailattachmentTest {
    
   static testMethod void TestinBoundEmail()
   {
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
      
      email.subject = 'Create Contact';
      email.fromAddress = 'someaddress@email.com';
      email.plainTextBody = 'email body';
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
     
      inboundEmailattachment  testInbound=new inboundEmailattachment ();
      testInbound.handleInboundEmail(email, env);
   }
}
please teach me test class 
 
  • September 24, 2017
  • Like
  • 0
public class ExtentionExample1 {
    public account acc   {get;set;}
    public ExtentionExample1(apexpages.standardcontroller cont){
        string[] names=new string[]{'name','phone','industry','rating'};
            cont.addfields(names);
        acc=(account)cont.getrecord();
    }
    public pagereference save(){
        string str=acc.name;        
        integer count=[select count() from account where name =: str];
        if(count>0){
            acc=[select name,phone,industry,rating from account where name =: str];
            return null;
        }
        else{
            insert acc;
        	pagereference pag=new pagereference('/'+acc.Id);
        	return pag;
        }
    }
}
plz write the test class for the above code
 
  • September 24, 2017
  • Like
  • 0
I have a developer who wants to create apex code to allow some validation rules to take place in an object that is related to another. Right now we have a process builder that is conflicting somehow with the validation rules. He's saying that in order for the rules to work he wants to build apex code to put the process builder into it and avoid this conflict. Does anyone have any info on what he's talking about? Not an apex expert and I'm trying to understand why he needs it to avoid the conflicts with process... he said it has something to do with the calculations that are not right to be used with process and need to be done with coding. 
HI ,

How to count the number of  records on opportunity  associated with on Account ? pls give me exammple ,
kindly help me on this 

viswsanath
U1,u2,u3 different roles and heirarchies only u3 under u4 how can we see u4 records particular u1
I am doing a hypothetical usercase for an assignment and I want to build out some basic objects for a non-profit.  We must make one account (I will use a company as a donor), a contact, and 5 opportunities.  What would 5 opportunities be for a non-profit performing fundraising?

I had the idea that the five opportunities could be different types of events they are raising money for.  For example, selling seating at a table for a dinner, soliciting donations to organize a conference, soliciting general donations for overhead, and so on.  So the account is an organization who is a regular donor, and they will approach them throughout the year regarding different events they can sponsor.

Thanks for any assitance you can offer in making sure my logic regarding opportunities is right!  I can think of lots of fields to add to page layouts, and I think it would be an exciting exercise.
I have strange behavior with a APEX Batch job

I run this job with batch size of 1 and it puts a job of 1000 Batches to process. However after it run for some time I have seen following behavior

1. I see the batches are processing fine say like it has processed 300. All of a sudden I see all jobs completed and it says it processed 800 batches (not sure where the other 200 batches go). Looking at the data looks like it did not process everything that should have been processed.

2. Some times I see it is processing fine say at 400th batch and all of a sudden it would say completed with all 1000 batch completed. Looking at the data looks like it did not process everything that should have been processed.

Any ideas why this could happen ?

The batch class internally call another class method in the execute method. This method has some what more logic in it. However this method when run individually does not have any issues (No Heap size issue or other performance issues).  Not sure because of the call method the complete Batch job is abruptly aborted. (with specifying any error)

I have opened a case with Salesforce but want to see if any one else have seen this issue.   
 
I've spent hours trying to figure this challenge out and finally got it working, but now when I go to 'Check' the challenge, it's not giving me the credit I deserve! The task seems pretty straightforward, but i'm sure i'm missing some code they think is necessary. Like the teacher telling you that you "solved the problem wrong" even though you got the right answer...

Error is: Challenge Not yet complete... here's what's wrong: 
The campingListItem JavaScript controller isn't setting the 'item' attribute correctly.

------ campingListItem.cmp ------
<aura:component >
    <aura:attribute name="item" type="Camping_Item__c" default="{'sobjectType':'Camping_Item__c','Packed__c':false}"/>
    <p>Name:
        <ui:outputText value="{!v.item.Name}"/>
    </p>
    <p>Price:
        <ui:outputCurrency value="{!v.item.Price__c}"/>
    </p>
    <p>Quantity:
        <ui:outputNumber value="{!v.item.Quantity__c}"/>
    </p>
    <p>Packed:
        <ui:outputCheckbox aura:id="checkbox" value="{!v.item.Packed__c}"/>
    </p>
    <ui:button label="Packed!" press="{!c.packItem}"/>  
</aura:component>


------ campingListItemController ------
({
    packItem : function(component, event, helper) {
        component.set("v.item.Packed__c",true);
        event.getSource().set("v.disabled",true);
    }
})
Hi Can someone explain how to set the lookup (from account name value) to conatct name when creating contact from anonymous window.

List<contact> contactToSave = new List<contact> ();
Contact cont = new Contact();
Account acctRef = new Account(name='University of Arizona'); // need to set this name to contact which I'm creating below. Account name already available on org 
cont.FirstName='Test1';
cont.LastName='Test2';
cont.Department='Finance';
cont.name=actRef;
contactToSave.add(cont);
insert contactToSave;

please explain how this works...
How to update a field automatically(OPA_Lifetime_Product_Forecast__c) recalculate when a primary is changed. meaning if values from product_is_primary__c  is changed value, it will recalculate the OPA_Lifetime_Product_Forecast__c
public with sharing class AgreementTriggerHandler{
    
    public static void onAfterInsert(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }
    
    public static void onAfterUpdate(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }
    
    public static void onAfterDelete(List<AP_Agreement__c> agrList) {
        isUpdatePanel(agrList);
    }

     public static void onBeforeInsert(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }



    public static void isUpdatePanel (List<AP_Agreement__c> agrList){
        Set<Id> ProjIDs = new Set<Id>();
        List<Project__c> PaneltoUpdate = new List<Project__c>();
        Double pfSum = 0;

         //Get the Project ID
        for(AP_Agreement__c pfs : agrList){
            ProjIDs.add(pfs.Panel__c);
        }
        
        //Checks if there are Projects on the Agreement
        if(!ProjIDs.isEmpty()){
        
            //Loop through Agreement and use the Product Forecast Condition(OPA_Lifetime_Product_Forecast__c) to filter the Primary and Seconadry Series and Panel/Project ID
            for(AP_Agreement__c  pf: [SELECT OPA_Lifetime_Product_Forecast__c, Panel__c  FROM AP_Agreement__c WHERE Panel__c =: ProjIDs]){
                
                //Check if OPA_Lifetime_Product_Forecast__c has a value as MPA records will not have any value here
                if(pf.OPA_Lifetime_Product_Forecast__c!=null){
                pfSum += pf.OPA_Lifetime_Product_Forecast__c;
                }
            }
        
        }


        
         //Update the Project with the summed up quantity from Agreements using the Product Forecast Condtion
        for(Project__c prj: [Select Id from Project__c where Id =: ProjIDs]){
            prj.Allocated_OEM_Project_Forecast__c = pfSum;
            PaneltoUpdate.add(prj);
        }

        //Update the Project
         if(!PaneltoUpdate.isEmpty()){
            update PaneltoUpdate;
        }
    }
}

 

I have created an action in process builder to Create a new contract once the Opportunity stage = Closed Won.

This is occurs when a record is created or edited, and I have unchecked the checkbox asking whether to Allow process to evaluate a record multiple times.

So the criteria to be met is Opportunity Stage = Closed Won

The first action I have written is to create a new contract, with the fields as follows:

 

User-added image
However, similar to how there is a lookup field on Contract Stage to link back to Account and (in this case, I have created another custom lookup field to link to Opportunity) Opportunity as well, I would like to have a lookup field on Opportunity stage to link to Accounts.

This Contract field on Opportunity object is just the mirror image of the Opportunity lookup on Contract object.

What I want to do is be able to, upon marking the Opportunity as Closed Won,

1) Create a new contract (all good this works already)

2) Update the previously empty Contract lookup field on Opportunity object with the Contract ID of the newly created contract.

I am having trouble completing step 2. 

I tried adding another action to Update the contract lookup field on Opportunity object 

User-added image
But upon marking an opportunity as closed won, I get the following error

 

An error occurred at element myRule_1_A3 (FlowRecordUpdate).
The flow failed to access the value for myVariable_current.Contract.Id because it hasn't been set or assigned.

Any ideas on how to automate this? Ideally, I would want users to be able to access the corresponding Contract immediately upon marking the Opportunity as Closed Won, as opposed to having to go to Contract object and searching for that contract.

I swear I'm somewhere close to the answer as I can successfully import the ID of the opportunity when creating a new contract (see first photo I inserted above)

Thanks!
We just wanted to know whether the syntax to fetch the queue owner 'Owner:Queue.QueueName='Duplicate Leads'' (in formula field)still works fine in salesforce becuase it seems like this is not working in our functionality.
OK, I open a Contact record...Scroll dowm and see this: 
User-added image

I want to make a new Course connection:
User-added image
Is it possible to customize the Program Enrollment ID field ; So that when i click on the magnifying glass only Programs the Contact is already linked to will show up there not ALL Program Enrollments in our ORG??

would this be a validation Rule?

Please help ASAP!! 
I have an encrypted field NRIC_NEW__C, after saving the record, I would like to copy the content of this field into another text field, how can I do this
  • December 14, 2016
  • Like
  • 0
I created 2 Custom Tab and Custom Fields in these two custom tabs. I created master detail relationship with accounts in these two custom tabs. I want to create new formula field in accounts to use these custom fields from custom tabs. I'm not able to populate in formula field. Can you help me

Trying to create a "New Event" button, when clicked, will automatically set the Event duration to 30 mins. I don't get a syntax error in my code but when I test it, the Event duration remains at the default 1 hour.

 

Here is my code.

 

/00U/e?title=Outside Sales Call&who_id={!Lead.Id}{!Contact.Id}&what_id={!Opportunity.Id}{!Account.Id}
{!Event.DurationInMinutes = 30}
&followup=1&tsk5=Outside Sales Call&retURL=%2F{!Lead.Id}{!Contact.Id}{!Opportunity.Id}{!Account.Id}

 

Thanks!

  • December 15, 2010
  • Like
  • 1
I have strange behavior with a APEX Batch job

I run this job with batch size of 1 and it puts a job of 1000 Batches to process. However after it run for some time I have seen following behavior

1. I see the batches are processing fine say like it has processed 300. All of a sudden I see all jobs completed and it says it processed 800 batches (not sure where the other 200 batches go). Looking at the data looks like it did not process everything that should have been processed.

2. Some times I see it is processing fine say at 400th batch and all of a sudden it would say completed with all 1000 batch completed. Looking at the data looks like it did not process everything that should have been processed.

Any ideas why this could happen ?

The batch class internally call another class method in the execute method. This method has some what more logic in it. However this method when run individually does not have any issues (No Heap size issue or other performance issues).  Not sure because of the call method the complete Batch job is abruptly aborted. (with specifying any error)

I have opened a case with Salesforce but want to see if any one else have seen this issue.   
 

I have created an action in process builder to Create a new contract once the Opportunity stage = Closed Won.

This is occurs when a record is created or edited, and I have unchecked the checkbox asking whether to Allow process to evaluate a record multiple times.

So the criteria to be met is Opportunity Stage = Closed Won

The first action I have written is to create a new contract, with the fields as follows:

 

User-added image
However, similar to how there is a lookup field on Contract Stage to link back to Account and (in this case, I have created another custom lookup field to link to Opportunity) Opportunity as well, I would like to have a lookup field on Opportunity stage to link to Accounts.

This Contract field on Opportunity object is just the mirror image of the Opportunity lookup on Contract object.

What I want to do is be able to, upon marking the Opportunity as Closed Won,

1) Create a new contract (all good this works already)

2) Update the previously empty Contract lookup field on Opportunity object with the Contract ID of the newly created contract.

I am having trouble completing step 2. 

I tried adding another action to Update the contract lookup field on Opportunity object 

User-added image
But upon marking an opportunity as closed won, I get the following error

 

An error occurred at element myRule_1_A3 (FlowRecordUpdate).
The flow failed to access the value for myVariable_current.Contract.Id because it hasn't been set or assigned.

Any ideas on how to automate this? Ideally, I would want users to be able to access the corresponding Contract immediately upon marking the Opportunity as Closed Won, as opposed to having to go to Contract object and searching for that contract.

I swear I'm somewhere close to the answer as I can successfully import the ID of the opportunity when creating a new contract (see first photo I inserted above)

Thanks!
Hi

I have a field where the lookup filter always delivers one record. Is it possible to build a trigger that populates this in the back end and prevents the user having to have to click on this. If so how would it look?

My Parent object is called "terms and conditions" and has fields for ID, Content, Retirement date and Active date. the filter on the lookup at the minute it shows the record that has no retirement date and the active date is after the current date.

The child object has a lookup field on that calles DOUM_TCs. 

Any help as I have never heard of apex or triggers before starting this development. Cheers

Trying to create a "New Event" button, when clicked, will automatically set the Event duration to 30 mins. I don't get a syntax error in my code but when I test it, the Event duration remains at the default 1 hour.

 

Here is my code.

 

/00U/e?title=Outside Sales Call&who_id={!Lead.Id}{!Contact.Id}&what_id={!Opportunity.Id}{!Account.Id}
{!Event.DurationInMinutes = 30}
&followup=1&tsk5=Outside Sales Call&retURL=%2F{!Lead.Id}{!Contact.Id}{!Opportunity.Id}{!Account.Id}

 

Thanks!

  • December 15, 2010
  • Like
  • 1