Store form values, form errors and form CSRF tokens
in it's own form session namespace.
@return \MvcCore\Ext\Form|\MvcCore\Ext\Forms\IForm
339911
public function & SaveSession () {
		/** @var $this \MvcCore\Ext\Forms\IForm */
		$session = & $this->getSession();
		$session->errors = $this->errors;
		$session->values = $this->values;
		return $this;
	}
1196346
public function SetUpCsrf () {
		$requestUrl = $this->request->GetBaseUrl() . $this->request->GetPath();
		$randomHash = bin2hex(openssl_random_pseudo_bytes(32));
		$nowTime = (string)time();
		$name = '____'.sha1($this->id . $requestUrl . 'name' . $nowTime . $randomHash);
		$value = sha1($this->id . $requestUrl . 'value' . $nowTime . $randomHash);
		$session = & $this->getSession();
		$session->csrf = [$name, $value];
		return [$name, $value];
	}
627456
protected function registerFormBuilder()
    {
        $this->app->singleton('form', function ($app) {
            $this->loadConfigurationOptions();

            $form = new FormBuilder(
                $app['html'],
                $app['url'],
                $app['session.store']->token(),
                $this->getTheme()
            );

            $form->novalidate(
                $app['config']->get('html.novalidate', false)
            );

            return $form->setSessionStore($app['session.store']);
        });
    }
201889
private function addCsrf()
    {
        if (!$this->getName()) {
            throw new \LogicException("Can't set CSRF token with form name");
        }

        $csrfName = 'CSRF_' . $this->getName();
        $csrfToken = md5((string) mt_rand());
        self::session()->set($csrfName, $csrfToken);
        $this->addFirst(new Hidden('_csrf', $csrfToken));
    }
510198
protected function prepareValuesToSave()
    {
        $values = parent::prepareValuesToSave();
        if ($this->changePassword) {
            $password = null;
            foreach ($this->formProperties as $key => $property) {
                if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && isset($this->formProperties[$key]['formValue'])) {
                    $password = $this->formProperties[$key]['formValue'];
                    break;
                }
            }

            $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($password);
        }

        return $values;
    }
356670
public function Form()
    {
        if ($this->currentRecord) {
            $fields = $this->currentRecord->getFrontEndFields();
            $required = $this->currentRecord->getRequiredFields();
        } else {
            $fields = singleton($this->recordType)->getFrontEndFields();
            $required = singleton($this->recordType)->getFrontEndFields();
        }

        $fields->push(new HiddenField('ID'));
        $form = new Form($this, __function__, $fields, new FieldList(new FormAction('doSave', 'Save')), $required);
        if ($this->currentRecord) {
            $form->loadDataFrom($this->currentRecord);
        }
        return $form;
    }
114472
public function getFormOptions()
    {
        $submit = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t(__CLASS__.'.SUBMITBUTTON', 'Submit');
        $clear = ($this->ClearButtonText) ? $this->ClearButtonText : _t(__CLASS__.'.CLEARBUTTON', 'Clear');

        $options = FieldList::create(
            TextField::create('SubmitButtonText', _t(__CLASS__.'.TEXTONSUBMIT', 'Text on submit button:'), $submit),
            TextField::create('ClearButtonText', _t(__CLASS__.'.TEXTONCLEAR', 'Text on clear button:'), $clear),
            CheckboxField::create('ShowClearButton', _t(__CLASS__.'.SHOWCLEARFORM', 'Show Clear Form Button'), $this->ShowClearButton),
            CheckboxField::create('EnableLiveValidation', _t(__CLASS__.'.ENABLELIVEVALIDATION', 'Enable live validation')),
            CheckboxField::create('DisplayErrorMessagesAtTop', _t(__CLASS__.'.DISPLAYERRORMESSAGESATTOP', 'Display error messages above the form?')),
            CheckboxField::create('DisableCsrfSecurityToken', _t(__CLASS__.'.DISABLECSRFSECURITYTOKEN', 'Disable CSRF Token')),
            CheckboxField::create('DisableAuthenicatedFinishAction', _t(__CLASS__.'.DISABLEAUTHENICATEDFINISHACTION', 'Disable Authentication on finish action'))
        );

        $this->extend('updateFormOptions', $options);

        return $options;
    }
