Trigger to copy image from child record to parent record - triggers

I am trying to write a trigger that will update a RTA field on a parent object with an image from a RTA field on the child object.
I am getting the below error when creating the child object
Apex trigger Updateparent caused an unexpected exception, contact your administrator: Updateparent: execution of AfterInsert caused by: System.StringException: Invalid id: (.....IMAGE IS DISPLAYED HERE....)External entry point.
Info
Man Utd is the child object
Account is the parent object
Image__c is the RTA field on the child object
Copy_image__c is the RTA field on accounts
Here is the trigger code
trigger Updateparent on Man_Utd_1__c (after insert, after update) {
Map<ID, Account> parentAccounts = new Map<ID, Account>();
List<Id> listIds = new List<Id>();
for (Man_Utd_1__c childObj : Trigger.new) {
listIds.add(childObj.Image__c);
}
parentAccounts = new Map<Id, Account>([SELECT id, (SELECT ID, Image__c FROM Man_Utd_s__r) FROM Account WHERE ID IN :listIds]);
for (Man_Utd_1__c manu : Trigger.new) {
Account myParentAccounts = parentAccounts.get(manu.Image__c);
myParentAccounts.Copy_image__c = manu.Image__c;
}
update parentAccounts.values();
}
Can anyone advise on how to rectify this or if it is even possible to do?

EDIT to answer comments
This one works for me, there's a slight modification around the null check. Give it a go? The field is called Image__c both on Account and Contact.
trigger rollupImage on Contact (after insert, after update) {
Set<Account> parents = new Set<Account>();
for (Contact child : trigger.new) {
if(child.AccountId != null && child.Image__c != null){
parents.add(new Account(Id = child.AccountId, Image__c = child.Image__c));
}
}
if(!parents.isEmpty()){
List<Account> toUpdate = new List<Account>();
toUpdate.addAll(parents);
update toUpdate;
}
}
ORIGINAL
The error
It's all written there ;)
List<Id> listIds = new List<Id>();
for (Man_Utd_1__c childObj : Trigger.new) {
listIds.add(childObj.Image__c); // boom happens here?
}
You're assigning rich text area value (very long string with encoded image in it) to Id variable (15 or 18 char special string)
Try like this:
Set<Id> ids = new Set<Id>(); // Set will ensure we won't have duplicate values
for (Man_Utd_1__c childObj : Trigger.new) {
ids.add(childObj.Account__c);
}
Optimization - round 1
In the second loop you're setting the Copy_Image__c field but on the local copy of Account (local variable in the scope of the loop). I'm not sure setting it there will propagate the change to the parent acc (it might be a full copy and not a reference to the item in the map. You could put it back (parentAccounts.put(manu.Account__c, myParentAccounts)) to the map or just do the image assignment directly:
parentAccounts = new Map<Id, Account>([SELECT id FROM Account WHERE ID IN :ids]);
// I've removed the subquery, you don't need it, right?
for (Man_Utd_1__c manu : Trigger.new) {
if(parentAccounts.containsKey(manu.Account__c)){
parentAccounts.get(manu.Account__c).Copy_image__c = manu.Image__c;
}
}
update parentAccounts.values();
Optimization - round 2
It looks bit stupid - we query for Accounts but all we need to fetch is the Id... But we know the Id already, right? So - behold this "pro trick" (shared just because my colleague is a big fan of Man U ;))
trigger Updateparent on Man_Utd_1__c (after insert, after update) {
Set<Account> parents = new Set<Account>();
for (Man_Utd_1__c child : trigger.new) {
if(child.Account__c != null){
parents.add(new Account(Id = child.Account__c, Copy_Image__c = child.Image__c));
}
}
if(!parents.isEmpty()){
List<Account> toUpdate = new List<Account>();
toUpdate.addAll(parents);
update toUpdate;
}
}

Note: Optimization is the key thing while writing trigger.
While writing trigger make sure you follow all the best practises:
Keynotes On Trigger:
OPTIMIZATION - I have specified it in Uppercase and in first line because its the key thing while writing logic
Proper indentation and code commenting, so that anyone who works on the same code will easily understand the logic by just glancing on the comments. Make sure you update lastModifiedBy line on initial comments so that it will be helpful to keep a trace who worked last/updated last and on what date. Better keep proper code comments on every line- IF NEEDED ONLY
Variables with proper names ex: if var of list type then 'lst' prefix or 'List' postfix and then the proper name ex: lstContactsToInsert OR lstContactsToUpdate
Always create a seperate handler class and don't write all the logics on trigger itself 'AS A BEST PRACTISE TO FOLLOW'
Have proper trigger contexts. Know when to use proper trigger contexts through salesforce documentations on trigger. Use 'Before' contexts if it can be handled using this, If Not then go for 'After' contexts so you limit DML's.
Keynotes On Handler:
The First 3 steps as mentioned for trigger applies here as well
Use common private methods where you write logic and use it in other methods
Keynotes On TestClass:
Always write a test class utilizing 'GENERIC TEST DATA CLASS' in your test class.
Use proper test method names like: test_Method_One 'OR' testImageUpdates as such
Use asserts and test all usecases - Both negative and positive tests
#1. Trigger
/**
* #TriggerName : ContactTrigger
* #CreatedBy : Rajesh Kamath
* #CreatedOn : 30-Nov, 2016
* #Description : Trigger to update the image on parent object 'Account' based on the child object 'Contact'
* #LastModified: None
*/
trigger ContactTrigger on Contact(after insert, after update) {
//Instantiate the handler class
ContactTriggerHandler objContactHandler = new ContactTriggerHandler();
/* Trigger Context */
if(Trigger.isAfter) {
//Fire on Insert
if(Trigger.isInsert) {
objContactHandler.onAfterInsert(trigger.new);
}
//Fire on Update
if(Trigger.isUpdate) {
objContactHandler.onAfterUpdate(trigger.new, trigger.oldMap);
}
}
}
#2. Handler
/**
* #HandlerName : ContactTriggerHandler
* #TriggerName : ContactTrigger
* #TestClassName : ContactTriggerHandlerTest [Make sure you create this with the steps at the end of this handler]
* #CreatedBy : Rajesh Kamath
* #CreatedOn : 30-Nov, 2016
* #Description : Trigger to update the image on parent object 'Account' based on the child object 'Contact'
* #LastModified: None
*/
public with sharing class ContactTriggerHandler {
/*
#MethodName : onAfterInsert
#Parameters : List<Contact> lstNewContactRecords
#LastModifiedBy : None [Make sure when anyone updates even this line will be updated for help for other users who work on later phase]
*/
public void onAfterInsert(List<Contact> lstNewContactRecords){
//Call a common method where we have logic
reflectChildImageOnParent(lstNewContactRecords, null);
}
/*
#MethodName : onAfterUpdate
#Parameters : List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords
#LastModifiedBy : None [Make sure when anyone updates even this line will be updated for help for other users who work on later phase]
*/
public void onAfterUpdate(List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords){
//Call a common method where we have logic
reflectChildImageOnParent(lstContactRecords, mapOldContactRecords);
}
/*
#MethodName : reflectChildImageOnParent
#Parameters : List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords
#LastModifiedBy : None [Make sure when anyone updates even this line will be updated for help for other users who work on later phase]
*/
private static void reflectChildImageOnParent(List<Contact> lstContactRecords, Map<Id, Contact> mapOldContactRecords){
/* Local variable declaration */
List<Account> lstAccountsToUpdate = new List<Account>();
for(Contact objContact : lstContactRecords) {
//Execute on insert and update
if((Trigger.isInsert || (Trigger.isUpdate && objContact.Child_Image__c != mapOldContactRecords.get(objContact.Id).Child_Image__c)) && objContact.Account__c != null) {
//List of accounts to update
lstAccountsToUpdate.add(new Account(Id = objContact.Account__c, Parent_Image__c = objContact.Child_Image__c));
}
}
//Update the account records
if(!lstAccountsToUpdate.isEmpty()) {
update lstAccountsToUpdate;
}
}
}
This can be referred for your usecase.
Please mark as 'Best Answer' if this was helpful

loyalty - Child Obj
fields:
lightingdata__Contact__c (relationship)
lightingdata__imagenims__c // Image field
Contact - Parent Obj
field: lightingdata__Imagefromloyalty__c
trigger loyaltytocon on Loyalty__c (after insert, after update) {
Map<id, Contact> conlist;
List<Id> idlist=new List<id>();
for (Loyalty__c loy:trigger.new) {
idlist.add(loy.lightingdata__Contact__c);
}
conlist= new Map<id, contact>([select id, lightingdata__Imagefromloyalty__c from contact where id In : idlist]);
for(Loyalty__c lo:trigger.new){
contact con = conlist.get(lo.lightingdata__Contact__c) ;
system.debug('con data' + con);
con.lightingdata__Imagefromloyalty__c = lo.lightingdata__imagenims__c;
}
update conlist.values();
}
In pareant object field it will return that image filed have URL.
Then you can create one formula filed and just refer (lightingdata__Imagefromloyalty__c) in formul it will display the image.

