Why is this form invalid all the time

87 Views Asked by At

I have this form which is just one field, the method isValid() keeps treating it as if it was invalid everytime I submit it, i've been submitting text like it should be

//form
class CategoryForm extends Form
{
 public function __construct()
 {
    parent::__construct('category');

    $this->setAttribute('method', 'post');

    $this->add(array(
        'name' => 'name',
        'type'  => 'text',
        'options' => array('label' => 'Name',),
        'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
    ));

    $this->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Save',
            'id' => 'submitbutton',
        ),
    ));
 }
}

and this would be the faulty part, I supose, and because it is kind of working there are no error messages.

//validation clause at controller
 $category = new Category;
 $form = new CategoryForm();
 $form->bind($category);
 $request = $this->getRequest();

    if ($request->isPost()) {
        $form->setInputFilter($category->getInputFilter());
        $form->setData($request->getPost());

        if ($form->isValid()) {
            $em = $this->getEntityManager();
            $em->persist($category);
            $em->flush();

            $this->flashMessenger()->addSuccessMessage('category Saved');

            return $this->redirect()->toRoute('category');
        }
    }

If I change The code to this it persists the data

public function addAction()
{
    $form = new CategoryForm();
    $form->get('submit')->setValue('Add');

    $request = $this->getRequest();
    if ($request->isPost()) {
        $category = new category();
        $form->setInputFilter($category->getInputFilter());
        $form->setData($request->getPost());
        $form->isValid();

        $category->exchangeArray($form->getData());
        $em = $this->getEntityManager();
        $em->persist($category);
        $em->flush();
        $this->flashMessenger()->addSuccessMessage('Category Saved');
        return $this->redirect()->toRoute('category');
    }
     return new ViewModel(array(
        'category' => $category,
        'form' => $form
    ));
}
1

There are 1 best solutions below

7
On BEST ANSWER

Are you actually passing the submitted values to the form before validating?

I usually do something like this:

if ($this->_request->isPost() && $form->isValid($this->getRequest()->getPost())) { 
...
Your save code here...

If you are doing that then check the form for what raised a validation error...

var_dump($form->getMessages());