1274761
protected function getFormFields()
    {
        $request = $this->getRequest();
        if ($request->getVar('BackURL')) {
            $backURL = $request->getVar('BackURL');
        } else {
            $backURL = $request->getSession()->get('BackURL');
        }

        $label = Member::singleton()->fieldLabel(Member::config()->get('unique_identifier_field'));
        $fields = FieldList::create(
            HiddenField::create("AuthenticationMethod", null, $this->getAuthenticatorClass(), $this),
            // Regardless of what the unique identifer field is (usually 'Email'), it will be held in the
            // 'Email' value, below:
            // @todo Rename the field to a more generic covering name
            $emailField = TextField::create("Email", $label, null, null, $this),
            PasswordField::create("Password", _t('SilverStripe\\Security\\Member.PASSWORD', 'Password'))
        );
        $emailField->setAttribute('autofocus', 'true');

        if (Security::config()->get('remember_username')) {
            $emailField->setValue($this->getSession()->get('SessionForms.MemberLoginForm.Email'));
        } else {
            // Some browsers won't respect this attribute unless it's added to the form
            $this->setAttribute('autocomplete', 'off');
            $emailField->setAttribute('autocomplete', 'off');
        }
        if (Security::config()->get('autologin_enabled')) {
            $fields->push(
                CheckboxField::create(
                    "Remember",
                    _t('SilverStripe\\Security\\Member.KEEPMESIGNEDIN', "Keep me signed in")
                )->setAttribute(
                    'title',
                    _t(
                        'SilverStripe\\Security\\Member.REMEMBERME',
                        "Remember me next time? (for {count} days on this device)",
                        [ 'count' => RememberLoginHash::config()->uninherited('token_expiry_days') ]
                    )
                )
            );
        }

        if (isset($backURL)) {
            $fields->push(HiddenField::create('BackURL', 'BackURL', $backURL));
        }

        return $fields;
    }
1243946
public function saveConfig()
    {
        Logger::log(t("Guardando configuración"), LOG_INFO);
        /* @var $form \PSFS\base\config\ConfigForm */
        $form = new ConfigForm(Router::getInstance()->getRoute('admin-config'), Config::$required, Config::$optional, Config::getInstance()->dumpConfig());
        $form->build();
        $form->hydrate();
        if ($form->isValid()) {
            $debug = Config::getInstance()->getDebugMode();
            $newDebug = $form->getFieldValue("debug");
            if (Config::save($form->getData(), $form->getExtraData())) {
                Logger::log(t('Configuración guardada correctamente'));
                //Verificamos si tenemos que limpiar la cache del DocumentRoot
                if (boolval($debug) !== boolval($newDebug)) {
                    GeneratorHelper::clearDocumentRoot();
                }
                Security::getInstance()->setFlash("callback_message", t("Configuración actualizada correctamente"));
                Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-config", true));
            } else {
                throw new \HttpException(t('Error al guardar la configuración, prueba a cambiar los permisos'), 403);
            }
        }
        return $this->render('welcome.html.twig', array(
            'text' => t("Bienvenido a PSFS"),
            'config' => $form,
            'typeahead_data' => array_merge(Config::$required, Config::$optional),
        ));
    }
653191
public function form()
    {
        return Administrator::form(function (Form $form) {
            $form->display('id', 'ID');

            $form->text('username', trans('admin.username'))->rules('required');
            $form->text('name', trans('admin.name'))->rules('required');
            $form->image('avatar', trans('admin.avatar'));
            $form->password('password', trans('admin.password'))->rules('required|confirmed');
            $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
                ->default(function ($form) {
                    return $form->model()->password;
                });

            $form->ignore(['password_confirmation']);

            $form->multipleSelect('roles', trans('admin.roles'))->options(Role::all()->pluck('name', 'id'));
            $form->multipleSelect('permissions', trans('admin.permissions'))->options(Permission::all()->pluck('name', 'id'));

            $form->display('created_at', trans('admin.created_at'));
            $form->display('updated_at', trans('admin.updated_at'));

            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $form->password = bcrypt($form->password);
                }
            });
        });
    }
222649
protected function createComponentRenameForm(): Form
	{
		$form = new Form;
		$form->setAjaxRequest();

		$form->addHidden('id');

		$form->addText('name')
			->setAttribute('autofocus', true);

		$form->onSuccess[] = [$this, 'renameFormSucceeded'];

		return $form;
	}
16201
public static function get() : array
  {
    return [
      'csrf_token' => CSRF::generate(),
      'errors' => Variable::has('validation.errors') ? Variable::get('validation.errors') : (new ValidatorFactory())->make([], [])->errors(),
      'old' => Variable::has('form.old') ? Variable::get('form.old') : [],
    ];
  }
