PHP Class symfony\component\form\ Form Code Examples

PHP symfony\component\form\Form - 30 examples found. These are the top rated real world PHP examples of class symfony\component\form\Form extracted from open source projects. You can rate examples to help us improve the quality of examples
A form is composed of a validator schema and a widget form schema. Form also takes care of CSRF protection by default. A CSRF secret can be any random string. If set to false, it disables the CSRF protection, and if set to null, it forces the form to use the global CSRF secret. If the global CSRF secret is also null, then a random one is generated on the fly.
Author: Fabien Potencier (fabien.potencier@symfony-project.com)
Author: Bernhard Schussek (bernhard.schussek@symfony-project.com)
Inheritance: extends Field, implements IteratorAggregate, implements Symfony\Component\Form\FormInterface
Example #1
0
 protected function getErrorMessages(\Symfony\Component\Form\Form $form, $name)
 {
     $errors = array();
     foreach ($form->getErrors() as $key => $error) {
         $errors[] = $error->getMessage();
     }
     foreach ($form->all() as $child) {
         $type = $child->getConfig()->getType()->getName();
         if ($child->count() && $type !== 'choice') {
             $childErrors = $this->getErrorMessages($child, $child->getName());
             if (sizeof($childErrors)) {
                 $errors = array_merge($errors, $childErrors);
             }
         } else {
             if (!$child->isValid()) {
                 if ($name == "responsable1" || $name == "responsable2") {
                     $errors[$child->getParent()->getParent()->getName() . '_' . $name . '_' . $child->getName()] = $this->getErrorMessages($child, $child->getName());
                 } else {
                     $errors[$name . '_' . $child->getName()] = $this->getErrorMessages($child, $child->getName());
                 }
             }
         }
     }
     return $errors;
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function process(Request $request, $grantType = 'password')
 {
     $account = $this->records->getAccountByEmail($this->submittedForm->get('email')->getData());
     if (!$account) {
         return null;
     }
     $oauth = $this->records->getOauthByGuid($account->getGuid());
     $requestPassword = $this->submittedForm->get('password')->getData();
     if ($this->isValidPassword($oauth, $requestPassword) === false) {
         return null;
     }
     $accessToken = $this->provider->getAccessToken('password', ['guid' => $account->getGuid()]);
     $this->session->addAccessToken('local', $accessToken)->createAuthorisation($account->getGuid());
     $request->query->set('code', Uuid::uuid4()->toString());
     try {
         parent::process($request, $grantType);
         $this->finish($request);
         $this->feedback->info('Login successful.');
     } catch (DisabledAccountException $ex) {
         $this->session->addRedirect($this->urlGenerator->generate('authenticationLogin'));
         if ($this->session->getAuthorisation()) {
             $this->dispatchEvent(MembersEvents::MEMBER_LOGIN_FAILED_ACCOUNT_DISABLED, $this->session->getAuthorisation());
         }
     }
     return $this->session->popRedirect()->getResponse();
 }
 public function saveCobroForm(Form $form, Cobro $cobro, $cuentaId)
 {
     $cuenta = $this->em->getRepository('AppBundle:Cuenta')->find($cuentaId);
     $result = false;
     $message = 'Ocurrion un error al guardar el cobro.';
     $amount = 0;
     $positive = false;
     if ($cuenta && $form->isValid()) {
         $cobro->setCuenta($cuenta);
         $this->em->persist($cobro);
         $cuenta->addPagoAmount($cobro->getMonto());
         $this->em->persist($cuenta);
         $this->em->flush();
         $result = true;
         $message = 'Cobro guardado con exito.';
         if ($cobro->getEnviado()) {
             //send email
             $message .= ' Email enviado correctamente';
         }
         $amount = $cuenta->getFormatedDiferencia();
         if ($cuenta->getDiferencia() < 0) {
             $positive = true;
         }
     }
     return array('result' => $result, 'message' => $message, 'amount' => $amount, 'positive' => $positive, 'cuentaId' => $cuentaId, 'cobro' => $cobro);
 }
Example #4
0
 protected function onCreateSuccess(Form $form)
 {
     $this->container->get('lichess_comment.authorname_persistence')->persistCommentInSession($form->getData());
     $response = parent::onCreateSuccess($form);
     $this->container->get('lichess_comment.authorname_persistence')->persistCommentInCookie($form->getData(), $response);
     return $response;
 }
 private function convertFormToArray(GenericSerializationVisitor $visitor, Form $data)
 {
     $isRoot = null === $visitor->getRoot();
     $form = new \ArrayObject();
     $errors = [];
     foreach ($data->getErrors() as $error) {
         $errors[] = $this->getErrorMessage($error);
     }
     if (!empty($errors)) {
         $form['errors'] = $errors;
     }
     $children = [];
     foreach ($data->all() as $child) {
         if ($child instanceof Form) {
             $children[$child->getName()] = $this->convertFormToArray($visitor, $child);
         }
     }
     if (!empty($children)) {
         $form['children'] = $children;
     }
     if ($isRoot) {
         $visitor->setRoot($form);
     }
     return $form;
 }
 /**
  * @param Request $request
  * @param Form $form
  * @param Eleve $eleve
  * @return bool
  */
 private function processPostedForm(Request $request, Form $form, Eleve $eleve, Period $periode)
 {
     $em = $this->getDoctrine()->getManager();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $temporary_taps_to_persist = $eleve->getTaps();
         // retire toutes les inscriptions au TAP pour la période qui ne sont pas
         // et qui n'ont pas été enregistré par le parent
         // dans la nouvelle sélection
         $repo = $em->getRepository('WCSCantineBundle:Eleve');
         $eleve_taps_periode = $repo->findAllTapsForPeriode($eleve, $periode, true);
         foreach ($eleve_taps_periode as $item) {
             if (!$temporary_taps_to_persist->contains($item)) {
                 $em->remove($item);
             }
         }
         // retire toutes les inscriptions à la garderie pour la période qui ne sont pas
         // et qui n'ont pas été enregistré par le parent
         // dans la nouvelle sélection
         $temporary_garderies_to_persist = $eleve->getGarderies();
         $eleve_garderies_periode = $repo->findAllGarderiesForPeriode($eleve, $periode, true);
         foreach ($eleve_garderies_periode as $item) {
             if (!$temporary_garderies_to_persist->contains($item)) {
                 $em->remove($item);
             }
         }
         $eleve->setTapgarderieSigned(true);
         $em->flush();
         return true;
     }
     return false;
 }
 public function persistTranslations(Form $form, $class, $field, $id, $locales, $userLocale)
 {
     $translations = $form->getData();
     $em = $this->em;
     $repository = $em->getRepository($class);
     $entity = $repository->find($id);
     // loop on locales
     // parse form data
     // get data stored in db
     // set form data on object if needed
     foreach ($locales as $locale) {
         if (array_key_exists($locale, $translations) && $translations[$locale] !== NULL) {
             $entity->setTranslatableLocale($locale);
             $em->refresh($entity);
             $postedValue = $translations[$locale];
             $storedValue = $this->getField($entity, $field);
             if ($storedValue !== $postedValue) {
                 $this->setField($entity, $field, $postedValue);
                 $em->flush();
             }
         }
     }
     // switch entity locale back to user's locale
     $this->setEntityToUserLocale($entity, $userLocale);
 }
 /**
  * @param Request $request
  * @param Form $form
  * @param Eleve $eleve
  * @return bool
  */
 private function processPostedForm(Request $request, Form $form, Eleve $eleve)
 {
     $em = $this->getDoctrine()->getManager();
     $form->handleRequest($request);
     if ($form->isValid()) {
         // la nouvelle sélection de dates (avec celles déjà présentes en
         // base de données, et les nouvelles à ajouter
         // (cette liste a été mise à jour avec LunchToStringTransformer)
         $lunchesNew = $eleve->getLunches();
         // récupère les réservations actuellement en base de données
         $lunchesOld = $em->getRepository("WCSCantineBundle:Lunch")->findByEleve($eleve);
         // supprime les dates qui ne sont plus sélectionnées
         foreach ($lunchesOld as $lunchOld) {
             if (!$lunchesNew->contains($lunchOld)) {
                 $em->remove($lunchOld);
             }
         }
         $eleve->setCanteenSigned(true);
         // met à jour la fiche élève (le régime alimentaire,...)
         $em->persist($eleve);
         $em->flush();
         return true;
     }
     return false;
 }
