• brielea1984
  • NEWBIE
  • 65 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 27
    Questions
  • 32
    Replies
On a Visualforce Page, I have a section which is collapsible by default and I use Javascript to toggle it
 
<script type="text/javascript">
    
    $(document).ready(function(){ 
        collapseSections();
        
    });
    
    function collapseSections(){
        $('img[id*="additionalProducts"]').each(function() {
            twistSection(this);
        });
    } 
</script>

<!--Some Code-->

<apex:pageBlockSection title="Service Products" id="additionalProducts" showheader="true" collapsible="true" columns="1">

<!--Some Code-->

The issue I'm having is should the user try to save, and a validation rule is flagged, when the page rerenders the section is collapsed again. I want the section collapsed on the initial page load, but if the user toggles the section down, saves, and hits a validation rule, I'd like the section to remain "uncollapsed".

Any ideas? I have a controller I can add code too as well if needed.

Thanks!
So I've implemented many many time the use case of for X Parent record, add multiple children on one page with an add/delete button as seen here: http://michaelwelburn.com/2013/10/21/how-to-create-a-reusable-editable-table-in-visualforce/

Is it possible to create this table in a loop for multiple parents?

As in, in my controller I have a SOQL query to return a list of Opportunities based on a condition, ex: [SELECT Name FROM Opportunity WHERE .....]
I want, for each Opportunity returned in the query, to display the list of opportunities. Then for each Opportunity, render an add/delete button to add/delete child records for that Opportunity.

Should appear like, on a visualforce page for the Account Object:
Opportunity 1 +/- (output)
     + Custom Object Record 1 (input)
     + Custom Object Record 2 (input)
Opportunity 2 +/-
    + Custom Object Record 3
Opportunity 3 +/-
     + Custom Object Record 4
     + Custom Object Record 5
and so on...
                       Save All Custom Object Records

Opportunity lookup on Custom Object Record saved with the Opportunity Id above them in the hierarchy in the table.

I tried creating a table with repeat values to list the "Opportunities", and then in the next table row add the code for adding a child record. This simply duplicates the same list, so when I click "add row", a row is added in table rows for that process. The button has the same value every time it's repeated, so I'm not sure how to dynamically assign a button value since the add button will appear X number of times. 

I know apps like Grid Buddy can achieve this, but this needs to be built natively.

If anyone can point me to any examples of this successfully implemented I'd be much appreciative. Barring that, any pointers would be awesome. 

Thanks!
I had this working the other day, then yesterday I erased my work thinking the client wanted something else (rookie mistake). Now I need to put it back and I can't get it to work! I think my brain got its wires crossed in the last two days...

Scenario:
  • Visualforce page for the Order object
  • On the page, created a list with checkboxes displaying the names of the Assets related the the same Account as the Order
  • On save, upsert the Order with values in the Order form and for each selected Asset in the list, I am trying to create a record passing info from the Asset
What's happening:
  • Doesn't seem to be looping through all selected checkboxes. Looking at the debug logs, only one checkbox is ever picked up.
Visualforce Page:
<apex:page standardController="Order" showHeader="false" sidebar="false" extensions="TestExtension">   

    <apex:form id="theForm">
        <apex:pageBlock title="Service Request">
            <apex:pageBlockButtons location="both">
                <apex:commandButton action="{!processSelected}" value="Continue"/>                        
            </apex:pageBlockButtons>
            
            <apex:pageBlockSection >
                <apex:inputField value="{!Order.BillToContactId}"/>
                <apex:outputField value="{!Order.OwnerId}"/>      
                <apex:inputField value="{!Order.Service_initiated_By__c}" style="width: 150px;"/>                
                <apex:outputField value="{!Order.Account.Name}"/>
                <apex:inputField value="{!Order.Description}" label="Problem Description"/>
                <apex:outputField value="{!Order.Sold_Order__c}"/>                                                
            </apex:pageBlockSection>
            
   <!--THIS IS THE DATA TABLE I'M WORKING WITH  -->    
   <apex:pageBlockSection title="Select Installed Products" columns="1">
                <apex:pageBlockTable value="{!assets}" var="a" id="table" width="1000px;" >
                    <apex:column >
                        <!-- This is our selected Boolean property in our wrapper class -->
                        <apex:inputCheckbox value="{!a.selected}"/>
                    </apex:column>
                    <apex:column value="{!a.asset.Name}"/>
                    <apex:column value="{!a.asset.Original_Order_Variant_Number__c}"/>
                    <apex:column value="{!a.asset.Install_Date__c}"/>
                    <apex:column value="{!a.asset.Location_Details__c}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            
        </apex:pageBlock>
    </apex:form>   
</apex:page>
Apex Code: 
public with sharing class TestExtension {
    
    private final Order o;
    public List<aAsset> assetList {get; set;} 
    
    public TestExtension(ApexPages.StandardController stdController) {
        this.o = (Order)stdController.getRecord();       
    }
    
       
    public List<aAsset> getAssets() {
        if(assetList == null) {
            assetList = new List<aAsset>();
            for(Asset a: [SELECT Id, Name, Product2Id, Original_Order_Variant_Number__c, Install_Date__c, Location_Details__c FROM Asset WHERE AccountId = :o.AccountId]) {
                
                assetList.add(new aAsset(a));
            }
        }
        return assetList;
    }
    
<!--This is where I'm saving and trying to insert. I know I'm missing something obvious in making sure it loops through everything-->

    public PageReference processSelected() {
        
        try{    
            List<Asset> selectedAssets = new List<Asset>();
            
            for(aAsset aAsst: getAssets()) {
                if(aAsst.selected == true) {
                    selectedAssets.add(aAsst.asset);
                }
            }
            
            System.debug('These are the selected Assets...');
            for(Asset asset: selectedAssets) {
                system.debug(asset);
                
                Service_Request_Configuration__c src = new Service_Request_Configuration__c ();
                
                src.Account__c = o.AccountId;
                src.Installed_Product_Asset__c = asset.Id;
                src.Installed_Product__c = asset.Product2Id;
                src.Order__c = o.id;
                
                insert src; 
                
                o.Service_Type__c = propPickValSelected;
                upsert o;
                
                PageReference pageRef = new PageReference('/apex/RMS_createServiceOrder4?id='+ o.Id + '&retUrl=' + o.Id);
                pageRef.setRedirect(true);
                return pageRef;
            }
        }
        catch(Exception ex){
            ApexPages.addMessages(ex);
        }
        return null;
    }
    
    public class aAsset {
        public Asset asset {get; set;}
        public Boolean selected {get; set;}

        public aAsset(Asset a) {
            asset = a;
            selected = false;
        }
    }
}

Like I commented in the code, I'm fairly certain it's something obvious and simple I'm missing to get it looping through properly, but I have been staring at it too long and it's not jumping at me anymore. Any help would be much appreciated!

Thanks!

 
I'm open to using either a trigger or Flow. I've been trying to do it as a Flow, but I'm getting stuck on getting it to loop through everything and can only get it to create a Demographic for the first Qualification in the list. I'm sure it's something in how to set the Loop and Assign. But I'm more familiar with Apex triggers, so I'm happy to go back to that.

This scenario uses 3 objects: Opportunity, Qualification, and Demographic. 
  • Qualifications have a picklist field called Default_Country__c
  • On Opportunities, the user selects their country from a picklist field Country__c
  • Demographics have a lookup to both Qualification and Opportunity.
I want when an Opportunity is created, for any Qualifications where Default_Country__c matches the Opportunity__c, a Demographic is created. My brain is a bit fried on this so I could use a bit of guidance. 

Thanks!
Need to route the user to a visualforce page for creating multiple child records on save of parent record.

