• AMIT KAMBOJ
  • NEWBIE
  • 305 Points
  • Member since 2014
  • Developer

  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 49
    Replies
Hi,
I'm trying to update a Text Field (Address__c) in a Custom Object (Qualification__c) with BillingAddress in its lookup Account Field (Company__c). For this I have created a formula field (Billing_Address__c) in Account object which pulls the data from BillingAddress.

Then, I have created a workflow rule on Qualification__c object.
Rule Criteria = " Qualification: Address EQUALS null ", and
Evaluation Criteria = "Evaluate the rule when a record is created, and any time it’s edited to subsequently meet criteria".
A Field Update Action associated with the Rule is as below:
Field to Update = Qualification: Address
Field Data type = Text
Formula Value = " Company__r.Billing_Address__c ".

For testing, I have created a Qualification record with Address__c leaving empty, but the field is not being updated with Billing_Address__c as stated. I request you to help me with this.
Hi,

I'm just starting to really get a handle on writing code for bulk triggers, did I do this right?  I want to update a field on my opportunity every time a task ray project gets archieved

Thanks,
 
trigger TaskRayProject on TASKRAY__Project__c (before update) {
    set<id> projSet = new set<id>();
    List<Opportunity> oppList = new List<Opportunity>();
    
     // get the taskray projects that have been have just been archieved and add to set 
    for (TASKRAY__Project__c proj :Trigger.new) {
        if(proj.TASKRAY__Status__c == true) {
            
            TASKRAY__Project__c oldProj = trigger.oldmap.get(proj.Id);
            if (oldProj.TASKRAY__Status__c != true) {
                if(proj.Opportunity__c !=NULL) {
                	projSet.add(proj.Opportunity__c);
                }
            }
        }
    }
	
    // query the opportunty for all items in the set
	oppList = [SELECT Id, Name, Task_Ray_Project_Completed__c FROM Opportunity WHERE ID IN :projSet ];
    
    // change field to true
    for(Opportunity opp :oppList) {
        opp.Task_Ray_Project_Completed__c = true;
    }
    
    
     update(oppList);
    
}



 
Hi guys, 

I have a custom object called User_Support__c in SFDC. I have an "Intake" record type that is the default for all users. Depending on there answer to a single field, i would like a trigger to change the record type. I have a formula field called "Record_Type_Conversion_Controller__c" that will determine the name of the record type i would like the record to be changed to. 

I get the following error when I try it : ConvertRecordType: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.ConvertRecordType: line 8, column 1 


Trigger ConvertRecordType on User_Support__c (after insert) {
User_Support__c u= Trigger.new[0];{
   

         //hold current User Support Fields
         u = [select Id, Record_Type_Conversion_Controller__c,Issue_Type__c, Name FROM User_Support__c WHERE Id=:u.id];
         
        RecordType RecType = [Select Id From RecordType Where SobjectType = 'Opportunity' and DeveloperName=:u.Record_Type_Conversion_Controller__c];
         

         If(u.Issue_Type__c =='License Request')
         u.name='License Request';
         If(u.Issue_Type__c !='License Request')
         u.name='';
         
        
         u.RecordTypeId=RecType.Id;
         
         update u;
         
         }
         }


If anyone could help it woudl be greatly appreciated!!!!
We had a developer write an apex plugin to use in a flow but he didn't write any test for code and now my overall code coverage is less than 75% so I can't deploy anything via a changeset.  Below is the code.  Any help is appreciated.