Example #9
0
 /**
  * @param Form $form
  * @param RuleAction $action
  * @return void
  */
 public function formIsSubmitted(Form $form, RuleAction $action)
 {
     $params = $this->getParams($action);
     $category = $form->get('category')->getData();
     $params['category_id'] = $category->getId();
     $action->setRawParams($params);
 }
 protected function addField(Form $form, $municipio)
 {
     $formOptions = array('class' => 'SiSuCuentaBundle:Parroquia', 'empty_value' => '-- Seleccionar --', 'attr' => array('class' => 'usuario_parroquia'), 'required' => true, 'label' => 'Parroquia', 'query_builder' => function (EntityRepository $er) use($municipio) {
         return $er->createQueryBuilder('parroquia')->where('parroquia.municipio = :municipio')->setParameter('municipio', $municipio);
     });
     $form->add('parroquia', 'entity', $formOptions);
 }
 /**
  * @param array $data
  * @param Form $form
  * @return string
  */
 protected function aggregatePluralValues(&$data, $form)
 {
     $labelManager = $this->labelManager;
     $labelValue = '';
     $standardRules = array();
     $explicitRules = array();
     foreach ($data as $property => $value) {
         if (0 === strpos($property, self::PLURAL_FIELD_PREFIX)) {
             $pluralForm = substr($property, strlen(self::PLURAL_FIELD_PREFIX));
             if (is_numeric($pluralForm)) {
                 $standardRules[$pluralForm] = $value;
             } else {
                 $explicitRules[$pluralForm] = sprintf('%s %s', $labelManager->reverseTransformInterval($pluralForm), $value);
             }
             $form->remove($property);
             unset($data[$property]);
         }
     }
     if ($standardRules) {
         $labelValue = implode('|', $standardRules);
         if ($explicitRules) {
             $labelValue .= '|' . implode('|', $explicitRules);
         }
     } elseif ($explicitRules) {
         $labelValue = implode('|', $explicitRules);
     }
     return $labelValue;
 }
 /**
  * Get rid on any fields that don't appear in the form
  *
  * @param Request $request
  * @param Form $form
  */
 protected function removeExtraFields(Request $request, Form $form)
 {
     $data = $request->request->all();
     $children = $form->all();
     $data = array_intersect_key($data, $children);
     $request->request->replace($data);
 }
 /**
  * @param Form $form
  *
  * @return mixed
  * @throws \Exception
  * @throws \PaymentSuite\PaymentCoreBundle\Exception\PaymentException
  */
 private function processPaymentData(Form $form)
 {
     if ($form->isValid()) {
         $data = $form->getData();
         $paymentMethod = new AuthorizenetMethod();
         $paymentMethod->setCreditCartNumber($data['credit_cart'])->setCreditCartExpirationMonth($data['credit_cart_expiration_month'])->setCreditCartExpirationYear($data['credit_cart_expiration_year']);
         try {
             $this->get('authorizenet.manager')->processPayment($paymentMethod);
             $redirectUrl = $this->container->getParameter('authorizenet.success.route');
             $redirectAppend = $this->container->getParameter('authorizenet.success.order.append');
             $redirectAppendField = $this->container->getParameter('authorizenet.success.order.field');
         } catch (PaymentException $e) {
             /**
              * Must redirect to fail route
              */
             $redirectUrl = $this->container->getParameter('authorizenet.fail.route');
             $redirectAppend = $this->container->getParameter('authorizenet.fail.order.append');
             $redirectAppendField = $this->container->getParameter('authorizenet.fail.order.field');
             throw $e;
         }
     } else {
         /**
          * If form is not valid, fail return page
          */
         $redirectUrl = $this->container->getParameter('authorizenet.fail.route');
         $redirectAppend = $this->container->getParameter('authorizenet.fail.order.append');
         $redirectAppendField = $this->container->getParameter('authorizenet.fail.order.field');
     }
     $redirectData = $redirectAppend ? array($redirectAppendField => $this->get('payment.bridge')->getOrderId()) : array();
     $returnData['redirectUrl'] = $redirectUrl;
     $returnData['redirectData'] = $redirectData;
     return $returnData;
 }
 private function createLoginForm($operator = null)
 {
     $form = new Form('login', array('validator' => $this->get('validator')));
     $form->add(new TextField('email'));
     $form->add(new PasswordField('passwd'));
     return $form;
 }
 function it_does_not_remove_user_form_type_if_users_data_is_submitted(FormEvent $event, Form $form)
 {
     $event->getData()->willReturn(['user' => ['plainPassword' => 'test']]);
     $event->getForm()->shouldNotBeCalled();
     $form->remove('user')->shouldNotBeCalled();
     $this->preSubmit($event);
 }
