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
Katie HambergKatie Hamberg 

Trigger on Custom Objects

I have two custom objects.  I want an auto task to be related to custom object 1 when the action occurs on object 2.  I'm new to writing triggers, any help would be much appreciated!
ShashForceShashForce
Hi,

Please provide as many details as possible regarding what you exactly need and I will provide you sample code.

Thanks,
Shashank
Katie HambergKatie Hamberg
Hi Shashank,

Thank you!  I'll try to be as descriptive as possible.  We have two custom objects, Object A and Object B.  Object B is a related list under Object A.  When a certain value is selected from a picklist on Object B, I want to have a task created, but have the task related to the record on Object A.  Does that make sense?

Thanks!
ShashForceShashForce
Yes it does, here's a sample:

trigger createtaskonobjectb on objectb__c (after insert, after update){
	set<Id> bIds = new set<Id>();
	list<task> tasks = new list<task>();
	for(objectb__c b:trigger.new){
		if(b.picklist_field__c=='certain value'){
			bIds.add(b.Id);
		}
	}
	for(objectb__c b2:[select objecta__c from from objectb__c where Id IN :bIds]){
		task t = new task();
		t.priority='some priority';
		t.status='some status';
		t.subject='some subject';
		t.whatId=b2.objecta__c;
		tasks.add(t);
	}
	if(tasks.size()>0){
		insert tasks;
	}
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
ShashForceShashForce
Typo: just remove the extra "from" in the select statement.
Katie HambergKatie Hamberg
This worked great!  Only other question I have is how do I have it assigned to a specific user and have the due date set to 'TODAY'?

Thanks
Katie HambergKatie Hamberg
I also just realized that I need to create a test class for this.  Any suggestions would be greatly appreciated.

Thanks!

Katie