Thanks to both of you for posting examples. I always enjoy seeing different implementations. Mine is actually a method, but I just didn't post the whole class.
arborint wrote:I think you can pass strings or objects as content.
I'm not quite sure from your comment as to whether or not you think that's good.
I haven't done it, but do you think it's worth writing an extending class for each type of element if you already have a generic constructor like this? I'm leaning toward not doing it.
Going back to the validation topic, a simple usage of my validate class looks like:
Code: Select all
$form = new Vm_Validate();
//Add a single validation
$form->addValidator('email', $_POST['email'], 'email', 'You must enter a valid email address');
//Add multiple validations
$form->addValidators('username', $_POST['username'], array(
'required'=>'A username is required',
'alphanum' //The default error is used
));
//Get all the errors for a single field
if ($form->errorsExist('username')){
$getErrors = $form->getErrors('username');
foreach($getErrors as $error){
$errorAttributes = array(
'class'=>'errorListItem',
'innerHtml'=>$error
);
$errors .= Vm_Xml::createTag('li', $errorAttributes)."\n";
}
$errorListAttributes = array(
'id'=>'usernameErrorList',
'class'=>'errorListClass',
'innerHtml'=>$errors
);
$errorList = Vm_Xml::createTag('ul', $errorListAttributes)."\n";
echo $errorList;
}
//Get all the errors for the form
if ($form->errorsExist()){
$getErrors = $form->getAllErrors();
foreach($getErrors as $error){
$errorAttributes = array(
'class'=>'errorListItem',
'innerHtml'=>$error
);
$errors .= Vm_Xml::createTag('li', $errorAttributes)."\n";
}
$errorListAttributes = array(
'id'=>'errorList',
'innerHtml'=>$errors
);
$errorList = Vm_Xml::createTag('ul', $errorListAttributes)."\n";
echo $errorList;
}
However, if I use my form class, I could write the above (plus the entire form code and labels) using just this code:
Code: Select all
$form = new VM_Form(array(), array('errorPosition'=>'beforeForm'));
$form->text('email', array(
'validators' => array(
'email',
'required'=>'An email is required'
),
'label' => array(
'innerHtml'=>'Email',
'class'=>'label'
),
'attributes' => array('class'=>'input')
));
$form->text('username', array(
'attributes' => array('class'=>'input'),
'label' => array(
'innerHtml'=>'Username',
'class'=>'label'
),
'validators' => array(
'required'=>'A username is required',
'alphanum'
)
));
$form->submit(array(
'value'=>'Submit',
'id'=>'submit'
));
//If you were to save the form data or do anything else with it, it would go here
echo $form->render();
Filters can be added the same way as validators and you have access to both the raw and filtered data.