Perform some actions on the form, right before it is displayed but already populated

Here we add the table display to the form.

@return \Zend_Form
337926
public function beforeDisplay()
    {
        if ($this->_csrf) {
            $this->_csrf->initCsrfToken();
        }

        $links = $this->getMenuList();
        if (\MUtil_Bootstrap::enabled()) {
            if ($links) {
                $element = $this->_form->createElement('html', 'menuLinks');
                $element->setValue($links);
                $element->setOrder(999);
                $this->_form->addElement($element);
            }
        } else {
            $table = new \MUtil_Html_TableElement(array('class' => $this->class));
            $table->setAsFormLayout($this->_form, true, true);

            // There is only one row with formLayout, so all in output fields get class.
            $table['tbody'][0][0]->appendAttrib('class', $this->labelClass);

            if ($links) {
                $table->tf(); // Add empty cell, no label
                $table->tf($links);
            }
        }
    }
383347
public function onLoadSetup()
    {
        $this->vars['columns'] = $this->getSetupListColumns();
        $this->vars['perPageOptions'] = $this->getSetupPerPageOptions();
        $this->vars['recordsPerPage'] = $this->recordsPerPage;
        return $this->makePartial('setup_form');
    }
1340829
protected function InitForm()
    {
        $this->checkbox = $this->LoadElement();
        $this->AddRequiredField();
        $this->AddNameField();
        $this->AddLabelField();
        $this->AddCheckedField();
        $this->AddCheckedValueField();
        $this->AddDisableFrontendValidationField();
        $this->AddCssIDField();
        $this->AddCssClassField();
        $this->AddTemplateField();
        $this->AddSubmit();
    }
306016
protected function buildForm()
    {
        $this->formBuilder
            ->add(
                'host',
                'text',
                array(
                    'constraints' => array(
                        new NotBlank(),
                    ),
                )
            )
            ->add(
                'user',
                'text',
                array(
                    'constraints' => array(
                        new NotBlank(),
                    ),
                )
            )
            ->add(
                'password',
                'text',
                array(
                    'constraints' => array(
                        new NotBlank(),
                    ),
                )
            )
            ->add(
                'port',
                'text',
                array(
                    'constraints' => array(
                        new NotBlank(),
                        new GreaterThan(
                            array(
                                'value' => 0,
                            )
                        ),
                    ),
                )
            )
            ->add(
                'locale',
                'hidden',
                array(
                    'constraints' => array(
                        new NotBlank(),
                    ),
                )
            );
    }
193340
protected function InitForm()
    {
        $this->htmlCode = $this->LoadElement();
        $name = 'Code';
        $this->AddField(new Textarea($name, $this->htmlCode->GetCode()));
        $this->SetRequired($name);
        $this->AddCssClassField();
        $this->AddCssIDField();
        $this->AddSubmit();
    }
666244
private function form() {

    // Iterate through all the fields, rendering them
    foreach ( $this -> form_fields as $form_field ) {
      // Get Tag Type (input, select, option, button...)
      $tag_type = $form_field -> getTagType();
      $html_field = "";

      if( $this -> isUsingBootstrap() ){
        $html_field .= "<div class='form-group'>";
      }

      echo $form_field -> getFieldPreHTML();

      $html_field .= "<" . $tag_type . " ";
      $attributes = $form_field -> getAttributes();

      foreach ( $attributes as $att => $val ) {
        $html_field .= $att . "='" . $val . "' ";
      }
      // Remove last whitespace
      $html_field = rtrim($html_field);
      $html_field .= ">";

      if ( $tag_type == "button" || $tag_type == "a" || $tag_type == "select" ){
        if( $tag_type == "select" ){
          $options = $form_field -> getOptions();
          $values = $form_field -> getValues();
          // First option (Disabled)
          $html_field .= "<option value='' disabled='disabled' selected='true'>" . $form_field -> getFirstOption() . "</option>";
          foreach ($options as $option_key => $option_value ) {
            $html_field .= "<option value='" . $values[$option_key] . "'>" . $option_value . "</option>";
          }
          $html_field .= "</" . $tag_type . ">";
        }else{
          $html_field .= $form_field -> getInnerText();
          $html_field .= "</" . $tag_type . ">";
        }
      }

      if( $this -> isUsingBootstrap() ){
        $html_field .= "</div>";
      }

      echo $html_field;
    }

    echo $form_field -> getFieldPostHTML();
  }
