• Alex Selwyn
  • NEWBIE
  • 245 Points
  • Member since 2015
  • Salesforce Architect
  • Infoglen

  • Chatter
    Feed
  • 8
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 41
    Replies
Hi,

Hoping someone can help to point us in the right direction, it seems that whatever we do, we are unable to get better than 26% code coverage with our Invocable Email Class calling an @future Method to send a single email with a visualforce attachement generated on the record. The Class works like a charm and does exactly what it is meant to do and we are even able to dummy an email being sent and assert the fact it was but it doesn't get close to covering the code. 

Any guidance would be greatfully appreciate, as even though we run at 95% coverage, i'm not prepared to push a class with only 26% even though it works fully.

Please help save my sanity? 
 
Invoked from process builder with 100% coverage

public class ProcessHandler {
    public class NPS{
        @InvocableVariable(required=true)
        public Id npsid;
        @InvocableVariable(required=true)
        public String mname;
        @InvocableVariable(required=true)
        public String oname;
        @InvocableVariable(required=true)
        public String subject;
        @InvocableVariable(required=true)
        public String client;
        @InvocableVariable(required=true)
        public String md;
        @InvocableVariable(required=true)
        public String body;
    }
    
    @InvocableMethod
   public static void invokeapexcallout(NPS[] nps) {
     Futureapexcallout.apexcallout(nps[0].mname, nps[0].oname, nps[0].npsid, nps[0].subject, nps[0].client,nps[0].md,nps[0].body);

    }
}
 
@Future Method with only 26% coverage

public class Futureapexcallout{