global class mLSendEmail implements Process.Plugin {
    
    global Process.PluginResult invoke(Process.PluginRequest request) { 
        
        // Get the subject of the Chatter post from the flowgj
        //String emailS = (String) request.inputParameters.get('emailListString');
        String campaignId = (String) request.inputParameters.get('campaignId');
        String tempId = (String) request.inputParameters.get('emailTempId');
        //system.debug(idS);
        String userIdVar = UserInfo.getUserId();
        //List<String> emailList = emailS.split(', ');
        
        User userObject = [SELECT Name, Email
                           FROM User
                           WHERE Id = :userIdVar.left(15)
                           LIMIT 1]; //(String) request.inputParameters.get('userName');
        
        List<CampaignMember> test = [SELECT ContactId, CampaignId
                                     FROM CampaignMember
                                     WHERE CampaignId = :campaignId];
        
        List<Contact> contacts = [SELECT Id, Name, Email 
                                  FROM Contact 
                                  WHERE Id IN (SELECT ContactId 
                                               FROM CampaignMember 
                                               WHERE CampaignId = :campaignId AND ContactId != null)
                                  ];
        
        List<Lead> leads = [SELECT Id, Name, Email 
                            FROM Lead
                            WHERE Id IN (SELECT LeadId 
                                         FROM CampaignMember 
                                         WHERE CampaignId = :campaignId AND LeadId != null)
                            ];
        system.debug('EMAIL TEMPLATE ID: ' + tempId);
        system.debug('VALUE OF CONTACTS: ' + contacts);
        List<Messaging.SingleEmailMessage> mails = 
  new List<Messaging.SingleEmailMessage>();
        if (!contacts.isEmpty()) {
            system.debug('mLSendEmail.cls - contacts != null');
            for (integer i = 0; i <= contacts.size()-1; i++) {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setTemplateId(tempId);
                mail.setReplyTo(userObject.Email);
                mail.setSenderDisplayName(userObject.Name);
                mail.setTargetObjectId(contacts.get(i).Id);
                mails.add(mail);
           }
        } else if (!leads.isEmpty()) {
            system.debug('mLSendEmail.cls - leads != null');
            for (integer i = 0; i <= leads.size()-1; i++) {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setTemplateId(tempId);
                mail.setReplyTo(userObject.Email);
                mail.setSenderDisplayName(userObject.Name);
                mail.setTargetObjectId(leads.get(i).Id);
                mails.add(mail);
            }
        } else {
            system.debug('mLSendEmail.cls - else');
        }
  Messaging.sendEmail(mails);
        
        
        
        
        // return to Flow
        Map<String,Object> result = new Map<String,Object>(); 
        return new Process.PluginResult(result); 
        
    } 
    
    global Process.PluginDescribeResult describe() { 
        Process.PluginDescribeResult result = new Process.PluginDescribeResult(); 
        result.Name = 'Marketing Email Plugin';
        result.Tag = 'ML Email';
        result.inputParameters = new 
           List<Process.PluginDescribeResult.InputParameter>{
               new Process.PluginDescribeResult.InputParameter('emailTempId',
               Process.PluginDescribeResult.ParameterType.STRING, true),
               new Process.PluginDescribeResult.InputParameter('campaignId',
               Process.PluginDescribeResult.ParameterType.STRING, true)
            };
        result.outputParameters = new 
           List<Process.PluginDescribeResult.OutputParameter>{ }; 
        return result; 
    }
}
  • March 26, 2015
  • Like
  • 0
Im am trying to create a trigger that will update a Opportunity Lookup field to the contact to pull in the primary contact role if there is one on the Opportunity record. Once this is updated, then I would like to setup a workflow rule when upon Closed Won, an email will be sent to that Primary contact role. Does this make sense? Im struggling ....
HI,
 I am new to salesforce, Can any one help me to fix this issue. I am trying to write test class for updating the record using standard controller, and extension .I am getting exception in objAccount , which throws System.QueryException: List has no rows for assignment to SObject.

      I can get the results in query editor by executing 'select name, owner.name, site ,id, Industry from account where id = '0019000001FYa8GAAT' ' this query ,
       
Account objAccount = [select name, owner.name, site ,id, Industry from account where id = '0019000001FYa8GAAT' ];
ApexPages.StandardController sc = new ApexPages.standardController(objAccount);
myPageCon = new AccountEditPageCon(sc);

Please help me to fix this issue. Thanks in advance
 
  • March 09, 2015
  • Like
  • 0
Hi,

I am getting code coverage for first two lines(9%) of my trigger which checks the older and newer records.
Can you please help me increasing the code coverage to more than 75%.
Below is my code :
 
-----------------------------------------------------------------
Trigger
-----------------------------------------------------------------
trigger UserAvailabilityCheck on Case (before update) { 

if(stopRecursion.stopRecursiveTriggerRun ) {
    return;
}

stopRecursion.stopRecursiveTriggerRun = true;

Boolean oooFlag;
Set<ID> ids = Trigger.newMap.keyset();
ID oId;

List<Case> caseList = [Select Id, Status, OwnerId from Case where Id in : ids];

for(Case c : caseList) {
oId = c.OwnerId;
}

for (Case c : Trigger.New) {
    Case oldCase = Trigger.oldMap.get(c.Id);

    Boolean oldStatusClosed = oldCase.Status.equals('Closed');
    Boolean oldStatusACR = oldCase.Status.equals('Awaiting Customer Response');
    Boolean oldStatusResolved = oldCase.Status.equals('Resolved');
    Boolean newStatusInProgress = c.Status.equals('In Progress');

    if ((oldStatusClosed && newStatusInProgress)||(oldStatusACR && newStatusInProgress)||(oldStatusResolved && newStatusInProgress)) {

      Map<Id, boolean> onlineMap = n2de.DistributionEngineGlobal.getAvailabilityByUser(oId);

      for (Id id : onlineMap.keySet()) {  
      oooFlag = onlineMap.get(id);
      System.debug('===oooFlag ' + oooFlag);
      break;
      }
      if(!oooFlag){
      c.OwnerId = Label.Case_ReDistributeCasesId;
      }

    }
  }

}
-----------------------------------------------------------------
Test Class 
-----------------------------------------------------------------

