/** * @param null $name * @return \Zend\Form\ElementInterface|Form */ public function getFilter($name = null) { if (!empty($name)) { return $this->filter->get($name); } return $this->filter; }
public function __invoke(Form $form) { $form->setAttribute('class', self::DEFAULT_FORM_CLASS); foreach ($form->getElements() as $element) { /* * controls how far the form indents into * the page using Twitter:Bootstrap CSS * */ $defLabelAttributes = array('class' => self::DEFAULT_LABEL_CLASS); $element->setLabelAttributes($defLabelAttributes); $element->setAttribute('class', self::DEFAULT_INPUT_CLASS); /* * set the id attribute of all inputs to be equal to their names * * makes life simple when trying to make the view * dynamic */ $element->setAttribute('id', $element->getName()); } /* * the submit button is a little different, it uses * a button class to proper rendering * */ $form->get('submit')->setAttribute('class', self::DEFAULT_SUBMIT_BUTTON_CLASS); return $form; }
/** * @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; }
public function __invoke($keyData, $keyEndPoint, array $data, Form $form) { $html = ''; $options = array_key_exists('options', $data) ? $data['options'] : array(); $form->get('endpoint')->setValue($keyEndPoint); $html .= $this->getView()->partial('helpers/partials/default-process-control', array('keyData' => $keyData, 'keyEndPoint' => $keyEndPoint, 'label' => $data['label'], 'processDescription' => array_key_exists('process-description', $data) ? $data['process-description'] : '', 'form' => $form, 'class' => 'DefaultProcessControl', 'options' => $options)); return $html; }
public function testResetPasswordValueIfFormIsNotValid() { $this->form->add(array('type' => 'Zend\\Form\\Element\\Password', 'name' => 'password')); $this->form->add(array('type' => 'Zend\\Form\\Element\\Email', 'name' => 'email')); $this->form->setData(array('password' => 'azerty', 'email' => 'wrongEmail')); $this->assertFalse($this->form->isValid()); $this->form->prepare(); $this->assertEquals('', $this->form->get('password')->getValue()); }
/** * @param \Zend\Form\Form $form */ protected function fixUserForm(Form &$form, $userId = null) { $auth = $this->getAuthenticationService(); $groupId = $form->get('groupId'); $groups = $groupId->getValueOptions(); if (empty($groups) || $auth->getIdentity()->id == $userId) { $form->remove('groupId'); } }
/** * @inheritdoc */ public function createService(ServiceLocatorInterface $serviceLocator) { $form = new Form(); $form->add(new Element\Text('filter', ['label' => 'Resource'])); $form->add(new Element\Button('submit', ['label' => 'filter'])); $form->setAttribute('method', 'GET'); $form->get('submit')->setAttribute('type', 'submit'); return $form; }
/** * @param Form $form * @param array $fields * @param array $overwrite * * @return string */ public function __invoke($form, $fields, $overwrite = null) { if ($overwrite === null) { $overwrite = array(); } if (!is_array($fields)) { $fields = array($fields); } $html = ''; foreach ($fields as $i => $field) { $addon = ''; if (!is_int($i)) { $addon = $field; $field = $i; } if (!$form->has($field)) { throw new \Exception(sprintf('Element doesn\'t exists \'%s\'', $field)); } $element = $form->get($field); $type = strtolower($element->getAttribute('type')); if (array_key_exists($field, $overwrite)) { if ($type === 'submit') { $element->setValue($overwrite[$field]); } else { $element->setOption('label', $overwrite[$field]); } } $plugin = $this->getPlugin($type); $prefix = ''; $encaps = '%s'; switch ($type) { case 'checkbox': $encaps = sprintf("<div class=\"checkbox-block\">%s</div><div class=\"col-xs-10\">%s</div>", '%s', $this->getLabel($element)); break; case "textarea": if (preg_match('/readonly/i', $element->getAttribute('class'))) { $prefix = '<p class="toggle-edit"><a href="#">Edit</a></p><iframe style="width:200px; height:100px; display: none;"></iframe>'; } default: $prefix .= $this->getLabel($element); break; } $input = $plugin($element); if (!empty($prefix)) { $prefix = sprintf($this->labelBlock, $prefix); } $html .= sprintf($this->format, $element->getName(), $prefix, sprintf($encaps, $input), $addon, $this->buildErrorMessage($element)); } return $html; }
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()); }
/** * Pega as mensagens do formulario e as dispoe * em forma de lista ul,li * @param \Zend\Form\Form $form * @return string HTML */ public function formErros($form) { $msg = ""; $arrayMessage = $form->getMessages(); foreach ($arrayMessage as $elemName => $messages) { foreach ($messages as $message) { $label = ""; $elemName = $form->get($elemName); if ($elemName != null) { $label = $elemName->getLabel(); } $msg .= "<ul><li>" . $label . " " . $message . "</li></ul>"; } } return $msg; }
/** * {@inheritDoc} */ public function get($elementOrFieldset) { if (!parent::has($elementOrFieldset)) { if ($elementOrFieldset === 'captcha') { $elementOrFieldset = $this->getCaptchaElementName(); } elseif ($elementOrFieldset === 'csrf') { $elementOrFieldset = $this->getCsrfElementName(); } } return parent::get($elementOrFieldset); }
public function testSubFieldsetsBindObject() { $form = new Form(); $fieldset = new Fieldset('foobar'); $form->add($fieldset); $value = new \ArrayObject(array('foobar' => 'abc')); $value['foobar'] = new \ArrayObject(array('foo' => 'abc')); $form->bind($value); $this->assertSame($fieldset, $form->get('foobar')); }
public function changePasswordAction() { $viewModel = new ViewModel(); $username = $this->getAuthService()->getIdentity()->getUsername(); $registerForm = new RegisterForm(); $form = new \Zend\Form\Form('changePasswordForm'); $form->add($registerForm->get('password')); $form->add($registerForm->get('re_password')); // $form->add($registerForm->get('submit')->setAttribute('value', '修改密碼')); $accountFilter = new AccountFIlter(); $filter = new InputFilter(); $filter->add($accountFilter->get('password'))->add($accountFilter->get('re_password')); $form->setInputFilter($filter); if ($this->getRequest()->isPost()) { $data = $this->getRequest()->getPost(); $form->setData($data); if ($form->isValid()) { $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default'); $user = $em->getRepository('Base\\Entity\\User')->findOneBy(array('username' => $username)); if ($user) { //$user->setPassword(md5($form->get('password')->getValue())); $user->setPassword(\Zend\Ldap\Attribute::createPassword($form->get('password')->getValue())); $em->persist($user); $em->flush(); $this->getServiceLocator()->get('Zend\\Log')->info($username . ' changed password'); $this->flashMessenger()->addSuccessMessage('更改密碼成功!'); return $this->redirect()->refresh(); } } } $viewModel->setVariable('form', $form); return $viewModel; }
/** * @param Form $form * @param int $moneyAccountId * @return Form */ public function fillData($form, $moneyAccountId) { /** @var UserManager $userDao */ $userDao = new UserManager($this->getServiceLocator(), '\\ArrayObject'); if ($moneyAccountId) { $users = $this->getMoneyAccountUsersInOperationTypes($moneyAccountId); $usersForView = $form->get('view_transactions')->getOption('value_options'); if (isset($users[self::OPERATION_VIEW_TRANSACTION]) && count($users[self::OPERATION_VIEW_TRANSACTION])) { foreach ($users[self::OPERATION_VIEW_TRANSACTION] as $relUserId) { if (!isset($usersForView[$relUserId])) { $userDomain = $userDao->getUserById($relUserId, true); $usersForView[$relUserId] = $userDomain['firstname'] . ' ' . $userDomain['lastname']; $form->get('view_transactions')->setOptions(['value_options' => $usersForView]); } } } $usersForAdd = $form->get('add_transactions')->getOption('value_options'); if (isset($users[self::OPERATION_ADD_TRANSACTION]) && count($users[self::OPERATION_ADD_TRANSACTION])) { foreach ($users[self::OPERATION_ADD_TRANSACTION] as $relUserId) { if (!isset($usersForAdd[$relUserId])) { $userDomain = $userDao->getUserById($relUserId, true); $usersForAdd[$relUserId] = $userDomain['firstname'] . ' ' . $userDomain['lastname']; $form->get('add_transactions')->setOptions(['value_options' => $usersForAdd]); } } } $transactionManagers = $form->get('manage_transactions')->getOption('value_options'); if (isset($users[self::OPERATION_MANAGE_TRANSACTION]) && count($users[self::OPERATION_MANAGE_TRANSACTION])) { foreach ($users[self::OPERATION_MANAGE_TRANSACTION] as $relUserId) { if (!isset($transactionManagers[$relUserId])) { $userDomain = $userDao->getUserById($relUserId, true); $transactionManagers[$relUserId] = $userDomain['firstname'] . ' ' . $userDomain['lastname']; $form->get('manage_transactions')->setOptions(['value_options' => $transactionManagers]); } } } $accountManagers = $form->get('manage_transactions')->getOption('value_options'); if (isset($users[self::OPERATION_MANAGE_ACCOUNT]) && count($users[self::OPERATION_MANAGE_ACCOUNT])) { foreach ($users[self::OPERATION_MANAGE_ACCOUNT] as $relUserId) { if (!isset($accountManagers[$relUserId])) { $userDomain = $userDao->getUserById($relUserId, true); $accountManagers[$relUserId] = $userDomain['firstname'] . ' ' . $userDomain['lastname']; $form->get('manage_transactions')->setOptions(['value_options' => $accountManagers]); } } } $form->setData(['view_transactions' => isset($users[self::OPERATION_VIEW_TRANSACTION]) ? $users[self::OPERATION_VIEW_TRANSACTION] : [], 'add_transactions' => isset($users[self::OPERATION_ADD_TRANSACTION]) ? $users[self::OPERATION_ADD_TRANSACTION] : [], 'manage_transactions' => isset($users[self::OPERATION_MANAGE_TRANSACTION]) ? $users[self::OPERATION_MANAGE_TRANSACTION] : [], 'manage_account' => isset($users[self::OPERATION_MANAGE_ACCOUNT]) ? $users[self::OPERATION_MANAGE_ACCOUNT] : []]); } return $form; }
/** * Fill form with the data * * @param \Zend\Form\Form $form * @param $entity */ protected function populateForm($form, $entity) { // $form->get('id')->setValue($entity->getId()); }
public function newForm($uom = null, $uomTextField = false, $quantity = 1) { $form = new ZendForm(); $form->add(array('name' => 'submit', 'type' => 'Zend\\Form\\Element\\Submit', 'attributes' => array('class' => 'btn add-to-cart'), 'options' => array('label' => 'Add To Cart'))); $form->add(array('name' => 'quantity', 'attributes' => array('type' => 'text', 'value' => $quantity, 'id' => 'quantity-to-cart'), 'options' => array('label' => 'Quantity'), 'value' => $quantity)); $form->get('quantity')->setValue($quantity); if ($uomTextField) { $form->add(array('name' => 'uom', 'attributes' => array('type' => 'hidden'))); $form->get('uom')->setValue($this->uomToKey($uom)); } return $form; }
/** * * @param type $elementName * @throws Exception$form = new \Zend\Form\Form ( $frmName ); */ public function addFormElement($elementName, array $elementSpec, $priority = 100, $defaultValue = null) { if (!$this->isLoadCrudSettings()) { return false; } if (!$this->frmMainCrud instanceof \Zend\Form\Form) { throw new Exception('You must define a Form object', $code, $previous); } if (!$priority) { $priority = $this->frmMainCrud->get($elementName)->getOption('priority'); } $this->frmMainCrud->add($elementSpec, array('priority' => $priority)); $element = $this->frmMainCrud->get($elementName); $element->setOption('priority', $priority); if ($elementSpec['type'] == '\\Zf2datatable\\Form\\Element\\CKEditor') { $basePath = $this->getPluginViewHelperManager()->get('BasePath')->__invoke(); $this->getPluginViewHelperManager()->get('HeadScript')->appendFile($basePath . '/ckeditor/samples/js/sample.js'); $this->getPluginViewHelperManager()->get('HeadScript')->appendFile($basePath . '/ckeditor/ckeditor.js'); $this->getPluginViewHelperManager()->get('HeadLink')->appendStylesheet($basePath . '/ckeditor/samples/css/samples.css'); $this->getPluginViewHelperManager()->get('HeadLink')->appendStylesheet($basePath . '/ckeditor/samples/toolbarconfigurator/lib/codemirror/neo.css'); } if ($defaultValue) { $element->setValue($defaultValue); } if ($element instanceof \DoctrineModule\Form\Element\ObjectSelect) { if (method_exists($element, 'getProxy')) { $entityManager = $this->getDataSource()->getEntityManager(); $proxy = $element->getProxy(); if (method_exists($proxy, 'setObjectManager')) { $proxy->setObjectManager($entityManager); } } } }
/** * Ajusta os elementos especiais do formulário, * como por exemplo os campos de tipo select, que * deverão listar todos os registros de uma entidade * por padrão. * * @param \Zend\Form\Form $form */ public function adjustOfSpecialElements(Form $form) { foreach ($form->getElements() as $element) { if ($element instanceof Select && $this->elementMustBePopulated($element)) { // Obtém os registros de listagens padrões, a partir da entidade definida para o campo. $results = $this->getListValuesToSelectElement($element); $listValues = array($element->getEmptyOption() => self::STR_NENHUM_REGISTRO); $element->setEmptyOption(null); foreach ($results as $result) { $title = !empty($result['title']) ? $result['title'] : $result['nome']; $listValues[$result['id']] = $title; } $form->get($element->getAttribute('name'))->setValueOptions($listValues); } } }
public function forgottenAction() { $email = new Element\Email('email'); $email->setLabel('Registered email'); $email->setAttribute('required', 'required'); $form = new Form('password_forgotten'); $form->add($email); $emailInput = new Input(); $emailInput->getFilterChain()->attachByName('StringTrim'); $emailInput->getValidatorChain()->attachByName('EmailAddress'); $inputFilter = new InputFilter(); $inputFilter->add($emailInput); $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $email = $form->get('email')->getValue(); //get the filtered value //Check if the email is present in the DB $entityManager = $this->getServiceLocator()->get('entity-manager'); $userEntity = $this->getServiceLocator()->get('user-entity'); $user = $entityManager->getRepository(get_class($userEntity))->findOneByEmail($email); if (!$user) { $this->flashMessenger()->addErrorMessage($this->translator->translate("The email entered is not present in our database")); return $this->redir()->toRoute('admin/default', array('controller' => 'log', 'action' => 'forgotten')); } else { //Check if the user is administrator $accessControlList = $this->getServiceLocator()->get('acl'); $allowed = $accessControlList->isAllowed($user->getRoleName(), 'index'); if (!$allowed) { $this->flashMessenger()->addErrorMessage(sprintf($this->translator->translate("The user with email %s does not have administrative privileges"), $email)); return $this->redir()->toRoute('admin/default', array('controller' => 'log', 'action' => 'forgotten')); } else { //generate token and send a link to the email $stdStrings = $this->getServiceLocator()->get('stdlib-strings'); $token = $stdStrings->randomString(10); $passwordResetsEntity = new PasswordResets($email, $token); //use this request to also delete password requests older than 24 hours $entityManager->getRepository(get_class($passwordResetsEntity))->deleteOldRequests(); $entityManager->persist($passwordResetsEntity); $entityManager->flush(); $uri = $this->getRequest()->getUri(); $renderer = $this->serviceLocator->get('Zend\\View\\Renderer\\RendererInterface'); $basePath = $renderer->basePath('/admin/log/reset'); $baseUrl = sprintf('%s://%s', $uri->getScheme(), $uri->getHost()); $link = $baseUrl . $basePath . '?email=' . urlencode($email) . '&token=' . $token; //send email with the generated password $config = $this->getServiceLocator()->get('config'); $message = new Mail\Message(); $message->setFrom($config['other']['no-reply'])->setTo($email)->setSubject('New password')->setBody(sprintf($this->translator->translate("Dear user,%sFollowing the new password request, here is a link for you to visit in order to create a new password:%s%s"), "\n\n", "\n\n", $link)); $transport = new Mail\Transport\Sendmail(); $transport->send($message); $this->flashMessenger()->addSuccessMessage(sprintf($this->translator->translate("A link was generated and sent to %s"), $email)); return $this->redir()->toRoute('admin/default', array('controller' => 'log', 'action' => 'in')); } } } } return array('form' => $form); }
public function userSettingsAction() { //check if user is already logged in, if so, redirect to the home page $objUser = FrontUserSession::isLoggedIn(); if ($objUser === FALSE) { return $this->redirect()->toRoute("home"); } //end if //set layout $this->layout("layout/layout"); //create form $objForm = new Form(); $objForm->add(array("type" => "text", "name" => "locale_timezone", "attributes" => array("id" => "locale_timezone", "disabled" => "disabled", "title" => "Timezone currently set for your profile"), "options" => array("label" => "Timezone"))); //populate form values using user settings foreach ($objForm as $objElement) { $objForm->get($objElement->getName())->setValue($objUser->user_settings->{$objElement->getName()}); } //end foreach return array("objUser" => $objUser, "form" => $objForm); }
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 testSettingSomeDataButNoneForCollectionReturnsSpecifiedNumberOfElementsAfterPrepare() { $form = new Form(); $form->add(new Element\Text('input')); $form->add(array('name' => 'names', 'type' => 'Collection', 'options' => array('target_element' => new Element\Text(), 'count' => 2))); $form->setData(array('input' => 'foo')); $this->assertCount(0, $form->get('names')); $form->prepare(); $this->assertCount(2, $form->get('names')); }
/** * @return array */ public function deleteAction() { $this->layout('layout/modal'); $className = $this->getEntityClassName(); $id = (int) $this->params()->fromRoute('id'); $entity = $this->getEntityManager()->find($className, $id); $form = new Form(); $form->setAttribute('action', $this->url()->fromRoute(null, array(), true)); $form->add(new Hidden('entity')); $form->add(new Buttons('Delete', 'btn-danger')); // TODO validate no M:1 references // TODO validate no M:M references $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $this->getEntityManager()->remove($entity); $this->getEntityManager()->flush(); return $this->response; } } $form->setData(array('entity' => $id)); if (!$form->isValid()) { $form->get('buttons')->get('submit')->setAttribute('disabled', true); } return array('singular' => $this->getDatagrid()->getSingularName(), 'plural' => $this->getDatagrid()->getPluralName(), 'form' => $form, 'entity' => $entity); }