  @future(Callout=true)
  public static void apexcallout(string mname,string oname,Id NPSId, String subject, String client, string md, string body){
         
        
         
        pageReference pdfPage = Page.NPS_Survey;
        pdfPage.getParameters().put('id',NPSID);
        
        if(Test.isRunningTest()){
        blob b = blob.valueOf('Unit.Test');
        }else{
        blob b = pdfpage.getContentaspdf(); 

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('NPS.pdf');
        efa1.setBody(b);

        String addresses;
        email.setSubject(subject);
        email.setToAddresses(new List<String> {mname});
        email.setCCAddresses(new List<String> {oname});
        email.setPlainTextBody(body);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
}
 
Test Class, probably really badly written :)

@isTest
private class testProcessHandler
{
private static testMethod void testProcessHandler() {
    
    test.startTest();
    
        User u2 = new User(Alias = 'nUr32', Email='newuser@testorg32.com', 
        EmailEncodingKey='UTF-8', LastName='Testing12', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = '00e90000001yvFD' , 
        TimeZoneSidKey='America/Los_Angeles', UserName='newuser32@testorg.com',External_Use__c='SRK1132AA',Operating_Country__c='Global',Region__c='Global' ,Team__c='Client Services - Global');
        insert u2;
     
        Account a = new Account(Name = 'Test A',
        BillingCountry = 'UK',
        Ownership_Type__c = 'Private',
        Phone = '07826533392',
        Industry = 'Property development & management',
        Type = 'Customer Direct');
        insert a;
    
        Contact c = new Contact (FirstName='Test', LastName='Test', AccountId = a.Id,
        Phone = '07826533392');
        insert c;    
        
        Net_Promoter__c n = new Net_Promoter__c (Account__c=a.Id,
        Assigned_To__c=u2.id,
        Client_Visiting__c=c.id,
        Activity_Date__c = datetime.newInstance(2017, 9, 15, 12, 30, 0),
        End_Time__c=datetime.newInstance(2017, 9, 15, 14, 30, 0),
        Site_Location__c='Test'                                                                                   
        );
        insert n;
        
        n.Survey_Status__c='Complete';
        n.Score_Updated__c=TRUE;
        update n;
        
        List<ProcessHandler.NPS> Params = new List<ProcessHandler.NPS>();

        ProcessHandler.NPS p = new ProcessHandler.NPS();
        p.npsid = n.id;
        p.mname = n.MD_Name__c;
        p.oname = n.Ops_Director__c;
        p.subject = n.subject__c;
        p.client = n.client_visiting__r.FirstName;      
        p.md = n.MD_Email__c;
        p.body = n.Body__c; 
        
        Params.add(p);
        
        ProcessHandler.Invokeapexcallout(params);
        
        Futureapexcallout.apexcallout(n.MD_Name__c, n.Ops_Director__c, n.id, n.subject__c,n.client_visiting__r.FirstName, n.MD_Name__c, N.Body__c );
        Integer invocations = Limits.getEmailInvocations();
        
        pageReference pdfPage = Page.NPS_Survey;
        pdfPage.getParameters().put('id',n.id);
        
        if(Test.isRunningTest()){
        blob b = blob.valueOf('Unit.Test');
        }else{
        blob b = pdfpage.getContentaspdf(); 
         
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('NPS.pdf');

        String addresses;
        email.setSubject(n.subject__c);
        email.setToAddresses(new List<String> {n.MD_Name__c});
        email.setCCAddresses(new List<String> {n.Ops_Director__c});
        email.setPlainTextBody(N.Body__c);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        
        test.stopTest();
        
        system.assertEquals(p.npsid, n.id);       
        system.assertEquals(1, invocations, '1 email should be sent');
}           
}
}

 
Hello all, 
I'm trying to create cases through incoming email by using Apex Inbound Emailhandler. It worked very well for a sample class which pulls the contact id based on incoming email address and creates case. However, when I try to create case based on our requirement, it wouldn't create. Please have a look at the below code. We receive emails in a particular template, we have to parse the emailbody to assign certain information to certain fields. We don't want the email body to be dumped in description field. Parsing is working fine, as I tested for the sample class. However, I'm unable to pull the location id (object of a managed package) for the incoming email. Can any one help me? There seems to be an issue with the query I think.  

Every incoming email has a location name, we have to use it to pull the location id and create a case. 
SVMXC__Site__c is the API name for the custom object Location from which I have to pull the location name and create case. 
 
global Class EtoCase implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
public String location;
public String notes;
public Integer locationIdx;
public Integer notesIdx;
public String locationFinal;
public String notesFinal;

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
          
if (email.fromaddress =='example@test.com') {

location = 'Location: ';   
notes = 'Notes ';      

    
locationIdx = email.plainTextBody.indexOf(location);
notesIdx = email.plainTextBody.indexOf(notes);

locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
          String[] locNme = locationFinal.split(' ', 3);
notesFinal = email.plainTextBody.substring(
                              notesIdx + notes.length(), email.plainTextBody.indexOf('\n', notesIdx + notes.length()));
         
    
     try{      
               
case c= new case();
c.subject= 'PRODUCT SERVICE REQUEST';
c.Case_Type__c= 'Service Request';
c.Priority='High';
c.Origin='Email';
c.Status='new';
string location = locationFinal;   
SVMXC__Site__c[] locArray = [SELECT Id, Name, NTT_Location_Name__c, SVMXC__Account__r.Id FROM SVMXC__Site__c where Name = 'locationFinal'  limit 1];
c.SVMXC__Site__r.Id = locArray[0].Id;           
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.recordtypeId = '012E0000000oRWX';         
c.Description= notesFinal;
 insert c;
     } catch (System.Dmlexception e)
                     {System.debug('Error: Not able to create new Case: ' + e);
        

            // If no email address is gathered from the email body, write to the debug log, and no actions
            // will be performed.
}
}
return result;

      } 
}

 
I have an automation process based on the returned value from a count roll-up summary field.
For instace I have two statuses.
Primary status
Secondary status
Let's say the user creates two records. 

One record with Primary status and another record with Secondary status.
The count which rollup field will return will be 2, because the number of records is two: One with Primary and one with Secondary.
At a certain point in time the user checks a custom checkbox field.
As soon as the checkbox is checked I need to know how to make the rollup field to start couting only the records with Secondary status.
Istead of having 2 the returned count will have to be reduced the to 1, becuse there is only one record with Secondary status and also because the custom checkbox field is checked.
Another example:
User creates
1. record with Primary status
2. record with Primary status
3. record with Secondary status
4. record with Secondary status
5. record with Secondary status

As soon as the user checks the custom checkbox field the returned count will have to be equal to 3, because there are three records with Secondary status and also because the custom checkbox is checked.
Until the custom checkbox field remains checked only the records with Secondary status must be counted.
Please advise how it can be achieved?
Hi,

I am trying to call a simple js function to default a field value in VF from another field, but the js keeps telling me that the field I am trying to get is null. I have tried various ways to make this work; the current code is below.