@isTest
private class UserAvailabilityCheckTest {

    private  static  RecordType supportCaseRecordType  = [SELECT Name, Id FROM RecordType 
                                                          WHERE Name ='Support Case' 
                                                          AND SObjectType = 'Case'];
    static testMethod void testUserAvailabilityCheck() {
        
        User testUser = new User();
        testUser.Username= 'm98704nn@companyn.com';
        testUser.Email = 'testuser198704nn@companyn.com';
        testUser.Lastname = 'user4';
        testUser.Firstname = 'test4';
        testUser.Alias = 'test4';
        testUser.CommunityNickname = '123464';
        testUser.UserRole = [ select id from userrole where id ='00EG00000015wJk' ];
        testUser.ProfileId = '00eG0000000fz9y';
        
        //testUser.CurrencyIsoCode = 'USD';
        testUser.TimeZoneSidKey = 'GMT';
        testUser.LocaleSidKey = 'en_US';
        testUser.EmailEncodingKey = 'ISO-8859-1';
        testUser.LanguageLocaleKey = 'en_US';
        testUser.UserPermissionsMobileUser = false;

        insert testUser;
        
        User testUser2 = new User();
        testUser2.Username= 'm987041nn@companyn.com';
        testUser2.Email = 'testuser1987041nn@companyn.com';
        testUser2.Lastname = 'user41';
        testUser2.Firstname = 'test41';
        testUser2.Alias = 'test4';
        testUser2.CommunityNickname = '1234641';
        testUser2.UserRole = [ select id from userrole where id ='00EG00000015wJk' ];
        testUser2.ProfileId = '00eG0000000fz9y';
        
        //testUser.CurrencyIsoCode = 'USD';
        testUser2.TimeZoneSidKey = 'GMT';
        testUser2.LocaleSidKey = 'en_US';
        testUser2.EmailEncodingKey = 'ISO-8859-1';
        testUser2.LanguageLocaleKey = 'en_US';
        testUser2.UserPermissionsMobileUser = false;

        insert testUser2;

        Account   testAccount = new Account();
        testAccount.Name  = 'Test Account';
    
        insert testAccount;
    
        Contact   testContact = new Contact();
        testContact.LastName  = 'Test Name';
        
        Test.startTest();

        insert testContact;

        Product2  testProduct = new Product2();
        testProduct.Name                  = 'Test Product Name';
        testProduct.Product_Category__c   = 'Category';
        testProduct.Product_Family__c     = 'Family';
        testProduct.Product_Sub_family__c = 'Sub-Family';    

        insert testProduct;
    
        Case  testCase  = new Case();
        testCase.RecordTypeId = supportCaseRecordType.Id;
        testCase.Summary__c   = 'Summary';
        testCase.Description  = 'Description';
        testCase.Origin       = 'Email';
        testCase.Status       = 'Awaiting Customer Response';
        testCase.I_Agree__c   = true;
        testCase.ContactId    = testContact.Id;
        testCase.ProductId    = testProduct.Id;
        testCase.OwnerId      = testUser.Id;        

        insert testCase;

        testCase.OwnerId = testUser2.Id;  
        update testCase; 

        Test.stopTest();  

        Case c = [SELECT Status,OwnerID FROM Case WHERE Id = :testCase.Id];

        System.assertEquals( testUser2.Id, c.OwnerId );
            
    }
}
  • March 09, 2015
  • Like
  • 0
 
<apex:pageblocktable value="{!list}" var="item">
    <apex:column>RECORDID
      <apex:outputLink value="{!item.Name}">{!item.Name}</apex:outputLink>
    </apex:column>       
</apex:pageblocktable>
 
public with sharing class customClass{

public List<StandardClass> list{get;set;}

 public customClass(){
        
        list = [Select Name, RECORDID
                     From ProfileSkill];
        
        }
}

I want to have a link which will redirect user to record type.

I do not know, what paramenter i can use for  RECORDID
  • March 08, 2015
  • Like
  • 0
Hi,

I have created a visualforce page to replace the standard page of my detail object (in this case Client_Plan__c as master, and Client_Plan_Product__c as detail).  This seems to be working fine for creating a new record, or save and new for a record.  However, when I try to go into edit mode from the parent object I get the error

