Dynamically Control the WhatId reference field popup

  • 1
  • Question
  • Updated 1 year ago
  • Answered
  • (Edited)
I am trying to dynamically control the table columns in a WhatId reference field popup. 

With the help from this post I was able to limit my WhatId field to the Account, Campaign, and Opportunity objects, but I need to go one step further and dynamically display table columns in the popup based on the selected object. 

I was able to "sort of" dynamically render the table columns with the below script, but it requires a user to enter text in the field, click on a selection and then press the lookup icon. If a users tries to switch the object and press the lookup icon either it will error out based on the prior selection or it won't switch. Any help is appreciated!
params = arguments[0],	model = params.model,
row = params.row,
   $ = skuid.$;

var whatId = row.WhatId;
var refString = String(whatId);
var refLength = refString.substring(0, 3);


switch ( refLength) {
    case "001":
        field.options.returnFields = [
        {id: 'Id', showInSearchDialog: false},
        {id: 'Name', showInSearchDialog: true},  
    ];
    break;
    case "701":
      field.options.returnFields = [
        {id: 'Id', showInSearchDialog: false},
        {id: 'Id', showInSearchDialog: true},  
    ];
    break;
    case "006":
        field.options.returnFields = [
        {id: 'Id', showInSearchDialog: false},
        {id: 'Name', showInSearchDialog: true},  
        {id: 'StageName', showInSearchDialog: true},  
        {id: 'CloseDate', showInSearchDialog: true},  
    ];
    break;
}

Photo of Josef Lagorio

Josef Lagorio

  • 3,394 Points 3k badge 2x thumb

Posted 2 years ago

  • 1
Photo of Bill McCullough

Bill McCullough, Champion

  • 13,612 Points 10k badge 2x thumb
Josef,

Since you have a limited number of objects that you want to dynamically control for, you could use Reference UI Only fields to display a lookup tied to a single object.  Here is a sample page that demonstrates this.

I have used a UI Only model with a picklist field to control what lookup field shows in a table or in a field editor.  I added model actions to the Task model to set the WhatId field based on the selection in the Reference UI Only field.  I think this will meet your needs.

Thanks,

Bill

