buildForm

@author Tom Haskins-Vaughan <tom@harvestcloud.com>
@since  2012-10-25
545511
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('day_of_week_numbers', 'choice', array(
                'choices'   => DayOfWeek::getChoices(),
                'multiple'  => true,
                'expanded'  => true,
                'label'     => 'Days of Week',
            ))
            ->add('start_time', 'choice', array(
                'choices'   => WindowMaker::getStartTimeChoices(),
            ))
            ->add('end_time', 'choice', array(
                'choices'   => WindowMaker::getEndTimeChoices(),
            ))
            ->add('delivery_type', 'choice', array(
                'choices' => array(
                  HubWindow::DELIVERY_TYPE_PICKUP   => 'Pickup',
                  HubWindow::DELIVERY_TYPE_DELIVERY => 'Delivery',
                ),
                'multiple'  => false,
                'expanded'  => true,
            ))
        ;
    }
123657
public function build()
	{
		$this->setLayout( 'locales/index.tpl' );
		$this->addModule( 'head', 'SharedHead' );
		$this->addModule( 'footer', 'SharedFooter' );
		$this->addModule( 'system_messages', 'SharedSystemMessages' );
		
		$params = $this->getParams();
		$action = \Sifo\Router::getReversalRoute( $params['path_parts'][0] );

		$params = $this->getParams();

		
		if ( $params['params'] !== false && in_array('saved-true', $params["params"]))
		{
			\Sifo\FlashMessages::set( 'File Saved OK.', \Sifo\FlashMessages::MSG_OK );
		}
		if ( $params['params'] !== false && in_array('created-true', $params["params"]))
		{
			\Sifo\FlashMessages::set( 'File Created OK.', \Sifo\FlashMessages::MSG_OK );
		}


		if ($this->getParsedParam( 'instance' ) !== false)
		{
			$this->assign('current_instance', $this->getParsedParam( 'instance' ));
			$this->assign('languages', $this->getLanguagesInstance($this->getParsedParam( 'instance' )));
			//var_dump($this->getLanguagesInstance($this->getParsedParam( 'instance' )));
		}
		if ($this->getParsedParam( 'language' ) !== false)
		{
			$this->assign('current_language', $this->getParsedParam( 'language' ));
			$temp = explode("_", $this->getParsedParam( 'language' ));
			if (  is_array( $temp))
			{
				$this->assign('lang', $temp[1]);
			}
		}

		$instances = $this->getInstances();
		$this->assign('instances', $instances);
		// For url with params generation:
		$this->assign( 'params', $this->getParam( 'parsed_params' ) );
		$this->assign( 'params_definition', $this->getParamsDefinition() );
	}
510550
public function buildDeleterBehaviour()
    {
        return '$(document).ready(function() {
                    $("#' . $this->buildDeleteButtonId() . '").click(function() {
                        var $form = $(this).parents("form"),
                            $fileHandling = $form.find("[name=\'' . $this->getName() . '\']");
                        if(!$fileHandling.length) {
                            $fileHandling = $("<input>", { name: "' . $this->getName() . '", type: "hidden" });
                            $form.prepend($fileHandling); 
                        }
                        $fileHandling.val("{\\"action\\":\\"delete\\"}");
                        $("#' . $this->buildWidgetContainerId() . '").empty();
                        ' . $this->buildUploaderBehaviour(true) . '
                    });
                });';
    }
