• Rov
  • SMARTIE
  • 1411 Points
  • Member since 2011

  • Chatter
    Feed
  • 46
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 227
    Questions
  • 660
    Replies
We have some strict requirements on account sharing amongst sales teams members in our org. I have created a custom object which holds the rules of who can see which account based on the Owner on the account. I wrote a trigger which makes use of AccountTeamMember object. Everything is working fine. However I would like to bulkify my trigger but have not been able too after a few attempts.
Below is part of my trigger I would like to bulkify: (the rest of it has code unrelated to account sharing).
Could someone suggest a solution?

Thank you
List<AccountTeamMember> atmToAdd = new List<AccountTeamMember>();

for (Account a : trigger.new) 
{
	//Custom object holding sharing rules
	SharingRuleMap__c[] sMap = [SELECT SharingWith_ID__c, 
										TeamMemberRole__c, 
										AccountAccessLevel__c, 
										ContactAccessLevel__c, 
										CaseAccessLevel__c, 
										OpportunityAccessLevel__c 
								   FROM SharingRuleMap__c
								  WHERE Dealing_Rep__c = :a.OwnerId];
	 
	if (sMap.size() > 0) 
	{ 
		For (Integer i=0; i<sMap.size();i++) 
		{
			AccountTeamMember atm = new AccountTeamMember();
			atm.AccountId = a.Id;
			atm.UserId = sMap.get(i).SharingWith_ID__c;
			atm.TeamMemberRole = sMap.get(i).TeamMemberRole__c;
			atm.AccountAccessLevel = sMap.get(i).AccountAccessLevel__c;
			atm.ContactAccessLevel = sMap.get(i).ContactAccessLevel__c;
			atm.CaseAccessLevel = sMap.get(i).CaseAccessLevel__c;
			atm.OpportunityAccessLevel = sMap.get(i).OpportunityAccessLevel__c;
			atmToAdd.add(atm);
		}
	}
}

insert atmToAdd;

 
Hello,

I need the trigger below to only find the duplicate record if the Status__c is 'Active' on both records. Status__c is a picklist field. Any assistance is greatly appreciated!
trigger DuplicateExecutiveContact on Committee_Board_Member__c (before insert. before update) {
        for(Committee_Board_Member__c c:Trigger.new)
        {
      
            List<Committee_Board_Member__c> comm=[select ID from Committee_Board_Member__c where Account__c=:c.Account__c and Committee_Board__c=:c.Committee_Board__c and Service_Discipline__c=:c.Service_Discipline__c and Status__c=:c.Status__c];
            if(comm.size()>0)
            {
                c.adderror('Duplicate Record');
            }
        }
    }

 
  • April 09, 2019
  • Like
  • 0
Hi

I am Beginner in Salesforce
I am trying to this Scenario but how to start i dont know 
So Please Help Me I am new In Salesforce
My Question is:
 my checkbox name is Display Amount when i clicked on checkbox  then one custom field is appear  field name is Amount and when unchecked the checkbox then field will be not appear
Please help me

Thanks in Advance
Neeraj Sharma
I am trying to build a page to clone a record.  I have the page and I am able to pass the current record to the new component in an attribute but I'm really struggling to figure out how I can take the values from that one record and populate x number of dummy records with the values.  I am new to javascript. 
 
What I have so far is the variable "CloneGS" which does get populated with the record.  I was trying to loop through x number of times (eventually, that number will also get passed from the original component) and then add a record to my attribute, "newgroupstructures" and then display these on the page so they can be edited and then created.
 
Any help would be greatly appreciated!!!!  thanks!!!  Fred
 
Here is my component:
 
  
<!-- here is the variable to hold thegroup structure that gets passed from the GroupStructures Component (that was clicked) -->
 <aura:attribute name="existinggroupstructure" type="Group_Structure__c" />
    <aura:attribute name="newGroupStructures" type="Group_Structure__c[]"/>
 
    <!-- Handle component initialization in a client-side controller -->
 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
 <!-- <aura:handler event="c:GSCloneRecords" action="{!c.createGS}" />  -->
   
    <aura:iteration items="{!v.newGroupStructures}" var="gs">
  <p>{!gs}</p>
 </aura:iteration>
Here is my controller:
Here is my doInit controller:
 
doInit : function(component, event, helper) {
    
        //variable for the record that we are cloning from the component
        var CloneGS = component.get("v.existinggroupstructure");
 
 //variable to hold the new records
        var gs = [];
    
      //Loop through and create 5 rows with same field data in the
        for(var i = 0;i < 5;i++){
            // doesnt work.... gs.push({'Name':'Test'+i, 'Group_Number__c': testfield});
            gs.push({'Name' : 'Test'+i});
         }
   component.set("v.newGroupStructures",gs);
  },


 
  • October 26, 2018
  • Like
  • 0
The "Search in Files" feature is particularly irritating because it doesn't search components.
Also, the debug logs won't show the last few lines without jumping back up the list.
The "Search"  box overlays the horizontal scroll bar.
Hi, I am new to salesforce i am finding difficulty in writing trigger.
I have 2 fields named 'Claim' on Account and Contract Object. Account is the parent record(Lookup Relationship).
How to automatically update the claim field of Account object with the Contract claim field using trigger.
Thanks in advance.
I'm trying to mass update a specific field using developer's console, but I only end up deleting the record itself. Here is my code: 