<skuidpage unsavedchangeswarning="yes" personalizationmode="server" useviewportmeta="true" showsidebar="true" showheader="true" tabtooverride="Task">
    <models>
        <model id="Task" limit="1" query="false" createrowifnonefound="true" datasource="salesforce" sobject="Task">
            <fields>
                <field id="Subject"/>
                <field id="WhatId"/>
                <field id="What.Name"/>
                <field id="CaseLookup" uionly="true" displaytype="REFERENCE" label="CaseLookup" ogdisplaytype="TEXT" datasource="salesforce" rel="Subject" keyfield="Id" targetobjects="Case" defaultvaluetype="fieldvalue">
                    <batchfields>
                        <batchfield field="Subject"/>
                        <batchfield field="Description"/>
                    </batchfields>
                </field>
                <field id="OpportunityLookup" uionly="true" displaytype="REFERENCE" label="OpportunityLookup" ogdisplaytype="TEXT" datasource="salesforce" rel="Name" keyfield="Id" targetobjects="Opportunity">
                    <batchfields>
                        <batchfield field="Name"/>
                        <batchfield field="Id"/>
                    </batchfields>
                </field>
            </fields>
            <conditions/>
            <actions>
                <action>
                    <actions>
                        <action type="updateRow" fieldmodel="Task" affectedrows="context" field="WhatId" fieldtargetobjects="Account,Asset,AssetRelationship,Campaign,Case,ChannelProgram,ChannelProgramLevel,Contract,Goal,LiveAgentSession,LiveChatTranscript,Metric,Opportunity,Order,PartnerFundAllocation,PartnerFundClaim,PartnerFundRequest,PartnerMarketingBudget,Product2,Quote,Solution,WorkCoaching" enclosevalueinquotes="true" value="{{CaseLookup}}"/>
                    </actions>
                    <events>
                        <event>row.updated</event>
                    </events>
                    <fields>
                        <field>CaseLookup</field>
                    </fields>
                </action>
                <action>
                    <actions>
                        <action type="updateRow" fieldmodel="Task" affectedrows="context" field="WhatId" fieldtargetobjects="Account,Asset,AssetRelationship,Campaign,Case,ChannelProgram,ChannelProgramLevel,Contract,Goal,LiveAgentSession,LiveChatTranscript,Metric,Opportunity,Order,PartnerFundAllocation,PartnerFundClaim,PartnerFundRequest,PartnerMarketingBudget,Product2,Quote,Solution,WorkCoaching" enclosevalueinquotes="true" value="{{OpportunityLookup}}"/>
                    </actions>
                    <events>
                        <event>row.updated</event>
                    </events>
                    <fields>
                        <field>OpportunityLookup</field>
                    </fields>
                </action>
            </actions>
        </model>
        <model id="Selector" query="true" createrowifnonefound="true" datasource="Ui-Only" processonclient="true">
            <fields>
                <field displaytype="PICKLIST" label="Select WhatId Object" id="SelectWhatIdObject" ogdisplaytype="TEXT" picklistsource="manual" defaultvaluetype="fieldvalue" required="true" defaultValue="Case">
                    <picklistentries>
                        <entry value="Case" label="Case"/>
                        <entry label="Opportunity" value="Opportunity"/>
                    </picklistentries>
                </field>
            </fields>
            <conditions/>
            <actions/>
        </model>
    </models>
    <components>
        <pagetitle model="Task" uniqueid="sk-Q3i-199">
            <maintitle>
                <template>New {{Model.label}}</template>
            </maintitle>
            <subtitle>
                <template>{{Model.labelPlural}}</template>
            </subtitle>
            <actions>
                <action type="savecancel" afterCancel="/{{Model.KeyPrefix}}/o" afterSave="/{{Id}}" rollbackonanyerror="true" uniqueid="sk-Q3i-197"/>
            </actions>
        </pagetitle>
        <basicfieldeditor showheader="true" showsavecancel="false" showerrorsinline="true" model="Selector" uniqueid="sk-Q3i-587" mode="edit">
            <columns>
                <column width="100%">
                    <sections>
                        <section title="Select WhatId" collapsible="no">
                            <fields>
                                <field uniqueid="sk-Q3i-655" id="SelectWhatIdObject">
                                    <renderconditions logictype="and" onhidedatabehavior="keep"/>
                                    <enableconditions/>
                                </field>
                            </fields>
                            <renderconditions logictype="and"/>
                        </section>
                    </sections>
                </column>
            </columns>
        </basicfieldeditor>
        <grid uniqueid="sk-Q3i-1242">
            <divisions>
                <division behavior="flex" minwidth="100px" ratio="1">
                    <components>
                        <skootable showconditions="true" showsavecancel="false" showerrorsinline="true" searchmethod="server" searchbox="false" showexportbuttons="false" hideheader="false" hidefooter="false" pagesize="10" alwaysresetpagination="false" createrecords="true" model="Task" buttonposition="" mode="edit" allowcolumnreordering="false" responsive="true" uniqueid="sk-Q3i-1092" emptysearchbehavior="query">
                            <fields>
                                <field id="CaseLookup" hideable="false" uniqueid="fi-Q3i-1117" showbydefault="true">
                                    <renderconditions logictype="and" onhidedatabehavior="keep">
                                        <rendercondition type="fieldvalue" operator="=" enclosevalueinquotes="true" fieldmodel="Selector" sourcetype="fieldvalue" nosourcerowbehavior="skipandnorender" field="SelectWhatIdObject" value="Case"/>
                                    </renderconditions>
                                    <enableconditions/>
                                </field>
                                <field id="OpportunityLookup" hideable="false" uniqueid="fi-Q3i-1118" showbydefault="true">
                                    <renderconditions logictype="and" onhidedatabehavior="keep">
                                        <rendercondition type="fieldvalue" operator="=" enclosevalueinquotes="true" fieldmodel="Selector" sourcetype="fieldvalue" nosourcerowbehavior="skipandnorender" field="SelectWhatIdObject" value="Opportunity"/>
                                    </renderconditions>
                                    <enableconditions/>
                                </field>
                                <field id="WhatId" hideable="false" uniqueid="fi-Q3i-1115" showbydefault="true"/>
                                <field id="Subject" hideable="false" uniqueid="fi-Q3i-1116" showbydefault="true"/>
                            </fields>
                            <rowactions>
                                <action type="edit"/>
                                <action type="delete"/>
                            </rowactions>
                            <massactions usefirstitemasdefault="true">
                                <action type="massupdate"/>
                                <action type="massdelete"/>
                            </massactions>
                            <views>
                                <view type="standard"/>
                            </views>
                            <searchfields/>
                        </skootable>
                    </components>
                </division>
                <division behavior="flex" verticalalign="top" minwidth="100px" ratio="1">
                    <components>
                        <basicfieldeditor showsavecancel="false" showheader="true" model="Task" mode="edit" uniqueid="sk-Q3i-212">
                            <columns>
                                <column width="50%">
                                    <sections>
                                        <section title="Basics">
                                            <fields>
                                                <field id="Subject" uniqueid="sk-Q3i-207"/>
                                            </fields>
                                        </section>
                                    </sections>
                                </column>
                                <column width="50%">
                                    <sections>
                                        <section title="Additional Info" collapsible="no">
                                            <fields>
                                                <field uniqueid="sk-Q3i-341" id="CaseLookup" pagesize="5" redirecttype="datasourcedefault">
                                                    <renderconditions logictype="and" onhidedatabehavior="keep">
                                                        <rendercondition type="fieldvalue" operator="=" enclosevalueinquotes="true" fieldmodel="Selector" sourcetype="fieldvalue" nosourcerowbehavior="skipandnorender" field="SelectWhatIdObject" value="Case"/>
                                                    </renderconditions>
                                                    <enableconditions/>
                                                    <searchfields/>
                                                    <filters/>
                                                </field>
                                                <field uniqueid="sk-Q3i-911" id="OpportunityLookup">
                                                    <renderconditions logictype="and" onhidedatabehavior="keep">
                                                        <rendercondition type="fieldvalue" operator="=" enclosevalueinquotes="true" fieldmodel="Selector" sourcetype="fieldvalue" nosourcerowbehavior="skipandnorender" field="SelectWhatIdObject" value="Opportunity"/>
                                                    </renderconditions>
                                                    <enableconditions/>
                                                </field>
                                                <field uniqueid="sk-Q3i-252" id="WhatId"/>
                                            </fields>
                                        </section>
                                    </sections>
                                </column>
                            </columns>
                        </basicfieldeditor>
                    </components>
                </division>
            </divisions>
            <styles>
                <styleitem type="background" bgtype="none"/>
            </styles>
        </grid>
    </components>
    <resources>
        <labels/>
        <css/>
        <javascript/>
        <actionsequences uniqueid="sk-Q3i-248"/>
    </resources>
    <styles>
        <styleitem type="background" bgtype="none"/>
    </styles>
