我陷入两难境地。我希望以我的形式将绑定(对象)的数据添加到表单中,具体取决于图像是否存在,该项目是否显示在表单上。
我这样解决了,但我不知道这是否正确。
$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');
}
可以解决更好的问题吗?
如果您希望更改表单本身的显示,则呈现/不呈现优惠券的逻辑很可能存在于View Helper中。
这使得渲染不受控制器的影响,并保持良好的关注点分离。