Esempio n. 1
0
 /**
  * Process form
  *
  * @param  Task $entity
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(Task $entity)
 {
     $action = $this->entityRoutingHelper->getAction($this->request);
     $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
     $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
     if ($targetEntityClass && !$entity->getId() && $this->request->getMethod() === 'GET' && $action === 'assign' && is_a($targetEntityClass, 'Oro\\Bundle\\UserBundle\\Entity\\User', true)) {
         $entity->setOwner($this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId));
         FormUtils::replaceField($this->form, 'owner', ['read_only' => true]);
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // TODO: should be refactored after finishing BAP-8722
             // Contexts handling should be moved to common for activities form handler
             if ($this->form->has('contexts')) {
                 $contexts = $this->form->get('contexts')->getData();
                 $this->activityManager->setActivityTargets($entity, $contexts);
             } elseif ($targetEntityClass && $action === 'activity') {
                 // if we don't have "contexts" form field
                 // we should save association between activity and target manually
                 $this->activityManager->addActivityTarget($entity, $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId));
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 public function testFields()
 {
     $this->assertCount(2, $this->form);
     $this->assertTrue($this->form->has('_operation'));
     $view = $this->form->createView();
     $this->assertCount(1, $view['_operation']);
     $this->assertArrayHasKey('confirm', $view['_operation']);
 }
Esempio n. 3
0
 /**
  * @param Account $entity
  */
 protected function handleContacts($entity)
 {
     if ($this->form->has('contacts')) {
         $contacts = $this->form->get('contacts');
         $this->appendContacts($entity, $contacts->get('added')->getData());
         $this->removeContacts($entity, $contacts->get('removed')->getData());
     }
 }
 protected function validateFields(FormInterface $form, $data)
 {
     if (!in_array($data->getType(), OneTimeContribution::getTypeChoices())) {
         $form->get('type')->addError(new FormError('Choose an option.'));
     } else {
         if ($data->getType() == OneTimeContribution::TYPE_FUNDING_BANK) {
             $bankInformationValidator = new BankInformationFormValidator($form->get('bankInformation'), $data->getBankInformation());
             $bankInformationValidator->validate();
             if (!$data->getStartTransferDate() instanceof \DateTime) {
                 $form->get('start_transfer_date_month')->addError(new FormError('Enter correct date.'));
             } else {
                 $minDate = new \DateTime('+5 days');
                 if ($data->getStartTransferDate() < $minDate) {
                     $form->get('start_transfer_date_month')->addError(new FormError("The start of your transfer should be at least 5 days after today’s date."));
                 }
             }
             if (!$data->getAmount()) {
                 $form->get('amount')->addError(new FormError('Required.'));
             }
             if ($form->has('transaction_frequency')) {
                 $frequency = $form->get('transaction_frequency')->getData();
                 if (null === $frequency || !is_numeric($frequency)) {
                     $form->get('transaction_frequency')->addError(new FormError('Choose an option.'));
                 }
             }
             if ($form->has('contribution_year')) {
                 $contributionYear = $data->getContributionYear();
                 if (null === $contributionYear || !is_numeric($contributionYear)) {
                     $form->get('contribution_year')->addError(new FormError('Enter valid year.'));
                 } else {
                     $currDate = new \DateTime();
                     $currYear = $currDate->format('Y');
                     $minDate = new \DateTime($currYear . '-01-01');
                     $maxDate = new \DateTime($currYear . '-04-15');
                     $startTransferDate = $data->getStartTransferDate();
                     if ($startTransferDate < $minDate || $startTransferDate > $maxDate) {
                         if ($contributionYear !== $currYear) {
                             $form->get('contribution_year')->addError(new FormError(sprintf('Value should be equal %s', $currYear)));
                         }
                     } else {
                         $prevYear = $currDate->add(\DateInterval::createFromDateString('-1 year'))->format('Y');
                         if ($contributionYear !== $currYear && $contributionYear !== $prevYear) {
                             $form->get('contribution_year')->addError(new FormError(sprintf('Value should be equal %s or %s', $prevYear, $currYear)));
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * @param FormInterface $form
  * @param FormException $formException
  */
 private static function addFormError(FormInterface $form, FormException $formException)
 {
     $fieldName = $formException->getFieldName();
     if ($form->has($fieldName)) {
         $form->get($fieldName)->addError(new FormError($formException->getMessage()));
     }
 }
 /**
  * Extracted POSTed data from JSON request
  *
  * @return array
  * @throws \Symfony\Component\HttpKernel\Exception\HttpException
  */
 protected function getPostJsonData()
 {
     $return = array();
     $body = $this->request->getContent();
     if (!empty($body) && !is_null($body) && $body != 'null') {
         $return = json_decode($body, true);
         if (null === $return || !is_array($return)) {
             throw new HttpException(400, "Bad JSON format of request body");
         }
     }
     // fix array type
     foreach ($return as $name => $value) {
         if (!$this->form->has($name)) {
             continue;
         }
         $formElement = $this->form->get($name);
         if ($formElement->getConfig()->getType()->getName() != 'collection') {
             continue;
         }
         if (!is_array($value) && !empty($value)) {
             $return[$name] = array($value);
         } elseif (!is_array($value) && empty($value)) {
             $return[$name] = array();
         }
     }
     // ignoring additional fields
     foreach ($return as $name => $value) {
         if (!$this->form->has($name)) {
             unset($return[$name]);
         }
     }
     return $return;
 }
Esempio n. 7
0
 /**
  * @param B2bCustomer $entity
  */
 protected function handleOpportunities(B2bCustomer $entity)
 {
     if ($this->form->has('opportunities')) {
         $opportunities = $this->form->get('opportunities');
         $this->appendOpportunities($entity, $opportunities->get('added')->getData());
         $this->removeOpportunities($entity, $opportunities->get('removed')->getData());
     }
 }
 /**
  * Recurse over nested errors
  *
  * @param FormInterface $form
  * @param array $errors
  */
 private function recurseErrors(FormInterface $form, array $errors)
 {
     foreach ($errors as $field => $error) {
         if (is_array($error)) {
             $this->recurseErrors($form->has($field) ? $form->get($field) : $form, $error);
         } else {
             // todo: this fix should not be in here - needs lifting out into mapping
             if ('addressLine1' == $field) {
                 $field = 'street';
             }
             if ($form->has($field)) {
                 $form->get($field)->addError(new FormError($error));
                 unset($errors[$field]);
             }
         }
     }
 }
 /**
  * Process form
  *
  * @param CalendarEvent $entity
  *
  * @return bool True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // TODO: should be refactored after finishing BAP-8722
             // Contexts handling should be moved to common for activities form handler
             if ($this->form->has('contexts')) {
                 $contexts = $this->form->get('contexts')->getData();
                 $this->activityManager->setActivityTargets($entity, $contexts);
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
Esempio n. 10
0
 /**
  * @param GridView $entity
  *
  * @return boolean
  */
 public function process(GridView $entity)
 {
     $entity->setFiltersData();
     $entity->setSortersData();
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $data = $this->request->request->all();
         unset($data['name']);
         if ($this->form->has('owner')) {
             $data['owner'] = $entity->getOwner();
         }
         $this->form->submit($data);
         if ($this->form->isValid()) {
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 /**
  * @param FormInterface $form
  *
  * @return mixed
  */
 private static function password(FormInterface $form)
 {
     if ($form->has('credentials_group')) {
         $credentialsGroup = $form->get('credentials_group');
         if ($credentialsGroup->has('plainPassword')) {
             $plainPasswordElement = $credentialsGroup->get('plainPassword');
             if (!empty($plainPasswordElement->getData())) {
                 return 'CsrPassword';
             }
         }
     }
 }
Esempio n. 12
0
 /**
  * Process form
  *
  * @param  CalendarEvent $entity
  * @return bool  True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $originalChildren = new ArrayCollection();
         foreach ($entity->getChildEvents() as $childEvent) {
             $originalChildren->add($childEvent);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // TODO: should be refactored after finishing BAP-8722
             // Contexts handling should be moved to common for activities form handler
             if ($this->form->has('contexts')) {
                 $contexts = $this->form->get('contexts')->getData();
                 $this->activityManager->setActivityTargets($entity, $contexts);
             }
             $this->onSuccess($entity, $originalChildren, $this->form->get('notifyInvitedUsers')->getData());
             return true;
         }
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 public function buildValuesForm(FormInterface $form, FamilyInterface $family, DataInterface $data = null, array $options = [])
 {
     foreach ($family->getAttributes() as $attribute) {
         if ($attribute->getGroup()) {
             $groupName = $attribute->getGroup();
             if (!$form->has($groupName)) {
                 $form->add($groupName, 'form', ['inherit_data' => true]);
             }
             $this->addAttribute($form->get($groupName), $attribute, $family, $data, $options);
         } else {
             $this->addAttribute($form, $attribute, $family, $data, $options);
         }
     }
 }
Esempio n. 14
0
 /**
  * Process form
  *
  * @param  CalendarEvent $entity
  *
  * @throws \LogicException
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $originalChildren = new ArrayCollection();
         foreach ($entity->getChildEvents() as $childEvent) {
             $originalChildren->add($childEvent);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $this->ensureCalendarSet($entity);
             // TODO: should be refactored after finishing BAP-8722
             // Contexts handling should be moved to common for activities form handler
             if ($this->form->has('contexts')) {
                 $contexts = $this->form->get('contexts')->getData();
                 $this->activityManager->setActivityTargets($entity, $contexts);
             }
             $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
             if ($targetEntityClass) {
                 $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
                 $targetEntity = $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId);
                 $action = $this->entityRoutingHelper->getAction($this->request);
                 if ($action === 'activity') {
                     $this->activityManager->addActivityTarget($entity, $targetEntity);
                 }
                 if ($action === 'assign' && $targetEntity instanceof User && $targetEntityId !== $this->securityFacade->getLoggedUserId()) {
                     /** @var Calendar $defaultCalendar */
                     $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($targetEntity->getId(), $targetEntity->getOrganization()->getId());
                     $entity->setCalendar($defaultCalendar);
                 }
             }
             $this->onSuccess($entity, $originalChildren, $this->form->get('notifyInvitedUsers')->getData());
             return true;
         }
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 public function chooseGroups(FormInterface $form)
 {
     // All other fields are validated through the Default validation group
     $validation_groups = array('Default');
     if ($form->has('phone') && $form->has('mobile')) {
         $phoneData = $form->get('phone')->getData();
         $mobileData = $form->get('mobile')->getData();
         // If both or neither phone and mobile fields are given,
         // validate both fields
         if (empty($phoneData) && empty($mobileData)) {
             $validation_groups[] = 'phone';
             $validation_groups[] = 'mobile';
         } else {
             // If only phone field alone is given, validate, but
             // not mobile. Only 1 is required.
             if (!empty($phoneData)) {
                 $validation_groups[] = 'phone';
             }
             // If only mobile field alone is given, validate, but
             // not phone. Only 1 is required.
             if (!empty($mobileData)) {
                 $validation_groups[] = 'mobile';
             }
         }
     }
     if ($form->has('bankAccount') && $form->get('bankAccount')) {
         $sortCodeData = $form->get('bankAccount')->get('accountSortcode');
         $accountNumberData = $form->get('bankAccount')->get('accountNumber');
         // If either the sort code or account no are given,
         // validate both fields
         if (!empty($sortCodeData) || !empty($accountNumberData)) {
             $validation_groups[] = 'bankaccount';
         }
     }
     return $validation_groups;
 }
 /**
  * @param FieldTypeInterface        $data
  * @param string                    $type
  * @param FormInterface             $form
  */
 protected function addDefaultValueField(FieldTypeInterface $data, $type, FormInterface $form)
 {
     if ($form->has('default_value')) {
         $form->remove('default_value');
     }
     if (is_null($type) || !array_key_exists($type, $this->options)) {
         return;
     }
     if ($data->getType() !== $type) {
         $data->setDefaultValue(null);
     }
     if (isset($this->options[$type]['default_value'])) {
         $defaultValueField = $this->options[$type]['default_value'];
         $defaultOption = isset($defaultValueField['options']) ? $defaultValueField['options'] : array();
         $form->add('default_value', $defaultValueField['type'], $defaultOption);
     }
 }
 public function finishView(FormView $view, FormInterface $form, array $options)
 {
     if ($options['honeypot'] && !$view->parent && $options['compound']) {
         if ($form->has($options['honeypot_field'])) {
             throw new \RuntimeException(sprintf('Honeypot field "%s" is already in use.', $options['honeypot_field']));
         }
         $formOptions = array('mapped' => false, 'label' => false, 'required' => false);
         if ($options['honeypot_use_class']) {
             $formOptions['attr'] = array('class' => $options['honeypot_hide_class']);
         } else {
             $formOptions['attr'] = array('style' => 'display:none');
         }
         $factory = $form->getConfig()->getAttribute('honeypot_factory');
         $honeypotForm = $factory->createNamed($options['honeypot_field'], 'text', null, $formOptions);
         $view->children[$options['honeypot_field']] = $honeypotForm->createView($view);
     }
 }
Esempio n. 18
0
 /**
  * Process form
  *
  * @param  Call $entity
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(Call $entity)
 {
     $targetEntityClass = $this->request->get('entityClass');
     $targetEntityId = $this->request->get('entityId');
     $options = [];
     if ($targetEntityClass && $this->request->getMethod() === 'GET') {
         $targetEntity = $this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId);
         if (!$entity->getId()) {
             $phone = $this->request->query->get('phone');
             if (!$phone) {
                 $phone = $this->phoneProvider->getPhoneNumber($targetEntity);
             }
             $entity->setPhoneNumber($phone);
         }
         $options = ['phone_suggestions' => array_unique(array_map(function ($item) {
             return $item[0];
         }, $this->phoneProvider->getPhoneNumbers($targetEntity)))];
     }
     $this->form = $this->formFactory->createNamed($this->formName, $this->formType, $entity, $options);
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // TODO: should be refactored after finishing BAP-8722
             // Contexts handling should be moved to common for activities form handler
             if ($this->form->has('contexts')) {
                 $contexts = $this->form->get('contexts')->getData();
                 $this->activityManager->setActivityTargets($entity, $contexts);
             } elseif ($targetEntityClass) {
                 // if we don't have "contexts" form field
                 // we should save association between activity and target manually
                 $targetEntity = $this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId);
                 $this->callActivityManager->addAssociation($entity, $targetEntity);
                 $phones = $this->phoneProvider->getPhoneNumbers($targetEntity);
                 foreach ($phones as $phone) {
                     if ($entity->getPhoneNumber() === $phone[0]) {
                         $this->callActivityManager->addAssociation($entity, $phone[1]);
                     }
                 }
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 protected function disableValidators(array $fields, $validators = null)
 {
     foreach ($fields as $field) {
         if (!$this->form->has($field)) {
             continue;
         }
         $fc_field = $this->fc_form->getFieldByName($field);
         if (!$fc_field instanceof FcField) {
             continue;
         }
         foreach ($fc_field->getConstraints() as $fc_constraint) {
             if (null === $validators || in_array($fc_constraint->getConstraint(), $validators)) {
                 $this->del_groups[] = $fc_constraint->getConstraint() . '_' . $fc_field->getId();
             }
         }
     }
 }
Esempio n. 20
0
 public function createView(FormInterface $form, FormView $view = null)
 {
     if ($view === null) {
         $view = $form->createView();
     }
     foreach ($view->children as $key => $child) {
         if ($form->has($key)) {
             $this->createView($form->get($key), $child);
         }
     }
     $innerType = $form->getConfig()->getType()->getInnerType();
     if ($innerType instanceof AssetsComponentType) {
         if ($innerType->getTheme()) {
             $this->twigRendererEngine->setTheme($view, $innerType->getTheme());
         }
         array_push($this->assetTypes, array('object' => $innerType, 'view' => $view));
     }
     return $view;
 }
 protected function validateTextFields(FormInterface $form, TransferInformation $data)
 {
     $title = $data->getAccountTitle();
     $number = $data->getAccountNumber();
     $financialInstitution = $data->getFinancialInstitution();
     $firmAddress = $data->getFirmAddress();
     if ($form->has('account_title') && (is_null($title) || !is_string($title))) {
         $form->get('account_title')->addError(new FormError('Required.'));
     }
     if ($form->has('account_number') && (is_null($number) || !is_string($number))) {
         $form->get('account_number')->addError(new FormError('Required.'));
     }
     if ($form->has('financial_institution') && (is_null($financialInstitution) || !is_string($financialInstitution))) {
         $form->get('financial_institution')->addError(new FormError('Required.'));
     }
     if ($form->has('firm_address') && (is_null($firmAddress) || !is_string($firmAddress))) {
         $form->get('firm_address')->addError(new FormError('Required.'));
     }
 }
 /**
  * @param FormInterface $form
  * @param mixed $precision
  * @param bool $force
  */
 protected function addQuantity(FormInterface $form, $precision, $force = false)
 {
     if ($force && $form->has('quantity')) {
         $form->remove('quantity');
     }
     $form->add('quantity', 'number', ['label' => 'orob2b.pricing.quantity.label', 'precision' => $precision, 'constraints' => [new NotBlank(), new Range(['min' => 0]), new Decimal()]]);
 }
Esempio n. 23
0
 /**
  * @param TransportInterface $selectedTransport
  * @param FormInterface $form
  */
 protected function addTransportSettingsForm(TransportInterface $selectedTransport, FormInterface $form)
 {
     if ($selectedTransport) {
         $transportSettingsFormType = $selectedTransport->getSettingsFormType();
         if ($transportSettingsFormType) {
             $form->add('transportSettings', $transportSettingsFormType, ['required' => true]);
         } elseif ($form->has('transportSettings')) {
             $form->remove('transportSettings');
         }
     }
 }
Esempio n. 24
0
 /**
  * @param array $requestData
  * @param FormInterface $form
  * @return array
  */
 private function cleanRequestData(array $requestData, FormInterface $form)
 {
     foreach ($requestData as $key => $value) {
         if (!$form->has($key)) {
             unset($requestData[$key]);
         }
     }
     return $requestData;
 }
 protected function validateMaritalStatus(FormInterface $form)
 {
     if ($form->has('marital_status')) {
         $maritalStatus = $form->get('marital_status')->getData();
         if (!in_array($maritalStatus, Profile::getMaritalStatusChoices())) {
             $form->get('marital_status')->addError(new FormError('Required.'));
         }
         if ($maritalStatus == Profile::CLIENT_MARITAL_STATUS_MARRIED) {
             if ($form->has('spouse_first_name')) {
                 $firstName = $form->get('spouse_first_name')->getData();
                 if (is_null($firstName) || !is_string($firstName)) {
                     $form->get('spouse_first_name')->addError(new FormError('Enter first name.'));
                 }
             }
             if ($form->has('spouse_last_name')) {
                 $firstName = $form->get('spouse_last_name')->getData();
                 if (is_null($firstName) || !is_string($firstName)) {
                     $form->get('spouse_last_name')->addError(new FormError('Enter last name.'));
                 }
             }
             if ($form->has('spouse_last_name')) {
                 $minYears = 18;
                 $birthDate = $form->get('spouse_birth_date')->getData();
                 if (!$birthDate) {
                     $form->get('spouse_birth_date')->addError(new FormError('Enter spouse date of birth.'));
                 } else {
                     $nowDate = new \DateTime('now');
                     $interval = $nowDate->diff($birthDate);
                     if ((int) $interval->format('%y%') < $minYears) {
                         $form->get('spouse_birth_date')->addError(new FormError("Your spouse must be at least {$minYears} years old."));
                     }
                 }
             }
         }
     }
 }
 /**
  * Validate form data
  *
  * @param FormInterface $form
  * @param ClientAccount $data
  */
 private function validate(FormInterface $form, ClientAccount $data)
 {
     $group = $form->get('group')->getData();
     if ($data) {
         $data->setClient($this->client);
         if ($group == AccountGroup::GROUP_EMPLOYER_RETIREMENT) {
             $data->setMonthlyDistributions(null);
             $data->setSasCash(null);
             if (floatval($data->getValue()) < 50000) {
                 $form->get('value')->addError(new FormError('Minimum value must be $50,000 for retirement plans.'));
             }
             if ($form->get('plan_provider')->getData()) {
                 $financialInstitution = $data->getFinancialInstitution();
                 $data->setFinancialInstitution($form->get('plan_provider')->getData() . " (" . $financialInstitution . ")");
             }
         }
         if ($this->validateAdditionalFields && $form->has('owners')) {
             if ($data->getTypeName() == 'Joint Account') {
                 $ownerTypes = $form->get('owners')->get('owner_types')->getData();
                 if (!is_array($ownerTypes) || count($ownerTypes) !== 2) {
                     $form->get('owners')->get('owner_types')->addError(new FormError('You should select two owners of the account.'));
                 }
                 if ($form->get('owners')->has('other_contact')) {
                     /** @var ClientAdditionalContact $otherContact */
                     $otherContact = $form->get('owners')->get('other_contact')->getData();
                     if (!$otherContact->getFirstName() || trim($otherContact->getFirstName() == '')) {
                         $form->get('owners')->get('other_contact')->get('first_name')->addError(new FormError('Required.'));
                     }
                     if (!$otherContact->getMiddleName() || trim($otherContact->getMiddleName() == '')) {
                         $form->get('owners')->get('other_contact')->get('middle_name')->addError(new FormError('Required.'));
                     }
                     if (!$otherContact->getLastName() || trim($otherContact->getLastName() == '')) {
                         $form->get('owners')->get('other_contact')->get('last_name')->addError(new FormError('Required.'));
                     }
                     if (!$otherContact->getRelationship() || trim($otherContact->getRelationship() == '')) {
                         $form->get('owners')->get('other_contact')->get('relationship')->addError(new FormError('Required.'));
                     }
                 }
             } elseif ($this->client->isMarried()) {
                 $ownerType = $form->get('owners')->get('owner_types')->getData();
                 $choices = ClientAccountOwner::getOwnerTypeChoices();
                 unset($choices[ClientAccountOwner::OWNER_TYPE_OTHER]);
                 if (!$ownerType || !in_array($ownerType, $choices)) {
                     $form->get('owners')->get('owner_types')->addError(new FormError('Select owner of the account.'));
                 }
             }
         }
     }
 }
Esempio n. 27
0
 /**
  * @{inheritdoc}
  */
 public function handle(FormInterface $form, $attributes = array())
 {
     if (!$form->isValid()) {
         return false;
     }
     $mediaIds = [];
     if ($form->has('files')) {
         $files = $form['files']->getData();
         if (count($files)) {
             $type = $this->formExtension->getType($form->getName());
             $collectionId = $type->getCollectionId();
             $ids = [];
             /** @var UploadedFile $file */
             foreach ($form['files']->getData() as $file) {
                 if ($file instanceof UploadedFile) {
                     $media = $this->mediaManager->save($file, ['collection' => $collectionId, 'locale' => $form->get('locale')->getData(), 'title' => $file->getClientOriginalName()], null);
                     $ids[] = $media->getId();
                 }
             }
             $mediaIds['files'] = $ids;
         }
     }
     $attributes['form'] = $form;
     $this->saveForm($form, $attributes, $mediaIds);
     $type = $this->formExtension->getType($form->getName());
     if ($type instanceof TypeInterface) {
         $this->sendMails($type, $attributes, $form);
     }
     return true;
 }
Esempio n. 28
0
 /**
  * Adds user default owner field to form.
  *
  * @param FormInterface $form
  */
 protected function addBusinessUnitField(FormInterface $form)
 {
     if ($form->has('defaultUserOwner')) {
         $form->remove('defaultUserOwner');
     }
     if (!$form->has('defaultBusinessUnitOwner')) {
         $form->add('defaultBusinessUnitOwner', 'oro_business_unit_select', ['required' => true, 'label' => 'oro.integration.integration.default_business_unit_owner.label', 'tooltip' => 'oro.integration.integration.default_business_unit_owner.description', 'constraints' => [new NotNull()]]);
     }
 }
 private function validateOwnerInformation(FormInterface $form, $data)
 {
     if ($form->has('first_name') && !$data->getFirstName()) {
         $form->get('first_name')->addError(new FormError('Required.'));
     }
     if ($form->has('middle_name') && !preg_match('/[A-Za-z]/', $data->getMiddleName())) {
         $form->get('middle_name')->addError(new FormError('Enter least 1 letter.'));
     }
     if ($form->has('last_name') && !$data->getLastName()) {
         $form->get('last_name')->addError(new FormError('Required.'));
     }
     if ($form->has('street') && !$data->getStreet()) {
         $form->get('street')->addError(new FormError('Required.'));
     }
     if ($form->has('city') && !$data->getCity()) {
         $form->get('city')->addError(new FormError('Required.'));
     }
     if ($form->has('state') && !$data->getState()) {
         $form->get('state')->addError(new FormError('Required.'));
     }
     if ($form->has('estimated_income_tax') && !$data->getEstimatedIncomeTax()) {
         $form->get('estimated_income_tax')->addError(new FormError('Required.'));
     }
     // Choices validation
     if ($form->has('marital_status') && !in_array($data->getMaritalStatus(), Profile::getMaritalStatusChoices())) {
         $form->get('marital_status')->addError(new FormError('Required.'));
     }
     if ($form->has('annual_income') && !in_array($data->getAnnualIncome(), Profile::getAnnualIncomeChoices())) {
         $form->get('annual_income')->addError(new FormError('Required.'));
     }
     if ($form->has('liquid_net_worth') && !in_array($data->getLiquidNetWorth(), array_keys(Profile::getLiquidNetWorthChoices()))) {
         $form->get('liquid_net_worth')->addError(new FormError('Required.'));
     }
     if ($form->has('employment_type') && !in_array($data->getEmploymentType(), array_keys(Profile::getEmploymentTypeChoices()))) {
         $form->get('employment_type')->addError(new FormError('Required.'));
     }
     if ($form->has('birth_date')) {
         $birthDateData = $form->get('birth_date')->getData();
         if ($birthDateData && $birthDateData instanceof \DateTime) {
             $year = (int) $birthDateData->format('Y');
             if ($year < 1900) {
                 $form->get('birth_date')->addError(new FormError('year must start with 19 or 20 e.g. 1980'));
             }
         } else {
             $form->get('birth_date')->addError(new FormError('date format must be MM-DD-YYYY'));
         }
     }
 }
Esempio n. 30
0
 /**
  * {@inheritdoc}
  */
 public function mapViolation(ConstraintViolation $violation, FormInterface $form, $allowNonSynchronized = false)
 {
     $this->allowNonSynchronized = $allowNonSynchronized;
     $violationPath = null;
     $relativePath = null;
     $match = false;
     // Don't create a ViolationPath instance for empty property paths
     if (strlen($violation->getPropertyPath()) > 0) {
         $violationPath = new ViolationPath($violation->getPropertyPath());
         $relativePath = $this->reconstructPath($violationPath, $form);
     }
     // This case happens if the violation path is empty and thus
     // the violation should be mapped to the root form
     if (null === $violationPath) {
         $this->scope = $form;
     }
     // In general, mapping happens from the root form to the leaf forms
     // First, the rules of the root form are applied to determine
     // the subsequent descendant. The rules of this descendant are then
     // applied to find the next and so on, until we have found the
     // most specific form that matches the violation.
     // If any of the forms found in this process is not synchronized,
     // mapping is aborted. Non-synchronized forms could not reverse
     // transform the value entered by the user, thus any further violations
     // caused by the (invalid) reverse transformed value should be
     // ignored.
     if (null !== $relativePath) {
         // Set the scope to the root of the relative path
         // This root will usually be $form. If the path contains
         // an unmapped form though, the last unmapped form found
         // will be the root of the path.
         $this->setScope($relativePath->getRoot());
         $it = new PropertyPathIterator($relativePath);
         while ($this->isValidScope() && null !== ($child = $this->matchChild($it))) {
             $this->setScope($child);
             $it->next();
             $match = true;
         }
     }
     // This case happens if an error happened in the data under a
     // virtual form that does not match any of the children of
     // the virtual form.
     if (null !== $violationPath && !$match) {
         // If we could not map the error to anything more specific
         // than the root element, map it to the innermost directly
         // mapped form of the violation path
         // e.g. "children[foo].children[bar].data.baz"
         // Here the innermost directly mapped child is "bar"
         $it = new ViolationPathIterator($violationPath);
         // The overhead of setScope() is not needed anymore here
         $this->scope = $form;
         while ($this->isValidScope() && $it->valid() && $it->mapsForm()) {
             if (!$this->scope->has($it->current())) {
                 // Break if we find a reference to a non-existing child
                 break;
             }
             $this->scope = $this->scope->get($it->current());
             $it->next();
         }
     }
     // Follow dot rules until we have the final target
     $mapping = $this->scope->getConfig()->getOption('error_mapping');
     while ($this->isValidScope() && isset($mapping['.'])) {
         $dotRule = new MappingRule($this->scope, '.', $mapping['.']);
         $this->scope = $dotRule->getTarget();
         $mapping = $this->scope->getConfig()->getOption('error_mapping');
     }
     // Only add the error if the form is synchronized
     if ($this->isValidScope()) {
         $this->scope->addError(new FormError($violation->getMessageTemplate(), $violation->getMessageParameters(), $violation->getMessagePluralization()));
     }
 }