</skuidpage>
Photo of Mark DeSimone

Mark DeSimone, Official Rep

  • 12,352 Points 10k badge 2x thumb
Joe, thank you for sharing this and contributing to the Community. 

Tim, is this helpful in your research?
Photo of Tim Shores

Tim Shores

  • 730 Points 500 badge 2x thumb
Maybe! I haven't had a chance to look at it yet. Joe, I greatly appreciate the code share, and I will let you know how it goes.
Photo of Tim Shores

Tim Shores

  • 730 Points 500 badge 2x thumb
Thanks again for sharing the code, Josef. I may misunderstand, but I am still unable to modify the WhatID field.options.searchTemplate parameter. I've tried running a script both from a field renderer, and from a model action that is initiated when the WhatID field is updated (which includes when someone changes the parent object picklist).

I've settled for restricting my targetObjects array to objects that have Name fields, which are easier to identify by search. One problem I have is that objects with autonumber IDs appear in the search layout as "C-0001", "C-0002" and so on. I removed those objects from my WhatID field to avoid frustrating my end users with unclear search results.

The drawback of course is that my Named objects will only return results based on search terms in the Name field, but I think I can live with that for now.

I may take another crack at this some day. If someone else has a great way to modify the searchTemplate of the polymorphic WhatID field, I'm all ears.
Photo of Josef Lagorio

Josef Lagorio

  • 3,394 Points 3k badge 2x thumb
I don't understand what you mean by unable to modify the field.options.searchTemplate. Can you share the modifications you've made to the code? 

Change the fields for field.options.searchTemplate in the case statements will modify what's displayed to the end user. 
Photo of Tim Shores

Tim Shores

  • 730 Points 500 badge 2x thumb
I figured out my problem... I have more than one picklist on the form, and the WhatId is not first. So when using jquery to run the function when the selector is changed, I had to use includes() instead of startsWith().

It is working now. My code is below.

Now I have one quibble that I'd like to work out. When I first select my WhatId object type, and begin typing to search, it displays the searchTemplate correctly, but it does not search on searchTemplate fields other than Name. If I choose one of the search results, then repeat my first search term, it successfully searches on searchTemplate fields other than Name.

Step 1: No results when searching on a field other than Name


Step 2: Search on Name, click any result



Step 3: Repeat the first search, now there are results




--

var $ = skuid.$,
    targetObjects = ['Campaign', 'Opportunity', 'Account', 'Program_Cohort__c', 'Proposal__c', 'Team__c'], // Define the objects made available in the selector.
    field = arguments[0], 
    value = skuid.utils.decodeHTML(arguments[1]), 
    metadata = field.metadata, 
    model = field.model,
    row = field.row,
    whatId = row.WhatId,
    whatString = String(whatId),
    whatPrefix = whatString.substring(0,3),
    renderAsPicklist = false; // if set to true, WhatId lookup field becomes a picklist. Not useful for objects with large number of search results.
    
