public function validateForm(DataEvent $event) { $form = $event->getForm(); if (!$form->isSynchronized()) { $form->addError(new FormError($form->getAttribute('invalid_message'), $form->getAttribute('invalid_message_parameters'))); } if (count($form->getExtraData()) > 0) { $form->addError(new FormError('This form should not contain extra fields')); } if ($form->isRoot() && isset($_SERVER['CONTENT_LENGTH'])) { $length = (int) $_SERVER['CONTENT_LENGTH']; $max = trim(ini_get('post_max_size')); if ('' !== $max) { switch (strtolower(substr($max, -1))) { // The 'G' modifier is available since PHP 5.1.0 case 'g': $max *= 1024; case 'm': $max *= 1024; case 'k': $max *= 1024; } if ($length > $max) { $form->addError(new FormError('The uploaded file was too large. Please try to upload a smaller file')); } } } }
public function preBind(DataEvent $event) { $form = $event->getForm(); $data = $event->getData(); if (null === $data || '' === $data) { $data = array(); } if (!is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\\Traversable and \\ArrayAccess)'); } // Remove all empty rows if ($this->allowDelete) { foreach ($form as $name => $child) { if (!isset($data[$name])) { $form->remove($name); } } } // Add all additional rows if ($this->allowAdd) { foreach ($data as $name => $value) { if (!$form->has($name)) { $form->add($this->factory->createNamed($this->type, $name, null, array_replace(array('property_path' => '[' . $name . ']'), $this->options))); } } } }
/** * {@inheritdoc} */ public function onBindNormData(DataEvent $event) { $data = $event->getData(); if (true === empty($data)) { return; } if (strpos($data, 'delete_') === false) { $upload = $this->em->getRepository('LowbiSystemBundle:Upload')->findOneById($data); if (!$upload) { throw $this->createNotFoundException($translator->trans('entities.notfound')); } $attributes = $event->getForm()->getTypes(); $lastType = $attributes[count($attributes) - 1]; $formType = get_class($lastType); if ($formType != null) { $type = substr($formType, strrpos($formType, '\\') + 1); $upload->setType($type); } $event->setData($upload); } else { $id = str_replace('delete_', '', $data); $upload = $this->em->getRepository('LowbiSystemBundle:Upload')->findOneById($id); $event->setData($upload); } return; }
public function postBind(DataEvent $event) { $user = $event->getForm()->getData(); if ($user instanceof UserInterface) { $this->userManager->updateCanonicalFields($user); } }
public function preBind(DataEvent $event) { if (!$this->resizeOnBind) { return; } $form = $event->getForm(); $data = $event->getData(); if (null === $data || '' === $data) { $data = array(); } if (!is_array($data) && !$data instanceof \Traversable) { throw new UnexpectedTypeException($data, 'array or \\Traversable'); } // Remove all empty rows except for the prototype row foreach ($form as $name => $child) { $form->remove($name); } // Add all additional rows foreach ($data as $name => $value) { if (!$form->has($name)) { $options = array_merge($this->typeOptions, array('property_path' => '[' . $name . ']')); $form->add($this->factory->createNamed($this->type, $name, null, $options)); } if (isset($value['_delete'])) { $this->removed[] = $name; } } }
/** * Form event - removes image if scheduled. * * @param DataEvent $event */ public function bind(DataEvent $event) { $entity = $event->getData(); if ($entity instanceof ImageInterface && null === $entity->getId() && null === $entity->getName()) { $event->setData(null); } }
public function preSetData(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); // During form creation setData() is called with null as an argument // by the FormBuilder constructor. You're only concerned with when // setData is called with an actual Entity object in it (whether new // or fetched with Doctrine). This if statement lets you skip right // over the null condition. if (null === $data) { return; } // Defaults $defaults = array(); $classTypes = $this->em->createQuery('SELECT u from TSK\\ClassBundle\\Entity\\ClassType u WHERE u.organization=:org')->setParameter('org', $this->org_id)->getResult(); if (count($classTypes)) { foreach ($classTypes as $classType) { $ctc = new ClassTypeCredit(); $ctc->setClassType($classType); $ctc->setClass($data); $ctc->setValue(0); $defaults[$classType->getName()] = $ctc; } } $results = array(); foreach ($data->getClassTypeCredits() as $idx => $ctc) { $results[$ctc->getClassType()->getName()] = $ctc; } $results = array_merge($defaults, $results); $payload = array('type' => 'tsk_class_types', 'label' => ' ', 'required' => false, 'data' => $results); $form->add($this->factory->createNamed('classTypeCredits', 'collection', NULL, $payload)); }
public function preSetData(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); if (null === $data) { return; } $form->add($this->factory->createNamed('password', 'repeated', null, array('first_options' => array('label' => 'form.label.password'), 'second_options' => array('label' => 'form.label.password_repeated'), 'invalid_message' => 'form.error.password_mismatch'))); }
public function onPostBind(DataEvent $event) { $contactDetail = $event->getData(); $country = $contactDetail->getCountry(); if ($country instanceof Country) { $code = (int) $country->getCountryCode(); $contactDetail->setCountryCode($code); } }
/** * {@inheritdoc} */ public function validate(DataEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ($this->captcha->getLength() !== strlen($data) || $this->captcha->getCode() !== $this->captcha->encode($data)) { $form->addError(new FormError('The captcha is invalid')); } $this->captcha->removeCode(); }
/** * Form event - adds entities to uow to be delete * * @param DataEvent $event */ public function postBind(DataEvent $event) { $collection = $event->getData(); if ($collection instanceof PersistentCollection) { foreach ($collection->getDeleteDiff() as $entity) { $this->om->remove($entity); } } }
public function onBindClientData(DataEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ((!$form->hasParent() || $form->getParent()->isRoot()) && !$this->csrfProvider->isCsrfTokenValid($this->intention, $data)) { $form->addError(new FormError('The CSRF token is invalid. Please try to resubmit the form')); // If the session timed out, the token is invalid now. // Regenerate the token so that a resubmission is possible. $event->setData($this->csrfProvider->generateCsrfToken($this->intention)); } }
/** * Ensures a root form has a CSRF field. * * This method should be connected to both form.pre_set_data and form.pre_bind. */ public function ensureCsrfField(DataEvent $event) { $form = $event->getForm(); $options = array(); if ($this->intention) { $options['intention'] = $this->intention; } if ($this->provider) { $options['csrf_provider'] = $this->provider; } $form->add($this->factory->createNamed('csrf', $this->name, null, $options)); }
public function preBind(DataEvent $event) { $form = $event->getForm(); $data = $event->getData(); if (null === $data) { return; } if (isset($data['estado'])) { $form->remove('cidade'); $form->add($this->factory->createNamed('cidade', 'entity', null, array('class' => 'BFOSBrasilBundle:Cidade', 'property' => 'nome', 'query_builder' => function (EntityRepository $er) use($data) { return $er->createQueryBuilder('c')->where('c.uf = :uf')->orderBy('c.nome', 'ASC')->setParameter('uf', $data['estado']); }))); } }
/** * {@inheritdoc} */ public function onBindNormData(DataEvent $event) { $data = $event->getData(); if (empty($data)) { return; } $address = $data['address']; $latitude = isset($data['latitude']) ? $data['latitude'] : null; $longitude = isset($data['longitude']) ? $data['longitude'] : null; $locality = isset($data['locality']) ? $data['locality'] : null; $country = isset($data['country']) ? $data['country'] : null; $geo = new AddressGeolocation($address, $latitude, $longitude, $locality, $country); $event->setData($geo); }
public function preSetData(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); if (null === $data) { return; } else { $newData = new \Doctrine\Common\Collections\ArrayCollection(); $newData['id'] = $data->getId(); $newData['title'] = $data->getTitle(); $data = $newData; } return $data; }
public function prebind(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); $locationService = LocationService::getCurrentInstance(); $countryId = !empty($data) && $data['country'] ? $data['country'] : 0; $choices = array(0 => null); if ($countryId) { $cities = $locationService->getGlobalCitiesListByContry($countryId); foreach ($cities['data'] as $id => $value) { $choices[$id] = $value['name']; } } $form->add($this->factory->createNamed('city', GlobalCityListType::NAME, null, compact('choices'))); }
public function preSetData(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); if (null === $data) { return; } else { $newData = new \Doctrine\Common\Collections\ArrayCollection(); foreach ($data as $item) { $newData[] = $item; } $data = $newData; } return $data; }
public function validate(DataEvent $event) { $form = $event->getForm(); $error = ''; $request = $this->request->request; $server = $this->request->server; $datas = array('privatekey' => $this->privateKey, 'challenge' => $request->get('recaptcha_challenge_field'), 'response' => $request->get('recaptcha_response_field'), 'remoteip' => $server->get('REMOTE_ADDR')); if (empty($datas['challenge']) || empty($datas['response'])) { $error = 'The captcha is not valid.'; } if (true !== ($answer = $this->check($datas, $form->getAttribute('option_validator')))) { $error = sprintf('Unable to check the captcha from the server. (%s)', $answer); } if (!empty($error)) { $form->addError(new FormError($error)); } }
/** * Validates the form and its domain object. * * @param DataEvent $event The event object */ public function validateForm(DataEvent $event) { $form = $event->getForm(); if ($form->isRoot()) { // Validate the form in group "Default" $violations = $this->validator->validate($form); if (count($violations) > 0) { foreach ($violations as $violation) { // Allow the "invalid" constraint to be put onto // non-synchronized forms $allowNonSynchronized = Form::ERR_INVALID === $violation->getCode(); $this->violationMapper->mapViolation($violation, $form, $allowNonSynchronized); } } } }
/** * {@inheritdoc} */ public function onBindNormData(DataEvent $event) { $data = $event->getData(); if (empty($data)) { return; } if ($this->multiple) { $paths = explode(',', $data); $return = array(); foreach ($paths as $path) { if ($handle = $this->getHandleToPath($path)) { $return[] = $handle; } } } else { if ($handle = $this->getHandleToPath($data)) { $return = $handle; } } $event->setData($return); }
public function preSetData(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); // During form creation setData() is called with null as an argument // by the FormBuilder constructor. You're only concerned with when // setData is called with an actual Entity object in it (whether new // or fetched with Doctrine). This if statement lets you skip right // over the null condition. if (null === $data) { return; } // check if the product object is "new" if ($data->getId()) { $form->add($this->factory->createNamed('datetime', 'created_at', null, array('label' => 'Fecha de creación:', 'widget' => 'single_text')))->add($this->factory->createNamed('datetime', 'start_fund_at', null, array('label' => 'Fecha de inicio de recaudación:', 'widget' => 'single_text', 'required' => false)))->add($this->factory->createNamed('datetime', 'extended_at', null, array('label' => 'Fecha de inicio de prorroga:', 'widget' => 'single_text', 'required' => false)))->add($this->factory->createNamed('integer', 'applause', null, array('label' => 'Aplausos:')))->add($this->factory->createNamed('integer', 'status', null, array('label' => 'Estado:'))); } else { // $builder = $this->factory->createBuilder(new \Crearock\ProjectBundle\Form\ProjectType()); $builder = $this->factory->createNamedBuilder('checkbox', 'terms', null, array('property_path' => false)); // $term_field = $builder->create('terms', 'checkbox', array('property_path' => 'false')) $term_field = $builder->addValidator(new CallbackValidator(function ($terms) { if (!$terms->getData()) { $terms->addError(new FormError('Debes aceptar los Términos de uso.')); } }))->getForm(); $form->add($term_field); // $name = $form->getName(); // $form = $this->factory->createNamed(new \Crearock\ProjectBundle\Form\ProjectType(), $name); /* $builder = $this->factory->createBuilder(new \Crearock\ProjectBundle\Form\ProjectType()); $builder->addValidator(new CallbackValidator( function (FormInterface $form){ $terms = $form->get('terms'); if (!$terms->getData()) { $terms->addError(new FormError('Debes aceptar los Términos de uso.')); } } )); */ } }
public function preSetData(DataEvent $event) { $data = $event->getData(); $form = $event->getForm(); // During form creation setData() is called with null as an argument // by the FormBuilder constructor. We're only concerned with when // setData is called with an actual Entity object in it (whether new, // or fetched with Doctrine). This if statement let's us skip right // over the null condition. if (null === $data) { return; } // check if the product object is "new" if ($data != null) { $choicesEntityName = array($data->entityName => $data->entityName); $choicesPropertyName = array($data->propertyName => $data->propertyName); $form->add($this->factory->createNamed('choice', 'entityName', $data->entityName, array('choices' => $choicesEntityName, 'multiple' => false, 'attr' => array('style' => 'width:120px;margin:0px;', 'class' => 'entityClass'), 'required' => false))); $form->add($this->factory->createNamed('choice', 'propertyName', $data->propertyName, array('choices' => $choicesPropertyName, 'multiple' => false, 'attr' => array('style' => 'width:120px;margin:0px;', 'class' => 'propertyClass'), 'required' => false))); if ($data->fieldType == 'entity') { $form->add($this->factory->createNamed('text', 'length', null, array('attr' => array('style' => 'width:120px;margin:0px;', 'disabled' => 'disabled', 'required' => false)))); } } }
/** * Validates the form and its domain object. * * @param DataEvent $event The event object */ public function validateForm(DataEvent $event) { $form = $event->getForm(); if ($form->isRoot()) { $mapping = array(); $forms = array(); $this->buildFormPathMapping($form, $mapping); $this->buildDataPathMapping($form, $mapping); $this->buildNamePathMapping($form, $forms); $this->resolveMappingPlaceholders($mapping, $forms); // Validate the form in group "Default" // Validation of the data in the custom group is done by validateData(), // which is constrained by the Execute constraint if ($form->hasAttribute('validation_constraint')) { $violations = $this->validator->validateValue($form->getData(), $form->getAttribute('validation_constraint'), self::getFormValidationGroups($form)); if ($violations) { foreach ($violations as $violation) { $propertyPath = new PropertyPath($violation->getPropertyPath()); $template = $violation->getMessageTemplate(); $parameters = $violation->getMessageParameters(); $pluralization = $violation->getMessagePluralization(); $error = new FormError($template, $parameters, $pluralization); $child = $form; foreach ($propertyPath->getElements() as $element) { $children = $child->getChildren(); if (!isset($children[$element])) { $form->addError($error); break; } $child = $children[$element]; } $child->addError($error); } } } elseif (count($violations = $this->validator->validate($form))) { foreach ($violations as $violation) { $propertyPath = $violation->getPropertyPath(); $template = $violation->getMessageTemplate(); $parameters = $violation->getMessageParameters(); $pluralization = $violation->getMessagePluralization(); $error = new FormError($template, $parameters, $pluralization); foreach ($mapping as $mappedPath => $child) { if (preg_match($mappedPath, $propertyPath)) { $child->addError($error); continue 2; } } $form->addError($error); } } } }
public function preBind(DataEvent $event) { // Get a snapshot of the current state of the normalized data // to compare against later $this->dataSnapshot = $event->getForm()->getNormData(); if (is_object($this->dataSnapshot)) { // Make sure the snapshot remains stable and doesn't change $this->dataSnapshot = clone $this->dataSnapshot; } if (null !== $this->dataSnapshot && !is_array($this->dataSnapshot) && !($this->dataSnapshot instanceof \Traversable && $this->dataSnapshot instanceof \ArrayAccess)) { throw new UnexpectedTypeException($this->dataSnapshot, 'array or (\\Traversable and \\ArrayAccess)'); } }