The message I get is: TypeError: userNameFld is null​
</apex:form>
 <apex:pageBlock rendered="{!validPermissions}" mode="edit">

  <apex:pageBlockSection title="Create a New User" collapsible="false" columns="1">
                
     <apex:pageBlockSectionItem helptext="The User's email address" 
           rendered="{!NOT(fromEditPerson)}">          
        <apex:outputLabel value="Email Address"/>	
        <apex:inputField id="newEmailFld" value="{!newUser.Email}" 
  	            		onmouseout="defaultUsername();"
  	            		style="width: 250px !important;" required="true" />
      </apex:pageBlockSectionItem>

      <apex:pageBlockSectionItem helptext="The the user ID that the user will log in with">          
        <apex:outputLabel value="User Name"/>	
        <apex:inputField id="userNameFld" value="{!newUser.Username}" style="width: 250px !important;" required="true" />
      </apex:pageBlockSectionItem>
               							
  </apex:pageBlockSection>
               
 </apex:pageBlock>
</apex:form>

<script type="text/javascript">
  function defaultUsername() {

        	var userNameFld = document.getElementById("userNameFld");
        	var newEmailFLD = document.getElementById("newEmailFld");

        	if (userNameFld.value === null) {
        		userNameFld.value = newEmailFLD.Value;
       		}
        }

</Script>

Any ideas?

Thanks
 
I'm getting Expression Cannnot be assigned when I'm trying to populate the Account field 

for(Account acc : newAcc){
            Account oldAcc = oldMap.get(acc.Id);
            for(String fieldAPI : FieldSet){
                if(acc.get(fieldAPI) != oldAcc.get(fieldAPI)){    
                    //getting error from the below field
                    acc.get(fieldAPI) = oldAcc.get(fieldAPI);
                }
             }//loop
}//end loop

 
I have a Junction object name AcctContactAff which I use to create a many-to-many relationship between Contacts and Accounts and stores (among other things) the title of the person at the account.

Being new to SOQL I am really struggling to get the following to work:

SELECT Id, Name, NPI__c,
(SELECT Title__c FROM AcctContactAff__r)
FROM Contact

When I run this I get the error message: "Didn't understand relationship 'AcctContactAff__r' in FROM part of query call."

However, I can get the query to work when I do this:

SELECT Contact__r.id, Contact__r.Name, Title__c, Name
FROM AcctContactAff__c

I absolutely need to run the query from the Parent object not the Child object.

Can anyone tell me what is wrong with the first query statement?
I am attempting to put a text message just above the buttons of some of the records which will indicate to the user that something is still needed in order to Submit his request. For some reason my text will not center properly. I thought maybe it was because I am trying to do it at the very top of the record, and maybe that was impossible in that section. But I tried moving it to other parts of the record and it wouldn't work either.

Here is the top portion of the VisualForce code which contains my style and outputtext :
 
<apex:page standardcontroller="Product_Review__c">

    <head>     
     <style >
        .italicText 
        { 
            font-style: italic; 
            font-weight: bold
            font-size: 24px;
            text-align:center;
            width :100%;
        }                   
     </style>
    </head>

<apex:messages />

    <apex:sectionheader title="{!$ObjectType.Product_Review__c.label} Detail" subtitle="{!Product_Review__c.Name}"/>
    <chatter:feedwithfollowers entityId="{!Product_Review__c.Id}"/>
    <apex:form >
    <apex:outputtext style="text-align:center; width : 100%;font-size: 16px; font-weight: bold ;  color : #FF0000" value="{!Product_Review__c.Docs_Still_Needed__c}" rendered="{!IF(Product_Review__c.Docs_Still_Needed__c = '', false, true)}" />
        <apex:pageblock mode="maindetail" title="{!$ObjectType.Product_Review__c.label} Detail">
            <apex:pageblockbuttons >
                <apex:commandbutton value="Edit" action="{!Edit}"/>
                <apex:commandbutton value="Delete" action="{!Delete}"/>
                <apex:commandButton value="Submit for Approval" action="{!URLFOR($Action.Product_Review__c.submit, Id)}" id="Submit_for_Approval" rendered="{!IF(Product_Review__c.Status__c = 'Approved', false, true)}"/>

            </apex:pageblockbuttons>

The align:center attribute in the outputtext line is having no effect. The rest of the attributes such as font size and color are working properly.

Any idea what I'm doing wrong here ?

Thank you for your help.
  • August 03, 2016
  • Like
  • 0
Attached is a trigger to grab values from the On_Call_Schedule object which stores the values I grab. I'm attempting to convert the location__c field to a mulitpick picklist. I've succeeded in the conversion of the actual field but now need converting the trigger to handle the possible multi value String in the List. As you can see, location__c is mapped with the Id of the On_Call_Schedule so that later is can be called to populate the Incident object that triggers it. I feel like it would be easiest to somehow store the multivalue string as a Set then parse it later. I've also considered moving the Maps and Lists under the Trigger.New statement so that I can just grab the Queue name from the Incident and add basically 'AND location__c = d.Owner.Id' to the SOQL for onCallList.

