Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Form Questions /

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba

ss 2.4.2 RequiredFields CheckboxField


Go to End
Reply


2 Posts   1531 Views

Avatar
golo

Community Member, 1 Post

14 November 2010 at 9:47am

Hi Forum,
i build an simle Contactform with some required fields - it works fine exapt of the CheckboxField - it need to be checked.
How can i do this?

Here my code (part of):

class ContactPage_Controller extends Page_Controller
{
function ContactForm() {

$fields = new FieldSet(
new CheckboxField('Datenschutz', _t('ContactForm.datenschutzklausel'),0),
new TextField('Name', 'Ihr Name*:'),
new EmailField('Email', 'Ihre E-Mail*:'),
new TextareaField('Comments','Nachricht an uns:')
);

$actions = new FieldSet(
new FormAction('SendContactForm', 'Send')
);

$validator = new RequiredFields(array('Name', 'Email', 'Datenschutz'));

return new Form($this, 'ContactForm', $fields, $actions, $validator);
}

function SendContactForm($data, $form) {

$From = $data['Email'];
$To = $this->Mailto;
$Subject = "Mediapool-Login beantragen";
$email = new Email($From, $To, $Subject);

$email->setTemplate('ContactEmail');

$email->populateTemplate($data);

$email->send();

Director::redirect($this->Link("?success=1"));
}

public function Success()
{
return isset($_REQUEST['success']) && $_REQUEST['success'] == "1";
}

}

thanx fpr helping

Avatar
FungshuiElephant

Community Member, 57 Posts

22 February 2011 at 5:56am

Another old post, but for others who need the same...

Subclass Checkboxfield and write your own validate method:

/**
 * Single checkbox field that must be ticked.
 * @package forms
 * @subpackage fields-basic
 */
class RequiredCheckboxField extends CheckboxField {

	/**
	 * Validate (i.e. see whether it's checked or not.
	 * @param validator
	 * @return boolean Whether the field validates or not.
	 */
	public function validate($validator){
		$valid = $this->value==1;
		
		//Report error?
		if (!$valid) {
			$validator->validationError(
				$this->name,
				($this->customValidationMessage)?$this->customValidationMessage:sprintf(_t('Form.FIELDISREQUIRED', '%s is required').'.', strip_tags('"' . ($this->Title() ? $this->Title() : $this->Name()) . '"')),
				"required"
			);
		}

		return $valid;
	}
	
}

then just use RequiredCheckboxField in place of CheckboxField in your form.

Works with a RequiredFields validator.
You can use $myField->setcustomValidationMessage("message") to set a custom message.

Aram's http://archive.ssbits.com/using-jquery-for-form-validation/
about jQuery validation stuff might also be of interest.