Summary
  • Three objects involved: Opportunity, Demographic, and Quota. 
  • One Opportunity has Many Demographics
  • One Demographic has Many Quotas
  • I've created a visualforce page where I add many Quotas to the Demographic at once. Currently this is launched from a custom button on the Demographic Detail Page.
    • Page Name = addQuotas
    • Page has a standard "add row"/"delete row" function to create a Quota record each row from custom controller
    • I pass multipe details from the parent Demographic onto each Quota row through an extension
  • I've created a visualforce page to override the standard new/edit Demographic layout so I can build a custom save button to route to the addQuotas page.
    • Page Name = addDemographic, uses a standard controller, no extensions at the moment
Question
What I want to have happen is when saving the Demographic, the user is immediately taken to the addQuotas page as if they had clicked the button on the detail page. I'm having difficulty making any of this work, trying custom buttons from the Opportunity and hacking the SaveURL, and I'm just not having luck saving the Demographic, grabbing the Id of that Demographic, and then going to the addQuotas page with that Demographic Id in tow. 

What do I add to the Save action on the addDemographic visualforce page to then route to the addQuotas page for THAT Demographic?

Basically, I want on Save of Demographic to automatically go here: /apex/addQuotas?id={!Demographic__c.Id}&retURL={!Demographic__c.Id}

Code and Pictures:
addDemographic page
<apex:page standardController="Demographic__c" tabStyle="Demographic__c">
     <apex:sectionHeader title="Edit Demographic" subtitle="New Demographic"/>
        <apex:form >
                <apex:pageBlock title="Edit Demograhic" mode="edit">
                    <apex:pageblockButtons >
                        <apex:commandButton action="{!save}" value="Add Quotas"/>
                    </apex:pageblockButtons>
                    <apex:pageblockSection title="Demographic Information" columns="1">
                        <apex:inputfield value="{!Demographic__c.Opportunity__c}"/>
                        <apex:inputfield value="{!Demographic__c.Qualification__c}"/>
                    </apex:pageblockSection> 
                </apex:pageBlock>
        </apex:form>

</apex:page>

addQuotas page:
<apex:page standardController="Demographic__c"
            extensions="EditableQuotaListExtension"
            showHeader="true" 
            sidebar="false"
            title="Edit Quota">
    <apex:form >
    <apex:pageMessages id="messages"/>
    <apex:pageBlock title="Edit Quotas">
      <apex:pageBlockButtons >
        <apex:commandButton value="Cancel" action="{!cancel}" />
        <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="Demographic Information" collapsible="false">
      <apex:outputLink value="/{!Demographic__c.Id}" target="_blank">{!Demographic__c.Name}</apex:outputLink>
        <apex:pageBlockSectionItem >
          <apex:outputText value="{!Demographic__c.QualificationName__c}" />
          <apex:outputText value="{!Demographic__c.Qualification_Text__c}" />
        </apex:pageBlockSectionItem>
      </apex:pageBlockSection>
      <apex:pageBlockSection id="childList" columns="1" title="Quotas" collapsible="false">
        <apex:variable var="rowNum" value="{!ZERO}" />
        <apex:outputLabel value="No Quotas currently exist. Click below to Add." rendered="{!NOT(hasChildren)}"/>
        <apex:pageBlockTable value="{!children}" var="quota" rendered="{!hasChildren}">
        <apex:column headerValue="Condition">
          <apex:inputField value="{!quota.Condition__c}"/>
        </apex:column>
        <apex:column headerValue="Option">
          <apex:inputField value="{!quota.Condition_Option__c}"/>
        </apex:column>
        <apex:column headerValue="Description">
          <apex:inputField value="{!quota.Description__c}"/>
        </apex:column>
        <apex:column headerValue="Quota Amount">
          <apex:inputField value="{!quota.Quota_Amount__c}" />
        </apex:column>        
        <apex:column headerValue="%/#">
          <apex:inputField value="{!quota.Quota_Calculation_Type__c}"/>
        </apex:column>
        <apex:column headerValue="Demographic">
          <apex:inputField value="{!quota.Demographic__c}"/>
        </apex:column>
        <apex:column headerValue="Qualification">
          <apex:inputField value="{!quota.Qualification__c}"/>
        </apex:column>
          <apex:column headerValue=" ">
            <!-- This is the second half of the trick to keep track
                  of your row index for deletion. -->
            <apex:variable var="rowNum" value="{!rowNum + 1}" />
            <apex:commandLink value="Delete" action="{!removeFromList}" rerender="childList, messages" immediate="true">
              <apex:param name="removeIndex" assignTo="{!removeIndex}" value="{!rowNum}" />
            </apex:commandLink>
          </apex:column>
        </apex:pageBlockTable>
        <apex:commandButton value="Add Quota" action="{!addToList}" rerender="childList, messages" immediate="true" />
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

addQuotas Extenstion (grabbing details from Demographic parent):
public with sharing class EditableQuotaListExtension extends EditableQuotaList
{


 public Demographic__c mydemo {get; private set;}

  public EditableQuotaListExtension(ApexPages.StandardController stdController) 
  {
    super(stdController);

    this.mydemo = [SELECT Id,
                              Name,
                                Qualification__r.Name
                            FROM Demographic__c
                            WHERE Id =: stdController.getRecord().Id];
    
    this.childList = [SELECT Id,
                          Condition__c,
                          Description__c,
                          Quota_Amount__c,
                          Quota_Calculation_Type__c,
                          Condition_Option__c,
                          Qualification__c,
                          Demographic__c
                      FROM Quota__c
                      WHERE Demographic__c =: mysObject.Id];
  }

  /*
   * This method is necessary for reference on the Visualforce page, 
   * in order to reference non-standard fields.
   */
  public List<Quota__c> getChildren()
  {
    return (List<Quota__c>)childList;
  }


  public override sObject initChildRecord()
  {
    Quota__c child = new Quota__c();
    child.Demographic__c = mydemo.Id;
    child.Qualification__c = mydemo.Qualification__c;
    child.Quota_Amount__c = 100;
    child.Quota_Calculation_Type__c = '%';
    
    return child;
  }
}

View of the addQuotas page so you get the idea of the page:
User-added image


Thank you in advance!!

 
I have two objects - Demographics and Quotas. Both objects also have a lookup to a third object called Qualification. I have used Visualforce and Apex to create a multi-entry screen for adding multiple Quotas to a Demographic at once. I have successfullly passed the Demographics Id directly into the Demographics lookup by using both the controller and the custom button URL. I haven't figured out yet what to write in the controller to pass a second parameter from the URL into the input field. I tried a few things, but just removed them since they weren't working. Below is what I'm working with.

Objects
Demographic: Demographic__c
Quota: Quota__c
Qualification: Qualification_Library__c

Fields
The Qualification field on both Demographics and Quotas is Qualification__c

Visualforce Page
<apex:page controller="addDemoController" tabstyle="Quota__c">
  <apex:form >
    <apex:pageBlock title="Define Demographic Quotas">
      <apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable">
        <apex:column headerValue="IDent" rendered="false">
          <apex:outputText value="{!wrapper.ident}"/>
        </apex:column>  
        <apex:column headerValue="Condition">
          <apex:inputField value="{!wrapper.quota.Condition__c}"/>
        </apex:column>
        <apex:column headerValue="Option">
          <apex:inputField value="{!wrapper.quota.Condition_Option__c}"/>
        </apex:column>
        <apex:column headerValue="Demographic">
          <apex:inputField value="{!wrapper.quota.Demographic__c}"/>
        </apex:column>
        <apex:column headerValue="Qualification">
          <apex:inputField value="{!wrapper.quota.Qualification__c}"/>
        </apex:column>                  
        <apex:column headerValue="Action">
          <apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable">
            <apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/>
          </apex:commandButton>
        </apex:column> 
      </apex:pageBlockTable>
      <apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable">
        <apex:param name="addCount" value="1" assignTo="{!addCount}"/>
      </apex:commandButton>    
      <apex:commandButton value="Save" action="{!save}"/>
    </apex:pageBlock>
  </apex:form>    
</apex:page>
Apex Class
public class addDemoController 

{
     public List<quotaWrapper> wrappers {get; set;}
     public static Integer toDelIdent {get; set;}
     public static Integer addCount {get; set;}
     private Integer nextIdent=0;
  
     public addDemoController()
     {
          wrappers=new List<quotaWrapper>();
          for (Integer idx=0; idx<1; idx++)
              {
               wrappers.add(new quotaWrapper(nextIdent++));
              }
     }
  
     public void delWrapper()
     {
          Integer toDelPos=-1;
          for (Integer idx=0; idx<wrappers.size(); idx++)
              {
                   if (wrappers[idx].ident==toDelIdent)
                   {
                    toDelPos=idx;
                   }
              }
           
          if (-1!=toDelPos)
              {
               wrappers.remove(toDelPos);
              }
     }
      
     public void addRows()
     {
          for (Integer idx=0; idx<addCount; idx++)
          {
           wrappers.add(new quotaWrapper(nextIdent++));
          }
     }
      
   public PageReference save()
   {
      Id eventId;
      eventId = ApexPages.currentPage().getParameters().get('eventId');
      List<Quota__c> quotas=new List<Quota__c>();
        for (quotaWrapper wrap : wrappers)
        {
         quotas.add(wrap.quota);
        }
       
      insert quotas;
       
      return new PageReference('/' + ApexPages.currentPage().getParameters().get('eventId'));
    
   }
  
   public class quotaWrapper
   {
    public Quota__c quota {get; private set;}
    public Integer ident {get; private set;}
     
      public quotaWrapper(Integer inIdent)
      {
       ident=inIdent;
       quota=new Quota__c(Demographic__c =ApexPages.currentPage().getParameters().get('eventId'));
      }
   }
 
}

Button
(URL)
/apex/AddQuotaSelect?eventId={!Demographic__c.Id}

Any help in getting that qualification id to populate in the Qualification__c field for each row would be much appreciated

Here's what it looks like in action, just need that one field autofilled!
User-added image

 

I have a parent object: Cycle__c

The child object is: Sessions__c

 

Each Cycle__c has multiple sessions. I have put a lookup field, Latest_Session__c, that I want populated with the most recently created Sessions__c record.

 

I figured I needed a way to denote which Sessions__c record was the most recent, so I put a checkbox on the Sessions__c called Most_Recent_Record__c which is checked by default, and wrote a trigger that unchecks that field for all other Sessions__c records related to the same Cycle__c.

 

I then tried to write a trigger that populated the Latest_Session__c field on the Cycle__c object, but it seemed to conflict with the other trigger.

 

Thoughts?? There is a date field on the Sessions__c object, so if that helps and means that I don't need the Most recent checkbox that is fine.

 

Here is the trigger for unchecking "most recent record" on the Sessions__c object:

trigger clearmostrecentflag on Sessions__c (before insert) {
 
//create a list to hold the records to update
List<Sessions__c> oldrecords = new List<Sessions__c>();
 
 
for(Sessions__c myrecord: trigger.new){
String parentname = myrecord.Cycle__c;
String myrecordid = myrecord.Id;
   for (Sessions__c myrecordlist : [select Cycle__c from Sessions__c where Cycle__c =:parentname AND Id != :myrecordid AND Most_Recent_Session2__c = true]){
 
 
myrecordlist.Most_Recent_Session2__c = false;
oldrecords.add(myrecordlist);
  
}
}
if(oldrecords.size()>0) {
update oldrecords;
}
else{
//do nothing
}
 
}

 Here is the trigger I attempted to write, to update the blank Latest_Session__c lookup field on the Cycle__c object (essentially, I want that field populated with whichever child Sessions__c record has Most_Recent_Record__c checked as true).

 

trigger updateLatestSession on Sessions__c (after update) {
    Set<Id> CycIds = new Set<Id>();
         for (Sessions__c sess : Trigger.new)
         if(sess.Most_Recent_Session2__c != false){
             CycIds.add(sess.Cycle__c);
}            
    Map<Id, Cycle__c> cycMap = new Map<Id, Cycle__c>(
    [SELECT Id  FROM Cycle__c WHERE Id IN :CycIds]);  
    
        for (Sessions__c sess : Trigger.new){    

         cycMap.get(sess.Cycle__c).Latest_Session__c = sess.ID;       
         
         //create list of ParentObjects
List<Cycle__c> ParentObjectList = cycMap.Values();

//save the ParentObjects
update ParentObjectList; 

} 
}

 The error message I got when trying to create a new Sessions__c:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger clearmostrecentflag caused an unexpected exception, contact your administrator: clearmostrecentflag: execution of BeforeInsert caused by: System.DmlException: Update failed. First exception on row 0 with id a0DQ00000044zThMAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updateLatestSession: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.updateLatestSession: line 12, column 1: []: Trigger.clearmostrecentflag: line 19, column 1

 

Any help would be much appreciated.

 

Thanks!

I have an object, ChildObject__c, which I have overidden with a visualforce page. On this page I have a tab where I've displayed fields and related lists from the ParentObject__c. I can hardcode it to show ParentObject__c's related list using <apex:relatedlist>, but what I'd really like to do is show the <apex:detail> of ParentObject__c on this tab.  Since this is in a managed package, and clients will not be able to alter the visualforce coding. The reason I am looking to do this is that they may not want all of the related lists I've hard coded on the ChildObject__c's tab. So theoretically, I'd like it if they remove the related list from ParentObject__c's page layout, the related list is also removed from the visualforce tab on the ChildObject__c's display, so that they don't have to copy and redo the visualforce page I've created.

 

Is this even possible? Any advice that points me in the right direction would be helpful.

 

Thanks!

So I've gotten pretty good at writing triggers, by simply altering coding I've found on here and salesforce.com. So I understand how to write them, but not necessarily WHY they work. So because I'm a novice, I'm having a bit of trouble figuring out the test codes. I've read the Introduction to Apex Test Methods, but it's not quite clicking for me. I'm hoping this is a really easy trigger that someone can help me figure out how to write the test code for it? If it isn't too much work to write it for me, I can probably figure out all of the other triggers.

 

trigger AutoCreateGeneralIntake on Contact (after insert) {
    List<General_Intakes__c> GeneralIntake = new List<General_Intakes__c>();

    
    for (Contact newContact: Trigger.New) {
        if (newContact.Screening_ID__c != null) {
            GeneralIntake.add(new General_Intakes__c(
                        Name = '1',
                        Primary_Contact__c = newContact.ID,
                        Screening_ID__c = newContact.Screening_ID__c,
                        Primary_Household_ID__c = newContact.Household_ID_del__c));
        }
    }
    insert GeneralIntake;
}

 Thank you in advance for any help.

I have a date field on Object__c called Contact_Date__c. The user cannot create an Object__c record where Contact_Date__c can only be the current month unless it is for the previous month and today's date is before the 5th.

 

Basically, an Object__c record for November (Contact_Date__c) must be created no later than December 5th.

 

I played around with AND/OR statments but am having difficulty. I was able to create the validation rule for having Today's month and Contact month the same: 

 

MONTH( Today() ) <> MONTH( hhs__Contact_Date__c )

 

but I need to somehow write in an exception of UNLESS, Month(Today()) is Month(hhs__Contact_Date__c)+1 and Day(Today()) < 5. 

 

Any ideas?

I have three objects: General_Intakes__c, Contact, and Households__c

 

The Households__c is the Parent of Contact. the Contact has a lookup field called Household_Id_del__c to the Household.

 

The General_Intakes__c is the child of both Households and Contacts,  with lookup fields called Primary_Contact__c and Primary_Household_Id__c. 

 

I was trying to write a trigger, which I am fairly new at, that when the Household_Id_del field is changed in the Contact object, the Primary_Household_Id__c field on the General_Intakes__c is updated to reflect the same.

 

Essentially, Primary_Household_Id__c must be the same as Primary_Contact__r.Household_Id_del__c.

 

I tried copying some code I found in these boards, but I keep getting this error: 

 

Error: Compile Error: Didn't understand relationship 'Households__r' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 9 column 42

 

Here is the code: 

trigger GeneralIntakeHHId on Contact (after update) {
    
    for( Contact parent: Trigger.new)
    {
    
        List<General_Intakes__c> children = [ SELECT Primary_Household_ID__c from 
                                               General_Intakes__c where Primary_Contact__r.id = :parent.Id];

        list <Households__c> household = [Select Household.Id
                                            from Households__c
                                            where Household.id = :parent.Household_ID_del__c];                                                       
        
        List<General_Intakes__c> childrenToUpdate = new List<General_Intakes__c>();
        
        for(General_Intakes__c thischild: children )
        {
           if( thischild.Primary_Household_Id__c !=  household[0].Id)
           {
               thischild.Primary_Household_Id__c =  household[0].Id;
               childrenToUpdate.add(thischild);
           }
        }
        
        if( !childrenToUpdate.isEmpty())
        {
           update childrenToUpdate;
        }
    
    }                       
}

 The error is for list <Households__c> household = [Select Household.Id

 

Any help would be much appreciated.

 

Hello, 

 

I have a custom button on an object called Service Plan, that allows the user to create a new record in the Assessment object. Through the custom button, fields are autopopulated. It seems that when I make these buttons for an object that has record types, the retURL doesn't pass through after a record type is selected. Thus, when the user clicks "Cancel" during data entry, they're kicked back to the home page rather than back to the Service Plan. 

 

Here is the code:

 

/setup/ui/recordtypeselect.jsp?ent={!$Setup.hhs__ButtonSettings__c.hhs__Assessment_Setup_Object_ID__c}&retURL=%2Fapex%2FServicePlan%3Fid%3D{!hhs__Service_Plan__c.Id}%26sfdc.override%3D1&save_new_url=%2F{!$ObjectType.hhs__Assessments__c}%2Fe%3F{!$Setup.hhs__ButtonSettings__c.hhs__Assessment_Service_Plan_ID__c}%3D{!hhs__Service_Plan__c.Name}%26{!$Setup.hhs__ButtonSettings__c.hhs__Assessment_Service_Plan_ID__c}_lkid%3D{!hhs__Service_Plan__c.Id}&{!$Setup.hhs__ButtonSettings__c.hhs__Assessment_Primary_Contact_ID__c}={!hhs__Service_Plan__c.hhs__Participant_Name__c}&{!$Setup.hhs__ButtonSettings__c.hhs__Assessment_Primary_Contact_ID__c}_lkid={!hhs__Service_Plan__c.hhs__Participant_NameId__c}&retURL={!hhs__Service_Plan__c.Id}}&Name="Assessment"

 

any ideas?

 

Thanks!

 

Hello,

 

I'm trying to create a checklist in salesforce that updates automatically.

 

A brief example - I have a Master-Detail Relationship between two objects: Program Intake (Master) and Client Checklist (Detail).  The API for the Program Intake field on the Client Checklist object is Program_Intake__c.

 

The Client Checklist has a checkbox called Service Plan (Service_Plan__c). 

 

There is also a Master-Detail Relationship between Program Intake (Master) and Service Plan (Detail). I then have a rollup summary on the Program Intake counting the # of Service Plans (PI_Service_Plan__c).

 

I want when PI_Service_Plan__c on the Program Intake is greater than 0 (basically, when a Service Plan record has been created), the checkbox Service_Plan__c on the Client Checklist is automatically checked.

 

I tried to do this via a workflow field update, but it doesn't work since I'm technically not editing the Client Checklist record. I essentially don't want the user to ever have to "Edit" this record. I have a feeling a trigger is needed, but I'm not all that adept at writing triggers. 

 

Is this a quick and easy trigger someone can write up? I've scoured the boards but haven't successfully copied anything yet.

 

Thanks!

Hi there,

I've developed a managed package for a client.Even though I could not include any approval processes in the package, I did have some field updates and tasks that are to be used in an approval process in the package. While these field updates and tasks did successfully deploy and appear in the client's list of field updates and tasks, when creating an approval process these actions are not available for selection. i.e. I created a field update on a custom object, that checks a box called "approved" on final approval. This field update is in the main list of field updates, but when creating an approval process for the custom object, this field update does not appear as a choice when selecting an existing action for steps. Does anyone have any ideas as to why? Currently this package is in its first beta version, not released yet. will this change when it's in released mode?

 

Thanks!

Hello,

 

I'm a novice in writing Apex classes, and copied some code I found on these boards. I need to write a test class to increase my code coverage and am incredibly unfamilliar with the language. Any help would be greatly appreciated.

 

public class ContactEntry {

    public List<Contact> con {get; set;}

    public ContactEntry(ApexPages.StandardController myController) {
        con = new List<Contact>();
        con.add(New Contact());}

    public void addrow() {
        con.add(new Contact());}
            
    public void removerow(){
        Integer i = con.size();
        con.remove(i-1);}
            
    public PageReference save() {
        insert con;
        //PageReference home = new PageReference('/home/home.jsp');
        //home.setRedirect(true);
        //return home; }}
        PageReference conlist = new PageReference('/apex/contactlist');
        conlist.setRedirect(true);
        return conlist; }}

 Thank you in advance!

Hi there,

 

I've created a quick entry visualforce page, which I got from this old Discussion Board post: Here

 

The Household (Households__c) object, is a child of the Case object with the Case ID lookup field on the Household object called Screening Number (Screening_Number__c). The child relationship name is Households__r.

 

The Contact object is a child of both the Household object and the Case object (follow me?). So the Contact object also has a lookup field to the Case object called Screening Number. (Field API: Screening_Number__c, Child relationship: Contacts__r)

 

I've recreated the code from the link above to be able to create multiple contact on the household object quickly. The household ID passes fine, but I'd love it if I could get the Screening Number field autopopulated in the table for quick entry.

 

Here is my Controller:

public class AddMultipleContacts {

    public List<Contact> cont {get; set;}
    private final Households__c parCont;
    public AddMultipleContacts(ApexPages.StandardController myController) {
        parCont=(Households__c)myController.getrecord();
        cont = new List<Contact>();
        Contact Hshld = new Contact();
        Hshld.Household_ID_del__c = parCont.id;
        cont.add(Hshld);}

    public void addrow() {
        Contact Hshld = new Contact();
        Hshld.Household_ID_del__c = parCont.id;
        cont.add(Hshld);}
            
    public void removerow(){
        Integer i = cont.size();
        cont.remove(i-1);}
            
    public PageReference save() {
        insert cont;
        //PageReference home = new PageReference('/home/home.jsp');
        //home.setRedirect(true);
        //return home; }}
        PageReference parrec = new PageReference('/'+parCont.id);
        parrec.setRedirect(true);
        return parrec; }}

 And here is my visualforce page:

 

<apex:page standardController="Households__c" extensions="AddMultipleContacts" sidebar="false">
    <apex:form >
    <apex:pageBlock title="Multiple Contact Quick Entry"  >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" rerender="error" />
                        <div style="text-align:right;margin-right:30px;font-weight:bold;">
            <apex:commandLink value="Add Row" action="{!addRow}" rerender="table,error" immediate="true" />
&nbsp;|&nbsp;&nbsp;
            <apex:commandLink value="Remove Row" action="{!removeRow}" rerender="table,error" immediate="true" />                
        </div>
            </apex:pageBlockButtons>
