How to make a field required in CiviCRM

$form->addRule();

Here’s an example from the hook_civicrm_buildForm() function in a custom module we’ve been working on.

if ($formName == ‘CRM_Contribute_Form_Contribution’) {
$form->addRule(‘receive_date’, ts(‘This field is required.’), ‘required’, NULL, NULL, NULL, TRUE);
$form->addRule(‘contribution_page_id’,  ts(‘This field is required.’), ‘required’, NULL, NULL, NULL, TRUE);
}

What does the TRUE at the end do?

It fixes the QuickForm “nonexistent html element” error, by forcing the rule to be applied, even if the target form element does not exist

http://pear.php.net/manual/en/package.html.html-quickform.html-quickform.addrule.php
So: try this first –

$form->addRule(‘receive_date’, ts(‘This field is required.’), ‘required’);

… and if you run into the nonexistent html element error, then add the extra parameters.

Advertisements
Posted in CiviCRM
One comment on “How to make a field required in CiviCRM
  1. Brandon Ferrell says:

    For everyone trying to make an image required, use this

    if($this->elementExists(‘attachFile_1’)) {
    $this->addRule(‘attachFile_1’, ts(‘You must upload a photo’), ‘required’);
    $this->addRule(‘attachFile_1’, ts(‘You must upload a photo’), ‘uploadedfile’);
    }

    For some reason, you need both and using the force flag causes the form not so save. Well, at least for PCP’s

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: