@param FormInterface $form

@return Question
428135
public function transform(FormInterface $form)
    {
        return new Question($this->questionFrom($form), $this->defaultValueFrom($form));
    }
216185
public function form($form = null)
    {
        if (func_num_args() === 1) {
            $form = $form ?: [];
            $this->_form = $form;
            $this->set($form);
            return $this;
        }
        return $this->_form;
    }
1023897
public function createForm(FormInterface $form, PostInterface $post)
    {
        return $this->formFactory->create(PostType::class, $post, ['form_id' => $form->getId()]);
    }
687001
public function handleRequest(FormInterface $form, $request = null)
    {
        if (null !== $request) {
            throw new UnexpectedTypeException($request, 'null');
        }

        $name = $form->getName();
        $method = $form->getConfig()->getMethod();

        if ($method !== self::getRequestMethod()) {
            return;
        }

        // For request methods that must not have a request body we fetch data
        // from the query string. Otherwise we look for data in the request body.
        if ('GET' === $method || 'HEAD' === $method || 'TRACE' === $method) {
            if ('' === $name) {
                $data = $_GET;
            } else {
                // Don't submit GET requests if the form's name does not exist
                // in the request
                if (!isset($_GET[$name])) {
                    return;
                }

                $data = $_GET[$name];
            }
        } else {
            // Mark the form with an error if the uploaded size was too large
            // This is done here and not in FormValidator because $_POST is
            // empty when that error occurs. Hence the form is never submitted.
            if ($this->serverParams->hasPostMaxSizeBeenExceeded()) {
                // Submit the form, but don't clear the default values
                $form->submit(null, false);

                $form->addError(new FormError(
                    $form->getConfig()->getOption('upload_max_size_message')(),
                    null,
                    ['{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()]
                ));

                return;
            }

            $fixedFiles = [];
            foreach ($_FILES as $fileKey => $file) {
                $fixedFiles[$fileKey] = self::stripEmptyFiles(self::fixPhpFilesArray($file));
            }

            if ('' === $name) {
                $params = $_POST;
                $files = $fixedFiles;
            } elseif (\array_key_exists($name, $_POST) || \array_key_exists($name, $fixedFiles)) {
                $default = $form->getConfig()->getCompound() ? [] : null;
                $params = \array_key_exists($name, $_POST) ? $_POST[$name] : $default;
                $files = \array_key_exists($name, $fixedFiles) ? $fixedFiles[$name] : $default;
            } else {
                // Don't submit the form if it is not present in the request
                return;
            }

            if (\is_array($params) && \is_array($files)) {
                $data = array_replace_recursive($params, $files);
            } else {
                $data = $params ?: $files;
            }
        }

        // Don't auto-submit the form unless at least one field is present.
        if ('' === $name && \count(array_intersect_key($data, $form->all())) <= 0) {
            return;
        }

        if (\is_array($data) && \array_key_exists('_method', $data) && $method === $data['_method'] && !$form->has('_method')) {
            unset($data['_method']);
        }

        $form->submit($data, 'PATCH' !== $method);
    }
236280
public function render(FormInterface $form, $renderMode = null)
    {
        if (method_exists($form, 'prepare')) {
            $form->prepare();
        }

        $fieldsetHelper = $this->getFieldsetHelper();
        if (method_exists($fieldsetHelper, 'setForm')) {
            $fieldsetHelper->setForm($form);
        }

        if (null === $renderMode) {
            $renderMode = $form->getOption('render_mode');
        }

        $rollbackRenderMode = null;
        if ($renderMode && $fieldsetHelper instanceof FormCollection) {
            $elementHelper = $this->view->plugin($fieldsetHelper->getDefaultElementHelper());
            if ($elementHelper instanceof FormRow) {
                $rollbackRenderMode = $elementHelper->getRenderMode();
                if ($rollbackRenderMode !== $renderMode) {
                    $elementHelper->setRenderMode($renderMode);
                }
            }
        }

        $formMessagesHelper = $this->getFormMessagesHelper();

        $markup = $this->openTag($form)
            . $formMessagesHelper($form)
            . $fieldsetHelper($form, false, false)
            . $this->closeTag();

        if ($rollbackRenderMode) {
            $elementHelper->setRenderMode($rollbackRenderMode);
        }

        return $markup;
    }
882934
public static function label(FormInterface $form)
    {
        $label = $form->getConfig()->getOption('label');

        if (!$label) {
            $label = self::humanize($form->getName());
        }

        return $label;
    }
390336
public function normalize(FormInterface $form)
    {
        $allFields = $form->all();
        if (!empty($allFields)) {
            $result = array();
            $result[$form->getName()] = array();
            foreach ($allFields as $name => $child) {
                $result[$form->getName()][$name] = $this->normalize($child);
            }

            $view = $form->createView();
            if (isset($view['_token'])) {
                $result[$form->getName()]['_token'] = array(
                    'name' => sprintf('%s[%s]', $form->getName(), '_token'),
                    'type' => 'hidden',
                    'required' => true,
                    'data' => $view['_token']->vars['value'],
                );
            }

            return $result;
        }

        $view = $form->createView();
        $flatten = array(
            'name' => $view->vars['full_name'],
            'type' => $view->vars['block_prefixes'][1],
            'required' => array_key_exists('required', $view->vars) ? $view->vars['required'] : false,
            'data' => $form->getData(),
        );

        if (array_key_exists('storage', $view->vars['attr']) && array_key_exists('route', $view->vars['attr']['storage'])) {
            if (array_key_exists('parameters', $view->vars['attr']['storage'])) {
                $flatten['storage'] = $this->router->generate($view->vars['attr']['storage']['route'], $view->vars['attr']['storage']['parameters']);
            } else {
                $flatten['storage'] = $this->router->generate($view->vars['attr']['storage']['route']);
            }
        }

        return $flatten;
    }
1278032
private function resolveDataSource(FormInterface $form)
    {
        if ($form->isRoot()) {
            // Nothing to do if root
            $dataForm = $form->getData();
        } else {
            $dataForm = $form;
            while ($dataForm->getConfig()->getDataClass() === null) {
                $dataForm = $form->getParent();
            }
        }

        $data = $dataForm->getData();
        return array(
            $data,
            $data === null ? $dataForm->getConfig()->getDataClass() : get_class($data)
        );
    }
1200849
private function handleAll(FormInterface $form)
    {
        $config = $form->get('value')->getConfig();
        $choiceValue = $config->getOption('choice_value');
        $choices = iterator_to_array($config->getOption('grid')->getDataSource(['all' => true]));

        $this->buildForm($form, $choices);

        return array_map(function ($choice) use ($choiceValue) {
            return call_user_func($choiceValue, $choice);
        }, $choices);
    }
319731
private function handlePostReset(Request $request, FormInterface $form)
    {
        $event = new AccessControlEvent($request);
        $username = $form->get('username')->getData();

        // Send a password request mail, if username exists.
        if ($username === null || $username === '') {
            $this->flashes()->error(Trans::__('general.phrase.please-provide-username'));
        } else {
            $this->password()->resetPasswordRequest($username, $request->getClientIp(), $event);
            $response = $this->redirectToRoute('login');
            $response->setVary('Cookies', false)->setMaxAge(0)->setPrivate();

            return $response;
        }

        return null;
    }
895384
private function addContentFieldset(FormInterface $form)
    {
        $contentData = $form->addChild($this->getElement('nested_fieldset', [
            'name'  => 'content_data',
            'label' => 'common.fieldset.description',
        ]));
        
        $languageData = $contentData->addChild($this->getElement('language_fieldset', [
            'name'        => 'translations',
            'label'       => 'common.fieldset.translations',
            'transformer' => $this->getRepositoryTransformer('translation', $this->get('page.repository')),
        ]));
        
        $languageData->addChild($this->getElement('rich_text_editor', [
            'name'  => 'content',
            'label' => 'common.label.description',
        ]));
    }
1044075
public function transform(FormInterface $form)
    {
        $formView = $form->createView();

        $question = new AlwaysReturnKeyOfChoiceQuestion($this->questionFrom($form), $formView->vars['choices'], $this->defaultValueFrom($form));

        if ($form->getConfig()->getOption('multiple')) {
            $question->setMultiselect(true);
        }

        return $question;
    }
2569
protected function addLabel(FormInterface $form, array $schema)
    {
        $translationDomain = $form->getConfig()->getOption('translation_domain');
        if ($label = $form->getConfig()->getOption('label')) {
            $schema['title'] = $this->translator->trans($label, [], $translationDomain);
        } else {
            $schema['title'] = $this->translator->trans($form->getName(), [], $translationDomain);
        }

        return $schema;
    }
611760
private function getAdultForm(array $form, FormStateInterface $form_state) {
    // Get steps for the form.
    $step = $form_state->getValue('step');
    if ($trigger = $form_state->getTriggeringElement()) {
      switch ($trigger['#name']) {
        case 'location':
          $step = 3;
          $this->clearForm(['program', 'category', 'rate', 'session'], $form_state);
          break;

        case 'category':
          $this->clearForm(['program', 'rate', 'session'], $form_state);
          $step = 4;
          break;

        case 'program':
          $this->clearForm(['rate', 'session'], $form_state);
          $step = 5;
          break;

        case 'session':
          $step = 6;
          break;
      }
      $form_state->setValue('step', $step);
    }

    // Locations.
    if ($form_state->getValue('step') >= 2) {
      $locations = $this->storage->getLocations();
      $options = array_filter($locations, [$this, 'filterLocations'], ARRAY_FILTER_USE_BOTH);
      if (empty($options)) {
        // Use all locations if user hasn't provided any filters.
        $options = $locations;
      }

      if (empty($options)) {
        return $this->noResults($form);
      }

      $form['location'] = [
        '#type' => 'radios',
        '#title' => $this->t('Location'),
        '#options' => $options,
        '#ajax' => $this->getAjaxDefaults(),
      ];
    }

    // Categories.
    if ($form_state->getValue('step') >= 3) {
      $categories = $this->storage->getCategoriesByBranch($form_state->getValue('location'));
      $items = array_filter($categories, [$this, 'filterCategories'], ARRAY_FILTER_USE_BOTH);
      if (empty($items)) {
        $items = $categories;
      }

      if (empty($categories)) {
        return $this->noResults($form);
      }

      $categories = [];
      foreach ($items as $item_id => $item_title) {
        $categories[$item_id] = $item_title;
      }

      $form['category'] = [
        '#type' => 'radios',
        '#title' => $this->t('Category'),
        '#options' => $categories,
        '#ajax' => $this->getAjaxDefaults(),
      ];
    }

    // Programs.
    if ($form_state->getValue('step') >= 4) {
      $items = $this->storage->getProgramsByBranchAndCategory($form_state->getValue('location'), $form_state->getValue('category'));
      if (empty($items)) {
        return $this->noResults($form);
      }

      $programs = [];
      foreach ($items as $item) {
        $programs[$item->id] = $item->name;
      }

      $form['program'] = [
        '#type' => 'radios',
        '#title' => $this->t('Program'),
        '#options' => $programs,
        '#ajax' => $this->getAjaxDefaults(),
      ];
    }

    if ($form_state->getValue('step') >= 5) {
      $items = $this->storage->getSessionsByProgramAndLocation($form_state->getValue('program'), $form_state->getValue('location'));
      if (empty($items)) {
        return $this->noResults($form);
      }

      $sessions = [];
      foreach ($items as $item) {
        $sessions[$item->id] = $item->name;
      }

      $form['session'] = [
        '#type' => 'radios',
        '#title' => $this->t('Session'),
        '#options' => $sessions,
        '#ajax' => $this->getAjaxDefaults(),
      ];
    }

    if ($form_state->getValue('step') >= 6) {
      $uri = $this->storage->getRegistrationLink($form_state->getValue('program'), $form_state->getValue('session'));
      $url = Url::fromUri($uri);
      $link = Link::fromTextAndUrl($this->t('link'), $url);

      $form['link'] = [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#attributes' => [
          'class' => 'result',
        ],
        '#value' => $this->t('Congrats! Here is your program registration %link!', ['%link' => $link->toString()]),
      ];
    }

    return $form;
  }