"SObject row was retrieved via SOQL without querying the requested field: Client_Plan_Product__c.Type__c "
Here is the URL that is getting passed in on the failed edit
"https://c.cs13.visual.force.com/apex/ClientProductPage?id=a0eW0000001t54N&retURL=%2Fa0QW0000002ILIY&sfdc.override=1"


I'm not quite sure what I'm doing wrong

thanks,
public class ClientProductClass {
    
    public Client_Plan_Product__C prod {get; set;}
    string prodId;
    string clientId;
    String retUrl;
    
    
    public ClientProductClass(ApexPages.StandardController stdcon) {
        prodId = ApexPages.currentPage().getParameters().get('id');  // access the product id from the URL
        clientId = ApexPages.currentPage().getParameters().get('CF00N50000003LQm5_lkid');  // access the product id from the URL
		
        
        if (prodId != null && prodId !='') {
            System.debug('id = ' +prodId);
            prod=(Client_Plan_Product__c)stdcon.getRecord();
        } else { 
            prod = new Client_Plan_Product__c(); 
            prod.Client_Plan__C = clientId;
               
               }
          
    }
    
    public PageReference save()
     {

       upsert prod; 
       // returns the page to the parent object after savings  
       Client_Plan__c plan = new Client_Plan__c(id=prod.Client_Plan__c);
       PageReference clientPage = new ApexPages.StandardController(plan).view();
       clientPage.setRedirect(true);
       return clientPage;   
     }
     
     public PageReference Cancel()
     {
      return null;
     }

    public PageReference saveNew() {

       upsert prod; 
            prod = new Client_Plan_Product__c(); 
            prod.Client_Plan__C = clientId;
       PageReference clientPage = new ApexPages.StandardController(prod).view();
       clientPage.setRedirect(true);
       return clientPage;  
    }
    
    
}
 
public class ClientProductClass {
    
    public Client_Plan_Product__C prod {get; set;}
    string prodId;
    string clientId;
    String retUrl;
    
    
    public ClientProductClass(ApexPages.StandardController stdcon) {
        prodId = ApexPages.currentPage().getParameters().get('id');  // access the product id from the URL
        clientId = ApexPages.currentPage().getParameters().get('CF00N50000003LQm5_lkid');  // access the product id from the URL
		
        
        if (prodId != null && prodId !='') {
            System.debug('id = ' +prodId);
            prod=(Client_Plan_Product__c)stdcon.getRecord();
        } else { 
            prod = new Client_Plan_Product__c(); 
            prod.Client_Plan__C = clientId;
               
               }
          
    }
    
    public PageReference save()
     {

       upsert prod; 
       // returns the page to the parent object after savings  
       Client_Plan__c plan = new Client_Plan__c(id=prod.Client_Plan__c);
       PageReference clientPage = new ApexPages.StandardController(plan).view();
       clientPage.setRedirect(true);
       return clientPage;   
     }
     
     public PageReference Cancel()
     {
      return null;
     }

    public PageReference saveNew() {

       upsert prod; 
            prod = new Client_Plan_Product__c(); 
            prod.Client_Plan__C = clientId;
       PageReference clientPage = new ApexPages.StandardController(prod).view();
       clientPage.setRedirect(true);
       return clientPage;  
    }
    
    
}

 
I am trying to create a button that will update the stage of an opportunity to a specific stage, and the owner to whom ever clicks the button, additionally I want the update to happen only if a specific profile clicks the button (this may be best accomplished through a validation rule though so its not in my code) 

This is what I have written just trying to get the stage to change.... I get this error: "Unexpected Token Illegal"

***Note*** I am not a developer but trying to learn so my knoweledge is mimited 


{!requireScript("/soap/ajax/10.0/connection.js")};
sforce.connection.session = "{!$Api.Session_ID}";