Disclaimer: I didn't originally write this so I may not be able to defend 'Why'. I've renamed variables and added notation for my sanity.
trigger OnCallTrigger on BMCServiceDesk__Incident__c (before insert, before update) {

    DateTime myTime = system.now();
	On_Call_Schedule__c OCSched = null;
    String location = '';
    
    //Create list of all possible on call schedules based on time period
    Map<String, On_Call_Schedule__c> onCallMap = new  Map<String, On_Call_Schedule__c>();
    List<On_Call_Schedule__c> onCallList = [select primary_on_call_assignee__c,
                                            secondary_on_call_assignee__c,
                                            primary_pager_pin__c,
                                            secondary_pager_pin__c,
                                            location__c
                                            from On_Call_Schedule__c
                                        	where (start_date_time__c <= :myTime)
                                        	and (end_date_time__c >= :myTime)];
    //For each on call schedule in list, add the location and Id to map
    Set<String> locationSet = new Set<String>();
    for(On_Call_Schedule__c d : onCallList) {
        onCallMap.put(d.location__c, d);
    }
    
    //Create list of all queues
	Map<id, string> QueueMap = new Map<id, string>();
    List<Group> grouplst = [select Name, Id 
                             from Group 
                             where TYPE = 'Queue' 
                             LIMIT 5000];
    //For each queue in list, add Id and Name to map
    for(Group grp : grouplst)
   		QueueMap.put(grp.id, grp.name);
    
    //For each triggered incident
    for(BMCServiceDesk__Incident__c d : Trigger.new) {
        
        string strQueue = ''; //Queue name
        
        //Set queueid to ticket 'owner' (user or queue) Id
        string queueid = d.OwnerId;
        //Check queue map to see if owner is queue (and not user)
        if(QueueMap.containsKey(queueid))
            strQueue = QueueMap.get(queueid);
        else
            strQueue = 'Service Desk';
        
        //Assigns prim/sec callers to incident 
        if(onCallMap.isEmpty() || !onCallMap.containsKey(strQueue))
			return;        
        else {
            OCSched = onCallMap.get(strQueue);
            d.Primary_On_Call_Assignment__c = OCSched.Primary_On_Call_Assignee__c;
        	d.Secondary_On_Call_Assignment__c = OCSched.Secondary_On_Call_Assignee__c;
            d.Primary_Pager_PIN_email_field__c = OCSched.Primary_Pager_PIN__c;
            d.Secondary_Pager_PIN_email_field__c = OCSched.Secondary_Pager_PIN__c;
        }
	}
}

 
Can anyone advise how I can get variable from a url and store them as attributes that I can use to filter data?  Here is my current url:

lightning/n/Group_Structures_List?Aid=001q000000nv4YT&Tid=001q000000nv52W

I need to understand how I create two different variables... Aid should hold the id that follows the and Tid should hold the id that follows.

Thank you!!

Fred
  • October 16, 2018
  • Like
  • 0
I'm getting ready to add a community, however, I'm concerned if enabling Communities has anything to do with My-Domain?  If I setup a community - do I have to enable My-Domain?  I have some external integrations that i'm sure are using my node isntance (ie NA56.salesforce.com)  in integrations, and I'm not ready to implement My-Domain yet.

Should I be concerned about setting up a Community with regard to not being ready to implement My-Domain?
Ajax call is not stopping by itself . The counter still keeps on incrementing. Can someone please let me know what am I doing wrong here?

VF page code:
<apex:page controller="polarExampleClass">
    <apex:form >
        <apex:outputText value="Watch this counter: {!count}" id="counter"/>
        <apex:actionPoller action="{!incrementCounter}" reRender="counter" interval="5" timeout="10000"/>
    </apex:form>
</apex:page>

Apex class code:
public class polarExampleClass {
Integer count = 0;
            
    public PageReference incrementCounter() {
        count++;
        return null;
    }
            
    public Integer getCount() {
        return count;
    }
}
Hi All,
          I have a requirement, I need to post a single picklist field into chatter on clicking on a button from a visualforce page. 
Please help me out with it.? 
Hi,

I'm attempting to implement Automatic Opportunity Territory Assignment from page 21 of the Enterprise Territory Management Implementation Guide which tells me to install the following Apex:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_interface_TerritoryMgmt_OpportunityTerritory2AssignmentFilter.htm

Two issues:

1. The Guide and the Help file fail to mention that you need to install in Sandbox and move as a Change Set to production.  I can't do this because I do not have the required Code Coverage.  How do I get the required Code Coverage?

2. We are new to SFDC Enterprise.  If SF is telling their customers to install their Apex to make one of their features work, why don't they just install the Apex themselves?  Unless I'm missing something completely, I would think this would affect a great many people.

Thanks for any guidance!

Ed
 
Hi,

Hoping someone can help to point us in the right direction, it seems that whatever we do, we are unable to get better than 26% code coverage with our Invocable Email Class calling an @future Method to send a single email with a visualforce attachement generated on the record. The Class works like a charm and does exactly what it is meant to do and we are even able to dummy an email being sent and assert the fact it was but it doesn't get close to covering the code. 

Any guidance would be greatfully appreciate, as even though we run at 95% coverage, i'm not prepared to push a class with only 26% even though it works fully.

Please help save my sanity? 
 
Invoked from process builder with 100% coverage

public class ProcessHandler {
    public class NPS{
        @InvocableVariable(required=true)
        public Id npsid;
        @InvocableVariable(required=true)
        public String mname;
        @InvocableVariable(required=true)
        public String oname;
        @InvocableVariable(required=true)
        public String subject;
        @InvocableVariable(required=true)
        public String client;
        @InvocableVariable(required=true)
        public String md;
        @InvocableVariable(required=true)
        public String body;
    }
    
    @InvocableMethod
   public static void invokeapexcallout(NPS[] nps) {
     Futureapexcallout.apexcallout(nps[0].mname, nps[0].oname, nps[0].npsid, nps[0].subject, nps[0].client,nps[0].md,nps[0].body);

    }
}
 
@Future Method with only 26% coverage

public class Futureapexcallout{

  @future(Callout=true)
  public static void apexcallout(string mname,string oname,Id NPSId, String subject, String client, string md, string body){
         
        
         
        pageReference pdfPage = Page.NPS_Survey;
        pdfPage.getParameters().put('id',NPSID);
        
        if(Test.isRunningTest()){
        blob b = blob.valueOf('Unit.Test');
        }else{
        blob b = pdfpage.getContentaspdf(); 

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('NPS.pdf');
        efa1.setBody(b);

        String addresses;
        email.setSubject(subject);
        email.setToAddresses(new List<String> {mname});
        email.setCCAddresses(new List<String> {oname});
        email.setPlainTextBody(body);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
}
 
Test Class, probably really badly written :)

@isTest
private class testProcessHandler
{
private static testMethod void testProcessHandler() {
    
    test.startTest();
    
        User u2 = new User(Alias = 'nUr32', Email='newuser@testorg32.com', 
        EmailEncodingKey='UTF-8', LastName='Testing12', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = '00e90000001yvFD' , 
        TimeZoneSidKey='America/Los_Angeles', UserName='newuser32@testorg.com',External_Use__c='SRK1132AA',Operating_Country__c='Global',Region__c='Global' ,Team__c='Client Services - Global');
        insert u2;
     
        Account a = new Account(Name = 'Test A',
        BillingCountry = 'UK',
        Ownership_Type__c = 'Private',
        Phone = '07826533392',
        Industry = 'Property development & management',
        Type = 'Customer Direct');
        insert a;
    
        Contact c = new Contact (FirstName='Test', LastName='Test', AccountId = a.Id,
        Phone = '07826533392');
        insert c;    
        
        Net_Promoter__c n = new Net_Promoter__c (Account__c=a.Id,
        Assigned_To__c=u2.id,
        Client_Visiting__c=c.id,
        Activity_Date__c = datetime.newInstance(2017, 9, 15, 12, 30, 0),
        End_Time__c=datetime.newInstance(2017, 9, 15, 14, 30, 0),
        Site_Location__c='Test'                                                                                   
        );
        insert n;
        
        n.Survey_Status__c='Complete';
        n.Score_Updated__c=TRUE;
        update n;
        
        List<ProcessHandler.NPS> Params = new List<ProcessHandler.NPS>();

        ProcessHandler.NPS p = new ProcessHandler.NPS();
        p.npsid = n.id;
        p.mname = n.MD_Name__c;
        p.oname = n.Ops_Director__c;
        p.subject = n.subject__c;
        p.client = n.client_visiting__r.FirstName;      
        p.md = n.MD_Email__c;
        p.body = n.Body__c; 
        
        Params.add(p);
        
        ProcessHandler.Invokeapexcallout(params);
        
        Futureapexcallout.apexcallout(n.MD_Name__c, n.Ops_Director__c, n.id, n.subject__c,n.client_visiting__r.FirstName, n.MD_Name__c, N.Body__c );
        Integer invocations = Limits.getEmailInvocations();
        
        pageReference pdfPage = Page.NPS_Survey;
        pdfPage.getParameters().put('id',n.id);
        
        if(Test.isRunningTest()){
        blob b = blob.valueOf('Unit.Test');
        }else{
        blob b = pdfpage.getContentaspdf(); 
         
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('NPS.pdf');

        String addresses;
        email.setSubject(n.subject__c);
        email.setToAddresses(new List<String> {n.MD_Name__c});
        email.setCCAddresses(new List<String> {n.Ops_Director__c});
        email.setPlainTextBody(N.Body__c);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        
        test.stopTest();
        
        system.assertEquals(p.npsid, n.id);       
        system.assertEquals(1, invocations, '1 email should be sent');
}           
}
}

 
First, I’m not a developer and this is my first time attempting to create a Visualforce page and, I’m sure this is very basic to most on here, but I need some help. What I want to do: Override the “New” button on a custom child object to Contacts. The object is called Equipment Assignments and I want users to be able to request equipment from their Contact record in Salesforce. So I want to call the button “New Equipment Request.”  Basically, I want the user to create the record, the have it go through an approval process so the project manager can approve or disapprove the request.
 
I have created the VF page with the below code and when I preview it, everything looks right. I’ve created my custom button and placed it on the related list, shown in the image. However, when I click on the New Equipment Request button, I get the error “Id value 0033C000006pAjR is not valid for the Equipment_Assignments__c standard controller”. So, obviously I need to do more, but I don’t know what that is. I’ve read some posts about public class and wrapper class, but I’m not sure how to go about writing any of that or what exactly I would even need.

Also, I am using record types on the Equipment Assignments, so I need to incorporate that into the VF. I also want to pull in some custom information from the contact record, such as the Manager and Department. I’m not sure how to do that.
 
<apex:page standardController ="Equipment_Assignments__c">
<apex:form >
   
<apex:pageBlock title="Equipment Request">
   