Example #16
0
 public static function handleFlashErrors(SymfonyForm $form, $identifier)
 {
     $errors = self::$app['flashbag']->get('form.' . $identifier . '.errors');
     foreach ($errors as $error) {
         $form->addError(new FormError($error));
     }
 }
Example #17
0
 /**
  * This method is here to make your life better, so overwrite  it
  *
  * @param \Symfony\Component\Form\Form $form the valid form
  * @param \Taskeet\MainBundle\Entity\Event $Event your \Taskeet\MainBundle\Entity\Event object
  */
 public function preSave(\Symfony\Component\Form\Form $form, \Taskeet\MainBundle\Entity\Event $Event)
 {
     if (!$form->get('reminder')->getData() instanceof DateTime && $form->get('reminder')->getData()) {
         $date = clone $form->get('startDate')->getData();
         $date->sub(new DateInterval($form->get('reminder')->getData()));
         $Event->setReminder($date);
     }
 }
Example #18
0
 public function stringifyFormErrors(Form $form)
 {
     $errors = [];
     foreach ($form->getErrors(true, true) as $error) {
         $errors[] = $error->getMessage();
     }
     return implode('<br>', $errors);
 }
 /**
  * @return bool
  */
 public function process()
 {
     $this->form->handleRequest($this->request);
     if ($this->form->isValid()) {
         return $this->onSuccess();
     }
     return false;
 }
 private function getErrorMessages(Form $form)
 {
     $errors = [];
     foreach ($form->getErrors(true, true) as $key => $error) {
         $errors[] = $error->getMessage();
     }
     return $errors;
 }