74233
protected function initForm()
    {
        $name = isset($this->options['name']) ? $this->options['name'] : '';
        if(empty($name)){
            $name = 'form_'.(count(self::$forms)+1);
        }
        unset($this->options['name']);

        $this->form = tao_helpers_form_FormFactory::getForm($name, $this->options);

        //add translate action in toolbar
        $actions = tao_helpers_form_FormFactory::getCommonActions();

        //add a hidden form element that states that it is an Instance Form.
        $instanceElt = tao_helpers_form_FormFactory::getElement('tao.forms.instance', 'Hidden');
        $instanceElt->setValue('1');
        $this->form->addElement($instanceElt, true);

        //add a token to protect against xsrf
        $tokenElt = tao_helpers_form_FormFactory::getElement('token', 'Token');
        $tokenElt->addValidator(new XsrfTokenValidator());
        $this->form->addElement($tokenElt, true);

        $this->form->setActions($actions, 'top');
        $this->form->setActions($actions, 'bottom');
    }
688873
public function initCreate()
    {
        // setting itemCreate manually is possible.
        if (!$this->itemCreate) {
            $this->itemCreate = $this->menu->addItem($this->itemCreate ?: ['Add new', 'icon' => 'plus']);
            $this->itemCreate->on('click.atk_CRUD', new jsModal('Add new', $this->pageCreate, [$this->name.'_sort' => $this->getSortBy()]));
            $this->itemCreate->set('Add New '.$this->model->getModelCaption());
        }

        // setting callback for the page
        $this->pageCreate->set(function () {

            // formCreate may already be an object added inside pageCreate
            if (!is_object($this->formCreate) || !$this->formCreate->_initialized) {
                $this->formCreate = $this->pageCreate->add($this->formCreate ?: $this->formDefault);
            }

            // $form = $page->add($this->formCreate ?: ['Form', 'layout' => 'FormLayout/Columns']);
            $this->formCreate->setModel($this->model, $this->fieldsCreate ?: $this->fieldsDefault);

            if ($sortBy = $this->getSortBy()) {
                $this->formCreate->stickyGet($this->name.'_sort', $sortBy);
            }

            // set save handler with reload trigger
            // adds default submit hook if it is not already set for this form
            if (!$this->formCreate->hookHasCallbacks('submit')) {
                $this->formCreate->onSubmit(function ($form) {
                    $form->model->save();

                    return $this->jsSaveCreate();
                });
            }
        });
    }
869755
public function editAction()
    {
        $default    = false;
        $params     = $this->params();
        $request    = $this->getRequest();
        $locator    = $this->getServiceLocator();
        $model      = $locator->get( 'Grid\Core\Model\SubDomain\Model' );
        /* @var $form \Zend\Form\Form */
        $form       = $locator->get( 'Form' )
                              ->create( 'Grid\Core\SubDomain' );

        if ( ( $id = $params->fromRoute( 'id' ) ) )
        {
            $subDomain = $model->find( $id );

            if ( empty( $subDomain ) )
            {
                $this->getResponse()
                     ->setStatusCode( 404 );

                return;
            }

            if ( empty( $subDomain->subdomain ) )
            {
                $default = true;

                $form->get( 'subdomain' )
                     ->setRequired( false );
            }
        }
        else
        {
            if ( ! $this->getServiceLocator()
                        ->get( 'Grid\User\Model\Permissions\Model' )
                        ->isAllowed( 'subDomain', 'create' ) )
            {
                $this->getResponse()
                     ->setStatusCode( 403 );

                return;
            }

            $subDomain = $model->create( array() );
        }

        /* @var $form \Zend\Form\Form */
        $form->setHydrator( $model->getMapper() )
             ->bind( $subDomain );

        if ( $request->isPost() )
        {
            $form->setData( $request->getPost() );

            if ( $form->isValid() && $subDomain->save() )
            {
                if ( $default && ! empty( $subDomain->subdomain ) )
                {
                    $newDefault = $model->create( array(
                        'subdomain'         => '',
                        'locale'            => $subDomain->locale,
                        'defaultLayoutId'   => $subDomain->defaultLayoutId,
                        'defaultContentId'  => $subDomain->defaultContentId,
                    ) );

                    $newDefault->save();
                }

                $this->messenger()
                     ->add( 'subDomain.form.success',
                            'subDomain', Message::LEVEL_INFO );

                return $this->redirect()
                            ->toRoute( 'Grid\Core\SubDomain\List', array(
                                'locale' => (string) $this->locale(),
                            ) );
            }
            else
            {
                $this->messenger()
                     ->add( 'subDomain.form.failed',
                            'subDomain', Message::LEVEL_ERROR );
            }
        }

        $form->setCancel(
            $this->url()
                 ->fromRoute( 'Grid\Core\SubDomain\List', array(
                        'locale' => (string) $this->locale(),
                    ) )
        );

        return array(
            'form'      => $form,
            'subDomain' => $subDomain,
        );
    }
