0

I have recreated the Task Edit page in VF. If I have a contact Id in a jquery variable, how can I set that Id to the Name field so that when the Task record is saved, the correct contact is saved? Obviously, I can't put the Id in the name field...

Task Edit Screenshot

selContact() is fired on a selectList onchange event. I've taken the selected contact's id and put it in the Name field for illustration purposes. My page:

<apex:page standardController="Task" tabStyle="task" extensions="GetContactsOnTaskExtension">
<script type="text/javascript" src="/resource/jQuery_1_8/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict(); 

function selContact()
{       
    var val = $j("[id$='selContacts']").val();
    $j("[id$='whoid']").val(val);
}

function getParameterByName(name) 
{
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
<apex:form >
    <apex:pageBlock title="Task Edit" mode="edit">
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
            <apex:commandButton action="{!cancel}" value="Cancel"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection title="Task Information" columns="2">
            <apex:inputField value="{!Task.ownerid}"/>
            <apex:inputField value="{!Task.whatid}"/>
            <apex:inputField value="{!Task.subject}"/>

            <apex:inputHidden value="{!whoId}" id="whoid"/> 

            <apex:inputField value="{!Task.status}"/>
            <apex:inputField value="{!Task.activitydate}"/>
            <apex:inputField value="{!Task.Call_Date__c}"/>
            <apex:inputField value="{!Task.Upsells__c}"/>
            <apex:inputField value="{!Task.Call_Time__c}"/>
            <apex:inputField value="{!Task.Cross_Sells__c}"/>
            <apex:inputField value="{!Task.priority}"/>
            <apex:inputField value="{!Task.Interaction_Type__c}"/>
            <apex:inputField value="{!Task.description}" style="width:100%;height:100px"/>     
            <apex:selectList id="selContacts" value="{!ContactOptions}" size="1" onchange="selContact()">
                <apex:selectOptions value="{!items}"></apex:selectOptions>
            </apex:selectList>           
        </apex:pageBlockSection>

        <apex:pageBlockSection title="Task Subject" columns="2">
            <apex:inputField value="{!Task.Extracts__c}"/>
            <apex:inputField value="{!Task.Ancillary__c}"/>
            <apex:inputField value="{!Task.Left_Packet_Insert__c}"/>            
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>

My controller extension:

public with sharing class GetContactsOnTaskExtension 
{

    public String accountId {get; set;}
    public String subject {get; set;}
    public String contactId {get; set;}
    public String whoId {get; set;}
    public List<Contact> contacts {get;set;}
    public List<Contact> provContacts {get; set;}
    public List<Affiliation__c> providers {get;set;}
    public List<String> providerIds = new List<String>();

    String[] ContactOptions = new String[]{};

    //TODO
    public Contact contact {get;set;}

    // Constructor
    public GetContactsOnTaskExtension(ApexPages.StandardController controller)
    {
            getParms();

            //setDefaultValues();

            getContacts();

            //TODO
            contact = new Contact();

    }

    // Get URL Parameters
    private void getParms()
    {
            // Account ID
            accountId = System.currentPageReference().getParameters().get('what_id');

            // Owner ID
            //whoId = System.currentPageReference().getParameters().get('who_id');

            // Subject
            //subject = System.currentPageReference().getParameters().get('subject');
    }

    // Main
    private void getContacts()
    {
            if (null!=accountId)
            {
                    getBusinessContacts();

                    getProviderContacts();

                    addProviderContacts();
            }
    }

    // Get contacts under the Business account
    private void getBusinessContacts()
    {
            contacts =
            [
                    SELECT id,Name,FirstName, LastName 
                    FROM Contact 
                    WHERE AccountId = : accountId
            ];
    }

    // Get Provider contact records affiliated with this account
    private void getProviderContacts()
    {       
            // Get Accounts 
            providers =
            [
                    SELECT Provider_Account__c // Provider_Account__c is a formula field on Affiliation
                    FROM Affiliation__c 
                    WHERE Account__c = : accountId
            ];

            // Set list of Person Account Id strings for contact query
            for (Affiliation__c aff : providers)
            {
                    providerIds.add(aff.Provider_Account__c);
            }

            // Query contact records
            if (providerIds.size() > 0)
            {
                    provContacts =
                    [
                            SELECT Id, FirstName, LastName, Name
                            FROM Contact
                            WHERE AccountId IN : providerIds
                    ];
            }
    }

    // Add provider contacts to contacts list
    private void addProviderContacts()
    {
            for (Contact cnt : provContacts)
            {
                    contacts.add(cnt);
            }
    }

    public List<SelectOption> getItems() 
    {
        List<SelectOption> options = new List<SelectOption>();

        options.add(new SelectOption('', '--None--'));

        for (Contact cnt : contacts) 
        {
            options.add(new SelectOption(cnt.Id, cnt.Name));
        }
        return options;
    }

    public String[] getContactOptions() 
    {
        return ContactOptions;
    }

    public void setContactOptions(String[] ContactOptions) 
    {
        this.ContactOptions = ContactOptions;
    }      
}

Added save method:

public pageReference saveTheTask()
    {
        Task newTask = new Task();

        newTask.WhoId = items; // Not sure this is right
        newTask.WhatId = Task.whatid; // compile stops here: Illegal assignment from Schema.SObjectField to Id
        newTask.Status = Task.status;
        newTask.Priority = Task.priority;

        insert newTask;

        return null;
    }

3 Answers 3

3

If you have Id in a Jquery variable.

Add a hidden inputfield in the existing <apex:form> and assign id to its value attribute.

Ex:

<apex:inputHidden value="{!contactId}" id="whoid"/>

script

function selContact()
{ 
    // assuming "val" contains id      
    var val = $j("[id$='selContacts']").val();
    $j("[id$='whoid_lkid']").val(val); // this will assign id
}
8
  • Thanks for the quick response. When trying that, I get "Error: Unknown property 'TaskStandardController.contactId'". I'm assuming that's the wrong Contact Id for Task object?
    – Adam H.
    Feb 26, 2014 at 16:35
  • You have to define property in controller like: public String contactId {get; set;} and use it in your logic. @AdamH.
    – Ashwani
    Feb 26, 2014 at 16:48
  • Thanks again. I've tried your suggestion. When saving the record, the edit page simply refreshes, no saved record. I don't see any errors either.
    – Adam H.
    Feb 26, 2014 at 16:59
  • If you are using Task standard controller, write is like: <apex:inputHidden value="{!whoId}" id="whoid"/> @AdamH.
    – Ashwani
    Feb 26, 2014 at 17:55
  • I've edited my original post to include my page and controller. Can you please take a quick look and tell me where I'm going wrong?
    – Adam H.
    Feb 26, 2014 at 18:58
1

To save the Id properly, you need to somehow send that information back to SFDC. There are two ways to do this:

(1) Via Controller - First, have a controller variable hold the Id that you want to record. Then, in your save method, make sure to attach the Id appropriately to your data.

Pros: Everything is easily managed in the Controller. This option requires minimal "extra" coding, so it's the go-to method for quick, simple applications.

Cons: Apex Action Methods cannot have any input parameters, so you need to store any "inputs" as Controller Variables. You might run into performance issues IF BOTH (1) the Controller / View State holds a LOT of data and (2) this method is called often on the VF page. Since the View State is large, it will take a long amount of time each time data is sent between the Client and SFDC.

(2) Via Javascript - Since the Id is already in Javascript (jQuery), it might make the most sense to save that information right in Javascript (via a @RemoteAction controller method or using the SOAP API). Documentation.

Pros: This option is independent of the controller, so invoking the Javascript methods to save the Id properly don't require sending the Controller's View State back and forth between the Client and SFDC. Javascript methods may have much faster response than using Controller methods. Plus, your data is already in Javascript.

Cons: This option is independent of the controller. If you need the Id you are setting to interact with ANY part of the Controller, this method won't work because @RemoteAction methods are asynchronous -- they talk to SFDC one-on-one. The benefit is you can have input parameters with your @RemoteAction method.


Your case seems to be rather simple, so I'd bet going with option (1) would be the best bet. When you get the ContactIds to select from, why not also grab the Contact records and store them in a map. Then when an Id is selected (maybe use apex:actionSupport on an onchange event), execute a method to set the ContactName using the map.

Also, I'm not exactly clear on what you're trying to do. From your code, the selected Contact Id is saved as the ContactOptions string since it's apex:selectList's value. I think you are trying to make sure to put the value of ContactOptions as the whoId in your task. If that's the case, then just make your own save method, and call the one you make instead of {!save} in VF.

Example:

public pageReference saveTheTask(){
    Task newTask=new Task(whoId=ContactOptions);
    // set other import stuff
    insert newTask;
    return null;  // or return wherever you want to go
}
1
  • Thank you for the thorough reply! I believe you last paragraph is the direction I need to go though. I'm simply trying to save a standard task, but letting the user selected the account's associated contacts from a drop down instead of using the flawed contact lookup. I've added my save method, but compilation stops short. See code block above.
    – Adam H.
    Feb 26, 2014 at 20:10
0

I was finally able to work this out. I completely scrapped what I had and started over reading the documentation as I went (imagine that). Here's what I came up with:

Page:

<apex:page standardController="Task" extensions="ext_GetAccountContacts">
<apex:form >
    <apex:pageBlock title="Task Edit" mode="edit">
    <apex:messages />
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
            <apex:commandButton action="{!cancel}" value="Cancel"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection title="Task Information" columns="2">

            ...
            <apex:selectList value="{!selContact}" label="Contact Name" size="1">
                <apex:selectOptions value="{!contacts}"></apex:selectOptions>
            </apex:selectList>  
            ...  

    </apex:pageBlock>
</apex:form>

Extension:

public with sharing class ext_GetAccountContacts 
{
public Task task;
public String acctIdParm = ApexPages.currentPage().getParameters().get('what_id');
public String selContact;

public ext_GetAccountContacts(ApexPages.StandardController stdController)
{
    task = (Task)stdController.getRecord();
}

public List<SelectOption> getContacts()
{
    ...
    return options;
}

public String getSelContact()
{
    return selContact;
}

// Set the selected Contact's ID as the whoid
public void setSelContact(String s)
{
    task.whoid = s;
}

public PageReference save()
{   
    insert task;

    if (acctIdParm != '' && acctIdParm != null)
    {
            PageReference pg = new PageReference('/' + acctIdParm);
            pg.setRedirect(true);
            return pg;
    }
    else
    {
            return null;
    }
}
}

Works like a champ. Hope this helps someone in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.