Example #21
0
 protected function assertViewIsValid(Form $form, array $formData)
 {
     $view = $form->createView();
     $children = $view->children;
     foreach (array_keys($formData) as $key) {
         $this->assertArrayHasKey($key, $children);
     }
 }
Example #22
0
 public function testValid()
 {
     $this->sut->submit(['fullName' => 'James T. Kirk', 'location' => 'San Francisco', 'placeOfBirth' => 'Iowa']);
     foreach ($this->sut as $name => $child) {
         $this->assertTrue($child->isValid(), $name);
     }
     $this->assertTrue($this->sut->isValid());
 }
Example #23
0
 /**
  * Get the expiration time of the ban based on the fields of the form
  *
  * @param  Form          $form The form
  * @return \TimeDate|null
  */
 private function getExpiration($form)
 {
     if ($form->get('automatic_expiration')->getData()) {
         return $form->get('expiration')->getData();
     } else {
         return null;
     }
 }
Example #24
0
 /**
  * Gets a form error messages
  *
  * @param Form $form
  *
  * @return array|string
  */
 public static function getFormErrorMessages(Form $form)
 {
     $errors = [];
     foreach ($form->getErrors(true, true) as $error) {
         $errors = $error->getMessage();
     }
     return $errors;
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Form $form, $webSpaceKey, array $options = [])
 {
     $user = $form->getData();
     $user = $this->setUserData($form, $user);
     $this->entityManager->persist($user);
     $this->entityManager->flush();
     return $user;
 }
 /**
  * Validate the given request with the given rules.
  *
  * @param  \Symfony\Component\Form\Form  $form
  * @param  \Illuminate\Http\Request  $request
  * @param  array  $rules
  * @param  array  $messages
  * @return void
  */
 public function validateForm(Form $form, Request $request, array $rules, array $messages = array())
 {
     $data = $form->getName() ? $request->get($form->getName()) : $request->all();
     $validator = $this->getValidationFactory()->make($data, $rules, $messages);
     if ($validator->fails()) {
         $this->throwValidationException($request, $validator);
     }
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 protected function groupChild(Form $form)
 {
     $group_child = array();
     foreach ($form->all() as $child) {
         $group_child[substr($child->getName(), 0, -1)][] = $child;
     }
     return $group_child;
 }
 /**
  * @param string $name
  * @param string $dataClass
  * @param array $options
  * @param FormInterface $parent
  * @return FormInterface
  */
 protected function createForm($name, $dataClass = null, array $options = array(), FormInterface $parent = null)
 {
     $eventDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
     $config = new FormConfigBuilder($name, $dataClass, $eventDispatcher, $options);
     $result = new Form($config);
     $result->setParent($parent);
     return $result;
 }
Example #29
0
 /**
  * This method is here to make your life better, so overwrite  it
  *
  * @param \Symfony\Component\Form\Form $form the valid form
  * @param \Taskeet\MainBundle\Entity\Event $Event your \Taskeet\MainBundle\Entity\Event object
  */
 public function preSave(\Symfony\Component\Form\Form $form, \Taskeet\MainBundle\Entity\Event $Event)
 {
     $Event->setOwner($this->getUser());
     if ($form->get('remind')->getData()) {
         $date = clone $form->get('startDate')->getData();
         $date->sub(new DateInterval($form->get('remind')->getData()));
         $Event->setReminder($date);
     }
 }
 function let(ProductRepositoryInterface $productRepository, UniqueValuesSet $uniqueValuesSet, ExecutionContextInterface $context, Form $form, ProductInterface $product, ProductValueInterface $value)
 {
     $this->beConstructedWith($productRepository, $uniqueValuesSet);
     $product->getValue('unique_attribute')->willReturn($value);
     $form->getData()->willReturn($product);
     $context->getPropertyPath()->willReturn(self::PROPERTY_PATH);
     $context->getRoot()->willReturn($form);
     $this->initialize($context);
 }