<b>Household Screening Number: </b>
<apex:outputField value="{!Households__c.Screening_Number__c}"/>
            <apex:pageBlockTable value="{!cont}" var="a" id="table">

                <apex:column headerValue="First Name">
                    <apex:inputField value="{!a.FirstName}"/>
                   
                </apex:column>                
                <apex:column headerValue="Last Name">
                    <apex:inputField value="{!a.LastName}"/>
                </apex:column>
                <apex:column headerValue="Screening Number">
                    <apex:inputField value="{!a.Screening_Number__c}" required="true"/>
                </apex:column>
                <apex:column headerValue="Birthdate">
                    <apex:inputField value="{!a.Birthdate}" required="false"/>
                </apex:column>
                <apex:column headerValue="Primary?">
                    <apex:inputField value="{!a.Primary_Contact_del__c}" required="false"/>
                </apex:column>
                <apex:column headerValue="Household Role">
                    <apex:inputField value="{!a.Family_Household_Role__c}" required="false"/>
                </apex:column> 
                <apex:column headerValue="Status">
                    <apex:inputField value="{!a.Case_Status__c}" required="true"/>
                </apex:column>                
                <apex:column headerValue="Privacy">
                    <apex:inputField value="{!a.Privacy__c}" required="true"/>
                </apex:column>                                                                   
            </apex:pageBlockTable>
 
    </apex:pageBlock>
    </apex:form>
</apex:page>

  Any advice would be much appreciated. I tried adding Hshld.Screening_Number__c = parCont.id; beneath Hshld.Household_ID_del__c = parCont.id; on the controller, but it didn't take. Any ideas?

 

Thanks!

