symfonysymfony-2.4

Symfony2 form validation without createFormBuilder


I am trying to validate the form that I have made myself in .twig file.I am not creating form using createFormBuilder. This is my Controller Code that is call for both case 1) for view 2) after submitting the form.

public function cart_newAction(Request $request)
 {      
    $entity = new Product();
    $errors = '';
    if ($request->getMethod() == 'POST') 
    {
        $validator = $this->get('validator');
        $errors = $validator->validate($entity);
        if (count($errors) > 0) {
            echo 'Error';
        } 
        else {
            echo 'Success';             
        }
    }
    return $this->render('CartCartBundle:Cart:Add.html.twig', array('errors' => $errors ));
}

this is view file and I am showing errors like this Add.html.twig

{% for error in errors %}
    {{error}}
{% endfor %}

I have set the error in validation.yml file for name that cannot be blank. So now when I run the view page it every times show the error after I submit the form. If no error it should not display me the error just show the blank error.

Note:Is there any better way that I can do this so please share it.Remember that I am doing it without createFormBuilder UPDATE It always show me Error.Even if my form is valid and don't missing any field.


Solution

  • If you want to make the form yourself then you can't validate it using the Syfmony form validator. You need to use a simple PHP validation Server-side. Something like this

    if ($request->getMethod() == 'POST') 
    {
        $username = $_POST['username'];
        if ($username == '')
        {
           // set error message here
        } 
    }