769634
protected function & getSession () {
		if (isset(self::$allFormsSessions[$this->id])) {
			$sessionNamespace = & self::$allFormsSessions[$this->id];
		} else {
			$sessionClass = self::$sessionClass;
			$toolClass = self::$toolClass;
			$formIdPc = $this->id;
			if (strpos($formIdPc, '-') !== FALSE)
				$formIdPc = $toolClass::GetPascalCaseFromDashed($formIdPc);
			if (strpos($formIdPc, '_') !== FALSE)
				$formIdPc = $toolClass::GetPascalCaseFromUnderscored($formIdPc);
			$namespaceName = '\\MvcCore\\Ext\\Form\\' . ucfirst($formIdPc);
			$sessionNamespace = $sessionClass::GetNamespace($namespaceName);
			// Do not use hoops expiration, because there is better
			// to set up any large value into session namespace
			// or zero value to browser close and after rendered
			// errors just clear the errors.
			//$sessionNamespace->SetExpirationHoops(1);
			$sessionNamespace->SetExpirationSeconds($this->sessionExpiration);
			if (!isset($sessionNamespace->values)) $sessionNamespace->values = [];
			if (!isset($sessionNamespace->csrf)) $sessionNamespace->csrf = [];
			if (!isset($sessionNamespace->errors)) $sessionNamespace->errors = [];
			self::$allFormsSessions[$this->id] = & $sessionNamespace;
		}
		return $sessionNamespace;
	}
618553
protected function definition() {
        $form = $this->_form;
        $stores = $this->_customdata;

        $options = array(
            cache_store::MODE_APPLICATION => array(),
            cache_store::MODE_SESSION => array(),
            cache_store::MODE_REQUEST => array()
        );
        foreach ($stores as $storename => $store) {
            foreach ($store['modes'] as $mode => $enabled) {
                if ($enabled && ($mode !== cache_store::MODE_SESSION || $store['supports']['searchable'])) {
                    if (empty($store['default'])) {
                        $options[$mode][$storename] = $store['name'];
                    } else {
                        $options[$mode][$storename] = get_string('store_'.$store['name'], 'cache');
                    }
                }
            }
        }

        $form->addElement('hidden', 'action', 'editmodemappings');
        $form->setType('action', PARAM_ALPHA);
        foreach ($options as $mode => $optionset) {
            $form->addElement('select', 'mode_'.$mode, get_string('mode_'.$mode, 'cache'), $optionset);
        }

        $this->add_action_buttons();
    }
1031796
protected function registerFormBuilder()
    {
        $this->app->bind('form', function ($app) {
            $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->token());

            return $form->setSessionStore($app['session.store']);
        });
    }
1053113
public function sessionFormAction()
    {
        $config = $this->configHandler->getPlatformConfig();
        $form = $this->formFactory->create(
            new AdminForm\SessionType(
                $config->getSessionStorageType(),
                $config,
                $this->configHandler->getLockedParamaters()
            )
        );

        return array('form' => $form->createView());
    }
1304876
public function createOptionsForms()
    {
        // construct form
        $factory = new \Zend\Form\Factory();
        $formElements = $this->getServiceLocator()->get('FormElementManager');
        $factory->setFormElementManager($formElements);
        $formConfig = $this->pluginBackConfig['modal_form'];

        $response = [];
        $render   = [];
        if (!empty($formConfig)) {
            foreach ($formConfig as $formKey => $config) {
                $form = $factory->createForm($config);
                $request = $this->getServiceLocator()->get('request');
                $parameters = $request->getQuery()->toArray();

                if (!isset($parameters['validate'])) {

                    $form->setData($this->getFormData());

                    $viewModelTab = new ViewModel();
                    $viewModelTab->setTemplate($config['tab_form_layout']);
                    $viewModelTab->modalForm = $form;
                    $viewModelTab->formData   = $this->getFormData();
                    $viewRender = $this->getServiceLocator()->get('ViewRenderer');
                    $html = $viewRender->render($viewModelTab);
                    array_push($render, [
                            'name' => $config['tab_title'],
                            'icon' => $config['tab_icon'],
                            'html' => $html
                        ]
                    );
                }
                else {

                    // validate the forms and send back an array with errors by tabs
                    $post = get_object_vars($request->getPost());
                    $success = false;
                    $form->setData($post);

                    $errors = array();
                    if ($form->isValid()) {
                        $data = $form->getData();
                        $success = true;
                        array_push($response, [
                            'name' => $this->pluginBackConfig['modal_form'][$formKey]['tab_title'],
                            'success' => $success,
                        ]);
                    } else {
                        $errors = $form->getMessages();

                        foreach ($errors as $keyError => $valueError) {
                            foreach ($config['elements'] as $keyForm => $valueForm) {
                                if ($valueForm['spec']['name'] == $keyError &&
                                    !empty($valueForm['spec']['options']['label'])
                                )
                                    $errors[$keyError]['label'] = $valueForm['spec']['options']['label'];
                            }
                        }

                        array_push($response, [
                            'name' => $this->pluginBackConfig['modal_form'][$formKey]['tab_title'],
                            'success' => $success,
                            'errors' => $errors,
                            'message' => '',
                        ]);
                    }

                }
            }
        }

        if (!isset($parameters['validate'])) {
            return $render;
        }
        else {
            return $response;
        }

    }