Dante
Dante

Reputation: 101

Edit form with file input in zend framework 2

I use fielrenameupload validation and fileprg to upload file in my form . It works very well but in edit action validation fails for file input How I can solve this problem in edit action ?

this is edit action that works great for add action :

public function editAction()
    {
        $id = $this->params()->fromRoute('id',0);
        $category = $this->categoryTable->get($id);

        $form = $this->getServiceLocator()->get('CategoryForm');

        $prg = $this->fileprg($form);
        $form->bind($category);

        if ($prg instanceof \Zend\Http\PhpEnviroment\Response)
        {
            return $prg;
        }
        elseif (is_array($prg))
        {
            if ($form->isValid())
            {
                $data = $form->getData();
                $data['image'] = $data['image']['tmp_name'];
                $category = new CategoryEntity;
                $category->exchangeArray($data);

                if ($this->categoryTable->save($category))
                    $this->redirect()->toRoute(null,array('action'=>'index'));
            }
        }

        $view = new ViewModel(array(
            'form'  =>  $form,
        ));
        $view->setTemplate('category/admin/add');
        return $view;
    }

And this is validation code for file input :

$image = new \Zend\InputFilter\FileInput('image');
        $image->getFilterChain()->attachByName('filerenameupload',array(
            'target'    =>  'data/upload/images/category',
            'use_upload_name'   =>  true,
            'randomize'     =>  true,
        ));

Upvotes: 1

Views: 1745

Answers (1)

lluisaznar
lluisaznar

Reputation: 2393

The add action passes the $form->isValid() validation because there is a image file posted in the form submit. However, in the edit action, it's empty.

In order to avoid avoid the problem you're facing try the following:

$imageFilter = $form->getInputFilter()->get( 'image' );
$imageFilter->setRequired( false );

Just be sure to place this lines before the $form->isValid() line.

Upvotes: 1

Related Questions