I to assign a default account to a custom object using Visualforce page - salesforce

I am new to salesforce development. I am trying to create a visualforce page which helps to insert a new record into the custom object. Custom object has master-detail relationship with account. I am having issue when assiging a default value to the Account. The account already exists in the accounts table. Here is the Apex class I am trying.
public class RelatedAccount{
public Account parent {get; set;}
public RelatedAccount(ApexPages.StandardController controller){
Transaction__c child = (Transaction__c)controller.getRecord();
if (child.Account__c != null) { parent = [Select ID,Name FROM Account WHERE Account.Name = :'1Company Inc.,' LIMIT 1];
child.Account__c = parent;
}
}}
I am getting the error : "Illegal assignment from Account to Id"
Thanks In advance.

This should work:
child.Account__c = parent.Id
In your case you try to put the "whole" account object object into the Lookup field. But this just needs the Id of the parent account.

Related

Salesforce Lookup field showing ID value instead of record name

Hi I have a custom object which has a custom field of type lookup to Account. The child custom record gets created when Account record is created. I am creating child record in after insert trigger on Account and keeping the name of child record same as of the name of Account.
But In the name I am getting 15 digit Id instead of real name of account. What can be the issue?
Code## for Trigger
if(Trigger.isAfter && (Trigger.isInsert)){
AccountTriggerHelper.createReferrer(Trigger.new);
}
In Apex Class:
public static void createReferrer(List<Account> accountList){
List<Referral__c> newReferral = new List<Referral__c>();
for(Account acc : accountList) {
if(acc.Talos_RecordType__c=='Referrer'){
system.debug('==acc=1='+acc);
Referral__c ref = new Referral__c();
System.debug('-----acc.Name----'+acc.Name);
ref.Name = acc.Name;
ref.Account__c = acc.Id;
ref.Email__c = acc.PersonEmail;
ref.Talos_IQOS_Expert_ID__c = acc.Talos_IQOS_Expert_ID__c;
ref.Talos_Referrer_Type__c = acc.Referrer_Type__c;
ref.User_Id__c = acc.UserID__c;
ref.Email_Validation__c = true;
ref.Store_Code__c = acc.Store_Code__c;
newReferral.add(ref);
system.debug('==referral=1='+newReferral);
}
}
Thanks,
Marc
This code can't lead to population of Id in the Name field. There might be another trigger on Account or child Object, or any workflow, process builder on your org creating that change again. Can you check the created date and modified date of the child record.
If they are different, then most probably I am right.

System.TypeException: DML operation INSERT not allowed on __Share

I have created share object in my salesforce environment.
From Setup-> security Controls -> Sharing Settings -> I made my custom object access to "Private". So suppose my object name is EVT_Client__c & I am trying to insert data into EVT_Client__Share from trigger(AfterInsert) I am unable to do it. I am getting error as given below.
Once data get inserted into EVT_Client__c object our trigger tries to insert data into EVT_Client__share object but we are getting error. Profile user who is inserting data into EVT_Client__c object through UI having Read/create/edit/delete access on object.
System.TypeException: DML operation INSERT not allowed on
EVT_Client__Share
My code in trigger is as below in which I am getting error.
public with sharing class EVT_Client_TriggerHandler {
private void ShareClientToThirdPartyJobGroup(List<EVT_Client__c> lstClients){
List<EVT_Client__Share> lstSharesForThirdPartyGroup = new List<EVT_Client__Share>();
List<Group> lstThirdPartyGroups = [Select Id, RelatedId from Group where Name = 'Third Party'];
for(EVT_Client__c client: lstClients){
for(Group roleGroup : lstThirdPartyGroups ){
EVT_Client___Share objShareForThirdPartyGroup = new EVT_Client__Share(ParentId = client.Id,
UserOrGroupId = roleGroup.Id,
AccessLevel = 'Edit',
RowCause = Schema.EVT_Client__Share.RowCause.User_Client__Access__c);
lstSharesForThirdPartyGroup.add(objShareForThirdPartyGroup);
}
}
insert lstSharesForThirdPartyGroup;
}
}
You're sure it's not a "detail" in any master-detail relationship? The OWD would then say "controlled by parent" instead of "private". Can you switch to Classic view, go to page layout and verify the [Sharing] button can be added, displays OK, this user can manually share this record from UI?
Post your code sample? I suspect you need to define Apex Sharing Reason first. It's bit like roles if you ever played with Account/Contact/Opportunity/Case roles.
Once it's set you should be able to do something like this code sample: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_bulk_sharing_creating_with_apex.htm (they use "manual" as sharing reason but you might have more luck with custom sharing reason.
I quickly created your object and this worked like a charm for me:
trigger Stack57201752 on EVT_Client__c (after insert) {
List<Group> groups = [SELECT Id FROM Group WHERE Name = 'Third Party'];
List<EVT_Client__Share> shares = new List<EVT_Client__Share>();
for(EVT_Client__c c : trigger.new){
for(Group g : groups){
shares.add(new EVT_Client__Share(
ParentId = c.Id,
UserOrGroupId = g.Id,
AccessLevel = 'Edit',
RowCause = 'Manual'
));
}
}
insert shares;
}
And when I click the [Sharing] button on the record it looks good:
So... Stupid question time: have you clicked this checkbox?

Attaching a Completed DocuSign Document to a Salesforce Standard Object (Not Opportunities)

I'm trying to attach a completed DocuSign document to the Contact or Account record that initiated the document (within Notes or Notes & Attachments).
I've found instructions for attaching documents to an Opportunity as well as attaching to custom objects. I've walked through these steps and tried to tailor the instructions for a Contact and Account record but with no success.
Please let me know the steps I can take to accomplish this. Much appreciated!
If you are communicating with docusign via a REST API then you should be receiving a base64 response. You would pass the response body into the 'execute' method below and it should insert to the specified contact and related account. The logic leading up to this would need to query the specific contact and account, but the code here is an example of pulling an existing salesforce ContentVersion and create a new content document from it. Also, you would need to either parse the incoming base64 data to determine the file information (extension, title) or match the extension within the response body. Your go to links would be as follows:
Salesforce Reference- ContentVersion
Salesforce Reference- EncodingUtil
Salesforce Reference- ContentDocumentLink
DocuSign API Docs- Envelopes
Hope this helps!
public with sharing class uploadDocument {
//Build this to accept whatever you need to relate the document to
public Contact ourContact {get; set;}
//Init
public uploadDocument() {
ourContact = [SELECT Id, Name, AccountId FROM Contact LIMIT 1];
}
public static void execute(String base64EncodedDocument){
uploadDocument classObject = new uploadDocument();
String extension;
//Conditional logic will need to be added if you want to handle other file types
if(base64EncodedDocument.contains('pdf')){
extension = 'pdf';
}
//Prep the raw document for insert via the ContentVersion class
Blob base64DecodedDocument = EncodingUtil.base64Decode(base64EncodedDocument);
ContentVersion sfDocumentObject = new ContentVersion();
sfDocumentObject.VersionData = base64DecodedDocument;
sfDocumentObject.Title = 'Our Test Document';
sfDocumentObject.FirstPublishLocationId = classObject.ourContact.Id;
sfDocumentObject.PathOnClient = '//' + sfDocumentObject.Title + '.' + extension;
insert sfDocumentObject;
//Add additional references for the document
List<additionalIdLink> additionalLinks = new List<additionalIdLink>();
additionalIdLink accountLink = new additionalIdLink();
accountLink.linkedId = classObject.ourContact.AccountId;
accountLink.documentId = sfDocumentObject.Id;
additionalLinks.add(accountLink);
linkToAdditionalRecords(JSON.serialize(additionalLinks));
}
//Ignore, just for testing purposes
//I uploaded a document just to test it and everything worked just fine, preview includedS
private static String setupExample(){
ContentVersion ourTestDocument = [SELECT Id, FileExtension, FileType, Title, VersionData, VersionNumber FROM ContentVersion WHERE Title =: 'Getting Started With Salesforce' ORDER BY VersionNumber DESC][0];
String result = EncodingUtil.base64Encode(ourTestDocument.VersionData);
return result;
}
//Ignore, just for testing purposes
public static void executeExample(){
String base64DocumentReceived = setupExample();
execute(base64DocumentReceived);
}
//Quick Access class to pass the previous values to the Future method
public class additionalIdLink{
public String linkedId {get; set;}
public String documentId {get; set;}
}
//Allows you to link to as many additional records as you need. I haven't run into any use cases where you will be adding over 200 links at a time, but it will throw a query exception if you attempt that
#future
public static void linkToAdditionalRecords(String jsonLinks){
List<additionalIdLink> links = (List<additionalIdLink>)JSON.deserialize(jsonLinks, List<additionalIdLink>.class);
List<ContentDocumentLink> result = new List<ContentDocumentLink>();
for(additionalIdLink link : links){
ContentDocumentLink accountLink = new ContentDocumentLink();
String documentId = [SELECT Id, VersionNumber, ContentDocumentId FROM ContentVersion WHERE Id =: link.documentId LIMIT 1].ContentDocumentId;
accountLink.ContentDocumentId = documentId;
accountLink.LinkedEntityId = link.linkedId;
accountLink.ShareType = 'V';
accountLink.Visibility = 'AllUsers';
result.add(accountLink);
}
if(result.size() > 0){
insert result;
}
}
}

Not able to insert AccountPartner through test class in salesforce

I was not able to insert mock data for AccountPartner through test class. I tried by inserting 2 accounts and one Partner object. Actually same code is working in case of running from Apex class or executing from developer console. Please see the below code and output and let me know solution..
#isTest
private class TestAccountPartner {
private static testmethod void unittest(){
test.startTest();
Account sourceAccount = new Account();
Account targetAccount = new Account();
sourceAccount.AccountNumber='Number1';
sourceAccount.Name='name1';
targetAccount.AccountNumber='Number2';
targetAccount.Name='name2';
insert sourceAccount;
insert targetAccount;
Partner p = new Partner(AccountFromId=sourceAccount.ID, AccountToId=targetAccount.ID);
insert p;
Account sa = [select ID from Account where Name='name1'];
Account ta = [select ID from Account where Name='name2'];
System.debug('Source Account is: '+sa);
System.debug('Target Account is: '+ta);
List<Partner> partners = [select AccountFromId from partner];
System.debug('Partner objects are: '+partners);
List<AccountPartner> accountPartners = [select AccountFromId from AccountPartner];
System.debug('account partners are: '+accountPartners);
test.stopTest();
}
}
Output is:
07:24:48:174 USER_DEBUG [26]|DEBUG|Source Account is: Account:{Id=00128000007YZk7AAG}
07:24:48:174 USER_DEBUG [27]|DEBUG|Target Account is: Account:{Id=00128000007YZk8AAG}
07:24:48:176 USER_DEBUG [30]|DEBUG|Partner objects are: (Partner:{AccountFromId=00128000007YZk7AAG, Id=00I28000000ZeBTEA0})
07:24:48:177 USER_DEBUG [33]|DEBUG|account partners are: ()
It's been a while but I think this is because account partner is one of the special Role type relationships. Have you tried accessing the Target account's AccountPartner collection and using the add() method to add the Source account.
This isn't identical to your situation, but the solution has a similar example that is adding partners:
https://salesforce.stackexchange.com/questions/3805/how-to-update-account-object-when-related-accountpartner-is-updated-inserted-del

Salesforce (SFDC) - public, static, global keywords - use one list for entire class?

I'm having a hard understanding using public, static, and global keywords with my variables and methods.
Below is a snippet of my code. What I'm trying to do is upon page load, in my constructor create a Set of accountIDs that the user has access to (8-33 this is working). This set will be used to filter queries used in later methods.
What I'm finding is that public pageReference runSearch() has access to 'terrAccSet', but the public static List getsearchAccounts does not have access to it.
If I change it to public static Set terrAccSet, I don't get data in either of the system.debugs - what can I do?
global with sharing class MyClass {
public static List<FRM_Metrics_gne__c> accountSearchGmap {get; set;}
public Set<Id> terrAccSet;
public List<String> terrIdList;
//Constructor
public MyClass() {
terrAccSet = new Set<Id>();
terrIdList = new List<String>();
Set<Id> grpIdSet = new Set<Id>();
Id uid = '00570000001R95e'; //member of TWO territories
//UserTerritory Utid = [SELECT TerritoryId FROM UserTerritory where UserId = :userInfo.getUserId()];
List<UserTerritory> Utid = [SELECT TerritoryId FROM UserTerritory where UserId =: uid ];
for(UserTerritory usrTerr: Utid){
terrIdList.add(usrTerr.TerritoryId);
}
List<Group> grp = [Select Id from Group where RelatedID IN :terrIdList];
for (Group eachgroupd : grp ){
grpIdset.add(eachgroupd.Id);
}
List<AccountShare> accountidList = [SELECT AccountId,UserOrGroupId FROM AccountShare where UserOrGroupId in :grpIdset];
//all accounst that the user has access according to territory hiearchy
for(AccountShare eachas:accountidList ){
terrAccSet.add(eachas.AccountId);
}
}
public PageReference runSearch() {
//Has Data
system.debug('**terrAccSet runSearch** '+terrAccSet);
}
public static List<Custom_Object__c> getsearchAccounts(String multiSearchString) {
//terrAccSet variable is missing
system.debug('**terrAccSet getSearchAccounts** '+terrAccSet);
//logic
return accountSearchGmap;
}
}
Below is a snippet of my code. What I'm trying to do is upon page load, in my constructor create a Set of accountIDs that the user has access to (8-33 this is working). This set will be used to filter queries used in later methods.
This set should be an instance property, not static.
Use static when you want to create a method that does not affect the state of a controller or class, eg. a text parser-text in text out.
You should make the class Global if you want to create a package and make your class available outside your package so that other Apex code can invoke it, or if your class will create webService or REST methods to be exposed.
Public should be used to expose properties to the VisualForce pages that will consume the properties. Otherwise, use Private methods and properties for controller side only processing.
public static List getsearchAccounts(String multiSearchString) {
//terrAccSet variable is missing
system.debug('terrAccSet getSearchAccounts '+terrAccSet);
//logic
return accountSearchGmap;
}
This method should not be static because it accesses an instance property (it reads state).
Simple rule of thumb, if it is a visualforce page + controller, you shouldn't need anything static to do your normal work of querying the database and returning data to the page.

Resources