Reputation: 12740
I want to add a validation so that the the keyword and the field form elements become compulsory. These are not attached to any kind of entity though. I'm just going to handle the request in my controller. I'm not interested in HTML5 validation which I can do it myself.
Rules: Keyword
cannot be null and Field
cannot have anything apart from firstname or middlename values.
FORM TYPE:
class SearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$field = array('' => '', 'firstname' => 'Firstname', 'middlename' => 'Middlename');
$builder
->setAction($options['action'])
->setMethod('POST')
->add('keyword', 'text', array('label' => 'Keyword', 'error_bubbling' => true))
->add('field', 'choice', array('label' => 'Field', 'choices' => $field, 'error_bubbling' => true))
->add('search', 'submit', array('label' => 'Search'));
}
public function getName()
{
return 'personsearch';
}
}
CONTROLLER:
class SearchController extends Controller
{
public function indexAction()
{
$form = $this->createForm(new SearchType(), array(),
array('action' => $this->generateUrl('searchDo')));
return $this->render('SeHirBundle:Default:search.html.twig',
array('page' => 'Search', 'form' => $form->createView()));
}
public function searchAction(Request $request)
{
//I'll carry out searching process here
}
}
Upvotes: 0
Views: 69
Reputation: 5237
This page in the docs details how to do what you want: http://symfony.com/doc/current/book/validation.html
Specifically, with your implementation of forms you can do something like this:
use Symfony\Component\Validator\Constraints\NotBlank;
// ...
$builder
->setAction($options['action'])
->setMethod('POST')
->add('keyword', 'text', array(
'label' => 'Keyword',
'error_bubbling' => true,
'constraints' => array(
new NotBlank(),
)
))
->add('field', 'choice', array(
'label' => 'Field',
'choices' => $field,
'error_bubbling' => true
))
->add('search', 'submit', array(
'label' => 'Search'
))
;
More on this at: http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class
As for your field
element, you may need to make a new constraint yourself for that.
You may also like to look at the "Validation and Forms" section. Personally I prefer using the annotations method when doing validation.
If you want to use that method then, on your model, add the following use statement:
use Symfony\Component\Validator\Constraints as Assert;
And then use an annotation above the property you are validating:
/**
* @Assert\NotBlank()
*/
public $name;
All of the constraints available may be found and described here: http://symfony.com/doc/current/book/validation.html#validation-constraints
From your code, it seems you're not checking if the form is valid, you can add this section, and then redirect to your search action when the model is deemed valid.
Upvotes: 1