Related

Salesforce Apex Trigger data copy from one field to other

This is my Apex Trigger in which I am taking data from Custom Field "Picklist Multiple" named(Opportunity_Picklist__c) in Opportunity and automatically paste it to a custom field "text" in Account. Now every selected option from Custom Field "Picklist Multiple" is coming to the custom field "text". I want to copy only Custom Field "Picklist Multiple" values with API Name "Premium" and "Basic". Other selected values can be avoided. Please look into the code below and suggest me relatable changes.
Custom Field "Picklist Multiple" have these data:-
Premium
Advanced
Basic
Free
If someone selected all four values in Custom Field "Picklist Multiple" they can remain as it is but I don't want all of them to be copied in custom field "text". I want the values with API Names "Premium" and "Basic" only in the custom field "text".
trigger OppTrigger on Opportunity (After insert,After update,After delete) {
if((Trigger.isInsert|| Trigger.isupdate|| Trigger.isDelete) && Trigger.isAfter)
{
Set<Id> acctSet = new Set<Id>();
List<Account> accList = new List<Account>();
for(Opportunity opp : Trigger.new)
{
acctSet.add(opp.AccountId);
}
Map<Id, Account> mapAccounts = new Map<Id, Account>([SELECT Id, Plan__c FROM Account where Id IN :acctSet]);
for(Opportunity opp : Trigger.new)
{
Account acc = mapAccounts.get(opp.AccountId);
If(Trigger.IsDelete){
acc.Plan__c = null;
}
if(Trigger.isInsert|| Trigger.isupdate){
acc.Plan__c = opp.Opportunity_Picklist__c;
}
accList.add(acc);
}
Update accList;
}
}
You'll be better off cutting it up a bit. Use a helper class as trigger handler. Will let you create some reusable functions rather than just a giant block of code executing top-down. There's this for general reading, I like that one but there are lots of examples, what you'll be comfortable with.
For example imagine a method called static void rollupToAccounts(Set<Id> ids). It'd accept account ids and you could call it from different scenarios (because you'll have different entry points. Insert is easy, base it on trigger.new, cool. Delete is funnier because there's no trigger.new, you need to get Account Ids out of trigger.old And after update if I move opportunity from Account A to B - your code should recalculate both! Good luck writing straight in the trigger's body.
As for actual "meat" of the method... many ways to do it, something like this?
static void rollupToAccounts(Set<Id> ids){
final Set<String> valuesToRollup = new Set<String>{'Premium', 'Basic'};
List<Account> toUpdate = new List<Account>();
List<Account> accounts = [SELECT Id, Plan__c,
(SELECT Opportunity_Picklist__c
FROM Opportunities
WHERE Opportunity_Picklist__c INCLUDES :valuesToRollup)
FROM Account WHERE Id IN :ids];
for(Account a : accounts){
Set<String> currentValues new Set<String>();
if(String.isNotBlank(a.Plan__c)){
currentValues.addAll(a.Plan__c.split(';'));
}
Set<String> newValues = new Set<String>();
if(!a.Opportunities.isEmpty()){
for(Opportunity o : a.Opportunities){
newValues.addAll(o.Opportunity_Picklist__c.split(';')); // this will include Advanced & Free too, it's ok, we'll fix it
}
newValues.retainAll(valuesToRollup); // filter out all the ones we don't want
}
System.debug('old: ' + currentValues + '; new: ' + newValues);
if(currentValues != newValues){
// we'll need to update this account with current data
List<String> temp = new List<String>(currentValues);
temp.sort();
a.Plan__c = String.join(temp, ';');
toUpdate.add(a);
}
}
System.debug(toUpdate);
update toUpdate;
}
It's not perfect. If you have 100 opportunities for same account with "Basic" it'll take them all and possibly waste query rows. You could do it as 2 (sub)queries, WHERE Opportunity_Picklist__c INCLUDES ('Basic') LIMIT 1 and then another query for Premium if you think it'd be a problem..
Why not just check the value of the opportunity picklist before saving it into the account value? You could write this code a little cleaner and more efficient. However, a simple solution is just to check if the values you want exist.
if(Trigger.isInsert|| Trigger.isupdate){
String strAccountPlan;
if(opp.Opportunity__PickList__c.Contains('Premium'){
strAccountPlan = 'Premium';
}
if(opp.Opportunity__PickList__c.Containt('Basic'){
if(String.isBlank(strAccountPlan){
strAccountPlan = 'Basic');
}
else{
strAccountPlan += ';Basic';
}
acc.Plan__c = strAccountPlan;
}

Clone Opportunity records with all the fields without using standard clone() method?

I have try to clone Opportunity records and done till 3 fix field But I need for all fields.But without using clone() method.
Code -
public class Cloningwithout {
public static void insertclone(){
Opportunity opp = new Opportunity(Name='Opportunity2', CloseDate=date.parse('06/07/2012'),StageName='Prospecting');
insert opp;
ID Oppid =opp.ID;
clone1(Oppid);
}
public static void clone1(String IDs){
Opportunity sourceopp = [SELECT Id,Name,CloseDate,StageName from Opportunity Where Id=:IDs];
Opportunity targertopp = new Opportunity();
targertopp.Name = sourceopp.Name;
targertopp.CloseDate = sourceopp.CloseDate;
targertopp.StageName = sourceopp.StageName;
insert targertopp;
} }
maximum trigger depth exceeded
Your trigger runs after Opportunity is inserted. It inserts new opportunity, which causes the trigger to run, which inserts new opportunity... Until about 16 recursive operations, then SF terminates your action. Using clone() or not has nothing to do with it.
What are you trying to do, insert just once and then skip the trigger? You could have helper checkbox on Opportunity or a static variable
trigger CloneTrigger on Opportunity (after insert) {
static Boolean skip = false;
if(!skip){
skip = true;
Opportunity[] ls=new Opportunity[]{};
for(Opportunity o: trigger.new){
Opportunity obj=new Opportunity();
// obj.id = null;
obj.name=o.name;
obj.CloseDate = o.CloseDate;
obj.StageName = o.StageName;
ls.add(obj);
}
insert ls;
}
}

Test Class in apex

So i am new to salesforce and i finished my training and now im working on a project. But on my project i have stumbled on a test class that i am not finding a way to write it, so i would appreciate if anyone can help me figure out a way to write it. Here is the code:
public class AP01_Opportunity
{
//Method to create a new service contract when opportunity = Gagné
public static void CreateContract(List<Opportunity> listOpp, Map<Id, Opportunity> oldMap)
{
//Variable Declaration
ServiceContract sc;
List<ServiceContract> listSCToAdd = new List<ServiceContract>();
List<ContractLineItem> listContractItems = new List<ContractLineItem>();
List<Opportunity> listOppGagne = new list<Opportunity>();
//Loop in list of opportunities
for(Opportunity opp : listOpp)
{
if(opp.StageName == Label.ClotureGagne && !oldMap.get(opp.Id).isWon)
{
listOppGagne.add(opp);
}
}
//check if list has opportunity becoming won
if(listOppGagne.size() > 0){
Map<Id, Opportunity> mapOppGagne = new Map<Id, Opportunity> ([SELECT Id,
Name,
StageName,
Pricebook2Id,
Account.Name,
(SELECT Id,
PricebookEntryId,
PricebookEntry.Name,
Quantity,
UnitPrice
FROM OpportunityLineItems)
FROM Opportunity
WHERE Id in :listOppGagne]);
for( Opportunity opp : listOppGagne )
{
//Create new service contract
sc = new ServiceContract();
sc.Name = opp.Name;
sc.ApprovalStatus = Label.Activated;
sc.OpportunityId__c = Id.valueOf(opp.Id);
sc.Pricebook2Id = opp.Pricebook2Id;
sc.StartDate = Date.today();
listSCToAdd.add(sc);
}
if(listSCToAdd.size() > 0){
insert listSCToAdd;
Opportunity currentOpp;
ContractLineItem cli;
Id oppId;
for(ServiceContract servcont : listSCToAdd)
{
oppId = servcont.OpportunityId__c;
if(mapOppGagne.containsKey(oppId))
{
currentOpp = mapOppGagne.get(oppId);
//copy the oppLineItems per opportunity to the respective Service Contract
for(OpportunityLineItem items : currentOpp.OpportunityLineItems)
{
cli = new ContractLineItem();
cli.PricebookEntryId = items.PricebookEntryId;
cli.Quantity = items.Quantity;
cli.UnitPrice = items.UnitPrice;
cli.ServiceContractId = servcont.Id;
listContractItems.add(cli);
}
}
}
if(listContractItems.size() > 0)
{
insert listContractItems;
}
}
}
}
}
this code is a trigger that creates a new service contract record with contract line items copied from the opportunity line items, when the opportunity stage changes to "Cloturé Gagné" which means closed won in french.
Thank you in advance.
In order to write a simple test class I would recommend you to use the following guide: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
The idea is simple: Lets say you create an Opportunity in your Test class and make an insert or update in your case - your trigger class will automatically fire and run the code from your AP01_Opportunity class. You can put some
System.debug('some message');
to check if your logic works as expected and also which code blocks are executed

Test class for trigger

I just wrote this trigger and it seems to be working fine in dev, I need to move it into production, however, the test class I wrote passes the test but does not cover the trigger. Any help would be greatly appreciated. I am a bit green here. I know I should be inserting a contact (the account is a req field) then updating the contact field I just have no earthly clue how to do taht. Thank you
trigger PropOwned on Contact (after update) {
for (Contact c : Trigger.new) {
McLabs2__Ownership__c ownNew = new McLabs2__Ownership__c();
Contact oldContact = Trigger.oldMap.get(c.id);
if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c && c.One_Prop_Owned__c != null) {
ownNew.McLabs2__Contact__c = c.id;
ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
insert ownNew;
}
}
}
This is the test class I wrote.
#isTest
public class TestOwnership {
static testMethod void createOwnership() {
McLabs2__Ownership__c ownNew = new McLabs2__Ownership__c();
ownNew.McLabs2__Contact__c = 'Michael Webb';
ownNew.McLabs2__Property__c = '131 West 33rd Street';
insert ownNew;
}
}
Your test class just creates a McLabs2__Ownership__c object and inserts this object in database. As a result of this trigger on McLabs2__Ownership__c(if exist) will be invoked, but you have to test a trigger on Contact object. Thus you need to insert an account and after that update it because your contact trigger works in after update mode.
So, you need something like that
#isTest
private class TestOwnership {
static testMethod void whenContactUpdatedNewOwnershipIsInserted() {
// create contact, you have to replace 'value1' with appropriate data type
Contact contact = new Contact(name = 'Test Contact', One_Prop_Owned__c = 'value1');
insert contact;
contact.One_Prop_Owned__c = 'value2'; // you have to replace value2 with appropriate data type
update contact;
// in this place you should has only one record of McLabs2__Ownership__c in database, because in test context real data isn't visible
List<McLabs2__Ownership__c> ownerships = [SELECT Id, McLabs2__Contact__c, McLabs2__Property__c FROM McLabs2__Ownership__c];
System.assertEquals(1, ownerships.size());
System.assertEquals(contact.Id, ownerships[0].McLabs2__Contact__c);
System.assertEquals(contact.One_Prop_Owned__c, ownerships[0].McLabs2__Property__c);
}
}
Read the following articles which might be pretty useful for you:
Apex Trigger best practice
SOQL in loop

Apex Trigger to Update Contact from Custom Object

Long story short, I need to update a custom field in my standard Contact, that fires after a different, unrelated Custom Object is updated. I've tried to write a trigger that passes the field value from my Custom Object to the Contact, but I keep getting a variety of errors - the most recent of which has stumped me. The end goal is to update Passing__c from Passing_Field__c.
I'm getting an unexpected Token: "(" error on the for(Contact C: line. It is literally so simple I cannot figure it out.
Here is my code below. I've simplified the naming convention to try and make it more relatable. Any help is appreciated. I'm pretty new to Apex and Triggers, and I've been at this for a couple of hours now, hopefully some advice can send me to 'home plate'.
trigger ContactUpdater on Custom_Object_Name__c (after update) {
List<Contact> updatedContacts = new List<Contact>();
Set<Id> ObjectIds = new Set<Id>();
Set<String> ObjectCont = new Set<String>();
Set<Boolean> ObjectActive = new Set<Boolean>();
Set<String> ObjectPass = new Set<String>();
for(Custom_Object_Name__c p : trigger.new)
{
If(p.Active__c == true){
ObjectIds.add(p.Id);
ObjectCont.add(p.Contact__c);
ObjectActive.add(p.Active__c);
ObjectPass.add(p.Passing_Field__c);
}
try{ for(Contact c : [SELECT Id, Passing__c FROM Contact WHERE (AccountId IN (Select Account__c from Custom_Object_Name__c )) AND ObjectActive = true])
{
set(c.Passing__c = p.Passing_Field__c);
c.FieldToUpdate = c.Passing__c;
updatedContacts.add(c);
}
update updatedContacts;
}
catch(exception e){
throw e;
}
}
}
Notes: Active__c is a checkbox. Passing__c and Passing_Field__c are both text boxes.
I believe the issue is in the WHERE clause of your SOQL query:
WHERE (AccountId = (Select Account__c from Custom_Object_Name__c ))
Salesforce is expecting you to compare AccountId to an Id of some sort, rather than the results of some subquery. You probably want to try something like:
WHERE (AccountId in (Select Account__c from Custom_Object_Name__c))