You need to sign in to do that
Don't have an account?
How can I match a field of parent in child records in a apex trigger
Please guide me as to where the problem might be. Any help is appreciated.
trigger repeatCase1 on Case (before insert,before update) {
List<Case> caseList = trigger.new;
Set<id> memberIdSet = new set<id>();
for(case c: caseList){
memberIdSet.add(c.Contact.Member_ID__c);
}
List<Case> allcase = [select Contact.Member_ID__c from case where contact.Member_ID__c IN: memberIdSet];
for(Case cs: caseList ){
for(Case all: allcase ){
if(cs.contact.Member_ID__c == all.contact.Member_ID__c ){
cs.Repeat_Caller__c=True;
}
}
}
}Challenge not yet complete... here's what's wrong: Could not find a customer object 'Offer__c'.
Best Answer chosen by Suzanne WasnerRemember, this module is meant for Lightning Experience. When you launch your hands-on org, switch to Lightning Experience to complete this challenge.
Please try the below steps:
1. You create new Trailhead Playground.
2. Click the Object Manager tab.
4. Click Create | Custom Object in the top right corner.
5. For Label, enter 'Offer'.
6. For Plural Label, enter 'Offers'.
7.Object Name 'Offer'.
8.Record Name 'Offer Name'.
9.Data type 'Auto Number'.
10.Display format 'OF-{0000}'.
11.string number 123.
12. Check the box for Launch New Custom Tab Wizard after saving this custom object.
13. Leave the rest of the values as default and click Save.
14. Select your desired Tab Style and click Next, Next, and Save.
15. Then goto Fields & Relationships in 'Offer' object and click 'New' button in top right corner.
16. In data type select Currency and click next.
17. For Label, enter 'Offer Amount'.
18. Select your desired Tab Style and click Next, Next, and Save.
19. In data type select Date and click next.
20. For Label, enter 'Target Close Date'.
21. Select your desired Tab Style and click Next, Next, and Save.
Please let me know if you have any query.
Please mark it as best Answer if you find it helpful.
Thank You
Ajay Dubedi
Nested table using apex:pageBlockTable, possible?
Hi, is it possible to create nested table on apex page using pageBlockTable or other tags?
I got an erreor: Save error: Object type not accessible. Please check permissions and make sure the object is not in development mode: SOQL statements cannot query aggregate relationships more than 1 level away from the root entity object. RequestAsPDF.page.
Using <apex:column breakbefore> and a controller extention could fill the child table content in a new row.
But is there anything already there to use? Thanks.
Best Answer chosen by Admin (Salesforce Developers) 
You can not do this:
<apex:page standardController="Account">
<apex:pageBlock>
<apex:pageBlockTable value="{!Account.Contacts}" var="theContact">
<apex:column>
{!theContact.FirstName} {!theContact.LastName}
</apex:column>
<apex:column>
<apex:pageBlock>
<apex:pageBlockTable value="{!theContact.ActivityHistories}" var="theActivity">
{!theActivity.Subject}
</apex:pageBlockTable>
</apex:pageBlock>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
When the page is compiled, it generates a SOQL query that looks like this:
SELECT Id,
(SELECT Id,FirstName,LastName,
(SELECT Id,Subject FROM ActivityHistories)
FROM Contacts)
FROM Account
This isn't a legal syntax (you can't query more than one level down). Instead, you need to query the data in a controller or extension and then expose the data that way.
Edit: Clarification. The point here is that you can't use something that will be dynamically generating a query in this case. Ideally, you'd do something like this:
public class account_wrapper {
public account record { get; set; }
public list<contact_wrapper> contacts { get; set; }
}
public class contact_wrapper {
public contact record { get; set; }
public list<activity_wrapper> activities { get; set; }
}
public class activity_wrapper {
public activityhistory record { get; set; }
}
Elsewhere in your controller, call the necessary recursive queries to get all the data you need to populate this structure.
Finally, in your VF page, you can nest the tags recursively, as what you were originally trying to do; the syntax will be slightly different, obviously, because now you have a class that wraps the values in a way that can be fed to the pageBlockTable tag.
Build Automated Metadata Updates for Multi-Org Deployment
Challenge Not yet complete... here's what's wrong:
Couldn't find newField.behavior set to 'Metadata.UiBehavior.Edit', or newField.field set to 'AMAPI__Apex_MD_API_Twitter_name__c' or method doesn't return 'layoutMetadata'. Please double-check the instructions
Everything looks right to me in the class. I can't use the namespace they provide because it's already taken. Earlier in the exercise, it tells you to use your own namespace which I've done. Can anyone see what's wrong?
public class UpdateContactPageLayout {
// Add custom field to page layout
public Metadata.Layout addLayoutItem () {
// Retrieve Contact layout and section
List<Metadata.Metadata> layoutsList =
Metadata.Operations.retrieve(Metadata.MetadataType.Layout,
new List<String> {'Contact-Contact Layout'});
Metadata.Layout layoutMetadata = (Metadata.Layout) layoutsList.get(0);
Metadata.LayoutSection contactLayoutSection = null;
List<Metadata.LayoutSection> layoutSections = layoutMetadata.layoutSections;
for (Metadata.LayoutSection section : layoutSections) {
if (System.equals(section.label, 'Additional Information')) {
contactLayoutSection = section;
break;
}
}
// Add the field under Contact info section in the left column
List<Metadata.LayoutColumn> contactColumns = contactLayoutSection.layoutColumns;
List<Metadata.LayoutItem> contactLayoutItems = contactColumns.get(0).layoutItems;
// Create a new layout item for the custom field
Metadata.LayoutItem newField = new Metadata.LayoutItem();
newField.behavior = Metadata.UiBehavior.Edit;
newField.field = 'BOBN_TRAILHEAD__Apex_MD_API_Twitter_name__c';
contactLayoutItems.add(newField);
return layoutMetadata;
}
}
Best Answer chosen by bobnunny1newField.field = 'AMAPI__Apex_MD_API_Twitter_name__c';
Challenge completed for me.
System.NullPointerException: Attempt to de-reference a null obj
The error that I get back after inputting is
Visualforce Error
Help for this Page
System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!insertChild}' in component <apex:commandButton> in page updatechild: Class.AddingChildController.insertChild: line 23, column 1
This is the VF page
<apex:page controller="AddingChildController" >
<apex:form >
<apex:variable var="rowNum" value="{!0}" />
<apex:pageBlock >
<apex:variable var="rowNum" value="{!0}" />
<apex:PageBlockTable value="{!childList}" var="int">
<apex:facet name="footer">
<apex:commandLink value="Add" action="{!insertRow}"/>
</apex:facet>
<apex:column headerValue="Lead Generator">
<apex:inputField value="{!int.Lead_Gen__c}"/>
</apex:column>
<apex:column headerValue="Monday">
<apex:inputField value="{!int.Monday__c}"/>
</apex:column>
<apex:column headerValue="Tuesday">
<apex:inputField value="{!int.Tuesday__c}"/>
</apex:column>
<apex:column headerValue="Wednesday">
<apex:inputField value="{!int.Wednesday__c}"/>
</apex:column>
<apex:column headerValue="Thursday">
<apex:inputField value="{!int.Thursday__c}"/>
</apex:column>
<apex:column headerValue="Friday">
<apex:inputField value="{!int.Friday__c}"/>
</apex:column>
<apex:column headerValue="Delete">
<apex:commandLink style="font-size:15px; font-weight:bold; text-align:center;color:red;" value="X" action="{!delRow}">
<apex:param value="{!rowNum}" name="index"/>
</apex:commandLink>
<apex:variable var="rowNum" value="{!rowNum+1}"/>
</apex:column>
</apex:PageBlockTable>
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!insertChild}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
And this is the controller
public class AddingChildController {
Id parentId;
public List<Time_Sheets__c> childList {get;set;}
public Integer rowNum{get;set;}
public Lead_Gen__c Parent {get;set;}
public AddingChildController(){
Id childId = ApexPages.currentPage().getParameters().get('childId');
childList = new List<Time_Sheets__c>();
childList.add(new Time_Sheets__c());
ParentId=ApexPages.currentPage().getParameters().get('ParentId');
}
public pagereference insertChild(){
insert childList;
Parent.Id=parentId;
update Parent;
Pagereference page=new pagereference('/'+parentId);
Return page;
}
public void insertRow(){
childList.add(new Time_Sheets__c());
}
public void delRow(){
rowNum =
Integer.valueof(apexpages.currentpage().getparameters().get('index'));
childList.remove(rowNum);
}
}
Could someone assist with what I am missing
cheers
Best Answer chosen by Derek Dolan
Khan Anas (Salesforce Developers) 
Greetings to you!
This error occurs when your variable (sObject, List, Set or any other data type) is not initialized (allocated memory). In order to use the non-primitive data type in the code, we need to initialize the memory first. If we don’t do that it may result in Attempt to de-reference a null object error.
For Example, if you use like this:
Account acc; acc.Name = 'Khan';
It will result in attempt to de-reference a null object error.
We should use it like this:
Account acc = new Account(); acc.Name = 'Khan';
Reference: http://www.sfdcpoint.com/salesforce/system-nullpointerexception-attempt-to-de-reference-a-null-object/
In your code, you need to initialize the Parent in the constructor:
Parent = new Account();
Please try below code:
public class AddingChildController {
Id parentId;
public List<Time_Sheets__c> childList {get;set;}
public Integer rowNum{get;set;}
public Lead_Gen__c Parent {get;set;}
public AddingChildController(){
Parent = new Account();
Id childId = ApexPages.currentPage().getParameters().get('childId');
childList = new List<Time_Sheets__c>();
childList.add(new Time_Sheets__c());
ParentId=ApexPages.currentPage().getParameters().get('ParentId');
}
public pagereference insertChild(){
insert childList;
Parent.Id=parentId;
update Parent;
Pagereference page=new pagereference('/'+parentId);
Return page;
}
public void insertRow(){
childList.add(new Time_Sheets__c());
}
public void delRow(){
rowNum =
Integer.valueof(apexpages.currentpage().getparameters().get('index'));
childList.remove(rowNum);
}
}
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.
Thanks and Regards,
Khan Anas
User Mode and system Mode
I have some difficulty in understanding the following
a) Normally apex code & trigger run in system.context
But How to make the apex code execute in USER Mode?
if the apex code executing in USER Mode is called by a trigger, will the trigger also execute in USER Mode?
b) Can a visual force page run in USER Mode instead of system.context , again what changes need to be done and why?
c) By default webservice classes written in apex , rest api execute in what Mode?
d) what is the use of system.RunAs with respect to the above.
I hope I am clear
Thanks
Vandana R
Best Answer chosen by vandana rajuSystem mode -
- System mode is nothing but running apex code by ignoring user's permissions. For example, logged in user does not have create permission but he/she is able to create a record.
- In system mode, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren't applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user.
- In Salesforce, all apex code run in system mode. It ignores user's permissions. Only exception is anonymous blocks like developer console and standard controllers. Even runAs() method doesn't enforce user permissions or field-level permissions, it only enforces record sharing.
- User mode is nothing but running apex code by respecting user's permissions and sharing of records. For example, logged in user does not have create permission and so he/she is not able to create a record.
- In Salesforce, only standard controllers and anonymous blocks like developer console run in user mode.
Navin Soni
Lead assignment rules help. Apex trigger maybe?
Hi,
We have a 3rd party webserivce that send leads from our site to SF with Lead Owner already assigned based on some coded rules. We now want to add a level of lead assignment above what this can handle, so I wrote a lead assignment rule and have activated it.
The rules seem to be completley ignored as leads are coming in, but work if a lead is edited and saved ticking the "use active assignmnet rules" checkbox. (i.e the lead assignment crieria works, but its not being triggered)
So I thought a trigger to re-run lead assignment directly after a lead has been created would be the only solution, issue is I have no coding experience (aside from one easy update trigger some guys on here helped with!)
Can anyone help? Or if another solution exists that woudl be great too!
Antony
Best Answer chosen by Admin (Salesforce Developers) 
You could use the AssignmentRuleHeader in an Apex trigger, as in this post:
http://salesforce.stackexchange.com/questions/13651/lead-assignment-rule-in-a-trigger
I assume you'll only want to reassign leads that came from your website, so you'll need a way to check that in your trigger. Assuming these leads have a source of "website", and drawing off of the example above, you could write something like
trigger LeadTrigger on Lead (after insert) {
List<Lead> ls = new List<Lead>();
for (Lead l : Trigger.new) {
if (l.LeadSource = 'Website') {
ls.add(new Lead(id = l.id));
}
}
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
Database.update(ls, dmo);
}If you're able to modify the code that is sending the leads from your site to Salesforce, you could set the AssignmentRuleHeader from that end as well.
Help for test class coverage
I have developed an apex class whcih basically assign users to queue dynamically.I have a VF page which will launch from a custom VF tab.This VF page shows few users and with the checkbox.When checkbox against the username is marked and hit Save button then seleected users will go to the queue defined in class.
Below is my clas:
public class TodayTelesalesDetails {
public Date Today {
get {
return Date.today();
}
}
public List<wrapAgent> wrapAgentList{get; set;}
public List<User> selectedAgents{get;set;}
public TodayTelesalesDetails (){
if(wrapAgentList == null) {
wrapAgentList = new List<wrapAgent>();
for(User teleSalesAgent: [select Id, Name, Email from User where Name IN('Steve Waugh','Yuvraj Singh')]) {
// As each agent is processed we create a new wrap object and add it to the wrapAgentList
wrapAgentList.add(new wrapAgent(teleSalesAgent));
}
}
}
public PageReference doFullSave(){
set<id> userSetId = new set<id>();
list<GroupMember> gmm = new list<GroupMember>();
List<GroupMember> toBeDeleted= [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = '00G9D000000toPYUAY'];
delete toBeDeleted;
List<User> userlist=[select Id, Name from User where Name IN('Steve Waugh','Yuvraj Singh')];
for(User u : userlist)
{
system.debug('message3>>'+u);
for(wrapAgent wrapAccountObj : wrapAgentList) {
if(wrapAccountObj.selected == true) {
userSetId.add(wrapAccountObj.teleAgent.id);
}
}
}
for(User us : [select id from User where id =: userSetId])
{
for(Group gg : [select id,name from Group where type = 'Queue' and Name = 'TeleSales Queue'])
{
GroupMember gm = new GroupMember();
gm.groupId = gg.id;
gm.UserOrGroupId = us.Id;
gmm.add(gm);
}
}
insert gmm;
PageReference pageRef = new PageReference('/');
pageRef.setRedirect(true);
return pageRef;
}
public PageReference doCancel(){
PageReference pageRef = new PageReference('/');
pageRef.setRedirect(true);
return pageRef;
}
public class wrapAgent{
public User teleAgent {get; set;}//Please put the custom metadata names
public Boolean selected {get; set;}
//This is the contructor method. When we create a new object we pass a telesales metadata member that is set to the acc property. We also set the selected value to false
public wrapAgent(User teleSalesAgent) {
teleAgent = teleSalesAgent;
selected = false;
}
}
}
and below is my test class:
@isTest
public class Test_TodayTeleSalesDetails {
public static testMethod void validateusersinqueue() {
Group testGroup = new Group(Name='test group', Type='Queue');
insert testGroup;
System.runAs(new User(Id=UserInfo.getUserId()))
{
QueuesObject testQueue = new QueueSObject(QueueID = testGroup.id, SObjectType = 'Lead');
insert testQueue;
}
Test.startTest();
TodayTelesalesDetails telesalesDetails=new TodayTelesalesDetails();
telesalesDetails.doFullSave();
telesalesDetails.doCancel();
Test.stopTest();
}
}
I am not able to cover below lines of code:
for(User us : [select id from User where id =: userSetId])
{
system.debug('message6>>'+us);
for(Group gg : [select id,name from Group where type = 'Queue' and Name = 'TeleSales Queue'])
{
GroupMember gm = new GroupMember();
gm.groupId = gg.id;
gm.UserOrGroupId = us.Id;
gmm.add(gm);
}
}
Below is the screenshot for the same:My current code coverage stands at 73%
Many I request to help me on same to get a code coverage above 75%
Many thanks in advance
Thanks & Regards,
Harjeet
Best Answer chosen by Harjeet Singh 28If you want to keep "selected" of wrapAgent as false and want to increase your code coverage then you can use Test.isRunningtest() in your code. You can update your code as below:
for(User u : userlist)
{
system.debug('message3>>'+u);
for(wrapAgent wrapAccountObj : wrapAgentList) {
if(!Test.isRunningTest()){
if(wrapAccountObj.selected == true) {
userSetId.add(wrapAccountObj.teleAgent.id);
}
}else{
userSetId.add(wrapAccountObj.teleAgent.id);
}
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
Trigger to update lead status when activity is logged
trigger changeLeadStatus on Task (before insert, before update) {
String desiredNewLeadStatus = 'Working';
List<Id> leadIds=new List<Id>();
for(Task t:trigger.new){
if(t.Status=='Completed'){
if(String.valueOf(t.whoId).startsWith('00Q')==TRUE){//check if the task is associated with a lead
leadIds.add(t.whoId);
}//if 2
}//if 1
}//for
List<Lead> leadsToUpdate=[SELECT Id, Status FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
For (Lead l:leadsToUpdate){
l.Status=desiredNewLeadStatus;
}//for
try{
update leadsToUpdate;
}catch(DMLException e){
system.debug('Leads were not all properly updated. Error: '+e);
}
}//trigger
Best Answer chosen by Marvin Castro 8You need to create the same trigger on the Event Object. Events and Tasks are both activities, but they are separate objects (They are special in that way). You already have the code, just copy it for Events and you should be good!
Hope this helps!
The process did not set the correct Type value on submitting for approval
Challenge not yet complete... here's what's wrong:
The process did not set the correct Type value on submitting for approval
I'm not sure why it isn't approving. Please help!
Best Answer chosen by Brock NortonHere is mine version of that Approval process which worked perfectly.
You will notice that in Approval steps I don't have any rejection step which is marked as red bold in your Approval process. remove that criteria and it should work.
Thanks,
Himanshu

Apex Code Development
if(Trigger.isBefore && Trigger.isInsert) { // Get the list of Cases from trigger.new List<Case> caseList = trigger.new; // Get a set of Contact Ids that will be used for queries Set<Id> contactIds = new Set<Id>(); for(case c: caseList){ // For each case from the trigger, add its Contact Id to the set contactIds.add(c.ContactId); } // Now, get a list of cases that would look up to the same Contact (and safety check to make sure its Member Id field is not null) List<Case> allcase = [select Id, ContactId, Contact.Member_Id__c from case WHERE ContactId IN :contactIds AND Contact.Member_Id__c != null]; // Grab a Map of Contacts that are looked up to by the trigger Cases Map<Id,Contact> conMap = new Map<Id,Contact>([SELECT Id, Name, Member_Id__c FROM Contact WHERE Id IN :contactIds AND Contact.Member_Id__c != null]); for(Case cs: caseList ){ for(Case all: allcase ){ // For the trigger Case, grab the Contact Member Id field from the Map and compare with the Case already existing if(conMap.get(cs.ContactId).Member_Id__c == all.Contact.Member_Id__c ){ // If there is a match, then set the field to true cs.Repeat_Caller__c=True; } } } }