Symfony2 form validation without createFormBuilder

symfony form validation
symfony form twig
symfony form without entity
symfony form constraints
symfony form type
symfony form action
symfony form group fields
symfony form submit

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.

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
    } 
}

How to Use a Form without a Data Class (Symfony Docs), How to Use a Form without a Data Class: In most cases, a form is tied to an Pass an object when creating the form (as the first argument to createFormBuilder() or use Symfony\Component\Validator\Constraints\​NotBlank; public function  Symfony Forms without Classes. If you’ve read Symfony’s form documentation, then you probably think that all forms must have a class behind them. This is actually not true – you can simply create a form and bind data to it. If you do this, the form returns an array of data instead of an object:

Ok let me be clear. I gonna give you tow solutions, the first is the best and the most proper way: 1) Generate your EntityForm Type: bin/console make:form or d:g:form command. 2) Then just add some few lines to submit and get the errors.

 public function cart_newAction(Request $request)
 {      
    $entity = new Product();
    $form = $this->createForm(EntityType::class, $entity);
    $form->submitForm($request->request->all(), false);

    if ($request->getMethod()->isPost()) 
    {
    if ($form->isValid()) {
            echo 'Error';
        } 
        else {
            echo 'Success';             
        }
    }
    return $this->render('CartCartBundle:Cart:Add.html.twig', [
         'errors' => $form->getErrors(),
    ]);
}

The second solution is bind your data into your entity object because we need to set the data into our object.

1) First step create a private fonction in your current class to bind all the submited data:

private function bindEntityValues(Product $entity, array $data) {
  foreach ($data as $key => $value){
    $funcName = 'set'+ucwords($key);
    if(method_exists($entity, $funcName)) $entity->$funcName($value);
  }
}

Then your cart_newAction should be like this:

 public function cart_newAction(Request $request)
 {      
    $entity = new Product();
    $this->bindEntityValues(entity, $request->request->all());
    $errors= $this->get('validator')->validate($entity)

    if (count($errors) > 0) {
            echo 'Error';
        } 
        else {
            echo 'Success';             
        }
    }
    return $this->render('CartCartBundle:Cart:Add.html.twig', ['errors' => $errors]);
}

Wish this helped you to have a clear vision.

Forms (Symfony Docs), You need to deal with rendering HTML form fields, validating submitted data, mapping the extends from the AbstractController, use the createFormBuilder() helper: Later, when you begin embedding forms, this will no longer be sufficient. If you're not familiar with Symfony's Validator component, read more about it: Validation. The Form component comes with a ValidatorExtension class, which automatically applies validation to your data on bind. These errors are then mapped to the correct field and rendered.

You must check if $errors is empty or not :

if (count($errors) > 0) {
    return $this->render('CartCartBundle:Cart:Add.html.twig', array('errors' => $errors ));
} else {
    return $this->render('CartCartBundle:Cart:Add.html.twig');
}

See the doc here.

Symfony2 Form and Validation without Classes, Sep 27, 2011 − Ever wanted to use Symfony's validation system just to validate some value? How about using a form without a class behind it? Pass an object when creating the form (as the first argument to createFormBuilder() or the second argument to createForm()); Declare the data_class option on your form. If you don't do either of these, then the form will return the data as an array.

[Form] Expression validation constraint on form without a Data Class , Hello, When using form without a data class (see: http://symfony.com/doc/current/​form/without_class.html), we are not able to use expression to  The recommended workflow when working with Symfony forms is the following: Build the form in a Symfony controller or using a dedicated form class; Render the form in a template so the user can edit and submit it; Process the form to validate the submitted data, transform it into PHP data and do something with it (e.g. persist it in a database).

UniqueEntity & Validation Directly on Form Fields > Symfony 4 Forms, No problem: let's add some validation constraints to email and plainPassword ! We know how to do this: add annotations to the class that is bound to this form:  If the nested entry_type is a compound form type, you must either set the required option to false or set the empty_data option to null. Both of these options can be set inside entry_options. Read about the form's empty_data option to learn why this is necessary.

Beautiful Form Validation > Symfony 3 Forms: Build, Render , Nope, there will be no validation code inside of GenusFormType . Instead, you add validation to the class that is bound to your form. When the form is submitted, it  The Symfony validator is a powerful tool that can be leveraged to guarantee that the data of any object is "valid". The power behind validation lies in "constraints", which are rules that you can apply to properties or getter methods of your object.

Comments
  • What is your question?
  • @xdazz actually I want the form validation I am not using the createFormBuilder so how can I do this.The work that I have done is not working properly
  • not working properly is just not enough to describe your problem. Could you describe the detail.
  • Error is not disappeared when I don't miss the form fields.It should not show the errors but it is always giving the error even the first time when I view the page it show error there too.
  • Unless I am missing something, I cannot see where you are binding your entity to your request in your controller method, so as far as I can see from the above code you are validating an newly created (i.e: empty) entity.