57502
protected function editTemplateAction()
    {
        $id = $this->params('id');
        $formIdentifier=$this->params()->fromQuery('form');
        //$job = $this->jobRepository->find($id);
        $job = $this->initializeJob()->get($this->params(), true, true); /* @var \Jobs\Entity\Job $job */
        $this->acl($job, 'edit');

        /** @var \Zend\Http\Request $request */
        $request              = $this->getRequest();
        $isAjax               = $request->isXmlHttpRequest();
        $viewHelperManager    = $this->viewHelper;
        $mvcEvent             = $this->getEvent();
        $applicationViewModel = $mvcEvent->getViewModel();
        $forms                = $this->formManager;

        /** @var \Jobs\Form\JobDescriptionTemplate $formTemplate */
        $formTemplate         = $forms->get(
            'Jobs/Description/Template',
            array(
            'mode' => $job->getId() ? 'edit' : 'new'
            )
        );

        $formTemplate->setParam('id', $job->getId());
        $formTemplate->setParam('applyId', $job->getApplyId());
        $formTemplate->setParam('snapshot', $job instanceof JobSnapshot ? $job->getSnapshotId() : '');

        $formTemplate->setEntity($job);

        if (isset($formIdentifier) && $request->isPost()) {
            // at this point the form get instantiated and immediately accumulated

            $instanceForm = $formTemplate->get($formIdentifier);
            if (!isset($instanceForm)) {
                throw new \RuntimeException('No form found for "' . $formIdentifier . '"');
            }

            // the id is part of the postData, but it never should be altered
            $postData = $request->getPost();

            unset($postData['id']);
            unset($postData['applyId']);
            unset($postData['snapshot']);

            $instanceForm->setData($postData);
            if ($instanceForm->isValid()) {
                $this->jobRepository->store($job);
            }
        }

        $model = $this->viewModelTemplateFilter->getModel($formTemplate);

        if (!$isAjax) {
            $basePath   = $viewHelperManager->get('basepath');
            $headScript = $viewHelperManager->get('headscript');
            $asset = $viewHelperManager->get('asset');
            $headScript->appendFile($basePath('dist/js/core.js'));
            $headScript->appendFile($basePath->__invoke('modules/Core/js/core.forms.js'));
            $headScript->appendScript('
                $(document).ready(function() {
                    var submitTextarea = function($area, $form) {
                        var bg = $area.css("background-color");
                        $area.css("background-color", "lightgrey");
                        $form.one("yk:forms:success yk:forms:fail", function() { $area.css("background-color", bg); }).submit();
                    };

                    $("textarea").blur(function(e) { var $area = $(e.target); submitTextarea($area, $area.parents("form")); })
                                 .keydown(function(e) { if ((10 == e.keyCode || 13 == e.keyCode) && e.ctrlKey) {
                                                var $area = $(e.target); submitTextarea($area, $area.parents("form"));
                                          }});
                });
            ');

            $headStyle = $viewHelperManager->get('headstyle');
            $headStyle->prependStyle(
                'form > input {
            color: inherit !important; margin:inherit !important;
            padding:inherit !important; border:0 !important; cursor:pointer !important; letter-spacing:inherit !important;
            line-height: inherit !important;
             font-size: inherit !important;
}
'
            );
        } else {
            return new JsonModel(array('valid' => true));
        }
        $applicationViewModel->setTemplate('iframe/iFrameInjection');
        return $model;
    }