  <apex:pageBlockSection title="Requestor Information">
    <apex:inputField value="{!Equipment_Assignments__c.name}"/>
  
    <apex:inputField value="{!Equipment_Assignments__c.Department__c}"/>
    <apex:inputField value="{!Equipment_Assignments__c.Assigned_To__c}"/>
    <apex:inputField value="{!Equipment_Assignments__c.Project__c}"/>
       
    </apex:pageBlockSection>  
  <apex:pageBlockSection title="Request Information">
    <apex:inputField value="{!Equipment_Assignments__c.Start_Date__c}"/>
    <apex:inputField value="{!Equipment_Assignments__c.End_Date__c}"/> 
 
      <apex:commandButton value="Submit Request" action="{!save}"/>
   </apex:pageBlockSection>
   
</apex:pageBlock>   
</apex:form>
</apex:page>
 
User-added image
Hello all, 
I'm trying to create cases through incoming email by using Apex Inbound Emailhandler. It worked very well for a sample class which pulls the contact id based on incoming email address and creates case. However, when I try to create case based on our requirement, it wouldn't create. Please have a look at the below code. We receive emails in a particular template, we have to parse the emailbody to assign certain information to certain fields. We don't want the email body to be dumped in description field. Parsing is working fine, as I tested for the sample class. However, I'm unable to pull the location id (object of a managed package) for the incoming email. Can any one help me? There seems to be an issue with the query I think.  

Every incoming email has a location name, we have to use it to pull the location id and create a case. 
SVMXC__Site__c is the API name for the custom object Location from which I have to pull the location name and create case. 
 
global Class EtoCase implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
public String location;
public String notes;
public Integer locationIdx;
public Integer notesIdx;
public String locationFinal;
public String notesFinal;

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
          
if (email.fromaddress =='example@test.com') {

location = 'Location: ';   
notes = 'Notes ';      

    
locationIdx = email.plainTextBody.indexOf(location);
notesIdx = email.plainTextBody.indexOf(notes);

locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
          String[] locNme = locationFinal.split(' ', 3);
notesFinal = email.plainTextBody.substring(
                              notesIdx + notes.length(), email.plainTextBody.indexOf('\n', notesIdx + notes.length()));
         
    
     try{      
               
case c= new case();
c.subject= 'PRODUCT SERVICE REQUEST';
c.Case_Type__c= 'Service Request';
c.Priority='High';
c.Origin='Email';
c.Status='new';
string location = locationFinal;   
SVMXC__Site__c[] locArray = [SELECT Id, Name, NTT_Location_Name__c, SVMXC__Account__r.Id FROM SVMXC__Site__c where Name = 'locationFinal'  limit 1];
c.SVMXC__Site__r.Id = locArray[0].Id;           
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.recordtypeId = '012E0000000oRWX';         
c.Description= notesFinal;
 insert c;
     } catch (System.Dmlexception e)
                     {System.debug('Error: Not able to create new Case: ' + e);
        

            // If no email address is gathered from the email body, write to the debug log, and no actions
            // will be performed.
}
}
return result;

      } 
}

 
I have an automation process based on the returned value from a count roll-up summary field.
For instace I have two statuses.
Primary status
Secondary status
Let's say the user creates two records. 