Contact[] contactDel = [SELECT Email__c FROM Contact
   WHERE Join_Date__c <= '2000'
   AND Email__c LIKE '%it.work.com’];

delete contactDel;

I'm currently trying to mass delete an email field that ends with "it.work.com," but only from people who joined on or before the year 2000. I don't want to necessarily remove the field from the record, but just delete the entry so that it's blank. However, this ends up deleting the whole record. Is there another way to do this? Maybe such as retrieving the ID's of these record? 
Issue: Below trigger forwards opp if opp name contains "TrailHead", our users are entering "Trailhead" and opp is not forwarding, it's getting forwarded if i use "TrailHead", i have used contains so why is my trigger using case sensitive?

Trigger AutoforwardOpp on Opportunity(after insert, after update)
{
    List <PartnerNetworkRecordConnection> prncList;
    List <PartnerNetworkConnection> connectionList;
    Map <ID, PartnerNetworkConnection> connMap;
    Map <ID, ID> oppIdvsAccountIdMap;
    Map<ID, Account> accountWithContactMap;
    
    ID cid;
    String status;
    String connName;

    if(Trigger.isafter  && (Trigger.isInsert || Trigger.isUpdate)){
            
        connectionList = new List<PartnerNetworkConnection>();
        prncList = new List<PartnerNetworkRecordConnection>();
        
        //This would ideally return multiple active Connections if they exist hence its best you use a
        //criteria to ensure only the appropriate connection record is returned.
        connMap = new Map<ID, PartnerNetworkConnection>(
            [Select ID, ConnectionStatus, ConnectionName
             From PartnerNetworkConnection
             Where ConnectionStatus = 'Accepted']);
        
        //get connection details        
        for(ID connId :connMap.keySet()){
            cid = connMap.get(connId).ID;
            status = connMap.get(connId).ConnectionStatus;
            connName = connMap.get(connId).ConnectionName;
        }
        
        //Populate a map of Opp Ids and associated Account Ids
        oppIdvsAccountIdMap = new Map<ID, ID>();
        for(Opportunity oppRecord :Trigger.new){
        
            if(oppRecord.Name.contains('TrailHead')){
                    //System.debug('Opp Id: ' + oppRecord.ID + '-> Account Id: ' + oppRecord.AccountId);
                    oppIdvsAccountIdMap.put(oppRecord.ID, oppRecord.AccountId);
            }
        }
        
        //Get associated Accounts and Contacts for every US opportunity if they exist
        if(oppIdvsAccountIdMap.keySet().size() > 0){
        
            accountWithContactMap = new Map<ID, Account>(
                [Select ID, Name,
                    (Select ID, Name, Account.Id From Account.Contacts)
                 From Account
                 Where ID IN :oppIdvsAccountIdMap.values()]);

            //Create PartnerNetworkRecordConnections for sharing the records
            for(ID oppId : oppIdvsAccountIdMap.keySet()){
            
                ID accountId = oppIdvsAccountIdMap.get(oppId);
                
                //Share Opportunity
                prncList.add(new PartnerNetworkRecordConnection(
                    ConnectionId = cid,
                    LocalRecordId = oppId,
                    SendClosedTasks = true,
                    SendOpenTasks = true,
                    SendEmails = true));
                
                //Share Account
                if(oppIdvsAccountIdMap.get(oppId) != null){
                
                    prncList.add(new PartnerNetworkRecordConnection(
                        ConnectionId = cid,
                        LocalRecordId = accountId,
                        SendClosedTasks = true,
                        SendOpenTasks = true,
                        SendEmails = true));
                }
                
                //Share associated Contacts
                if(accountWithContactMap.get(accountId).Contacts != null){
                                   
                    for(Contact contact :accountWithContactMap.get(accountId).Contacts){
                    
                        prncList.add(new PartnerNetworkRecordConnection(
                            ConnectionId = cid,
                            LocalRecordId = contact.ID,
                          //ParentRecordId = Contact.AccountId,
                            SendClosedTasks = true,
                            SendOpenTasks = true,
                            SendEmails = true));
                    }
                }
            }
            
            //Insert record connections
            if(!prncList.isEmpty()){
            
                try{
                    insert prncList;
                }
                catch(System.Dmlexception dmlExceptionInstance){
                    System.debug('Record Share Error:' + dmlExceptionInstance.getMessage());
                }
            }
        }
    }
}
When deploying some updates to exiting apex classes, the deploy is failing because it says 0% code coverage. When I check coverage in the developer console it shows 83% coverage. Not sure what is going on. This just starting happening this week, I deployed a few changes last week without issue. Nothing has been changed or packages added in the meantime. I've had this issue in the past, but usally went away after 24 hours. Any ideas? Is this a bug?
I used Below codes  i didn't get any result

Decimal toRound = 3.14159265359;   
Decimal rounded = Math.round(toRound, 2);
system.debug(rounded);

Decimal toround = 3.14159265;
Decimal rounded = toround.setScale(2);
system.debug(rounded);

Hi,

 

I am very much new to the salesforce

 

I am creating recruiting app using a following book

http://www.salesforce.com/us/developer/docs/fundamentals/salesforce_creating_on_demand_apps.pdf

 

in its security and sharing data section I have created a user Phil Katz, and trying to make this as a DBA owner as per the steps given in the book but I am getting error saying

 

Transfer Requires Read The new owner must have "Read" permissions on this type of record.

Click hereto return to the previous page.

 

how to get it resolved, how to provide read access to this new user.

 

please suggest

 

Thanks,

Manish.

Hi,

 

I have a field with check box. If it is ticked, then the user has to fill the text box, else not required.

How can I configure it ?

 

Your help needed.

 

Regards,

Blue

Hi

 

Interview question:Can we use the check box in dependent picklists?Can anybody help me?

I'm trying to create a field at the Opportunity Product level that divides the "Total Price" by the number of months in the contract (at the opp level). However, I only want it to calculate if the Product Name is not equal to "Cart".

 

IF(PricebookEntry.Product2.Name <> "Cart",TotalPrice/Opportunity.Months_in_Contract__c)

 

I keep getting an error that says I have an incorrect number of parameters for function IF(). Expected 3, received 2.

 

Any help would be very much appreciated!

 

 

HI  -

I created a text field and now I want to have it default to "no".  There's no data in it yet, so is there a way to edit the field and set the Default value?

I feel like I've done this before, but I can't remember or find it.

 

Thanks -

Sara

  • October 24, 2012
  • Like
  • 0

As of today, I cannot deploy change sets from my sandbox (cs11) to the sandbox (cs10) site. I get emails that the upload worked but it just doesnt apper in the list of inbound change sets.  Any Infos about this issue? 

 

 

Thanks

 

Diego Moreira

 Where can I find a test class written for a particular apex class.......I can only see the code covered for a particular class but unable to find the test class for it..... 

Hello
I´m new with visualforce and I need to create an email template to show data of the opportunity, show the related quote and show the list of a custom object (call CE) that is related to the quote. The next is an example of what a need:

 

- Quote has a relation master detail with opportunity
- CE (My_custom_object) has a relation master detail with quote

 

Dear {!recipient.Name}

 

{!Opportunity.Name}
{!Opportunity.closeDate}
{!Quote.name}
{!Quote.date}

 

(here I need to show a table with the list of items of my custom object)
Code- Name - Date

 

I hope you understand me. I appreciate your help.

We are evaluating ETL/Middleware to integrate Salesforce with our external database, and the sync should happen in real time. 

Use Case: When an Account gets created in Salesforce, check if the accounts exists in the external database. If it does not exist, create a record in external database. The record gets an autogenerated ExternalID__c. Then, bring the ExternalID__c back to salesforce , and and update the Salesforce record to populate the ExternalID__c field.

If the Account already exists in external database, update the record with the data from salesforce, and then bring the ExternalID__c back to salesforce , and and update the Salesforce record to populate the ExternalID__c field.

My question is  what is the best solution for this use case ? 
I was looking into Jitterbit and Mulesoft. 

What are the Pros and Cons of of using Jitterbit vs Mulesoft for my use case? 

Thanks !
  • October 23, 2019
  • Like
  • 0
We enabled Coonected Campaign in Pardot, a feature that allows to connect SAlesforce + PArdot Campaigns. 

However, by doing this, our pardot admin, can no longer create campaigns in Pardot. 

What are the repurcussions if we now disable the feature that connects Salesforce + Pardot Campaigns. ?
  • July 16, 2019
  • Like
  • 0
I am doing this trail head module :
https://trailhead.salesforce.com/content/learn/projects/quickstart-vscode-salesforce/vscode-salesforce-ready?trail_id=force_com_dev_beginner

when trying to install the CLI through the installer, I get the error 
'The requested operation requires elevation'
  • June 25, 2019
  • Like
  • 0
Why do i see Export option on some reports in lightning and some reports do not have the Export option. ? 

The only reason i can think of is, the reports that have Export option may have been created after feature was delivered in lightning by Salesforce . 

Can someone please verify ? 

Thanks !
 
  • May 28, 2019
  • Like
  • 0
// I am trying to translate the following pseudo code to Apex -> base64(hmac-sha256({accessKeySecret}, UTF8({stringToSign})))

// My atempt at translating to Apex
String dateString = Datetime.now().formatGmt('EEE, dd MMM yyyy HH:mm:ss Z'); 

String stringtoSign = 'GET\n\n\n'+dateString;

String secretAccessKey = '9PK^:WAvBrl1?jz3^U{7+)){igpCG\"Y;<.3DGy8gX+' +'\'' + '6p{|D2#MwI#It8{+@W?>*'; 

Blob mac = Crypto.generateMac('HMAC-SHA256', blob.valueOf(stringToSign),blob.valueOf(secretAccessKey)); 

String signature = EncodingUtil.base64Encode(mac); system.debug(signature);

This compiles correctly in Dev Console. However how do i ensure that that I have translated in the format as mentioned in the pseudo code. ? 
  • May 21, 2019
  • Like
  • 0
I am looking for an integration specialist who can guide me . ? 

I need help with code review for generating HMAC signature . 

 
  • May 17, 2019
  • Like
  • 0
I am researching ways to Integrate our External System (Database) with Salesforce. 
Salesforce Connect/ Lightning Connect would do exactly what we want but its far too expensive. 
I don't want to store data into salesforce. I want to only send requests to External System, and display the response in Salesforce. 

Can someone please point me to resources or  guide how I would create go about doing webservice callouts from salesforce to external system? 
Thanks you !!
  • April 15, 2019
  • Like
  • 0
So I will be deling about 5000 contacts. 
Before deleting, i ran Data Export and took a back up of Contacts and Accounts

In event if i want to import the deleted Contacts back into salesforce -  what steps should i follow before deletion and before deletion? 
what steps should i follow before deletion and after deletion?
what steps should i take to import the deleted contacts back into salesforce and relate these to the correct accounts?

I read all documentationa and help topics but not feeling very comfortable. 

Can somene please suggest resources or steps by step walk through to undertake this task ?  

​​​​​​​Thanks !!
  • March 22, 2019
  • Like
  • 0
The standard Phone field on Account has data type Phone. As per documentation, a phone number is validated and formatted based on user locale. However that doesn't seem to be the case. I can enter any characters and digits and it gets saved as is. 

Am i missing something ? 
  • March 20, 2019
  • Like
  • 0
I have Created a Duplicate Rule for Contact,  based on the standard Matching Rule for Contacts. 

My 'Potential Duplicate lightning Component' card correctly shows me the duplicates. 

I thought I would be able to see all of these Duplicate Contact records in the DuplicateRecordSet, but I don't. 

All I see in the DuplicateRecordSet > DuplicateRecordItems is the duplicates that were created after I activated tehe Duplicate Rule. 

Am I missing something?  
  • March 01, 2019
  • Like
  • 0
I have read the documentation 
Considerations for Relating a Contact to Multiple Accounts (https://help.salesforce.com/articleView?id=shared_contacts_considerations.htm&type=5)

If you have enabled 'Contact  to multiple Accounts'  can you please share your experience. 

Anything i should be aware of ? 
Anything that i should avoid / do ?  

Thanks!
 
  • February 28, 2019
  • Like
  • 0
No such column 'SobjectType' on entity 'DuplicateRecordSet'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.
 
String query =[Select id,DuplicateRecordSetId,Name,RecordId from DuplicateRecordItem Where DuplicateRecordSet.SobjectType='Contact'];
        
return Database.getQueryLocator(query);
  • February 25, 2019
  • Like
  • 0
I am unable to login to Salesforce from outlook  if i have a login flow for my profile. 
Has anyone experience this ? If so,  what did you do? 
 
  • February 08, 2019
  • Like
  • 0
I created a login flow for the System Admin profile, that references an active flow. 
When I tried to login  to data loader from the remote desktop, I got the following error. 

This page has an error. You might just need to refresh it. 
Action failed: salesforceIdentity:lightningLoginFlow$controller$statusChange [Unable to get property 'Submit' of undefined or null reference] 
Callback failed: serviceComponent://ui.interaction.runtime.components.controllers.FlowRuntimeController/ACTION$executeAction 
Failing descriptor: {salesforceIdentity:lightningLoginFlow$controller$statusChange}"

Please note that when i didn;t have the login flow, I had no issue logging to Dataloader from remote desktop, it's only after creating a login flow. 
  • February 05, 2019
  • Like
  • 0
In visualforce page I could do this <apex:actionSupport event="onchange" action="{!pickvalOnChange}" />

I have built a picklist of users . how  can i pass the selected picklist value to apex controller in lightning. ? 
 
<aura:component 
                controller="BuildPicklistOfUsers" 
                implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    
   	<aura:handler name="init" value="{!this}" action="{!c.doInit}"></aura:handler>
    <aura:attribute name="users" type="user[]"></aura:attribute>
    
    <lightning:select label="Choose User" name="uzr" aura:id="uzr"> 
        <aura:iteration items="{!v.users}" var="user">
			<option value="{!user.Id}">{!user.Name}</option>
        </aura:iteration>
	</lightning:select>
	
</aura:component>

// client side controller

({
     doInit: function(component, event, helper) {
    
    var action = component.get("c.getUserList");
    console.log("@@@action",action);
    action.setCallback(this, function(result){
    var users = result.getReturnValue();
    console.log("@@@@users",users);
    component.set("v.users", users);
    window.setTimeout(
    $A.getCallback( function() {
    component.find("uzr").set("v.value", users[4].Id);
    }));
    });
    $A.enqueueAction(action);
    }
})

// Server side controller
global class BuildPicklistOfUsers {
    @AuraEnabled global static User[] getUserList() {
    	return [SELECT id, Name FROM User];
    }
}

 
  • October 22, 2018
  • Like
  • 0
<aura:component  controller = "EmailViewController">
    
    <aura:attribute name="userList" type="User[]"/> 
    <aura:handler name="init" value="{!this}" action="{!c.pickUser}"/>

    <lightning:combobox name="general" label="Many Options" 
               placeholder="Select a User Option" options{!v.userList}" onchange="{! c.pickUser}"/>
   
</aura:component>

<.JS controller>

pickUser: function (component, event, helper) {
        var action = component.get("c.getUsers");
        action.setCallback(this, function(response){
                var state = response.getState();
                if (state === "SUCCESS") {
                    var listItems = response.getReturnValue();
                    component.set("v.userList", listItems);
                }
        });
        
        $A.enqueueAction(action);
    }


<Apex Controller>

@AuraEnabled
	public static List<User> getUsers()
	{
		List<User> lstUsers = [SELECT Id,FirstName,LastName FROM User];

		return lstUsers;
	}

Can some one please check my coode and tell me why my picklist in the lightning cmponent is not populating with anu values? 

Basiclaly on my lightning component I want a picklist of Users. 

Thanks !
  • October 19, 2018
  • Like
  • 0
<div class="slds-grid slds-grid_vertical">
        <lightning:card title="{!v.headerTitle}" iconName="standard:email">
            
            <lightning:layoutItem size="4" class="left-align">
                <ui:inputSelect label="User" class="dynamic" aura:id="dynamicInputSelect" change="{!c.onPicklistChange}"/>
            </lightning:layoutItem>
            <div>
            <lightning:layoutItem size="4" class="right-align">
                <lightning:button label="Email Previewer" onclick="{!c.previewEmail}"/>
            </lightning:layoutItem>    
            </div>
            <div class="slds-card__body ">
                <div class="slds-grid slds-grid_vertical slds-card__body_inner" > 
                    <aura:iteration var="e" items="{!v.campaignEmails}" >
    				<p>{!e}</p>
    				</aura:iteration>
                </div>
            </div>
                
        </lightning:card>
	</div>

User-added image

How can i aligh the picklist and button side by side ? 

Thanks
  • October 19, 2018
  • Like
  • 0
On a Lightning Record Page I added the Standard button 'Add To Campaigns' under the Salesforce Mobile and Lightning Exprience Actions section. When i navigate to the page, in the highlight panel I don't see the Add to Campaigns button. Any thoughts? 

I see that  Camapign Memeber is not available for selection in the Object Specific Action, neither is it available for selection in the Global Action. 

I tried replication the Add to Campaign buttons through process builderrr/Flow, without success. 

Any other way to replicate the Add to campaign button as a quick Action on the record Detail page? 

Thanks! 
  • October 15, 2018
  • Like
  • 0
I am aware this ia know issue https://success.salesforce.com/issues_view?id=a1p3A000000oAQnQAM

Could someone suggest  a workaround? 
 I tried testing through Dev Console, as an tab but all i see is the cancel and save button
 
<aura:component 
                implements="flexipage:availableForAllPageTypes,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId,force:hasSObjectName" 
                access="global" >
  
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="fieldsArray" type="String[]" default="['Name','Email','HomePhone','MobilePhone','AccountId']" />
       
    <lightning:card class="slds-card__body slds-card__body_inner" iconName="standard:contact" title="Quick PersonAccount" >
        
         <lightning:recordForm 
								aura:id="recordForm"
                                recordId="{!v.recordId}" 
        						objectApiName="Contact"
        						layoutType="Compact" 
                               	fields="{!v.fieldsArray}"
        						columns="2"
                               	mode="edit" 
  								onsubmit="{!c.onSubmit}"
                     			
		/>
    </lightning:card>
</aura:component>

 
  • October 01, 2018
  • Like
  • 0
// Trigger

trigger Opportunity_Misc on Opportunity (before insert, before Update) 
if(Trigger.isBefore && Trigger.isInsert){

      MyHelperClass.NewStep(Trigger.new);        
    }

// class
public with sharing class MyHelperClass  {
    public static void NewStep(List<Opportunity> newstepopps){

}


// test clas 

@isTest
    public static void testNewStep(){
   
    // create test opportunity 
        Opportunity opp = Test_Helper.CreateOpp(contact,user);
        insert(opp);

Test.startTest();

        Opportunity opp1 = opp.clone(true);
        
            List<Opportunity> newloanopps = AutoAssignCampaignHelper.NewLoan(opp1);    

        Test.stopTest();
}


 
  • September 17, 2018
  • Like
  • 0

I have a VFp , which open another VFP as a popup, after the pop is closed, i want the parent page that opened the popup to be refreshed. 

My code/javscript  closes the VFP popup but it doesnt reload the parent page. I have to manually reload the parent page to see the updated record.

Note:  The reason i am using window.open is becuase i want users to have the ability to scroll through the parent window. 

Any suggestions????


**********************************************************************************************************************
VFP1

<script type="text/javascript">
function OpenVfpage(){
window.open('/apex/SendEmailPage?id={!recordId}', '_blank','scrollbars=yes,width=600,height=800,resizable=no,toolbar=0,location=0,menubar=0');
}
</script>

<apex:commandButton value="Send Email" id="email" onclick="javascript:OpenVfpage();"/>

**********************************************************************************************************************


VFP2

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

if("{!$Request.success}" == "true") {
parent.window.close();
window.close();
        
}
</script>

<apex:commandButton id="saveBtn" value="Send" action="{!sendEmail}" onComplete="javascript:closeVFP();"/>


**********************************************************************************************************************
Controller

public PageReference sendEmail(){
// logic to send the email
return new PageReference ('javascript:window.close()');

}
  • May 13, 2014
  • Like
  • 1
I have a validation rule on a field Status__c.The error message is as follows -

You cannot "manually " change the Status.

In the Visualforce page I am using this field.

When this validation fires, I see the error in the VFP as -


You cannot &quot;manually&quot; change the status.

Is there a way to display the word manually in double quotes ?

Note in my page i have <apex:pagemessages / >

and in my controller

catch(System.DMLException e){
            ApexPages.addMessages(e);
            return null;

Thanks!
  • February 27, 2014
  • Like
  • 1
In the Documents, I have a public Folder called 'Images' where I have 6 images. How can I avoid hardcoding the file_id and instead get it dynamically.

Object__c obj = new Object__c();

obj.Test__c = '<img alt="comment image" src="/servlet/servlet.FileDownload?file=015n00000004vra" ></img>';

I know I can create custom setting but again that would mean hardcoding the value.

I want to Query the the folder  from Documents and get respective fileid from the folder.

Thanks!
  • February 16, 2014
  • Like
  • 1
Why do i see Export option on some reports in lightning and some reports do not have the Export option. ? 

The only reason i can think of is, the reports that have Export option may have been created after feature was delivered in lightning by Salesforce . 

Can someone please verify ? 

Thanks !
 
  • May 28, 2019
  • Like
  • 0
Hello,

I'm a novice at Apex code and am trying to adjust my extension for SavePDF so that it saves as a file as well.  I get an error message related to the line that says:  file.Origin = 'a';

I am indicating the wrong origin or something?  Or do I need to complete the attachment fully before I can add the file?  Any help would be appreciated!

 
public pageReference savePDF(){
    
        Date dateToday = Date.today();
        String sMonth = String.valueof(dateToday.month());
        String sDay = String.valueof(dateToday.day());
        if(sMonth.length()==1){
          sMonth = '0' + sMonth;
        }
        if(sDay.length()==1){
          sDay = '0' + sDay;
        }
        String sToday = String.valueof(dateToday.year())+ '-' + sMonth +  '-' + sDay ;
        
      PageReference pagePdf = new PageReference('/apex/SalesAgreement_PDF');
          pagePdf.getParameters().put('id', idVal);
          Blob pdfPageBlob;
          pdfPageBlob = pagePdf.getContentAsPDF();
                 
          Attachment a = new Attachment();
          a.Body = pdfPageBlob;
          a.ParentID = idVal;
          a.Name = 'Service_Agreement_' + strOppName + '_' + sToday + '.pdf';
          a.Description = 'Service Agreement_' + sToday;
          insert a;

          ContentVersion file = new ContentVersion();
		  file.Title = 'Service_Agreement_' + strOppName + '_' + sToday + '.pdf';
		  file.PathOnClient = 'Service_Agreement_' + Datetime.now().getTime() + '.txt';
		  file.VersionData = Blob.valueOf('Service_Agreement_' + 
		  Datetime.now().getTime() + '.txt');
		  file.Origin = 'a';
		  insert file;         
    
        
        pop_msg='Successfully saved';
        displayPopup = true;  
       
        
        opp.Signature_Date__c = null;
        opp.Signature_Key__c = '';
        opp.Signature_Name__c = '';
        opp.Signature_URL__c = null;
        opp.Signature__c = null;

        
        update opp;
      return new PageReference('/apex/SalesAgreement_HTML?id=' + idVal);
      
        
    }



 
Hi Team,


I am sorry if my question is stupid, but I tried to use Lightning Starter and create a trial account, I did not receive any notifications on email and cannot change password, SF informs me that the old password incorrect. If I try to change it, SF asks me a secret question, Could you please help me?
// I am trying to translate the following pseudo code to Apex -> base64(hmac-sha256({accessKeySecret}, UTF8({stringToSign})))

// My atempt at translating to Apex
String dateString = Datetime.now().formatGmt('EEE, dd MMM yyyy HH:mm:ss Z'); 

String stringtoSign = 'GET\n\n\n'+dateString;

String secretAccessKey = '9PK^:WAvBrl1?jz3^U{7+)){igpCG\"Y;<.3DGy8gX+' +'\'' + '6p{|D2#MwI#It8{+@W?>*'; 

Blob mac = Crypto.generateMac('HMAC-SHA256', blob.valueOf(stringToSign),blob.valueOf(secretAccessKey)); 

String signature = EncodingUtil.base64Encode(mac); system.debug(signature);

This compiles correctly in Dev Console. However how do i ensure that that I have translated in the format as mentioned in the pseudo code. ? 
  • May 21, 2019
  • Like
  • 0
Hello Gurus,
I had a trigger(generates an email on department name change) and a test class related to this trigger.  The coverage was 100%. I changed the trigger to fire only when the profile is <> System Administrator.  The trigger is working fine as expected but the Test class is failing.  Here is the trigger code and followed by Test class code.
--------------------------------------------------------------
trigger SendEmailAfterDeptCodeUpdate on Department__c (after update) {
Profile p = [ Select Id, Name from Profile where Id =: UserInfo.getProfileId() ];
        if( !p.Name.equalsIgnoreCase( 'System Administrator' ) ) 
        {
  List<Id> lstdeptsToUpdate=new List<Id>(); 
for(Department__c dept : trigger.new)
{
    If (dept.Name !=trigger.oldMap.get(dept.Id).Name)
    {
    lstdeptsToUpdate.add(dept.Id);
    }
}
    
    If(lstdeptsToUpdate.size()>0)
    {
    Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
    
   // string header = '*TR Customer Code, *Customer Name,*TR Department ID,*Original Department Code,*New Department Code,*SubBranchCode,TR Customer Id \n';
 string header = 'SubBranchCode,TRCustomerId,TRDepartmentID,OriginalDepartmentCode,NewDepartmentCode,TRCustomerCode \n';

    string finalstr = header ;
    String Emailbody;
        
    
    string csvname= 'template_to_update_WO_inv_dept.txt';
    csvAttc.setFileName(csvname);
    
    system.debug('header:' + header);
     String messageBody,priorvalue;   
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    //email.setSubject('Department Code change in Salesforce');     
   for (Department__c dep1 : [Select id, Name,Service_Entity__r.Customer_Name__c,TR_Customer_Code__c,trDepartmentID__c,Service_Entity__r.Sub_Branch__c,Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c,Service_Entity__r.TR_Customer_Id__c from Department__c where id in : lstdeptsToUpdate and Service_Entity__r.Send_To_TR__c=True])
        {
     priorvalue=trigger.oldMap.get(dep1.Id).Name; 
     //string recordString = dep1.TR_Customer_Code__c + ','+ dep1.Service_Entity__r.Customer_Name__c+','+dep1.trDepartmentID__c +','+priorvalue+','+dep1.Name+','+dep1.Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c +','+dep1.Service_Entity__r.TR_Customer_Id__c +'\n';
     string recordString = dep1.Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c+','+dep1.Service_Entity__r.TR_Customer_Id__c+','+dep1.trDepartmentID__c +','+priorvalue+','+dep1.Name +','+ dep1.TR_Customer_Code__c  +'\n';

          finalstr = finalstr +recordString;
      
         messageBody = '<html><body>';
         messageBody = messageBody + 'Here are the details for the change in Department Code in Salesforce ';
         messageBody = messageBody + '<br>';
         messageBody = messageBody + '<br>';            
         messageBody = messageBody + 'TR Customer Code: '+ dep1.TR_Customer_Code__c;
         messageBody = messageBody + '<br>';
         messageBody = messageBody + 'TR Department ID: ' + dep1.trDepartmentID__c;
         messageBody = messageBody + '<br>';
               
         messageBody = messageBody + 'Original Department Code: ' + priorvalue;
         messageBody = messageBody + '<br>';
         messageBody = messageBody + 'New Department Code: ' + dep1.Name;
         messageBody = messageBody + '<br>';
         messageBody = messageBody + '<br>';            
         messageBody = messageBody + 'Additional details are available in the attached excel. Please update the Work Order and Invoicing details with the new department code.';
         messageBody = messageBody + '<br>';
         messageBody = messageBody + '<br>';            
         messageBody = messageBody + 'Assign ticket to - Data Management Backend group';
    
         messageBody = messageBody + '</body></html>';       
    
    blob csvBlob = Blob.valueOf(finalstr);    
    csvAttc.setBody(csvBlob);

    system.debug('----');    
    email.setSubject('Department Code change in Salesforce updated to ' + dep1.Name ); 
    email.setHtmlBody(messageBody);

    email.setToAddresses(new String[]{'raos@gmail.com'});
    email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
    system.debug('email...' + email );
    if(email != null)
      {
       Messaging.sendEmail(new Messaging.singleEmailMessage[] {email}); 
       //   system.debug('Inside send email');
      } 
    }        
}
        }
}
--------------------------------------------------------------
@IsTest
public class SendEmailAfterDeptCodeUpdateTest {
static testMethod void SendEmailAfterDeptCodeUpdateTest()
    {
        Profile p = [ Select Id, Name from Profile where name='System Administrator' limit 1 ];
        //Profile p = [ Select Id, Name from Profile where name='Standard Sales User' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales)
        {   /*Account a=new Account(Name='Test1',BillingCountry='United States',BillingState='Indiana');
            insert a;
         
            Acquisition__c ac= new Acquisition__c(Name='Test Ac');
            insert ac;
         
            Service_Entity__c Se1=new Service_Entity__c(Customer_Name__c='Testa',Legal_Entity__c='Archive Systems Inc.',Account__c=a.id,AcquisitionDB__c=ac.id);
            insert Se1;*/
            
            Department__c dept1= new Department__c(Name='Test Dept',Department_Name__c='Sample Dept',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un1kR'); //Se1.Id);
            test.startTest();
            insert dept1;
            test.stopTest();
        }


    }
    static testMethod void updateDepartmentTest1(){
                
        Profile p2 = [ Select Id, Name from Profile where name='Onboarding Team' limit 1 ];
        User standardSales2 = new User(profileId = p2.id, username ='standarduserAdmin123@peak.com', email = 'standarduseranc@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname1231');
        insert standardSales2;

       system.runAs(standardSales2)
        {   Department__c dept11= new Department__c(Name='Test Dept123',Department_Name__c='Sample Dept123',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un1qH'); //Se1.Id);
            insert dept11  ;   
            test.startTest();
            dept11.Name='Test Dept1243';
            Update dept11;
            test.stopTest();
        }   
    }
    static testMethod void updateDepartmentTest(){
        Profile p = [ Select Id, Name from Profile where name='System Administrator' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales){
            Department__c dept2= new Department__c(Name='Test Dept2',Department_Name__c='Sample Dept2',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un4UM'); //Se1.Id);
            insert dept2;
            
            test.startTest();
            dept2.Name='Test Dept3';
            Update dept2;
            test.stopTest();
        }
    }
}
--------------------------------------------------------------

I am getting the following error message

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

Stack trace is showing this message:
Class.SendEmailAfterDeptCodeUpdateTest.updateDepartmentTest1: line 39, column 1

I have highlighted the line 39.  The new method that i have include is updateDepartmentTest1().

Let me know the mistake I am doing.

Thanks
Rao
  • May 21, 2019
  • Like
  • 0
I am looking for an integration specialist who can guide me . ? 

I need help with code review for generating HMAC signature . 

 
  • May 17, 2019
  • Like
  • 0
Need to know complete trail (steps) to become a Salesforce developer
I have a custom object that is not active which contains 2 triggers, both inactive as well.  I need to delete the custom object but cannot due to the presence of the triggers.  How can I delete this custom object?
We have some strict requirements on account sharing amongst sales teams members in our org. I have created a custom object which holds the rules of who can see which account based on the Owner on the account. I wrote a trigger which makes use of AccountTeamMember object. Everything is working fine. However I would like to bulkify my trigger but have not been able too after a few attempts.
Below is part of my trigger I would like to bulkify: (the rest of it has code unrelated to account sharing).
Could someone suggest a solution?

Thank you
List<AccountTeamMember> atmToAdd = new List<AccountTeamMember>();

for (Account a : trigger.new) 
{
	//Custom object holding sharing rules
	SharingRuleMap__c[] sMap = [SELECT SharingWith_ID__c, 
										TeamMemberRole__c, 
										AccountAccessLevel__c, 
										ContactAccessLevel__c, 
										CaseAccessLevel__c, 
										OpportunityAccessLevel__c 
								   FROM SharingRuleMap__c
								  WHERE Dealing_Rep__c = :a.OwnerId];
	 
	if (sMap.size() > 0) 
	{ 
		For (Integer i=0; i<sMap.size();i++) 
		{
			AccountTeamMember atm = new AccountTeamMember();
			atm.AccountId = a.Id;
			atm.UserId = sMap.get(i).SharingWith_ID__c;
			atm.TeamMemberRole = sMap.get(i).TeamMemberRole__c;
			atm.AccountAccessLevel = sMap.get(i).AccountAccessLevel__c;
			atm.ContactAccessLevel = sMap.get(i).ContactAccessLevel__c;
			atm.CaseAccessLevel = sMap.get(i).CaseAccessLevel__c;
			atm.OpportunityAccessLevel = sMap.get(i).OpportunityAccessLevel__c;
			atmToAdd.add(atm);
		}
	}
}

insert atmToAdd;

 

Hi,

I'm trying to calculate the number of days between Saturday and Sunday by using daysBetween(toStartofWeek).

If it's 0, I count it as a Sunday, if it's -6, I count it as a Saturday.

This was working fine until I saw this link and changed the user locale

https://help.salesforce.com/articleView?id=admin_supported_date_time_format.htm&type=5

Now as per this post, for some locales 0 will be Monday and for some -6 will be a Friday.

I thought of using a map, but I'm already using one to set locale adjusted date format.

Can anyone help me in resolving this as per logged in user's locale(which I am getting correctly)?

Hello,

I need the trigger below to only find the duplicate record if the Status__c is 'Active' on both records. Status__c is a picklist field. Any assistance is greatly appreciated!
trigger DuplicateExecutiveContact on Committee_Board_Member__c (before insert. before update) {
        for(Committee_Board_Member__c c:Trigger.new)
        {
      
            List<Committee_Board_Member__c> comm=[select ID from Committee_Board_Member__c where Account__c=:c.Account__c and Committee_Board__c=:c.Committee_Board__c and Service_Discipline__c=:c.Service_Discipline__c and Status__c=:c.Status__c];
            if(comm.size()>0)
            {
                c.adderror('Duplicate Record');
            }
        }
    }

 
  • April 09, 2019
  • Like
  • 0
So I will be deling about 5000 contacts. 
Before deleting, i ran Data Export and took a back up of Contacts and Accounts

In event if i want to import the deleted Contacts back into salesforce -  what steps should i follow before deletion and before deletion? 
what steps should i follow before deletion and after deletion?
what steps should i take to import the deleted contacts back into salesforce and relate these to the correct accounts?

I read all documentationa and help topics but not feeling very comfortable. 

Can somene please suggest resources or steps by step walk through to undertake this task ?  

​​​​​​​Thanks !!
  • March 22, 2019
  • Like
  • 0
The standard Phone field on Account has data type Phone. As per documentation, a phone number is validated and formatted based on user locale. However that doesn't seem to be the case. I can enter any characters and digits and it gets saved as is. 

Am i missing something ? 
  • March 20, 2019
  • Like
  • 0
I have an issue where i run an apex class and print some objects along the way to log using `System.debug()`.

my problem is that for some reason, the log rows are getting written, but the value of the objects is being "trimmed". the size that it writes and which gets trimmed isn't consistent (sometimes it prints a lot of content sometimes less) but it does not write the entirety of the objects values i choose to log.
It does this to both SObjects and json encoded strings, and my entire log size is just about 80KB so i know i'm not breaking some size limit.

I also checked my log levels and everything is set as it should (again my logs are being written just not "fully").

for example, I have the json string:

 `[{"sum":"2300","serial":"","repaymentDate":null,"payment":{"attributes":{"type":"Payment__c"},"Payment_Method__c":"Cash","checkdate__c":null,"Payment_Collected_Date__c":"2019-03-11"},"ownerId":null,"numOfPayments":null,"firstPaymentAmount":null,"digits":null,"cardType":null,"branch":null,"bank":"","account":""}`

But it gets written to the log file as:

    15:29:57:085 USER_DEBUG [69]|DEBUG|payments json: [{"sum":"2300","serial":"","repaymentDate":null,"payment":{"attributes":{"type":"Payment__c"},"Payment_Method__c":"Cash","checkdate__c":null,"Payment_Collected_Date__c":"2019-03-11"},"ownerId":null,"numOfPayments":null,"firstPaymentAmount":null,"digits":null,"cardType":null,"branch":nu

any ideas?