var updateFieldData = function(field, whatPrefix) {
    
    // this function controls which fields are searched and made visible in the selector popup.
    // https://community.skuid.com/skuid/topics/use-javascript-to-control-the-display-and-search-templates-...
    switch ( whatPrefix ) {
        
        case "701":     // Campaign
            field.options.returnFields = [
                {id: 'Id', showInSearchDialog: false},
                {id: 'Name', showInSearchDialog: true},
                {id: 'Program__c', showInSearchDialog: true},
                {id: 'StartDate', showInSearchDialog: true},
                {id: 'EndDate', showInSearchDialog: true},
            ];
            field.options.searchTemplate = "{{Name}}, Program: {{Program__c}}, {{StartDate}} - {{EndDate}}";
            break;
            
        case "006":     // Opportunity
            field.options.returnFields = [
                {id: 'Id', showInSearchDialog: false},
                {id: 'Name', showInSearchDialog: true},  
                {id: 'StageName', showInSearchDialog: true},  
            ];
            field.options.searchTemplate = "{{Name}}, Stage: {{StageName}}";
            break;
            
        case "001":     // Account aka Organization
            field.options.returnFields = [
                {id: 'Id', showInSearchDialog: false},
                {id: 'Name', showInSearchDialog: true},
                {id: 'Organization_Alias_Name__c', showInSearchDialog: true},
            ];
            field.options.searchTemplate = "{{Name}}, Alias: {{Organization_Alias_Name__c}}";
            break;
        
        case "a2C":     // Program Cohort
            field.options.returnFields = [
                {id: 'Id', showInSearchDialog: false},
                {id: 'Name', showInSearchDialog: true},
                {id: 'Program_Start_Date__c', showInSearchDialog: true},
                {id: 'Program_End_Date__c', showInSearchDialog: true},
            ];
            field.options.searchTemplate = "{{Name}}, {{Program_Start_Date__c}} - {{Program_End_Date__c}}";
            break;
        
        case "a2m":     // Proposal
            field.options.returnFields = [
                {id: 'Id', showInSearchDialog: false},
                {id: 'Name', showInSearchDialog: true},
                {id: 'Program__c', showInSearchDialog: true},
                {id: 'nciia_id__c', showInSearchDialog: true},
                {id: 'Legacy_ID__c', showInSearchDialog: true},
            ];
            field.options.searchTemplate = "{{Name}}, {{Program_Start_Date__c}} - {{Program_End_Date__c}}";
            break;
            
        case "a26":     // Team
            field.options.returnFields = [
                {id: 'Id', showInSearchDialog: false},
                {id: 'Name', showInSearchDialog: true},
            ];
            field.options.searchTemplate = "{{Name}}";
            break;
    }
    
};
if (field.mode == 'edit') { 
    // Limit the set of target objects 
    var targets = [], 
        uniqueTargets = {}; 
        
    $.each(metadata.referenceTo,function(i,r){ 
        if (($.inArray(r.objectName,targetObjects) != -1) && (!uniqueTargets[r.objectName])) { 
            targets.push(r); 
            uniqueTargets[r.objectName] = 1; 
            if (targets.length == targetObjects.length) return false; 
        } 
    }); 
    if (targets.length) { 
        
        // Make this field render as a picklist? (no - var is set to false for this implementation)
        if (renderAsPicklist) field.options.type = 'REFPICK'; 
        // Override the current referenceTo 
        metadata.referenceTo.length = 0; 
        metadata.ref = $.map(targets,function(targ){return targ.objectName;}).join();
        metadata.referenceTo = targets; 
    } 
}
// Get field renderer - https://docs.skuid.com/latest/en/skuid/api/skuid_ui.html#skuid.ui.getFieldRenderer
skuid.ui.getFieldRenderer(field)[field.mode](field, value);
// control the search layout
if ( whatPrefix === 'und') whatPrefix = "701";    // default to Campaign
updateFieldData(field, whatPrefix);
$(field.element).find("select").bind("change", function(e) {
    var val = $( "select option:selected" ).text();
    
    if( val.includes("Campaign") ) {
        
        updateFieldData(field,"701");
        
    } else if ( val.includes("Opportunity")) {
    
        updateFieldData(field,"006");
    
    } else if ( val.includes("Organization")) {
    
        updateFieldData(field,"001");
    
    } else if (val.includes("Program Cohort")) {
        
        updateFieldData(field,"a2C");
        
    } else if (val.includes("Proposal")) {
        
        updateFieldData(field,"a2m");
        
    } else if (val.includes("Team")) {
        
        updateFieldData(field,"a26");
        
    } else { 
        
        updateFieldData(field, whatPrefix);
        
    }
});