One record with Primary status and another record with Secondary status.
The count which rollup field will return will be 2, because the number of records is two: One with Primary and one with Secondary.
At a certain point in time the user checks a custom checkbox field.
As soon as the checkbox is checked I need to know how to make the rollup field to start couting only the records with Secondary status.
Istead of having 2 the returned count will have to be reduced the to 1, becuse there is only one record with Secondary status and also because the custom checkbox field is checked.
Another example:
User creates
1. record with Primary status
2. record with Primary status
3. record with Secondary status
4. record with Secondary status
5. record with Secondary status

As soon as the user checks the custom checkbox field the returned count will have to be equal to 3, because there are three records with Secondary status and also because the custom checkbox is checked.
Until the custom checkbox field remains checked only the records with Secondary status must be counted.
Please advise how it can be achieved?
Hi, 

My salesforce site was just restricted by saledorce new update " Restrict Record Access for Guest Users"

Now guest users cant register using our site.

I am asked to review the update and acknowledge. 

Whatt happens after I acknowledge? How do i give users access to enter data on our site?

Thank you
Hello! 

I am setting up Google SSO for Salesforce and I have this autoreghandler that I need a test class for. I'm not really a developer so I was wondering if someone could help me? I just need the code coverage so I can upload other things into production. 
 
//TODO:This autogenerated class includes the basics for a Registration
//Handler class. You will need to customize it to ensure it meets your needs and
//the data provided by the third party.

global class AutocreatedRegHandler1537799224416 implements Auth.RegistrationHandler{
global boolean canCreateUser(Auth.UserData data) {
	//TODO: Check whether we want to allow creation of a user with this data
	//Set<String> s = new Set<String>{'usernamea', 'usernameb', 'usernamec'};
	//if(s.contains(data.username)) {
		//return true;
	//}
	return false;
}

global User createUser(Id portalId, Auth.UserData data){
	if(!canCreateUser(data)) {
		//Returning null or throwing an exception fails the SSO flow
		return null;
	}
	if(data.attributeMap.containsKey('sfdc_networkid')) {
		//We have a community id, so create a user with community access
		//TODO: Get an actual account
		Account a = [SELECT Id FROM account WHERE name='Acme'];
		Contact c = new Contact();
		c.accountId = a.Id;
		c.email = data.email;
		c.firstName = data.firstName;
		c.lastName = data.lastName;
		insert(c);

		//TODO: Customize the username and profile. Also check that the username doesn't already exist and
		//possibly ensure there are enough org licenses to create a user. Must be 80 characters or less.
		User u = new User();
		Profile p = [SELECT Id FROM profile WHERE name='Customer Portal User'];
		u.username = data.username + '@acmecorp.com';
		u.email = data.email;
		u.lastName = data.lastName;
		u.firstName = data.firstName;
		String alias = data.username;
		//Alias must be 8 characters or less
		if(alias.length() > 8) {
			alias = alias.substring(0, 8);
		}
		u.alias = alias;
		u.languagelocalekey = UserInfo.getLocale();
		u.localesidkey = UserInfo.getLocale();
		u.emailEncodingKey = 'UTF-8';
		u.timeZoneSidKey = 'America/Los_Angeles';
		u.profileId = p.Id;
		u.contactId = c.Id;
		return u;
	} else {
		//This is not a community, so create a regular standard user
		User u = new User();
		Profile p = [SELECT Id FROM profile WHERE name='Standard User'];
		//TODO: Customize the username. Also check that the username doesn't already exist and
		//possibly ensure there are enough org licenses to create a user. Must be 80 characters
		//or less.
		u.username = data.username + '@myorg.com';
		u.email = data.email;
		u.lastName = data.lastName;
		u.firstName = data.firstName;
		String alias = data.username;
		//Alias must be 8 characters or less
		if(alias.length() > 8) {
			alias = alias.substring(0, 8);
		}
		u.alias = alias;
		u.languagelocalekey = UserInfo.getLocale();
		u.localesidkey = UserInfo.getLocale();
		u.emailEncodingKey = 'UTF-8';
		u.timeZoneSidKey = 'America/Los_Angeles';
		u.profileId = p.Id;
		return u;
	}
}

global void updateUser(Id userId, Id portalId, Auth.UserData data){
	User u = new User(id=userId);
	//TODO: Customize the username. Must be 80 characters or less.
	//u.username = data.username + '@myorg.com';
	u.email = data.email;
	u.lastName = data.lastName;
	u.firstName = data.firstName;
	//String alias = data.username;
	//Alias must be 8 characters or less
	//if(alias.length() > 8) {
		//alias = alias.substring(0, 8);
	//}
	//u.alias = alias;
	update(u);
}
}