244458
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            '__tab_main',
            TabType::class,
            [
                'label' => 'admin.user.tab.main.label',
                'inherit_data' => true,
            ]
        );
        /** @var FormBuilderInterface $mainTab */
        $mainTab = $builder->get('__tab_main');
        $mainTab
            ->add(
                'username',
                TextType::class,
                [
                    'label' => 'admin.user.form.username.label',
                ]
            )
            ->add(
                'email',
                EmailType::class,
                [
                    'label' => 'admin.user.form.email.label',
                ]
            );

        if ($this->getUser() && $this->authorizationChecker->isGranted('ROLE_ADMIN', $this->getUser())) {
            $mainTab
                ->add(
                    'enabled',
                    SwitchType::class,
                    [
                        'label' => 'admin.user.form.enabled.label',
                    ]
                )
                ->add(
                    'rawRoles',
                    RoleHierarchyType::class,
                    [
                        'label' => 'admin.user.form.roles.label',
                    ]
                )
                ->add(
                    'familyPermissions',
                    BootstrapCollectionType::class,
                    [
                        'label' => 'admin.user.form.familyPermissions.label',
                        'entry_type' => FamilyPermissionType::class,
                        'entry_options' => [],
                        'allow_add' => true,
                        'allow_delete' => true,
                        'required' => false,
                        'sortable' => false,
                        'by_reference' => false,
                    ]
                );

            $builder->add(
                '__tab_groups',
                TabType::class,
                [
                    'label' => 'admin.user.tab.groups.label',
                    'inherit_data' => true,
                ]
            );
            /** @var FormBuilderInterface $groupsTab */
            $groupsTab = $builder->get('__tab_groups');
            $groupsTab
                ->add(
                    'groups',
                    EntityType::class,
                    [
                        'label' => 'admin.user.form.groups.label',
                        'class' => Group::class,
                        'expanded' => true,
                        'multiple' => true,
                    ]
                );
        }

        $builder->add(
            '__tab_info',
            TabType::class,
            [
                'label' => 'admin.user.tab.info.label',
                'inherit_data' => true,
            ]
        );
        // Add EAV data edition
        $this->buildDataForm($builder);

        $builder->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) {
                /** @var User $user */
                $user = $event->getData();
                if ($user) {
                    $user->setUpdatedAt(new \DateTime());
                }
            }
        );
    }
580131
public function build( Form $form, $offset, $length, $params = array() ) {

        $data = $form->getData();

        if ($length == 0)
            return array( 'query' => $data['term'], 'sort_by' => array( 'name' => 'asc' ), 'offset' => $offset );
        else
            return array( 'query' => $data['term'], 'sort_by' => array( 'name' => 'asc' ), 'offset' => $offset, 'limit' => $length );
    }
654170
protected function buildForm()
    {
        $this->form = Yii::createObject(array_merge([
            'scenario' => $this->scenario,
            'parent_id' => $this->parent_id,
            'parentTariff' => $this->parentTariff,
            'tariff' => $this->tariff,
        ], $this->getFormOptions()));
    }
1053790
public function createForm($form) {
        $params = array();
        foreach ($form as $key => $value) {
            foreach ($value as $k => $v) {
                if ($key == "properties") {
                    $params["{$key}[{$k}]"] = $v;
                } else {
                    foreach ($v as $a => $b) {
                        $params["{$key}[{$k}][{$a}]"] = $b;
                    }
                }
            }
        }
        return $this->_executePostRequest('user/forms', $params);
    }
31018
public function buildForm()
    {

        $this
            ->add('range', 'datepicker',
                [
                    'label'      => trans('expendable::form.date'),
                    'validation' => 'required',
                    'range'      => true
                ])
            ->add('type', 'choice', [
                'choices'    => StaticLabel::typeExport(),
                'validation' => 'required',
                'label'      => trans('expendable::form.type')
            ])
            ->addDefaultActions();
    }
684443
function traitEntity_formBuild() {
        $form_class = $this->getClassForm();
        $form       = new $form_class(static::getEntity());
        $form->setModel($this->model);
        $form->setAction($_SERVER['REQUEST_URI']);
        $form->setAction(\Request::getUri());
        //        dd($form);
        //::factory($this->model)
        //билдим форму, если надо - переопределяем метод "traitEntityFormBuild"
        $this->traitEntity_formAddFields($form);
        $form->addRecursiveFilter('trim');
        //        $form_builder->form->setVendor($this->getVendor())
        //                           ->setEntity($this->getEntity())
        //                           ->setDataId(isset($this->model->id) ? $this->model->id : 0);
        $this->form = $form;
        $this->traitEntity_formBuildAfter();
    }
833913
public function build()
    {
        if (empty($this->form)) {
            Throw new ControlException('Editbox control needs a set FormDesigner or Form object.');
        }

        // Editbox CSS class needed
        $this->panel->html->addCss('editbox');

        // Create panel heading with title
        $heading = $this->panel->createHeading();

        $title = $heading->createTitle();
        $title->setTitle($this->caption);

        if (! empty($this->description)) {
            $title->setDescription($this->description, true);
        }

        $heading->addContent($title);

        // Create panel body

        if ($this->form instanceof FormDesigner) {
            $form_id = $this->form->html->getId();
            $form_action = $this->form->html->getAttribute('action');

            // Ajax form?
            $this->is_ajax = $this->form->getSendMode() == 'ajax' ? true : false;
        }
        else {
            $form_id = $this->form->getId();
            $form_action = $this->form->getAttribute('action');
        }

        // Build form here because it's possible that form id will be autogenerated
        // and we need this id in the next step.
        $body = $this->panel->createBody();
        $body->addContent($this->form);

        // Footer with toolbar

        /* @var $toolbar \Core\Html\Bootstrap\Buttongroups\ButtonToolbar */
        $toolbar = $this->factory->create('Bootstrap\Buttongroups\ButtonToolbar');

        $create_action = function (Action $action, $with_link = false) {

            $text = $action->getText();
            $icon = $action->getIcon();

            if (! empty($icon)) {
                $text = $icon->build() . ' ' . $text;
            }

            if ($with_link) {

                $href = $action->getHref();

                if (! empty($href)) {

                    /* @var $a \Core\Html\Elements\A */
                    $a = $this->factory->create('Elements\A');

                    $a->setHref($href);

                    if ($action->getAjax()) {
                        $a->addData('ajax');
                    }

                    if ($action->getConfirm()) {
                        $a->addData('confirm', $action->getConfirm());
                    }

                    $a->setInner($text);

                    $text = $a->build();
                }
            }
            return $text;
        };

        // Make sure that he buttons have the correct order
        ksort($this->actions);

        foreach ($this->actions as $type => $action) {

            switch ($type) {
                case 0:
                case 1:

                    /* @var $group \Core\Html\Bootstrap\Buttongroups\ButtonGroup */
                    $group = $toolbar->createButtongroup();
                    $group->addCss('btn-group-sm');

                    switch ($type) {
                        case 0:

                            $button = $group->createButton();
                            $button->setFormId($form_id);
                            $button->setFormAction($form_action);
                            $button->isSuccess();

                            if ($this->is_ajax) {
                                $button->addData('ajax');
                            }
                            else {
                                $button->setType('submit');
                            }

                            break;

                        case 1:
                            $group->addCss('pull-right');

                            /* @var $button \Core\Html\Controls\UiButton */
                            $button = $group->createButton('Controls\UiButton');
                            $button->setHref($action->getHref());
                            $button->addCss('btn-danger');

                            if ($this->is_ajax) {
                                $button->addData('ajax');
                            }
                            break;
                    }

                    $button->setInner($create_action($this->actions[$type]));

                    break;

                case 2:
                default:

                    /* @var $group \Core\Html\Bootstrap\Buttongroups\ButtonGroup */
                    $group = $toolbar->createButtongroup();
                    $group->addCss('btn-group-sm pull-right dropup');

                    /* @var $context_menu \Core\Html\Form\Button */
                    $context_menu = $this->factory->create('Bootstrap\Button\Button');
                    $context_menu->addCss('dropdown-toggle');
                    $context_menu->addAria([
                        'haspopup' => "true",
                        'expanded' => "false"
                    ]);
                    $context_menu->addData('toggle', 'dropdown');

                    // Do we have a text to show on actions button?
                    if (! empty($this->context_text)) {
                        $context_menu->addInner($this->context_text . ' ');
                    }

                    $context_menu->addInner('<span class="caret"></span>');

                    $group->setInner($context_menu->build());

                    // Create the actions dropdown menu
                    $dropdown = '<ul class="dropdown-menu">';

                    foreach ($this->actions[$type] as $action) {
                        $dropdown .= '<li>' . $create_action($action, true) . '</li>';
                    }

                    $dropdown .= '</ul>';

                    $group->addInner($dropdown);

                    break;
            }
        }

        $footer = $this->panel->createFooter();
        $footer->addContent($toolbar);

        return $this->panel->build();
    }
32263
public function buildForm()
    {
        $formBuilder = $this
            ->formFactory
            ->createNamedBuilder(null);

        $orderId = $this
            ->paymentBridge
            ->getOrderId();

        $orderCurrency = $this
            ->paymentBridge
            ->getCurrency();

        $this->checkCurrency($orderCurrency);

        /**
         * Creates the success return route, when coming back
         * from PayPal web checkout.
         */
        $successReturnUrl = $this
            ->urlFactory
            ->getSuccessReturnUrlForOrderId($orderId);

        /**
         * Creates the cancel payment route, when cancelling
         * the payment process from PayPal web checkout.
         */
        $cancelReturnUrl = $this
            ->urlFactory
            ->getCancelReturnUrlForOrderId($orderId);

        /**
         * Creates the IPN payment notification route,
         * which is triggered after PayPal processes the
         * payment and returns the validity of the transaction.
         *
         * For forther information
         *
         * https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/
         * https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
         */
        $processUrl = $this
            ->urlFactory
            ->getProcessUrlForOrderId($orderId);

        $formBuilder
            ->setAction($this->urlFactory->getApiEndpoint())
            ->setMethod('POST')
            ->add('business', 'hidden', [
                'data' => $this->business,
            ])
            ->add('return', 'hidden', [
                'data' => $successReturnUrl,
            ])
            ->add('cancel_return', 'hidden', [
                'data' => $cancelReturnUrl,
            ])
            ->add('notify_url', 'hidden', [
                'data' => $processUrl,
            ])
            ->add('currency_code', 'hidden', [
                'data' => $orderCurrency,
            ])
            ->add('env', 'hidden', [
                'data' => '',
            ]);

        /**
         * Create a PayPal cart line for each order line.
         *
         * Project specific PaymentBridgeInterface::getExtraData
         * should return an array of this form
         *
         *   ['items' => [
         *       0 => [ 'item_name' => 'Item 1', 'amount' => 1234, 'quantity' => 2 ],
         *       1 => [ 'item_name' => 'Item 2', 'amount' => 2345, 'quantity' => 1 ],
         *   ]]
         *
         * The 'items' key consists of an array with the basic information
         * of each line of the order. Amount is the price of the product,
         * not the total of the order line
         */
        $cartData = $this->paymentBridge->getExtraData();
        $itemsData = $cartData['items'];
        $iteration = 1;

        foreach ($itemsData as $orderLine) {
            $formBuilder
                ->add('item_name_' . $iteration, 'hidden', [
                    'data' => $orderLine['item_name'],
                ])
                ->add('amount_' . $iteration, 'hidden', [
                    'data' => $orderLine['amount'],
                ])
                ->add('quantity_' . $iteration, 'hidden', [
                    'data' => $orderLine['quantity'],
                ]);
            ++$iteration;
        }

        if (isset($cartData['discount_amount_cart'])) {
            $formBuilder->add('discount_amount_cart', 'hidden', [
                'data' => $cartData['discount_amount_cart'],
            ]);
        }

        return $formBuilder
            ->getForm()
            ->createView();
    }
923307
private function build(): void
    {
        $prefix = "<?xml version='1.0' encoding='UTF-8'?>" . $this->glue() . "<feed xmlns='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'>";
        $suffix = '</feed>';

        $xml = collect($this->filters)->map(function ($items) {
            return $this->buildEntry($items);
        })->implode($this->glue());

        $this->xml = collect([$prefix, $xml, $suffix])->implode($this->glue());

        if ($this->writeFile) {
            $this->filesystem->dumpFile($this->outputFile, $this->xml);
        }
    }
1301056
protected function createComponentAddForm(): Form
	{
		$form = $this->formFactory->create();
		$form->addProtection();

		$form->addText('username', 'cms.user.username')
			->setRequired();
		$form->addText('firstName', 'cms.user.firstName');
		$form->addText('surname', 'cms.user.surname');
		$form->addText('email', 'cms.user.email')
			->setRequired()
			->addRule(Form::EMAIL);
		$form->addPhone('phone', 'cms.user.phone');
		$form->addSelectUntranslated('language', 'cms.user.language', $this->localeService->allowed, 'form.none');

		$form->addMultiSelectUntranslated('roles', 'cms.permissions.roles', $this->orm->aclRoles->fetchPairs($this->user->isAllowed('dockbar.settings.permissions.superadmin', 'view')))
			->setRequired();

		if ($this->configurator->sendNewUserPassword) {
			$form->addCheckbox('generatePassword', 'cms.user.generatePassword')
				->addCondition($form::EQUAL, false)
				->toggle('password')
				->toggle('passwordVerify');
		} else {
			$form->addHidden('generatePassword', false);
		}

		$form->addPassword('password', 'cms.user.newPassword')
			->setOption('id', 'password')
			->addConditionOn($form['generatePassword'], Form::EQUAL, false)
			->setRequired()
			->addRule(Form::MIN_LENGTH, null, $this->minPasswordLength)
			->endCondition();
		$form->addPassword('passwordVerify', 'cms.user.passwordVerify')
			->setOption('id', 'passwordVerify')
			->addConditionOn($form['generatePassword'], Form::EQUAL, false)
			->setRequired()
			->addRule(Form::EQUAL, null, $form['password'])
			->endCondition();

		$form->addSubmit('save', 'form.save');
		$form->addLink('back', 'form.back', $this->getBacklink());

		$form->onSuccess[] = [$this, 'addFormSucceeded'];
		return $form;
	}
