I am creating a new Case via a VF page in a VF+Tabs Community (not using SFDC stylesheets) and want the user to be able to set the Asset Name to the Asset related to their new Case. The Asset Name is a Lookup Field.
I have a Controller Extension and VF and that shows the current logged in user a list of all of their Asset Names for them to choose one for their Case.
I am stuck on how to use their selection for the {!Case.Asset.Name} field. I am not able to just write that value to the {!Case.Asset.Name} field since it is a Lookup field.
How do I set the value of the {!Case.Asset.Name} field based on the users selection from the list of Asset Names they have been presented with?
Is there a better way to present them with the list of Asset Names via a Lookup directly on my VF page that will set the value of that field when submitting that new Case?
Here is the Controller Extension I am currently using:
public class myWeb2CaseExtension {
public Case webcase {get;set;}
public SelectOption[] assetOptions {get;set;}
public myWeb2CaseExtension(ApexPages.StandardController stdController) {
webcase = (Case) stdController.getRecord();
User[] users = [SELECT ContactId FROM User WHERE Id = :UserInfo.getUserId()];
User usr = users[0];
Contact[] contacts = [SELECT Id, AccountId FROM Contact WHERE Id = :usr.ContactId];
if (contacts.isEmpty()) {
// handle when contacts is empty
} else {
Contact cont = contacts[0];
Asset[] assets = [SELECT Name, ContactId, AccountId FROM Asset WHERE AccountId = :cont.AccountId];
assetOptions = new SelectOption[] {};
//if you want people to be able to choose no asset do this
assetOptions.add(new SelectOption('None', 'None'));
for (Asset asst: assets) {
assetOptions.add(new SelectOption(asst.Id, asst.Name));
}
}
}
public PageReference saveCase() {
try {
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.useDefaultRule = true;
webcase.setOptions(dmlOpts);
webcase.Origin = 'Web';
insert(webcase);
} catch (System.DMLException e) {
ApexPages.addMessages(e);
return null;
}
PageReference p = Page.MyCases;
p.setRedirect(true);
return p;
}
}
Here is the section of my Visualforce page that currently lists the Asset names from the code in the Controller Extension
<apex:selectList value="{!Case.Asset.Name}" size="7" >
<apex:selectOptions value="{!assetOptions}" />
</apex:selectList>
PROBLEM SOLVED : I solved my problem by replacing the Visualforce code mentioned above with the following code in my Visualforce page
<apex:selectList value="{!Case.AssetId}" size="7" >
<apex:selectOptions value="{!assetOptions}" />
</apex:selectList>