function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sree sfdcsree sfdc 

write trigger for contact object custom field primary of type checkbox

hi friends ,
pls help me to write following trigger
here contact is having custom field primary of type checkbox
● Each account may have multiple contacts but only one marked “Primary”
● Each account must have 1 primary contact.
● The account should display the name of its primary contact on the account detail screen (i.e. in a field).

pls help me
Best Answer chosen by sree sfdc
Vidhyasagaran MuralidharanVidhyasagaran Muralidharan
Consideration:
accountname is field in contact object.
Contact name is field in account object.
Primary contact checkboxfield in account object.
primary or secondary field named as "con"custom field.
code:
trigger contactupdate on contact_c(after insert){
List<contact> c1 =new List<contact>();
For (Account a:trigger.new)
{
if(a.PrimaryContact_Checkbox==true || a.PrimaryContact_Checkbox==false)
{
List<contact> c =[select accountname from contact where c.accountname=a.accountname];
if(c.size()>0)
{
c1.con='secondary';
}
else
{
c1.con='primary';
}
}
c1.accountname=a.accountname;
c1.contactname=a.contactname;
\\some other fields you need
}
database.insert (c1);
}
try to change according to your requirement

All Answers

Vidhyasagaran MuralidharanVidhyasagaran Muralidharan
Can you brief you requirement.

Like you mean there are two object like account and contact.if you are entering the details in account object .There is checkbox with the name primary if you check and insert a record.in account a contact  record has to be created if it is first record then in a filed it will mark as primary and if you enter a second  record for same account even if you check the primary it should insert in contact object as secondary.whether my understanding is correct
sree sfdcsree sfdc
hi muralidaran,
thank u for quick rply

your analysis is correct.
Vidhyasagaran MuralidharanVidhyasagaran Muralidharan
Consideration:
accountname is field in contact object.
Contact name is field in account object.
Primary contact checkboxfield in account object.
primary or secondary field named as "con"custom field.
code:
trigger contactupdate on contact_c(after insert){
List<contact> c1 =new List<contact>();
For (Account a:trigger.new)
{
if(a.PrimaryContact_Checkbox==true || a.PrimaryContact_Checkbox==false)
{
List<contact> c =[select accountname from contact where c.accountname=a.accountname];
if(c.size()>0)
{
c1.con='secondary';
}
else
{
c1.con='primary';
}
}
c1.accountname=a.accountname;
c1.contactname=a.contactname;
\\some other fields you need
}
database.insert (c1);
}
try to change according to your requirement
This was selected as the best answer
Sakthi RSakthi R
Is it a adviced one to write query inside for loop
Vidhyasagaran Muralidharan ??