function updateOpportunity( )
{
    try
    {

 
var opp = new sforce.SObject(“Opportunity”); 
opp.id =”{!Opportunity.Id}”;                  
opp.StageName = "AE Qualified”;               

var saveResult = sforce.connection.update([Opportunity]); 


if (result[0].getBoolean("success") == false ) { 
alert(result[0].errors.message); 
return; 

window.top.location.href=window.top.location.href; 

catch (e) { 
alert(e); 
}    


updateOpportunity();
Hi,
I'm trying to update a Text Field (Address__c) in a Custom Object (Qualification__c) with BillingAddress in its lookup Account Field (Company__c). For this I have created a formula field (Billing_Address__c) in Account object which pulls the data from BillingAddress.

Then, I have created a workflow rule on Qualification__c object.
Rule Criteria = " Qualification: Address EQUALS null ", and
Evaluation Criteria = "Evaluate the rule when a record is created, and any time it’s edited to subsequently meet criteria".
A Field Update Action associated with the Rule is as below:
Field to Update = Qualification: Address
Field Data type = Text
Formula Value = " Company__r.Billing_Address__c ".

For testing, I have created a Qualification record with Address__c leaving empty, but the field is not being updated with Billing_Address__c as stated. I request you to help me with this.
So I have a Visualforce page called Activities that is showing on the accounts page which shows the activities linked to that account id. On Activites Visualforce page i have an edit button which links to another Visualforce page, but I can not figure out how to get the id from the 2nd Visualforce page.
Here is my Class:
 public PageReference EditPage()
    {
   
        string path='/apex/pg_Add_Work_Activity?acctid='+ acct.id + '&id=' + workAccountId;
        PageReference pageRef= new PageReference(path);
        pageRef.setredirect(true);
        return pageRef;
        }

And here is the Visualforce Page:(notice i have some attempts commented out):

<apex:column>
                <!--<apex:commandButton value="Edit" action="{!EditPage}"/>-->
                <apex:commandButton value="Edit" action="{!EditPage}">
                  <apex:param name="EditId" value="{!a.id}" assignto="{!workAccountId}"/></apex:commandButton>
               
             <!--<apex:commandButton action="{!URLFOR($Action.Work_Activity__c.EditPage,null,[retURL=$Page.pg_Add_Work_Activity+'?id='+'Id'], true)}" value="Edit" id="theButton"/>-->
            </apex:column>
 
Hello all,

I have a trigger that one of y'all helped me build (many thanks!). The trigger works perfectly to change the case status when a FeedItem is posted witha  Parent ID of a case where the feed body ends with "Case closed".
As noted, the trigger works fine in the Sandbox, however my Apex Class used for testing is failing due to the following error:
System.QueryException: List has no rows for assignment to SObject

The Apex Trigger is:
trigger UpdateCaseCloseStatus on FeedItem (after insert) {
    
    List<Case> listOfCases = new List<Case>();
    
    for (FeedItem fi : Trigger.new) {
        
        //--- This retrieves the case for which feed has been entered.
        Case c = [select id from Case where Id = :fi.ParentId];

        //--- Now we check if the feed ends with text 'Case Closed'. We are checking case insensitive text.
        if (fi.Body.endsWithIgnoreCase('Case Closed')) {
            c.Status = 'Complete';
        }
        listOfCases.add(c);
    }
    update listOfCases;
}

The Apex Class is:
@isTest
public class TestFeedPost    {
    static testMethod void insertNewFeedPost()     {
        
        FeedItem feedToCreate = new FeedItem();
        
        feedToCreate.ParentId    =       '500q0000001Pavd';
        feedToCreate.Body        =       'Blah blah blah close case';
        feedToCreate.Type        =        'TextPost';
        
        insert feedToCreate;
        }
        }


The full error message is:
<span unselectable="on" "="" style="display: block; padding: 3px 4px; overflow: hidden; margin-left: 0px; color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: normal; white-space: nowrap; background-color: rgb(218, 240, 249);">
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateCaseCloseStatus: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.UpdateCaseCloseStatus: line 8, column 1: []



Any assistance would be greatly appreciated.

Thanks!
Hi,

I have written a fucntionality to convert lead to case. The only problem is I have a field on Lead as Web-to-Lead Notes which is Text Area long and that is being popualated on Case Subject on Conversion. It gives error if the length is big. So I need to truncate the length of Lead to Web Notes field to 50 to properly fit in the Case Subject. Please help. Here is my code VFP and Apex:

Visualforce Page:
<apex:page standardController="Lead" extensions="CaseConverter">
    <apex:form >
        <apex:pageBlock title="Convert information to a new Case.">
            <apex:pageBlockButtons >
                <apex:commandbutton action="{!createCase}" value="Finish"/>
                <apex:commandbutton action="{!returnToLead}" value="Previous"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Lead content Section">            
                <tr><th class="labelCol vfLabelColTextWrap " scope="row">Lead Record Type</th><td class="dataCol "><span id="j_id0:j_id1:j_id2:j_id6:nameId">{!recordTypeName}</span></td></tr>
                <apex:outputText value="{!lead.Web_To_Lead_Notes__c} " rendered="true"/>
                <apex:outputField value="{!lead.Name}" id="nameId"/>
                <apex:outputField value="{!lead.Company}" id="companyId"/>
                <apex:outputField value="{!lead.Phone}" id="phoneid"/>
                <apex:outputField value="{!lead.City}" id="cityId"/>
                <apex:outputField value="{!lead.Street}" id="streetId"/>
                <apex:outputField value="{!lead.Country}" id="countryid"/>
                <apex:outputField value="{!lead.Email}" id="emailid"/>
                <apex:outputField value="{!lead.PostalCode}" id="postalId"/>
                <apex:outputField value="{!lead.MobilePhone}" id="mobileId"/>
                <apex:outputField value="{!lead.Website}" id="websiteId"/>
                <apex:outputField value="{!lead.Description}" id="descriptionId"/>
                <apex:outputField value="{!lead.Industry}" id="industryId"/>                           
            </apex:pageBlockSection>
            
         
   Apex Class:
public with sharing class CaseConverter {
    public Lead curLead{set;get;}
    private final String name;
    private final String company;
    private final String phone;
    private final String city;
    private final String street;
    private final String country;
    private final String email;
    private final String postal;
    private final String mobile;
    private final String website;
    private final String description;
    private final String industry;
    private final String leadId;
    public String Web_To_Lead_Notes_Case;
    public string accountOwnerId;
    
    //getter,setter for the selected list values
    public String statusCaseSelected{get;set;}
    public String originSelected{get;set;}
    
    //getter,setter for the input fields
    public String subjectInput{get;set;}
    
    //getter,setter for the input fields
    public String recordTypeName{get;set;}
    
    //getter setter for the checkboxes
    public Boolean createAccount{get;set;}
    
    /*get the select options from the case system schema for the status field
    * Input: nothing
    * Output: List of the select options from case status
    */
    public List<Selectoption> getStatusCaseItems(){
        List<Selectoption> statusValues = new List<Selectoption>();
        Schema.Describefieldresult systemCaseStatus = Case.Status.getDescribe();
        for(Schema.Picklistentry plEntry : systemCaseStatus.getPicklistValues()){
            statusValues.add(
                new Selectoption(
                    plEntry.getValue(),
                    plEntry.getLabel()
                )
            );
        }
        return statusValues;
    }
    
    /*get the select options from the case system schema for the origin field
    * Input: nothing
    * Output: List of the select options from case origin
    */
    public List<Selectoption> getOriginItems(){
        List<Selectoption> originValues = new List<Selectoption>();
                 originValues.add(
                       new Selectoption(
                                'Customer Service','Customer Service'
                )
           );
                
        
        return originValues;
    }

    //constructor, this page will be called from the LeadToCase Page
    public CaseConverter(ApexPages.StandardController controller) {
        this.curLead= (Lead)controller.getRecord();
        List<QueueSobject> lstQueues = [SELECT Id,queue.Name, QueueId FROM QueueSobject WHERE SobjectType = 'Case'and queue.Name = 'Customer Service Cases'];
        curLead.OwnerId = lstQueues[0].QueueId;
        
        List<recordType> recordTypeList = [select Name from recordType where Id = :curlead.recordTypeId];
        if(recordTypeList.Size() > 0 ) {
            recordTypeName = recordTypeList[0].Name;
        } 
        this.name = curLead.FirstName + ' ' + curLead.LastName;
        this.company = curLead.Company;
        this.phone = curLead.Phone;
        this.city = curLead.City;
        this.street = curLead.Street;
        this.country = curLead.Country;
        this.email = curLead.Email;
        this.postal = curLead.PostalCode;
        this.mobile = curLead.MobilePhone;
        this.website = curLead.Website;
        this.description = curLead.Description;
        this.industry = curLead.Industry;
        this.leadId = curLead.Id; 
        this.Web_To_Lead_Notes_Case = curLead.Web_To_Lead_Notes__c;
        subjectInput = curLead.Web_To_Lead_Notes__c; 
       
    }
    
    
    
  • April 03, 2015
  • Like
  • 0
Hi,

I'm just starting to really get a handle on writing code for bulk triggers, did I do this right?  I want to update a field on my opportunity every time a task ray project gets archieved

Thanks,
 
trigger TaskRayProject on TASKRAY__Project__c (before update) {
    set<id> projSet = new set<id>();
    List<Opportunity> oppList = new List<Opportunity>();
    
     // get the taskray projects that have been have just been archieved and add to set 
    for (TASKRAY__Project__c proj :Trigger.new) {
        if(proj.TASKRAY__Status__c == true) {
            
            TASKRAY__Project__c oldProj = trigger.oldmap.get(proj.Id);
            if (oldProj.TASKRAY__Status__c != true) {
                if(proj.Opportunity__c !=NULL) {
                	projSet.add(proj.Opportunity__c);
                }
            }
        }
    }
	
    // query the opportunty for all items in the set
	oppList = [SELECT Id, Name, Task_Ray_Project_Completed__c FROM Opportunity WHERE ID IN :projSet ];
    
    // change field to true
    for(Opportunity opp :oppList) {
        opp.Task_Ray_Project_Completed__c = true;
    }
    
    
     update(oppList);
    
}



 
I'm going through the Site.com Workbook, trying to add a datatable to a site.com site, but the only data available from a custom object are the standard fields.  I have edited the guest user profile via the site configuration link in the Overview tab of the site to enable read access to the custom object.  I can not find where to set field-level security on the custom object because the guest user profile is not included in the list of available profiles for the objects FLS.
Hi guys, 

I have a custom object called User_Support__c in SFDC. I have an "Intake" record type that is the default for all users. Depending on there answer to a single field, i would like a trigger to change the record type. I have a formula field called "Record_Type_Conversion_Controller__c" that will determine the name of the record type i would like the record to be changed to. 

I get the following error when I try it : ConvertRecordType: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.ConvertRecordType: line 8, column 1 


Trigger ConvertRecordType on User_Support__c (after insert) {
User_Support__c u= Trigger.new[0];{
   

         //hold current User Support Fields
         u = [select Id, Record_Type_Conversion_Controller__c,Issue_Type__c, Name FROM User_Support__c WHERE Id=:u.id];
         
        RecordType RecType = [Select Id From RecordType Where SobjectType = 'Opportunity' and DeveloperName=:u.Record_Type_Conversion_Controller__c];
         

         If(u.Issue_Type__c =='License Request')
         u.name='License Request';
         If(u.Issue_Type__c !='License Request')
         u.name='';
         
        
         u.RecordTypeId=RecType.Id;
         
         update u;
         
         }
         }


If anyone could help it woudl be greatly appreciated!!!!
public PageReference report(){ 
    	PageReference np = null;
    	
        starts = startDate.format(); //formats date as MM/DD/YYYY 
        ends = endDate.format();
        
        String value = getClassisObject().get(0).getValue();
        
        if(reportObj.equals('church')){
            String[] splitter = churchObj.split(':');
            churchReport(year, splitter[0].trim(), startDate,  endDate);
            
            np = new PageReference('/apex/crcna_MinistryShare_ChurchReport');
        }
        
        if(reportObj.equals('full')){
            List<Account> lstClassis = ClassisList(classisObj, value, reportObj);
            List<Account> lstChurches = ChurchList(lstClassis);
            if(classisObj <> value){  
                lstSubtotals = fullDetail(countryObj, lstChurches, year, startDate, endDate);

            np = new PageReference('/apex/crcna_MinistryShare_ClassisReport');

            }
       }
np.setRedirect(true);
return np;
}
Hi all,

can anyone help with a example of test code so i can test the following batch code please?
 
global class BulkRecordDelete implements Database.Batchable<sObject> {

    
    global string obj;
    private string query = 'SELECT Id FROM ';

    global database.querylocator start(Database.BatchableContext BC) {
        query = query + obj;
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<sObject> ob = new List<sObject>();

        for(sObject s : scope) {
            ob.add(s);
        }
        delete ob;
    }
    
    global void finish(Database.BatchableContext BC) {
        
		if (ApplicationClass.BatchEmailsEnabled) {
	        Id userId = UserInfo.getUserId();
	        String notify = [select Email from User where Id = :userId].Email;
	        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	
	        mail.setToAddresses(new String[] {notify});
	        mail.setReplyTo('batch@acme.com');
	        mail.setSenderDisplayName('Batch Processing');
	        mail.setSubject('Batch Process Completed');
	        mail.setPlainTextBody('Bulk ' + obj + ' delete has completed');
	
	        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
		}
    }
}
Thanks...
 
I'm trying to create asimple validation rule such that when an user is trying ot convert lead and enters "System" in the the "Record Owner" file, it should display error. Formula I'm using is  - >  Owner:User.LastName='System'
System is an integration user and does not have first name in the user profile.
1. I'm not sure why the formula is not working . Joshn Smith is valid user .
2. Why does the error keeps displaying below the "convert" field when I mentioned in the validation rule to display the erorr next to lead owner field. (screenshot below)

User-added image

Thanks
  • March 26, 2015
  • Like
  • 0
We had a developer write an apex plugin to use in a flow but he didn't write any test for code and now my overall code coverage is less than 75% so I can't deploy anything via a changeset.  Below is the code.  Any help is appreciated.

global class mLSendEmail implements Process.Plugin {
    
    global Process.PluginResult invoke(Process.PluginRequest request) { 
        
        // Get the subject of the Chatter post from the flowgj
        //String emailS = (String) request.inputParameters.get('emailListString');
        String campaignId = (String) request.inputParameters.get('campaignId');
        String tempId = (String) request.inputParameters.get('emailTempId');
        //system.debug(idS);
        String userIdVar = UserInfo.getUserId();
        //List<String> emailList = emailS.split(', ');
        
        User userObject = [SELECT Name, Email
                           FROM User
                           WHERE Id = :userIdVar.left(15)
                           LIMIT 1]; //(String) request.inputParameters.get('userName');
        
        List<CampaignMember> test = [SELECT ContactId, CampaignId
                                     FROM CampaignMember
                                     WHERE CampaignId = :campaignId];
        
        List<Contact> contacts = [SELECT Id, Name, Email 
                                  FROM Contact 
                                  WHERE Id IN (SELECT ContactId 
                                               FROM CampaignMember 
                                               WHERE CampaignId = :campaignId AND ContactId != null)
                                  ];
        
        List<Lead> leads = [SELECT Id, Name, Email 
                            FROM Lead
                            WHERE Id IN (SELECT LeadId 
                                         FROM CampaignMember 
                                         WHERE CampaignId = :campaignId AND LeadId != null)
                            ];
        system.debug('EMAIL TEMPLATE ID: ' + tempId);
        system.debug('VALUE OF CONTACTS: ' + contacts);
        List<Messaging.SingleEmailMessage> mails = 
  new List<Messaging.SingleEmailMessage>();
        if (!contacts.isEmpty()) {
            system.debug('mLSendEmail.cls - contacts != null');
            for (integer i = 0; i <= contacts.size()-1; i++) {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setTemplateId(tempId);
                mail.setReplyTo(userObject.Email);
                mail.setSenderDisplayName(userObject.Name);
                mail.setTargetObjectId(contacts.get(i).Id);
                mails.add(mail);
           }
        } else if (!leads.isEmpty()) {
            system.debug('mLSendEmail.cls - leads != null');
            for (integer i = 0; i <= leads.size()-1; i++) {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setTemplateId(tempId);
                mail.setReplyTo(userObject.Email);
                mail.setSenderDisplayName(userObject.Name);
                mail.setTargetObjectId(leads.get(i).Id);
                mails.add(mail);
            }
        } else {
            system.debug('mLSendEmail.cls - else');
        }
  Messaging.sendEmail(mails);
        
        
        
        
        // return to Flow
        Map<String,Object> result = new Map<String,Object>(); 
        return new Process.PluginResult(result); 
        
    } 
    
    global Process.PluginDescribeResult describe() { 
        Process.PluginDescribeResult result = new Process.PluginDescribeResult(); 
        result.Name = 'Marketing Email Plugin';
        result.Tag = 'ML Email';
        result.inputParameters = new 
           List<Process.PluginDescribeResult.InputParameter>{
               new Process.PluginDescribeResult.InputParameter('emailTempId',
               Process.PluginDescribeResult.ParameterType.STRING, true),
               new Process.PluginDescribeResult.InputParameter('campaignId',
               Process.PluginDescribeResult.ParameterType.STRING, true)
            };
        result.outputParameters = new 
           List<Process.PluginDescribeResult.OutputParameter>{ }; 
        return result; 
    }
}
  • March 26, 2015
  • Like
  • 0
I created a validation rule on for the Task Object. 
 
And( 
IsBlank(Text(Activity_Type_01__c )), 
RecordType.Name = "MCC Event", 
CONTAINS(Upper(Subject), "EMAIL") = False
)
The purpose is to ensure the Activity_Type_01__c field is populated every time a task is created other than if the Task Subject contains "Email", pretty striaght forward.  The problem is, it only works when the Task is editted, it does not fire when the Task is initially created.  

Any Thoughts?

Thanks, 

Todd B.

 
Hi Masters,

I am new to Salesforce.

At the moment, I am trying to create a trigger.
In the code, there is one picklist in my lead, and then there is another exact same picklist in my task. When ther is log a call or new task coming in. The task's picklist value will be default to same as the lead's picklist value automacally.

However, the trigger that I created is not running. Is there anything wrong with what I did? Or I just made it too complicated?

Here is my trigger,
Trigger PrePopulateTaskPromoCode on Task (before insert) {
        
    List<Lead> leadsToUpdate = new List<Lead>();
    List<Task> tasks = new List<Task>();
    
    for (Task t : trigger.new) {
        if (String.valueOf(t.WhoId).substring(0,3) == '00Q') {
            Lead leadToLookup = [Select promo_code__c FROM Lead WHERE Id = :t.WhoId];
            String promoCode = leadToLookup.Promo_Code__c;
            t.Promo_Code__c = promoCode;
            tasks.add(t);
  
        }
    }
   // update tasks;
}