I have this test class but it's only covering like 9%
 
@isTest
//https://help.salesforce.com/articleView?id=sso_authentication_providers.htm
private class StandardUserRegistrationHandlerTest3 {
static testMethod void testCreateAndUpdateUser() {
    AutocreatedRegHandler1537799224416 handler = new AutocreatedRegHandler1537799224416();
    // UserData class: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Auth_UserData.htm
    // https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_auth_plugin.htm
    Auth.UserData sampleData = new Auth.UserData('testId', 'testFirst', 'testLast',
        'testFirst testLast', 'testuser@example.org', null, 'testuserlong', 'en_US', 'facebook',
        null, new Map<String, String>{'language' => 'en_US','site' => 'test'});
    Id portalId = null;
    User u = handler.createUser(portalId, sampleData);
    //System.assertEquals('testuserlong@myorg.com', u.userName);
    //System.assertEquals(true,sampleData.attributeMap.containsKey('language'));
    //System.debug(sampleData.attributeMap);
    
    System.assertEquals('testuser@example.org', u.email);
    System.assertEquals('testLast', u.lastName);
    System.assertEquals('testFirst', u.firstName);
    System.assertEquals('testuser', u.alias);
    insert(u);
    String uid = u.id;
    
    sampleData = new Auth.UserData('testNewId', 'testNewFirst', 'testNewLast',
        'testNewFirst testNewLast', 'testnewuser@example.org', null, 'testnewuserlong', 'en_US', 'facebook',
        null, new Map<String, String>{'language' => 'en_US'});
    handler.updateUser(uid, null, sampleData);
    
    
    User updatedUser = [SELECT userName, email, firstName, lastName, alias FROM user WHERE id=:uid];
    //System.assertEquals('testnewuserlong@acmecorp.com', updatedUser.userName);
    System.assertEquals('testnewuser@example.org', updatedUser.email);
    System.assertEquals('testNewLast', updatedUser.lastName);
    System.assertEquals('testNewFirst', updatedUser.firstName);
    //System.assertEquals('testnewu', updatedUser.alias);
}
}

 
Hi all,
I know we can access Custom Labels in Apex and VF.
But, Can we Update the value of a Custom Label through Apex Controller?


If So, How?

With Thanks.
Using a Sobject name(which will be String) I should able to access fields of that SObject.
Hi,

I have a rest resource class which returns the content from one of the VF pages and then i call this rest resource from site.com and embed the returned VF page content to static site.com pages. Everything was working fine until we need to access the page using site.com authenticated user, I am passing session id in Oauth Header which makes the rest resources class running as site logged in user but the VF page whose content I am fetching is still running as Public guest user context.

I tried below urls:-

vfPage=new PageReference('https://mysitedomain/myVFpage');  // it runs as guest user.
vfPage=new PageReference('https://mysitedomain/myVFpage?sid='+sid);  // session id that i am using to call the rest resource but still it runs as guest user.

vfPage=new PageReference('https://c.cs44.visual.force.com/apex/myVfpage?sid='+sessionId+'&nooverride=1&inline=-1');// this is throwing Maximum redirects (100) exceeded.i also tried setting Redirect property to false but still throwing exception.

Please let me know what do i need to pass to run the VF page as logged in user or any workaround to avoid "Maximum redirects" issue.

Thanks In Advance,
Shubham

I am exposing content in an authenticated site using visualforce pages. I have to add the provision for users to rate the content. The fields  postive rating count, negative rating count, rating count etc on contentversion are read only. Not sure where the data is stored for content rating. Or is there any other API which can be use to achieve this (similar to the API for knowledge) Any help in proceeding with this is appreciated. Thanks!