271721
public function createAction()
    {
        if ($form = $this->processForm()) {
            $this->setPageTitle(sprintf($this->_('New %s...'), $this->getTopic()));
            $this->html[] = $form;
        }
    }
506492
protected function initForm()
    {
    	(isset($this->options['name'])) ? $name = $this->options['name'] : $name = ''; 
    	if(empty($name)){
			$name = 'form_'.(count(self::$forms)+1);
		}
		unset($this->options['name']);
			
		$this->form = \tao_helpers_form_FormFactory::getForm($name, $this->options);
		
		//create action in toolbar
		$createElt = \tao_helpers_form_FormFactory::getElement('create', 'Free');
		$createElt->setValue('<button class="btn-info" type="submit" id="addButton">'.\tao_helpers_Icon::iconAdd().__('Create').'</button>');
		$this->form->setActions(array(), 'top');
		$this->form->setActions(array($createElt), 'bottom');
    }
1140704
public function LinkForm()
    {
        $this->getLinkObject();

        $action = FormAction::create('doSaveLink', _t('Linkable.SAVE', 'Save'))
            ->setUseButtonTag('true');

        if (!$this->isFrontend) {
            $action
                ->addExtraClass('ss-ui-action-constructive')
                ->setAttribute('data-icon', 'accept');
        }

        $link = null;
        if ($linkID = (int)$this->request->getVar('LinkID')) {
            $link = Link::get()->byID($linkID);
        }

        $link = $link ? $link : singleton(Link::class);
        $link->setAllowedTypes($this->getAllowedTypes());

        /** @var $fields FieldList */
        $fields = $link->getCMSFields();

        $title = $link ? _t('Linkable.EDITLINK', 'Edit Link') : _t('Linkable.ADDLINK', 'Add Link');
        $fields->insertBefore(
            _t('Linkable.TITLE', 'Title'), HeaderField::create('LinkHeader', $title)
        );

        $actions = FieldList::create($action);
        $form = Form::create($this, 'LinkForm', $fields, $actions);

        if ($link) {
            $form->loadDataFrom($link);
            $fields->push(HiddenField::create('LinkID', 'LinkID', $link->ID));
        }

        $this->owner->extend('updateLinkForm', $form);

        return $form;
    }
78660
public function render()
    {
        $this->getEventManager()->trigger(
            'formBeforeRender',
            $this,
            array(

            )
        );
        $output = parent::render();
        $this->getEventManager()->trigger(
            'formAfterRender',
            $this,
            array(
                'output' => &$output
            )
        );
        return $output;
    }
53223
protected function beforeRenderFormType()
    {
        $controller = $this->_controller();

        $controller->set('formEnableDirtyCheck', $this->_getFormEnableDirtyCheck());
        $controller->set('formSubmitButtonText', $this->_getFormSubmitButtonText());
        $controller->set('formSubmitExtraButtons', $this->_getFormSubmitExtraButtons());
        $controller->set('formSubmitExtraLeftButtons', $this->_getFormSubmitExtraLeftButtons());
        $controller->set('formUrl', $this->_getFormUrl());
    }
12500
public function display()
    {
        $options = $this->getOptions();

        if (!$this->visible || $options === null) {
            return;
        }

        SwatWidget::display();

        // add a hidden field so we can check if this list was submitted on
        // the process step
        $this->getForm()->addHiddenField($this->id . '_submitted', 1);

        if ($this->show_blank) {
            $options = array_merge(
                array(new SwatOption(null, $this->blank_title)),
                $options
            );
        }

        $table_tag = new SwatHtmlTag('table');
        $table_tag->id = $this->id;
        $table_tag->class = $this->getCSSClassString();
        $table_tag->open();

        foreach ($options as $index => $option) {
            $this->displayRadioTableOption($option, $index);
        }

        $table_tag->close();
    }
632807
final public function populateFormOnce()
    {
        if (!$this->_formPopulated) {
            if (!empty($this->controller) && $this->controller->propagateId()) {
                $this->form->addElement(
                    'hidden', HTML_QuickForm2_Controller::KEY_ID,
                    array('id' => HTML_QuickForm2_Controller::KEY_ID)
                )->setValue($this->controller->getId());
            }
            $this->populateForm();
            $this->_formPopulated = true;
        }
    }