/** * @param mixed $model */ public function setModel($model) { $modelClass = get_class($model); $this->form = $this->annotationBuilder->createForm($modelClass); $this->form->bind($model); $this->setVariables(['form' => $this->form, 'object' => $model, 'title' => $this->getFieldSetTitle($model)]); $this->buildFormViewModel($this->form, $this); }
/** * @param Entity\Note $note * @param string $url * @param string $action * @param array $members * @return \Zend\Form\Form */ public function getNoteForm(Entity\Note $note, $url = '', $action = 'add', $members = null) { if (is_null($this->noteForm)) { $builder = new AnnotationBuilder($this->getEntityManager()); $this->noteForm = $builder->createForm($note); $this->noteForm->setAttribute('action', $url); $this->noteForm->setAttribute('id', 'noteForm'); $this->noteForm->setHydrator(new DoctrineObject($this->getEntityManager(), 'Secretary\\Entity\\Note')); $this->noteForm->bind($note); if ($action == 'edit' && $note->getPrivate() === false) { $this->noteForm->remove('private'); $group = $note->getGroup(); $membersString = $this->getMembersString(array_keys($members)); $this->noteForm->get('groupHidden')->setValue($group->getId()); $this->noteForm->get('members')->setValue($membersString); $this->noteForm->getInputFilter()->remove('__initializer__'); $this->noteForm->getInputFilter()->remove('__cloner__'); $this->noteForm->getInputFilter()->remove('__isInitialized__'); $this->noteForm->getInputFilter()->remove('lazyPropertiesDefaults'); } else { $this->noteForm->get('private')->setAttribute('required', false); $this->noteForm->getInputFilter()->get('private')->setRequired(false); } } return $this->noteForm; }
/** * Create a new post * * @param array $data * @param \Zend\Form\Form $form * @return bool */ public function create($data, &$form) { $post = new PostEntity(); $em = $this->getEntityManager(); $form->bind($post); $form->setData($data); if (!$form->isValid()) { return false; } // we rename the file with a unique name $newName = FileUtilService::rename($data['post']['thumbnail'], 'images/posts', "post"); foreach (PostEntity::$thumbnailVariations as $variation) { $result = FileUtilService::resize($newName, 'images/posts', $variation["width"], $variation["height"]); if (!$result) { $this->message = $result; return false; } } $post->setThumbnail($newName); $post->setPostDate("now"); $post->setUrl($this->getPostUrl($post)); try { $em->persist($post); $em->flush(); $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_POST_CREATED"]); return true; } catch (\Exception $e) { $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_POST_NOT_CREATED"]); return false; } }
/** * Bind an object to the form * * Ensures the object is populated with validated values. * Set isEditForm to true so that edit form is distinguished * * @param object $object * @param int $flags ,default value is FormInterface::VALUES_NORMALIZED * @param bool $isEditForm ,default value is true * @return mixed|void * @throws Exception\InvalidArgumentException */ public function bind($object, $flags = FormInterface::VALUES_NORMALIZED, $isEditForm = true) { if ($isEditForm === true) { $this->isEditForm = true; } parent::bind($object, $flags); }
/** * Create a new image * * @param array $data * @param \Zend\Form\Form $form * @return bool */ public function create($data, &$form) { $entity = new ImageEntity(); $em = $this->getEntityManager(); $form->bind($entity); $form->setData($data); if (!$form->isValid()) { return false; } // we rename the file with a unique name $newName = FileUtilService::rename($data['image']['image'], 'images/gallery', "gallery"); foreach (ImageEntity::$thumbnailVariations as $variation) { $result = FileUtilService::resize($newName, 'images/gallery', $variation["width"], $variation["height"]); if (!$result) { $this->message = $result; return false; } } $entity->setImage($newName); try { $em->persist($entity); $em->flush(); $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_IMAGE_CREATED"]); return true; } catch (\Exception $e) { $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_IMAGE_NOT_CREATED"]); return false; } }
public function testPreserveEntitiesBoundToCollectionAfterValidation() { $this->form->setInputFilter(new \Zend\InputFilter\InputFilter()); $fieldset = new TestAsset\ProductCategoriesFieldset(); $fieldset->setUseAsBaseFieldset(true); $product = new Entity\Product(); $product->setName('Foobar'); $product->setPrice(100); $c1 = new Entity\Category(); $c1->setId(1); $c1->setName('First Category'); $c2 = new Entity\Category(); $c2->setId(2); $c2->setName('Second Category'); $product->setCategories(array($c1, $c2)); $this->form->add($fieldset); $this->form->bind($product); $data = array('product' => array('name' => 'Barbar', 'price' => 200, 'categories' => array(array('name' => 'Something else'), array('name' => 'Totally different')))); $hash1 = spl_object_hash($this->form->getObject()->getCategory(0)); $this->form->setData($data); $this->form->isValid(); $hash2 = spl_object_hash($this->form->getObject()->getCategory(0)); // Returned object has to be the same as when binding or properties // will be lost. (For example entity IDs.) $this->assertTrue($hash1 == $hash2); }
/** * (non-PHPdoc) * * @see \Zend\Form\Form::bind() */ public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { if (null != $object->getId() && null != $this->get('submit')) { $this->get('submit')->setAttribute('value', 'BTN_UPDATE'); } parent::bind($object, $flags); }
public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { foreach ($this->getFieldsets() as $fieldset) { $fieldset->setObject($object); } $result = parent::bind($object, $flags); return $result; }
public function updateAction() { if (!($seo = $this->loadObject($this->seoService, "Seo record doesn't exist."))) { return $this->redirect()->toRoute('seo', array('action' => 'list')); } $this->seoForm->bind($seo); if ($this->request->isPost()) { $this->seoForm->setData($this->request->getPost()); if ($this->seoForm->isValid()) { $this->seoService->update($this->seoForm->getData()); $this->flashMessenger()->addSuccessMessage(sprintf('Seo "%s" has been successfully updated.', $seo->getId())); return $this->redirect()->toRoute('seo', array('action' => 'list')); } } $view = new ViewModel(array('id' => $seo->getId(), 'form' => $this->seoForm)); $view->setTerminal(true); return $view; }
/** * Returns a form for the current entity with an input filter set * built using the provided annotations in model * * @return Form */ public function getForm() { if (empty($this->form)) { $builder = new AnnotationBuilder(); $this->form = $builder->createForm($this); $this->form->bind($this); } return $this->form; }
/** * @return \Zend\Form\Form */ public function getForm($entity) { if ($this->form->hasValidated()) { return $this->form; } $this->form->bind($entity); $this->form->bindOnValidate(); $this->getEventManager()->trigger($this->createEvent(CrudEvent::FORM_READY, $this->form)); return $this->form; }
/** * @param \Zend\Form\Form $form * @param $data * @return bool */ public function login(&$form, $data) { $user = new User(); $form->bind($user); $form->setData($data); if ($form->isValid()) { return true; } else { return false; } }
/** * createFromForm * * @param Form $form * @return CdliTwoStageSignup\Model\EmailVerification */ public function createFromForm(Form $form) { $form->bind(new Model()); if (!$form->isValid()) { return false; } $model = $form->getData(); $model->generateRequestKey(); $this->getEventManager()->trigger(__FUNCTION__, $this, array('record' => $model, 'form' => $form)); $this->getEmailVerificationMapper()->insert($model); return $model; }
/** * Edit * * @return ViewModel */ public function editAction() { $object = $this->getObject(); if ($this->form) { $this->form->bind($object); } $request = $this->getRequest(); if ($request->isPost()) { if ($response = $this->processForm()) { return $response; } } $viewModel = new ViewModel(); $viewModel->setTemplate($this->templates['edit']); $viewModel->setVariables(array('form' => $this->form, 'object' => $object, 'templates' => $this->templates, 'routes' => $this->routes)); return $viewModel; }
public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { parent::bind($object, $flags); $pluginClasses = $this->getAttribute(static::BIND_PLUGIN_CLASSES); if (!empty($pluginClasses)) { if (!is_array($pluginClasses)) { throw new \InvalidArgumentException('The plugin classes attribute must be an array'); } foreach ($pluginClasses as $pluginClass) { if (!is_subclass_of($pluginClass, '\\Zork\\Form\\Plugin\\BindInterface')) { throw new \InvalidArgumentException('The plugin class must be implement \\Zork\\Form\\Plugin\\BindInterface'); } $plugin = new $pluginClass(); $plugin->bind($this); } } return $this; }
public function testCorrectlyHydrateBaseFieldsetWhenHydratorThatDoesNotIgnoreInvalidDataIsUsed() { $fieldset = new Fieldset('example'); $fieldset->add(array('name' => 'foo')); // Add an hydrator that ignores if values does not exist in the $fieldset->setObject(new Entity\SimplePublicProperty()); $fieldset->setHydrator(new \Zend\Stdlib\Hydrator\ObjectProperty()); $this->form->add($fieldset); $this->form->setBaseFieldset($fieldset); $this->form->setHydrator(new \Zend\Stdlib\Hydrator\ObjectProperty()); // Add some inputs that do not belong to the base fieldset $this->form->add(array('type' => 'Zend\\Form\\Element\\Submit', 'name' => 'submit')); $object = new Entity\SimplePublicProperty(); $this->form->bind($object); $this->form->setData(array('submit' => 'Confirm', 'example' => array('foo' => 'value example'))); $this->assertTrue($this->form->isValid()); // Make sure the object was not hydrated at the "form level" $this->assertFalse(isset($object->submit)); }
/** * Create a new gallery * * @param array $data * @param \Zend\Form\Form $form * @return bool */ public function create(&$data, &$form) { $entity = new GalleryEntity(); $em = $this->getEntityManager(); if (isset($data['gallery']['images'])) { $data['gallery']['images'] = json_decode($data['gallery']['images'], true); } $form->bind($entity); $form->setData($data); $form->setBindOnValidate(Form::BIND_MANUAL); if (!$form->isValid()) { return false; } $entity->setName($data['gallery']['name']); $entity->setUrl($this->getGalleryUrl($entity)); if (isset($data['gallery']['parentGallery']) && !empty($data['gallery']['parentGallery'])) { $parent = $this->getGalleryRepository()->find($data['gallery']['parentGallery']); if ($parent) { $entity->setParentGallery($parent); } } // WHY THE F**K DO I HAVE TO FLUSH HERE $em->persist($entity); $em->flush(); foreach ($data['gallery']['images'] as $join) { $image = $this->getImageRepository()->find($join['joinId']); if ($image) { $galleryImage = new GalleryImage($join['title'], $join['position']); $image->addGalleries($galleryImage); $entity->addImages($galleryImage); } } try { $em->persist($entity); $em->flush(); $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_GALLERY_CREATED"]); return true; } catch (\Exception $e) { $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_GALLERY_NOT_CREATED"]); return false; } }
/** * Create a new user * * @param array $data * @param \Zend\Form\Form $form * @return bool */ public function create($data, &$form) { $user = new UserEntity(); $em = $this->getEntityManager(); $form->bind($user); $form->setData($data); if (!$form->isValid()) { return false; } $user->setPassword(UserEntity::hashPassword($user->getPassword())); try { $em->persist($user); $em->flush(); $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_USER_CREATED"]); return true; } catch (\Exception $e) { $this->message = $this->getTranslator()->translate($this->getVocabulary()["MESSAGE_USER_NOT_CREATED"]); return false; } }
/** * If the bound object is an content-node we remove some fields, that mustn't be modified. * * (non-PHPdoc) * * @see \Zend\Form\Form::bind() */ public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { if ('mvc' != $object->getNodeType()) { $this->remove('node_route_config'); $this->remove('node_original_route'); $this->getInputFilter()->remove('node_route_config'); $this->getInputFilter()->remove('node_original_route'); } if ('redirect' == $object->getNodeType()) { if (true == $this->getNodeOptions()->getEnableMetaTags()) { $this->remove('node_meta'); $this->getInputFilter()->remove('node_meta'); } } if ('redirect' != $object->getNodeType()) { $this->remove('node_redirect_code'); $this->remove('node_redirect_target'); $this->getInputFilter()->remove('node_redirect_code'); $this->getInputFilter()->remove('node_redirect_target'); } parent::bind($object, $flags); }
public function testElementInAFieldsetForSomeModel() { $element = $this->getMoneyFieldset(); $element->init(); $fieldset = new Fieldset('hasMoneyElementFieldset'); $fieldset->add($element, ['name' => 'price']); $fieldset->setHydrator(new ClassMethods()); $fieldset->setUseAsBaseFieldset(true); $form = new Form(); $form->add($fieldset); // todo: can't load this $form->bind(new HasMoneyPropertyModel()); $data = ['hasMoneyElementFieldset' => ['price' => ['amount' => '500.25', 'currency' => 'BRL']]]; $form->setData($data); $this->assertTrue($form->isValid()); $amountValue = $form->get('hasMoneyElementFieldset')->get('price')->get('amount')->getValue(); $currencyValue = $form->get('hasMoneyElementFieldset')->get('price')->get('currency')->getValue(); $object = $form->getData(); $this->assertSame('500.25', $amountValue); $this->assertSame('BRL', $currencyValue); $this->assertInstanceOf(Money::class, $object->getPrice()); $this->assertSame(50025, $object->getPrice()->getAmount()); $this->assertSame('BRL', $object->getPrice()->getCurrency()->getName()); }
public function bind($valuesOrObject, $flags = FormInterface::VALUES_NORMALIZED) { $this->init(); $valuesOrObject = $this->beforeBind($valuesOrObject); if (!$valuesOrObject) { return $this; } if (is_array($valuesOrObject) || $valuesOrObject instanceof \Zend\Stdlib\Parameters) { $this->setData((array) $valuesOrObject); } else { parent::bind($valuesOrObject); } $this->afterBind(); return $this; }
public function testBindEmptyValue() { $value = new \ArrayObject(array('foo' => 'abc', 'bar' => 'def')); $inputFilter = new InputFilter(); $inputFilter->add(array('name' => 'foo', 'required' => false)); $inputFilter->add(array('name' => 'bar', 'required' => false)); $form = new Form(); $form->add(new Element('foo')); $form->add(new Element('bar')); $form->setInputFilter($inputFilter); $form->bind($value); $form->setData(array('foo' => '', 'bar' => 'ghi')); $form->isValid(); $this->assertSame('', $value['foo']); $this->assertSame('ghi', $value['bar']); }
public function testCreatesNewObjectsIfSpecified() { $this->productFieldset->setUseAsBaseFieldset(true); $categories = $this->productFieldset->get('categories'); $categories->setOptions(array('create_new_objects' => true)); $form = new \Zend\Form\Form(); $form->setHydrator(new \Zend\Stdlib\Hydrator\ClassMethods()); $form->add($this->productFieldset); $product = new Product(); $product->setName("foo"); $product->setPrice(42); $cat1 = new \ZendTest\Form\TestAsset\Entity\Category(); $cat1->setName("bar"); $cat2 = new \ZendTest\Form\TestAsset\Entity\Category(); $cat2->setName("bar2"); $product->setCategories(array($cat1, $cat2)); $form->bind($product); $form->setData(array("product" => array("name" => "franz", "price" => 13, "categories" => array(array("name" => "sepp"), array("name" => "herbert"))))); $form->isValid(); $categories = $product->getCategories(); $this->assertNotSame($categories[0], $cat1); $this->assertNotSame($categories[1], $cat2); }
public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { $ids = $object->getRoleIds(); parent::bind($object, $flags)->get('roles')->setValue($ids); }
public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { $this->getEventManager()->trigger('pre.' . __FUNCTION__, $this, $object); parent::bind($object, $flags); $this->getEventManager()->trigger('post.' . __FUNCTION__, $this, $object); }
/** * Bind an object to the form */ public function bind($object, $flags = FormInterface::VALUES_NORMALIZED) { parent::bind($object, $flags); }
public function testDoNotCreateExtraFieldsetOnMultipleBind() { $form = new \Zend\Form\Form(); $this->productFieldset->setHydrator(new \Zend\Stdlib\Hydrator\ClassMethods()); $form->add($this->productFieldset); $form->setHydrator(new \Zend\Stdlib\Hydrator\ObjectProperty()); $product = new Product(); $categories = array(new \ZendTest\Form\TestAsset\Entity\Category(), new \ZendTest\Form\TestAsset\Entity\Category()); $product->setCategories($categories); $market = new \StdClass(); $market->product = $product; // this will pass the test $form->bind($market); $this->assertSame(count($categories), iterator_count($form->get('product')->get('categories')->getIterator())); // this won't pass, but must $form->bind($market); $this->assertSame(count($categories), iterator_count($form->get('product')->get('categories')->getIterator())); }
public function testNestedCollections() { // @see https://github.com/zendframework/zf2/issues/5640 $addressesFieldeset = new \ZendTest\Form\TestAsset\AddressFieldset(); $addressesFieldeset->setHydrator(new \Zend\Stdlib\Hydrator\ClassMethods()); $form = new Form(); $form->setHydrator(new ObjectPropertyHydrator()); $form->add(array('name' => 'addresses', 'type' => 'Collection', 'options' => array('target_element' => $addressesFieldeset, 'count' => 2))); $data = array(array('number' => '0000000001', 'street' => 'street1'), array('number' => '0000000002', 'street' => 'street2')); $phone1 = new Phone(); $phone1->setNumber($data[0]['number']); $phone2 = new Phone(); $phone2->setNumber($data[1]['number']); $address1 = new Address(); $address1->setStreet($data[0]['street']); $address1->setPhones(array($phone1)); $address2 = new Address(); $address2->setStreet($data[1]['street']); $address2->setPhones(array($phone2)); $customer = new stdClass(); $customer->addresses = array($address1, $address2); $form->bind($customer); //test for object binding foreach ($form->get('addresses')->getFieldsets() as $_fieldset) { $this->assertInstanceOf('ZendTest\\Form\\TestAsset\\Entity\\Address', $_fieldset->getObject()); foreach ($_fieldset->getFieldsets() as $_childFieldsetName => $_childFieldset) { switch ($_childFieldsetName) { case 'city': $this->assertInstanceOf('ZendTest\\Form\\TestAsset\\Entity\\City', $_childFieldset->getObject()); break; case 'phones': foreach ($_childFieldset->getFieldsets() as $_phoneFieldset) { $this->assertInstanceOf('ZendTest\\Form\\TestAsset\\Entity\\Phone', $_phoneFieldset->getObject()); } break; } } } //test for correct extract and populate $index = 0; foreach ($form->get('addresses') as $_addresses) { $this->assertEquals($data[$index]['street'], $_addresses->get('street')->getValue()); //assuming data has just 1 phone entry foreach ($_addresses->get('phones') as $phone) { $this->assertEquals($data[$index]['number'], $phone->get('number')->getValue()); } $index++; } }
/** * @param \Phpro\SmartCrud\Gateway\CrudGatewayInterface $gateway * @param \Zend\EventManager\EventManager $eventManager * @param \Zend\Form\Form $form * @param \Phpro\SmartCrud\Service\SmartServiceResult $result */ public function it_should_handle_valid_data($gateway, $eventManager, $form, $result) { $entity = new \StdClass(); $entity->id = 1; $postData = $this->getMockPostData(); $gateway->loadEntity('entityKey', $entity->id)->shouldBecalled()->willReturn($entity); $gateway->update($entity, $postData)->shouldBecalled()->willReturn(true); $form->hasValidated()->shouldBeCalled()->willreturn(false); $form->bind(Argument::any())->shouldBeCalled(); $form->bindOnValidate()->shouldBeCalled(); $form->setData(Argument::exact($this->getMockPostData()))->shouldBeCalled()->willReturn($form); $form->isValid()->shouldBeCalled()->willreturn(true); $result->setSuccess(true)->shouldBeCalled(); $result->setForm($form)->shouldBeCalled(); $result->setEntity($entity)->shouldBeCalled(); $this->setEntityKey('entityKey'); $this->setGateway($gateway); $this->setForm($form); $this->setResult($result); $this->run($entity->id, $this->getMockPostData())->shouldReturn($result); $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_DATA_HYDRATION))->shouldBeCalled(); $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_DATA_VALIDATION))->shouldBeCalled(); $eventManager->trigger(Argument::which('getName', CrudEvent::INVALID_UPDATE))->shouldNotBeCalled(); $eventManager->trigger(Argument::which('getName', CrudEvent::BEFORE_UPDATE))->shouldBeCalled(); $eventManager->trigger(Argument::which('getName', CrudEvent::AFTER_UPDATE))->shouldBeCalled(); }