My client is frustrated that at times, when they click the "Cancel" button in an edit page, Salesforce takes them back to the home page rather than back to the previous page. I know how to make an easy "back" button, but it can only be presented on the detail page (I don't want to rebuild all of my objects in visualforce). Is it possible to hack into the "Cancel" button and override it to have it redirect the user to the previous page?

 

Thanks!

A problem I'm having with my visualforce pages is that if I have a tab that is a related list of an object that is not visible to a certain profile, they cannot access the overall page at all.

 

Example: My contact object has been made into a tabbed visualforce page. One of the tabs is the related list, Case Notes using the <apex:related list> function. . I did a test where the Visualforce page is available to a profile called Basic. the Basic profile has full access to the Contact object, but no access whatsoever to the Case Note object. When clicking on a contact, I get the error that the relationship with the Case Notes is not a relationship.

 

How do I override this other than making Case Notes available but making each field hidden for the Basic profile? Is there a way in coding to allow the Basic profile to see everything but the related list for Case Notes does not appear on the tab?

 

Thanks!

I have two objects, General Intake and Program Intake. Program Intake has a lookup to the General Intake. Both objects have a lookup to the Contact.

 

We don't want the Program Intake related list to appear on the page layout of the General Intake, but we want to build a custom button that creates a new Program Intake (goes to the edit page of a new program intake). 

 

1. I want the General Intake and Contact Name to automatically populate on the Program Intake record from the General Intake record that it was created from (do not want to use formulas, need these to remain lookup fields).

 

2. In changing the URLs, you cannot change the Field ID for the General Intake lookup field. This would be fine if we didn't have to deploy between multiple environments.

 

It has been suggested to write a button using Javascript. Does anyone have any coding they might share with me to make this happen? I am unfamiliar with Javascript.

 

Thanks!

I'm going to do my best to explain this, I'm having trouble understanding and envisioning how custom settings works:

We have an object called "Program Intakes", in which the user will select a program for which they are doing an intake for. They select a Program through a lookup field on the Program Intake object.

We have several objects that lookup to the program intake consisting of various demographic info. For brevity's sake I'll use just one - housing history.

Housing history has various record types.

We are trying to create a custom setting where when a certain program is selected, only 1 record type is available on the housing history related list when creating a new record. Here is an example of the custom setting, where should the user select "Long Term Housing" as the program, when creating a new "Housing HIstory" record, only Record Type 1 is available.

Name: HousingLTHCMA                           Object Name: Housing History
Object ID: 01Id0000000ujiK                       Program Name: Long Term Housing
Program ID: 01tK0000000GeGa               Modality: Name CM Adult
Modality ID: a15K0000000D5N8               Record Type Name: Record Type 1
Record Type ID: 012K00000004SNL       Composite ID 01Id0000000ujiK01tK0000000GeGaa15K0000000D5N8

I know when creating a visualforce page I need it to reference this setting, but I'm just not clear on how to do this. Do I do this on a visualforce page for the program intake? Or do I do it on a visualforce page for Housing History? How should this look?Does this require apex code?

Any help would be much appreciated, please send a question if you think you know an answer but aren't clear on my question.

Thanks!

Need to route the user to a visualforce page for creating multiple child records on save of parent record.

Summary
  • Three objects involved: Opportunity, Demographic, and Quota. 
  • One Opportunity has Many Demographics
  • One Demographic has Many Quotas
  • I've created a visualforce page where I add many Quotas to the Demographic at once. Currently this is launched from a custom button on the Demographic Detail Page.
    • Page Name = addQuotas
    • Page has a standard "add row"/"delete row" function to create a Quota record each row from custom controller
    • I pass multipe details from the parent Demographic onto each Quota row through an extension
  • I've created a visualforce page to override the standard new/edit Demographic layout so I can build a custom save button to route to the addQuotas page.
    • Page Name = addDemographic, uses a standard controller, no extensions at the moment
Question
What I want to have happen is when saving the Demographic, the user is immediately taken to the addQuotas page as if they had clicked the button on the detail page. I'm having difficulty making any of this work, trying custom buttons from the Opportunity and hacking the SaveURL, and I'm just not having luck saving the Demographic, grabbing the Id of that Demographic, and then going to the addQuotas page with that Demographic Id in tow. 

What do I add to the Save action on the addDemographic visualforce page to then route to the addQuotas page for THAT Demographic?

Basically, I want on Save of Demographic to automatically go here: /apex/addQuotas?id={!Demographic__c.Id}&retURL={!Demographic__c.Id}

Code and Pictures:
addDemographic page
<apex:page standardController="Demographic__c" tabStyle="Demographic__c">
     <apex:sectionHeader title="Edit Demographic" subtitle="New Demographic"/>
        <apex:form >
                <apex:pageBlock title="Edit Demograhic" mode="edit">
                    <apex:pageblockButtons >
                        <apex:commandButton action="{!save}" value="Add Quotas"/>
                    </apex:pageblockButtons>
                    <apex:pageblockSection title="Demographic Information" columns="1">
                        <apex:inputfield value="{!Demographic__c.Opportunity__c}"/>
                        <apex:inputfield value="{!Demographic__c.Qualification__c}"/>
                    </apex:pageblockSection> 
                </apex:pageBlock>
        </apex:form>

</apex:page>

addQuotas page:
<apex:page standardController="Demographic__c"
            extensions="EditableQuotaListExtension"
            showHeader="true" 
            sidebar="false"
            title="Edit Quota">
    <apex:form >
    <apex:pageMessages id="messages"/>
    <apex:pageBlock title="Edit Quotas">
      <apex:pageBlockButtons >
        <apex:commandButton value="Cancel" action="{!cancel}" />
        <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="Demographic Information" collapsible="false">
      <apex:outputLink value="/{!Demographic__c.Id}" target="_blank">{!Demographic__c.Name}</apex:outputLink>
        <apex:pageBlockSectionItem >
          <apex:outputText value="{!Demographic__c.QualificationName__c}" />
          <apex:outputText value="{!Demographic__c.Qualification_Text__c}" />
        </apex:pageBlockSectionItem>
      </apex:pageBlockSection>
      <apex:pageBlockSection id="childList" columns="1" title="Quotas" collapsible="false">
        <apex:variable var="rowNum" value="{!ZERO}" />
        <apex:outputLabel value="No Quotas currently exist. Click below to Add." rendered="{!NOT(hasChildren)}"/>
        <apex:pageBlockTable value="{!children}" var="quota" rendered="{!hasChildren}">
        <apex:column headerValue="Condition">
          <apex:inputField value="{!quota.Condition__c}"/>
        </apex:column>
        <apex:column headerValue="Option">
          <apex:inputField value="{!quota.Condition_Option__c}"/>
        </apex:column>
        <apex:column headerValue="Description">
          <apex:inputField value="{!quota.Description__c}"/>
        </apex:column>
        <apex:column headerValue="Quota Amount">
          <apex:inputField value="{!quota.Quota_Amount__c}" />
        </apex:column>        
        <apex:column headerValue="%/#">
          <apex:inputField value="{!quota.Quota_Calculation_Type__c}"/>
        </apex:column>
        <apex:column headerValue="Demographic">
          <apex:inputField value="{!quota.Demographic__c}"/>
        </apex:column>
        <apex:column headerValue="Qualification">
          <apex:inputField value="{!quota.Qualification__c}"/>
        </apex:column>
          <apex:column headerValue=" ">
            <!-- This is the second half of the trick to keep track
                  of your row index for deletion. -->
            <apex:variable var="rowNum" value="{!rowNum + 1}" />
            <apex:commandLink value="Delete" action="{!removeFromList}" rerender="childList, messages" immediate="true">
              <apex:param name="removeIndex" assignTo="{!removeIndex}" value="{!rowNum}" />
            </apex:commandLink>
          </apex:column>
        </apex:pageBlockTable>
        <apex:commandButton value="Add Quota" action="{!addToList}" rerender="childList, messages" immediate="true" />
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

addQuotas Extenstion (grabbing details from Demographic parent):
public with sharing class EditableQuotaListExtension extends EditableQuotaList
{


 public Demographic__c mydemo {get; private set;}

  public EditableQuotaListExtension(ApexPages.StandardController stdController) 
  {
    super(stdController);

    this.mydemo = [SELECT Id,
                              Name,
                                Qualification__r.Name
                            FROM Demographic__c
                            WHERE Id =: stdController.getRecord().Id];
    
    this.childList = [SELECT Id,
                          Condition__c,
                          Description__c,
                          Quota_Amount__c,
                          Quota_Calculation_Type__c,
                          Condition_Option__c,
                          Qualification__c,
                          Demographic__c
                      FROM Quota__c
                      WHERE Demographic__c =: mysObject.Id];
  }

  /*
   * This method is necessary for reference on the Visualforce page, 
   * in order to reference non-standard fields.
   */
  public List<Quota__c> getChildren()
  {
    return (List<Quota__c>)childList;
  }


  public override sObject initChildRecord()
  {
    Quota__c child = new Quota__c();
    child.Demographic__c = mydemo.Id;
    child.Qualification__c = mydemo.Qualification__c;
    child.Quota_Amount__c = 100;
    child.Quota_Calculation_Type__c = '%';
    
    return child;
  }
}

View of the addQuotas page so you get the idea of the page:
User-added image


Thank you in advance!!

 
On a Visualforce Page, I have a section which is collapsible by default and I use Javascript to toggle it
 
<script type="text/javascript">
    
    $(document).ready(function(){ 
        collapseSections();
        
    });
    
    function collapseSections(){
        $('img[id*="additionalProducts"]').each(function() {
            twistSection(this);
        });
    } 
</script>

<!--Some Code-->

<apex:pageBlockSection title="Service Products" id="additionalProducts" showheader="true" collapsible="true" columns="1">

<!--Some Code-->

The issue I'm having is should the user try to save, and a validation rule is flagged, when the page rerenders the section is collapsed again. I want the section collapsed on the initial page load, but if the user toggles the section down, saves, and hits a validation rule, I'd like the section to remain "uncollapsed".

Any ideas? I have a controller I can add code too as well if needed.

Thanks!
I had this working the other day, then yesterday I erased my work thinking the client wanted something else (rookie mistake). Now I need to put it back and I can't get it to work! I think my brain got its wires crossed in the last two days...

Scenario:
  • Visualforce page for the Order object
  • On the page, created a list with checkboxes displaying the names of the Assets related the the same Account as the Order
  • On save, upsert the Order with values in the Order form and for each selected Asset in the list, I am trying to create a record passing info from the Asset
What's happening:
  • Doesn't seem to be looping through all selected checkboxes. Looking at the debug logs, only one checkbox is ever picked up.
Visualforce Page:
<apex:page standardController="Order" showHeader="false" sidebar="false" extensions="TestExtension">   

    <apex:form id="theForm">
        <apex:pageBlock title="Service Request">
            <apex:pageBlockButtons location="both">
                <apex:commandButton action="{!processSelected}" value="Continue"/>                        
            </apex:pageBlockButtons>
            
            <apex:pageBlockSection >
                <apex:inputField value="{!Order.BillToContactId}"/>
                <apex:outputField value="{!Order.OwnerId}"/>      
                <apex:inputField value="{!Order.Service_initiated_By__c}" style="width: 150px;"/>                
                <apex:outputField value="{!Order.Account.Name}"/>
                <apex:inputField value="{!Order.Description}" label="Problem Description"/>
                <apex:outputField value="{!Order.Sold_Order__c}"/>                                                
            </apex:pageBlockSection>
            
   <!--THIS IS THE DATA TABLE I'M WORKING WITH  -->    
   <apex:pageBlockSection title="Select Installed Products" columns="1">
                <apex:pageBlockTable value="{!assets}" var="a" id="table" width="1000px;" >
                    <apex:column >
                        <!-- This is our selected Boolean property in our wrapper class -->
                        <apex:inputCheckbox value="{!a.selected}"/>
                    </apex:column>
                    <apex:column value="{!a.asset.Name}"/>
                    <apex:column value="{!a.asset.Original_Order_Variant_Number__c}"/>
                    <apex:column value="{!a.asset.Install_Date__c}"/>
                    <apex:column value="{!a.asset.Location_Details__c}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            
        </apex:pageBlock>
    </apex:form>   
</apex:page>
Apex Code: 
public with sharing class TestExtension {
    
    private final Order o;
    public List<aAsset> assetList {get; set;} 
    
    public TestExtension(ApexPages.StandardController stdController) {
        this.o = (Order)stdController.getRecord();       
    }
    
       
    public List<aAsset> getAssets() {
        if(assetList == null) {
            assetList = new List<aAsset>();
            for(Asset a: [SELECT Id, Name, Product2Id, Original_Order_Variant_Number__c, Install_Date__c, Location_Details__c FROM Asset WHERE AccountId = :o.AccountId]) {
                
                assetList.add(new aAsset(a));
            }
        }
        return assetList;
    }
    
<!--This is where I'm saving and trying to insert. I know I'm missing something obvious in making sure it loops through everything-->

    public PageReference processSelected() {
        
        try{    
            List<Asset> selectedAssets = new List<Asset>();
            
            for(aAsset aAsst: getAssets()) {
                if(aAsst.selected == true) {
                    selectedAssets.add(aAsst.asset);
                }
            }
            
            System.debug('These are the selected Assets...');
            for(Asset asset: selectedAssets) {
                system.debug(asset);
                
                Service_Request_Configuration__c src = new Service_Request_Configuration__c ();
                
                src.Account__c = o.AccountId;
                src.Installed_Product_Asset__c = asset.Id;
                src.Installed_Product__c = asset.Product2Id;
                src.Order__c = o.id;
                
                insert src; 
                
                o.Service_Type__c = propPickValSelected;
                upsert o;
                
                PageReference pageRef = new PageReference('/apex/RMS_createServiceOrder4?id='+ o.Id + '&retUrl=' + o.Id);
                pageRef.setRedirect(true);
                return pageRef;
            }
        }
        catch(Exception ex){
            ApexPages.addMessages(ex);
        }
        return null;
    }
    
    public class aAsset {
        public Asset asset {get; set;}
        public Boolean selected {get; set;}

        public aAsset(Asset a) {
            asset = a;
            selected = false;
        }
    }
}

Like I commented in the code, I'm fairly certain it's something obvious and simple I'm missing to get it looping through properly, but I have been staring at it too long and it's not jumping at me anymore. Any help would be much appreciated!

Thanks!

 
I'm open to using either a trigger or Flow. I've been trying to do it as a Flow, but I'm getting stuck on getting it to loop through everything and can only get it to create a Demographic for the first Qualification in the list. I'm sure it's something in how to set the Loop and Assign. But I'm more familiar with Apex triggers, so I'm happy to go back to that.

This scenario uses 3 objects: Opportunity, Qualification, and Demographic. 
  • Qualifications have a picklist field called Default_Country__c
  • On Opportunities, the user selects their country from a picklist field Country__c
  • Demographics have a lookup to both Qualification and Opportunity.
I want when an Opportunity is created, for any Qualifications where Default_Country__c matches the Opportunity__c, a Demographic is created. My brain is a bit fried on this so I could use a bit of guidance. 

Thanks!
Need to route the user to a visualforce page for creating multiple child records on save of parent record.

Summary
  • Three objects involved: Opportunity, Demographic, and Quota. 
  • One Opportunity has Many Demographics
  • One Demographic has Many Quotas
  • I've created a visualforce page where I add many Quotas to the Demographic at once. Currently this is launched from a custom button on the Demographic Detail Page.
    • Page Name = addQuotas
    • Page has a standard "add row"/"delete row" function to create a Quota record each row from custom controller
    • I pass multipe details from the parent Demographic onto each Quota row through an extension
  • I've created a visualforce page to override the standard new/edit Demographic layout so I can build a custom save button to route to the addQuotas page.
    • Page Name = addDemographic, uses a standard controller, no extensions at the moment
Question
What I want to have happen is when saving the Demographic, the user is immediately taken to the addQuotas page as if they had clicked the button on the detail page. I'm having difficulty making any of this work, trying custom buttons from the Opportunity and hacking the SaveURL, and I'm just not having luck saving the Demographic, grabbing the Id of that Demographic, and then going to the addQuotas page with that Demographic Id in tow. 

What do I add to the Save action on the addDemographic visualforce page to then route to the addQuotas page for THAT Demographic?

Basically, I want on Save of Demographic to automatically go here: /apex/addQuotas?id={!Demographic__c.Id}&retURL={!Demographic__c.Id}

Code and Pictures:
addDemographic page
<apex:page standardController="Demographic__c" tabStyle="Demographic__c">
     <apex:sectionHeader title="Edit Demographic" subtitle="New Demographic"/>
        <apex:form >
                <apex:pageBlock title="Edit Demograhic" mode="edit">
                    <apex:pageblockButtons >
                        <apex:commandButton action="{!save}" value="Add Quotas"/>
                    </apex:pageblockButtons>
                    <apex:pageblockSection title="Demographic Information" columns="1">
                        <apex:inputfield value="{!Demographic__c.Opportunity__c}"/>
                        <apex:inputfield value="{!Demographic__c.Qualification__c}"/>
                    </apex:pageblockSection> 
                </apex:pageBlock>
        </apex:form>

</apex:page>

addQuotas page:
<apex:page standardController="Demographic__c"
            extensions="EditableQuotaListExtension"
            showHeader="true" 
            sidebar="false"
            title="Edit Quota">
    <apex:form >
    <apex:pageMessages id="messages"/>
    <apex:pageBlock title="Edit Quotas">
      <apex:pageBlockButtons >
        <apex:commandButton value="Cancel" action="{!cancel}" />
        <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="Demographic Information" collapsible="false">
      <apex:outputLink value="/{!Demographic__c.Id}" target="_blank">{!Demographic__c.Name}</apex:outputLink>
        <apex:pageBlockSectionItem >
          <apex:outputText value="{!Demographic__c.QualificationName__c}" />
          <apex:outputText value="{!Demographic__c.Qualification_Text__c}" />
        </apex:pageBlockSectionItem>
      </apex:pageBlockSection>
      <apex:pageBlockSection id="childList" columns="1" title="Quotas" collapsible="false">
        <apex:variable var="rowNum" value="{!ZERO}" />
        <apex:outputLabel value="No Quotas currently exist. Click below to Add." rendered="{!NOT(hasChildren)}"/>
        <apex:pageBlockTable value="{!children}" var="quota" rendered="{!hasChildren}">
        <apex:column headerValue="Condition">
          <apex:inputField value="{!quota.Condition__c}"/>
        </apex:column>
        <apex:column headerValue="Option">
          <apex:inputField value="{!quota.Condition_Option__c}"/>
        </apex:column>
        <apex:column headerValue="Description">
          <apex:inputField value="{!quota.Description__c}"/>
        </apex:column>
        <apex:column headerValue="Quota Amount">
          <apex:inputField value="{!quota.Quota_Amount__c}" />
        </apex:column>        
        <apex:column headerValue="%/#">
          <apex:inputField value="{!quota.Quota_Calculation_Type__c}"/>
        </apex:column>
        <apex:column headerValue="Demographic">
          <apex:inputField value="{!quota.Demographic__c}"/>
        </apex:column>
        <apex:column headerValue="Qualification">
          <apex:inputField value="{!quota.Qualification__c}"/>
        </apex:column>
          <apex:column headerValue=" ">
            <!-- This is the second half of the trick to keep track
                  of your row index for deletion. -->
            <apex:variable var="rowNum" value="{!rowNum + 1}" />
            <apex:commandLink value="Delete" action="{!removeFromList}" rerender="childList, messages" immediate="true">
              <apex:param name="removeIndex" assignTo="{!removeIndex}" value="{!rowNum}" />
            </apex:commandLink>
          </apex:column>
        </apex:pageBlockTable>
        <apex:commandButton value="Add Quota" action="{!addToList}" rerender="childList, messages" immediate="true" />
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>

addQuotas Extenstion (grabbing details from Demographic parent):
public with sharing class EditableQuotaListExtension extends EditableQuotaList
{


 public Demographic__c mydemo {get; private set;}

  public EditableQuotaListExtension(ApexPages.StandardController stdController) 
  {
    super(stdController);

    this.mydemo = [SELECT Id,
                              Name,
                                Qualification__r.Name
                            FROM Demographic__c
                            WHERE Id =: stdController.getRecord().Id];
    
    this.childList = [SELECT Id,
                          Condition__c,
                          Description__c,
                          Quota_Amount__c,
                          Quota_Calculation_Type__c,
                          Condition_Option__c,
                          Qualification__c,
                          Demographic__c
                      FROM Quota__c
                      WHERE Demographic__c =: mysObject.Id];
  }

  /*
   * This method is necessary for reference on the Visualforce page, 
   * in order to reference non-standard fields.
   */
  public List<Quota__c> getChildren()
  {
    return (List<Quota__c>)childList;
  }


  public override sObject initChildRecord()
  {
    Quota__c child = new Quota__c();
    child.Demographic__c = mydemo.Id;
    child.Qualification__c = mydemo.Qualification__c;
    child.Quota_Amount__c = 100;
    child.Quota_Calculation_Type__c = '%';
    
    return child;
  }
}

View of the addQuotas page so you get the idea of the page:
User-added image


Thank you in advance!!

 
I have two objects - Demographics and Quotas. Both objects also have a lookup to a third object called Qualification. I have used Visualforce and Apex to create a multi-entry screen for adding multiple Quotas to a Demographic at once. I have successfullly passed the Demographics Id directly into the Demographics lookup by using both the controller and the custom button URL. I haven't figured out yet what to write in the controller to pass a second parameter from the URL into the input field. I tried a few things, but just removed them since they weren't working. Below is what I'm working with.

Objects
Demographic: Demographic__c
Quota: Quota__c
Qualification: Qualification_Library__c

Fields
The Qualification field on both Demographics and Quotas is Qualification__c

Visualforce Page
<apex:page controller="addDemoController" tabstyle="Quota__c">
  <apex:form >
    <apex:pageBlock title="Define Demographic Quotas">
      <apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable">
        <apex:column headerValue="IDent" rendered="false">
          <apex:outputText value="{!wrapper.ident}"/>
        </apex:column>  
        <apex:column headerValue="Condition">
          <apex:inputField value="{!wrapper.quota.Condition__c}"/>
        </apex:column>
        <apex:column headerValue="Option">
          <apex:inputField value="{!wrapper.quota.Condition_Option__c}"/>
        </apex:column>
        <apex:column headerValue="Demographic">
          <apex:inputField value="{!wrapper.quota.Demographic__c}"/>
        </apex:column>
        <apex:column headerValue="Qualification">
          <apex:inputField value="{!wrapper.quota.Qualification__c}"/>
        </apex:column>                  
        <apex:column headerValue="Action">
          <apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable">
            <apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/>
          </apex:commandButton>
        </apex:column> 
      </apex:pageBlockTable>
      <apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable">
        <apex:param name="addCount" value="1" assignTo="{!addCount}"/>
      </apex:commandButton>    
      <apex:commandButton value="Save" action="{!save}"/>
    </apex:pageBlock>
  </apex:form>    
</apex:page>
Apex Class
public class addDemoController 

{
     public List<quotaWrapper> wrappers {get; set;}
     public static Integer toDelIdent {get; set;}
     public static Integer addCount {get; set;}
     private Integer nextIdent=0;
  
     public addDemoController()
     {
          wrappers=new List<quotaWrapper>();
          for (Integer idx=0; idx<1; idx++)
              {
               wrappers.add(new quotaWrapper(nextIdent++));
              }
     }
  
     public void delWrapper()
     {
          Integer toDelPos=-1;
          for (Integer idx=0; idx<wrappers.size(); idx++)
              {
                   if (wrappers[idx].ident==toDelIdent)
                   {
                    toDelPos=idx;
                   }
              }
           
          if (-1!=toDelPos)
              {
               wrappers.remove(toDelPos);
              }
     }
      
     public void addRows()
     {
          for (Integer idx=0; idx<addCount; idx++)
          {
           wrappers.add(new quotaWrapper(nextIdent++));
          }
     }
      
   public PageReference save()
   {
      Id eventId;
      eventId = ApexPages.currentPage().getParameters().get('eventId');
      List<Quota__c> quotas=new List<Quota__c>();
        for (quotaWrapper wrap : wrappers)
        {
         quotas.add(wrap.quota);
        }
       
      insert quotas;
       
      return new PageReference('/' + ApexPages.currentPage().getParameters().get('eventId'));
    
   }
  
   public class quotaWrapper
   {
    public Quota__c quota {get; private set;}
    public Integer ident {get; private set;}
     
      public quotaWrapper(Integer inIdent)
      {
       ident=inIdent;
       quota=new Quota__c(Demographic__c =ApexPages.currentPage().getParameters().get('eventId'));
      }
   }
 
}

Button
(URL)
/apex/AddQuotaSelect?eventId={!Demographic__c.Id}

Any help in getting that qualification id to populate in the Qualification__c field for each row would be much appreciated

Here's what it looks like in action, just need that one field autofilled!
User-added image

 
after update trigger for account object.. condition is if name is changed you need to update the same name in new custom field in same object ....
 
  • July 14, 2015
  • Like
  • 0

I have a parent object: Cycle__c

The child object is: Sessions__c

 

Each Cycle__c has multiple sessions. I have put a lookup field, Latest_Session__c, that I want populated with the most recently created Sessions__c record.

 

I figured I needed a way to denote which Sessions__c record was the most recent, so I put a checkbox on the Sessions__c called Most_Recent_Record__c which is checked by default, and wrote a trigger that unchecks that field for all other Sessions__c records related to the same Cycle__c.

 

I then tried to write a trigger that populated the Latest_Session__c field on the Cycle__c object, but it seemed to conflict with the other trigger.

 

Thoughts?? There is a date field on the Sessions__c object, so if that helps and means that I don't need the Most recent checkbox that is fine.

 

Here is the trigger for unchecking "most recent record" on the Sessions__c object:

trigger clearmostrecentflag on Sessions__c (before insert) {
 
//create a list to hold the records to update
List<Sessions__c> oldrecords = new List<Sessions__c>();
 
 
for(Sessions__c myrecord: trigger.new){
String parentname = myrecord.Cycle__c;
String myrecordid = myrecord.Id;
   for (Sessions__c myrecordlist : [select Cycle__c from Sessions__c where Cycle__c =:parentname AND Id != :myrecordid AND Most_Recent_Session2__c = true]){
 
 
myrecordlist.Most_Recent_Session2__c = false;
oldrecords.add(myrecordlist);
  
}
}
if(oldrecords.size()>0) {
update oldrecords;
}
else{
//do nothing
}
 
}

 Here is the trigger I attempted to write, to update the blank Latest_Session__c lookup field on the Cycle__c object (essentially, I want that field populated with whichever child Sessions__c record has Most_Recent_Record__c checked as true).

 

trigger updateLatestSession on Sessions__c (after update) {
    Set<Id> CycIds = new Set<Id>();
         for (Sessions__c sess : Trigger.new)
         if(sess.Most_Recent_Session2__c != false){
             CycIds.add(sess.Cycle__c);
}            
    Map<Id, Cycle__c> cycMap = new Map<Id, Cycle__c>(
    [SELECT Id  FROM Cycle__c WHERE Id IN :CycIds]);  
    
        for (Sessions__c sess : Trigger.new){    

         cycMap.get(sess.Cycle__c).Latest_Session__c = sess.ID;       
         
         //create list of ParentObjects
List<Cycle__c> ParentObjectList = cycMap.Values();

//save the ParentObjects
update ParentObjectList; 

} 
}

 The error message I got when trying to create a new Sessions__c:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger clearmostrecentflag caused an unexpected exception, contact your administrator: clearmostrecentflag: execution of BeforeInsert caused by: System.DmlException: Update failed. First exception on row 0 with id a0DQ00000044zThMAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updateLatestSession: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.updateLatestSession: line 12, column 1: []: Trigger.clearmostrecentflag: line 19, column 1

 

Any help would be much appreciated.

 

Thanks!

So I've gotten pretty good at writing triggers, by simply altering coding I've found on here and salesforce.com. So I understand how to write them, but not necessarily WHY they work. So because I'm a novice, I'm having a bit of trouble figuring out the test codes. I've read the Introduction to Apex Test Methods, but it's not quite clicking for me. I'm hoping this is a really easy trigger that someone can help me figure out how to write the test code for it? If it isn't too much work to write it for me, I can probably figure out all of the other triggers.

 

trigger AutoCreateGeneralIntake on Contact (after insert) {
    List<General_Intakes__c> GeneralIntake = new List<General_Intakes__c>();

    
    for (Contact newContact: Trigger.New) {
        if (newContact.Screening_ID__c != null) {
            GeneralIntake.add(new General_Intakes__c(
                        Name = '1',
                        Primary_Contact__c = newContact.ID,
                        Screening_ID__c = newContact.Screening_ID__c,
                        Primary_Household_ID__c = newContact.Household_ID_del__c));
        }
    }
    insert GeneralIntake;
}

 Thank you in advance for any help.

I have a date field on Object__c called Contact_Date__c. The user cannot create an Object__c record where Contact_Date__c can only be the current month unless it is for the previous month and today's date is before the 5th.

 

Basically, an Object__c record for November (Contact_Date__c) must be created no later than December 5th.

 

I played around with AND/OR statments but am having difficulty. I was able to create the validation rule for having Today's month and Contact month the same: 

 

MONTH( Today() ) <> MONTH( hhs__Contact_Date__c )

 

but I need to somehow write in an exception of UNLESS, Month(Today()) is Month(hhs__Contact_Date__c)+1 and Day(Today()) < 5. 

 

Any ideas?