I was adding some “fancy” to a Contact form today that I thought I would share with you:
[wpgist id=”38d9fb0f91118186f96e”]
The Concept
On the Contact form, I have added the two sets of addresses that are built into Contact and am calling them Primary Address and Secondary Address. I thought it would enhance the user experience to change the label when a user specifies the actual type of address.
The result is something like this:
The Implementation
Follow these steps to implement this solution:
Step 1
1. Create two sections on the form to hold the fields, one for Address1 fields, the second for Address2 fields. Each should be configured like this:
2. Add the address fields to the form, to their respective sections.
Step 2
Add the JavaScript above to the web resource for Contact. If you already have an onLoad method, just add those two lines of code to your method.
Step 2:
Add events to each of the Address Type fields:
Notice that the Pass execution context as first parameter is checked. This is vitally important and the process will not work without it..
Save and publish the form.
Step 3:
Testing using the following protocol:
1. Open a new Contact.
2. Change the value of the Primary Address type.
3. You should see the Primary Address section label change.
4. Repeat steps 1-3 for the Secondary address.
5. Save and close the record.
6. Reopen the record.
7. Verify that the section headers change.
Code Review
Let’s take a deeper dive into the code. I could have hard-coded the section values into our JavaScript but I thought that it would be better to make a fairly generic version of our code.
Take a look at the beginning of function.
function addressType_onChange(executionContextObj) { var field = executionContextObj.getEventSource();
This code gets a handle to the attribute which fired the change event.
Since we are working with an OptionSet, we need to get the label for the currently selected value:
var addressType = field.getText();
Next, a check to make sure we actually have a value:
if (addressType != null && addressType != "") {
And finally, the tricky part:
field.controls.get(0).getParent().setLabel(addressType + " Address")
field is a handle to the attribute, but we need to get to the parent Section where the attribute resides. Unfortunately, the getParent() method is only associate with a form control.
.controls.get ( 0 ).getParent() will get the parent of the first control associated with the attribute, with the parent being the Section itself
Note: This is making an assumption that the field is not on the form more than once.
Finally, setLabel() is actually going to reset the label for the Section using the value from the Address Type OptionSet and the word Address.
Conclusion
You can use the exact same technique with other field types, but you will need to modify the .getText method to .getValue and change the validity check statement to match the data type being retrieved.
Other than that, this is a pretty simple piece of code.