Dynamically Control the WhatId reference field popup

  • 1
  • Question
  • Updated 1 month ago
  • In Progress
  • (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

  • 2,864 Points 2k badge 2x thumb

Posted 8 months ago

  • 1
Photo of Bill McCullough

Bill McCullough, Champion

  • 12,436 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

  • 11,050 Points 10k badge 2x thumb
Hi Tim,

It doesn't look like that link is working. Could there have been a problem when posting it? I believe late last week, the Community may have had some intermittent issues. Let me know if you are able to link to the post, or if you end up writing another one, and I'd be happy to look at your question. 
Photo of Tim Shores

Tim Shores

  • 512 Points 500 badge 2x thumb
Hmm ... oh well. Yeah after I posted it, the community site was having some issues. My post shows up in search results, but there's nothing behind it. If it can't be recovered based on this clue, I'll try to find time to rewrite it.

Photo of Josef Lagorio

Josef Lagorio

  • 2,852 Points 2k badge 2x thumb
Hey Tim, I know the struggle of looking for answers so heres the end product.

Use this as your "Related to" field's snippet: 

var targetObjects = ['Account', 'Opportunity', 'Campaign']; 
var renderAsPicklist = false; 
field = arguments[0];
var value = skuid.utils.decodeHTML(arguments[1]), 
    metadata = field.metadata, 
    $ = skuid.$; 
var params = arguments[0], model = params.model,
row = params.row,
   $ = skuid.$;

var updateFieldData = function(field, refLength) {
    switch ( refLength) {
        case "001": // Account
            field.options.returnFields = [
            {id: 'Id', showInSearchDialog: false},
            {id: 'Name', showInSearchDialog: true},  
            {id: 'Type', showInSearchDialog: true}, 
            {id: 'Owner.Name', showInSearchDialog: true},  
        ];
        field.options.searchTemplate = "{{Name}} - Type: {{Type}} - Owner: {{Owner.Name}}";
        break;
        case "701":  // Campaign
          field.options.returnFields = [
            {id: 'Id', showInSearchDialog: false},
            {id: 'Name', showInSearchDialog: true},  
            {id: 'Campaign_Channel__c', showInSearchDialog: true},
            {id: 'Type', showInSearchDialog: true},
            {id: 'Period__c', showInSearchDialog: true},
        ];
        field.options.searchTemplate = "{{Name}} - Channel: {{Campaign_Channel__c}} - Period: {{Period__c}}";
        break;
        case "006":  // Oppty
            field.options.returnFields = [
            {id: 'Id', showInSearchDialog: false},
            {id: 'Name', showInSearchDialog: true},  
            {id: 'StageName', showInSearchDialog: true},  
            {id: 'CloseDate', showInSearchDialog: true},  
            {id: 'Industry__c', showInSearchDialog: true}, 
            {id: 'Owner.Name', showInSearchDialog: true},  
        ];
        field.options.searchTemplate = "{{Name}} - Type: {{StageName}} - Industry: {{Industry__c}}";
        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? 
       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; 
    }
}

    skuid.ui.getFieldRenderer(field)[field.mode]( field, value );
    //skuid.ui.fieldRenderers[metadata.displaytype][field.mode](field,value); 

var params = arguments[0],
    model = params.model,
    row = params.row,
    $ = skuid.$;

var whatId = row.WhatId;

var refString = String(whatId);
var refLength = refString.substring(0, 3);
if ( refLength === 'und') refLength = "001";//default to account

$(field.element).find("select").bind("change", function(e) {
   var val = $( "select option:selected" ).text();
   if ( val.startsWith("Opportunity")) {
       updateFieldData(field,"006");
   } else if ( val.startsWith("Account")) {
       updateFieldData(field,"001");
   } else if ( val.startsWith("Campaign")) {
       updateFieldData(field,"701");
   }
   
});

updateFieldData(field, refLength);
Photo of Mark DeSimone

Mark DeSimone, Official Rep

  • 11,050 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

  • 512 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.