46875
private function getErrorResponse(FormInterface $form)
    {
        $errors = $form->getErrors();
        $errorCollection = [];

        foreach ($errors as $error) {
            $errorCollection[] = $error->getMessage();
        }

        return new JsonResponse([
            'messages' => $errorCollection,
        ], 400);
    }
847168
public static function getValidationGroups(FormInterface $form)
    {
        $cfg = $form->getConfig();

        if ($cfg->hasOption('jquery_validation_groups')) {
            $groups = $cfg->getOption('jquery_validation_groups');
        } else {
            $groups = $cfg->getOption('validation_groups');
        }

        # Is the default validation group used
        if ($groups === null) {
            return array(Constraint::DEFAULT_GROUP);
        }

        # Is the validation suppressed
        if ($groups === false) {
            return array();
        }

        # Is a unsupported group used
        if (!is_string($groups) && is_callable($groups)) {
            throw new UnsupportedException('Callable validation_groups are not supported. Disable jquery_validation or set jquery_validation_groups');
        }

        return (array) $groups;
    }
433175
protected function getErrorsFromForm(FormInterface $form)
    {
        $errors = [];
        /** @var FormError $error */

        if($form->getErrors()->count() === 0 && $form->isRoot() && !$form->isValid()){
            $errors["_self"] = "Empty post data";
        }

        foreach ($form->getErrors() as $error) {
            $key = $error->getOrigin()->getName();
            $errors[($form->isRoot()) ? "_self" : $key] = $error->getMessage();
        }

        foreach ($form->all() as $childForm) {
            if ($childForm instanceof FormInterface) {
                if ($childErrors = $this->getErrorsFromForm($childForm)) {
                    unset($errors["_self"]);
                    $errors = array_merge_recursive($errors, $childErrors);
                }
            }
        }

        return $errors;
    }