294347
public function buildForm()
    {

        $this
            ->add($this->model->getKeyName(), 'hidden')
            ->add('libelle', 'text', [
                'validation' => 'required',
                'label'      => trans('expendable::form.subject')
            ])
            ->add('body_type', 'choice', [
                'choices'     => StaticLabel::bodyType(),
                'empty_value' => '-',
                'validation'  => 'required',
                'label'       => trans('expendable::form.body_type')
            ])
            ->add('action', 'choice', [
                'choices'     => StaticLabel::mailActions(),
                'empty_value' => '-',
                'validation'  => 'required',
                'label'       => trans('expendable::form.action')
            ])
            ->add('cc', 'tag', [
                'label' => trans('expendable::form.cc')
            ])
            ->add('bcc', 'tag', [
                'label' => trans('expendable::form.bcc')
            ])
            ->add('content', 'tinymce', [
                'validation' => 'required',
                'label'      => trans('expendable::form.content')
            ])
            ->add('status', 'choice', [
                'choices'     => StaticLabel::status(),
                'empty_value' => '-',
                'validation'  => 'required',
                'label'       => trans('expendable::form.status')
            ])
            ->addDefaultActions();
    }
1103146
public function build()
    {
        if ($this->isBuild) {
            return;
        }

        $settings = $this->getObject();
        $form     = $this->formManager->get($settings->getForm());

        $this->setLabel(
            $form->getOption('settings_label') ?: sprintf(
                /*@translate*/ 'Customize enabled elements for %s',
                get_class($form)
            )
        );

        $this->add(
            array(
            'type' => 'Checkbox',
            'name' => 'isActive',
            'options' => array(
                'label' => /*@translate*/ 'Activate',
                'long_label' => /*@translate*/ 'Enables the form element customization.',
            ),
            'attributes' => array(
                'class' => 'decfs-active-toggle',
            ),
            )
        );
        $element = new DisableElementsCapableFormSettings('disableElements');
        $element->setForm($form);
        $this->add($element);

        $this->isBuild = true;
    }
956399
public function buildForm(array $form, FormStateInterface $form_state, $token = null)
    {
        if ($token === null) {
            return [];
        }

        /* @var Token $token */
        $token = $this->tokenManager->loadToken($token);
        if ($token === null) {
            drupal_set_message(
                $this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
            return [];
        }

        $currentUser = $this->currentUser();
        $userStorage = $this->entityManager->getStorage('user');

        if ($currentUser->id()) {
            // The existing user is already logged in.
            if ($currentUser->id() == $token->uid) {
                drupal_set_message($this->t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', [
                    '%user' => $currentUser->getAccountName(),
                    '!user_edit' => url('user/password'),
                ]));
            }
            // A different user is already logged in on the computer.
            else {
                /* @var UserInterface $user */
                $tokenUser = $userStorage->load($token->uid);

                drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.', [
                    '%other_user' => $currentUser->getAccountName(),
                    '%resetting_user' => $tokenUser->getAccountName(),
                    '!logout' => url('user/logout'),
                ]), 'warning');
            }

            drupal_goto();
        }
        else {
            /* @var UserInterface $user */
            $user = $userStorage->load($token->uid);

            if ($user->isBlocked() && $user->getLastLoginTime() > 0) {
                drupal_access_denied();
                drupal_exit();
            }

            if ($token->isValid()) {
                $form_state->setTemporaryValue('token', $token);
                $form_state->setTemporaryValue('user', $user);

                $form['#form_horizontal'] = true;

                $form['password'] = [
                    '#type' => 'password_confirm',
                    '#size' => 20,
                    '#required' => true,
                    '#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]),
                ];

                $form['actions'] = [
                    '#type' => 'actions',
                    'submit' => [
                        '#type' => 'submit',
                        '#value' => $this->t('Save my password'),
                    ],
                ];
            }
            else {
                drupal_set_message(
                    $this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
                drupal_goto('user/password');
            }
        }

        return $form;
    }
168142
private function fetchForm() : bool
    {
        // Get the field keys
        $form_key = preg_grep('/^form_' . preg_quote($this->name, '/') . '_[a-f0-9]+$/', array_keys($_SESSION));
        if (empty($form_key)) {
            return false;
        }
        $this->key = array_values($form_key)[0];

        // Save properties
        foreach ($_SESSION[$this->key] as $key => $value) {
            if (substr($key, -2) === '[]') {
                $this->keys[substr($key, 0, -2)] = $value;
            } else {
                $this->keys[$key] = $value;
            }
        }
        return true;
    }