Zend Framework 2 form

101 Views Asked by At

I have a dilemma. I would like to in my form if the data that are bind (object) added to the form, depending on whether the image exists or not, the item is shown on the form or not.

I solved it like this, but I do not know if this is correct.

        $id = (int) $this->params()->fromRoute('id', 0);
        $coupon = $this->getEntityManager()->find('Application\Entity\Coupon', $id);

        $forms = $this->getServiceLocator()->get('FormElementManager');
        $form = $forms->get('CouponForm');

        $form->bind($coupon);
        $form->setBindOnValidate(false);
        $form->get('dateStart')->setValue($coupon->getDateStart()->format('Y-m-d'));
        $form->get('dateEnd')->setValue($coupon->getDateEnd()->format('Y-m-d'));

        if($coupon->getImageUrl()) {
            $form->get('image')->setAttribute('src', $coupon->getImageUrl());
        }else {
            $form->remove('image');
        }

Can it be nicer to solve?

1

There are 1 best solutions below

0
On

In the event you're looking to change the display of the form itself, the logic for rendering/not rendering the coupon should most likely live in a View Helper.

This keeps the rendering free from the controller and maintains a nice separation of concerns.