Thursday, September 25, 2008

Visualforce Tip: Custom Components + DML

I built a Visualforce custom component today and ran in to (what should have been) a fairly trivial problem.

As you can see below, my Visualforce custom component has a CommandLink and the controller has a corresponding action method that updates a field on the displayed Contact record.

CommandLink:
<apex:commandlink value="Associate External Id to Contact" action="{!associate}">

Action Method:
public PageReference associate()
{

c.ExternalId__c = ExternalId;
update c;

return ApexPages.currentPage();
}


There's not much complexity here, but every time I clicked on the ComandLink, I kept getting this error:

System.Exception: DML currently not allowed

I had read the documentation, scoured the message boards, thoroughly searched the wiki and was about to submit my own question to the message boards when I gave the documentation one last look. To my joy/chagrin, I discovered the allowDML attribute on the Visualforce component standard component. It has this description:

If this attribute is set to true, you can include DML within the component. The default is false.

Here's what my component tag looks like now:
<apex:component controller="MyContactController" allowDML="true">

2 comments:

Michael Reiley said...

Thank you for posting this... I had the exact same issue and finding your post saved me a lot time.

Massi said...

thank you so mutch !! you save me !!