Default js action when saving form.

@throws \atk4\core\Exception

@return array
186317
public function jsSave($notifier)
    {
        return [
            // close modal
            new jsExpression('$(".atk-dialog-content").trigger("close")'),

            // display notification
            $this->factory($notifier),

            // reload Grid Container.
            $this->container->jsReload([$this->name.'_sort' => $this->getSortBy()]),
        ];
    }
1042663
public function generateAndIncludeJavaScript()
    {
        $filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath() . '.js';

        $this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
            $filePath,
            function () {
                return
                    // Form initialization code.
                    $this->getFormInitializationJavaScriptAssetHandler()
                        ->getFormInitializationJavaScriptCode() .
                    LF .
                    // Fields validation code.
                    $this->getFieldsValidationJavaScriptAssetHandler()
                        ->getJavaScriptCode() .
                    LF .
                    // Fields activation conditions code.
                    $this->getFieldsActivationJavaScriptAssetHandler()
                        ->getFieldsActivationJavaScriptCode() .
                    LF .
                    // Fields validation activation conditions code.
                    $this->getFieldsValidationActivationJavaScriptAssetHandler()
                        ->getFieldsValidationActivationJavaScriptCode();
            }
        );

        $this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));

        return $this;
    }
488833
protected function defaultActionStruct()
    {
        return [
            'ident'         => null,
            'priority'      => null,
            'permissions'   => [],
            'condition'     => null,
            'active'        => true,
            'empty'         => false,
            'label'         => null,
            'showLabel'     => true,
            'icon'          => null,
            'url'           => null,
            'name'          => null,
            'value'         => null,
            'target'        => null,
            'isText'        => false,
            'isLink'        => false,
            'isButton'      => true,
            'isHeader'      => false,
            'isSubmittable' => false,
            'isSeparator'   => false,
            'cssClasses'    => null,
            'actionType'    => 'dark',
            'buttonType'    => 'button',
            'splitButton'   => false,
            'hasActions'    => false,
            'actions'       => [],
        ];
    }
292330
public function init()
    {
        parent::init();

        $this->form->addHook('displayError', function ($form, $fieldName, $str) {
            // default behavior
            $jsError = [$form->js()->form('add prompt', $fieldName, $str)];

            // if field is part of an accordion section, will open that section.
            $section = $form->getClosestOwner($form->getField($fieldName), '\atk4\ui\AccordionSection');
            if ($section) {
                $jsError[] = $section->owner->jsOpen($section);
            }

            return $jsError;
        });
    }
305580
protected function setDefaultRowActions()
    {
        $actions = $this->info->list->default_action ?: [];

        if (count($actions)) {
            return $this;
        }

        $addEditAction = config('cms-models.defaults.default-listing-action-edit', false);
        $addShowAction = config('cms-models.defaults.default-listing-action-show', false);

        if ( ! $addEditAction && ! $addShowAction) {
            return $this;
        }

        // The edit and/or show action should be set as default index row click action.

        $modelSlug        = $this->getRouteHelper()->getRouteSlugForModelClass(get_class($this->model));
        $permissionPrefix = $this->getRouteHelper()->getPermissionPrefixForModelSlug($modelSlug);

        if ($addEditAction) {
            $actions[] = [
                'strategy'    => ActionReferenceType::EDIT,
                'permissions' => "{$permissionPrefix}edit",
            ];
        }

        if ($addShowAction) {
            $actions[] = [
                'strategy'    => ActionReferenceType::SHOW,
                'permissions' => "{$permissionPrefix}show",
            ];
        }

        $this->info->list->default_action = $actions;

        return $this;
    }
128046
protected function createComponentEditForm(): Form
	{
		$form = new Form;
		$form->setAjaxRequest();

		$form->addHidden('id');

		$form->addTextArea('content')
			->setAttribute('autofocus', true);

		$form->addSubmit('save', $this->translator->translate('nattreid.fileManager.save'));

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

		return $form;
	}
231815
private function allDefaults()
    {
        return [
            'wrapper' => ['class' => $this->formHelper->getConfig('defaults.wrapper_class')],
            'attr' => ['class' => $this->formHelper->getConfig('defaults.field_class')],
            'help_block' => ['text' => null, 'tag' => 'p', 'attr' => [
                'class' => $this->formHelper->getConfig('defaults.help_block_class')
            ]],
            'value' => null,
            'default_value' => null,
            'label' => $this->formHelper->formatLabel($this->getRealName()),
            'is_child' => false,
            'label_attr' => ['class' => $this->formHelper->getConfig('defaults.label_class')],
            'errors' => ['class' => $this->formHelper->getConfig('defaults.error_class')]
        ];
    }
1003148
public function getForm()
	{
		$form = new App_Form_New();

		$elements = [];

		foreach($this->_settings as $column => $setting)
		{
			if(!$this->recordColumnExists($column) )
			{
				continue;
			}

			if(isset($setting['show_in']) && (isset($setting['show_in']) && !in_array('form', $setting['show_in'])))
			{
				continue;
			}

			$settingColumn = array(
				'type' => 'text'
			);

			if(isset($setting['formOptions']))
			{
				$settingColumn['options'] = $setting['formOptions'];
			}
			elseif(!array_key_exists('options', $settingColumn))
			{
				$settingColumn['options'] = array();
			}

			$type = 'text';
			if(isset($setting['type']))
			{
				$type = $setting['type'];
			}
			if(isset($setting['label']))
			{
				$settingColumn['options']['label'] = $setting['label'];
			}
			elseif(isset($setting['title']))
			{
				$settingColumn['options']['label'] = $setting['title'];
			}

			if(isset($setting['options']['validators']))
			{
				$settingColumn['options']['validators'] = $setting['validators'];
			}
			if(isset($setting['filters']))
			{
				$settingColumn['options']['filters'] = $setting['filters'];
			}
			if(isset($setting['decorators']))
			{
				$settingColumn['options']['decorators'] = $setting['decorators'];
			}

			if(isset($setting['helper']) && isset($setting['helper']['name']))
			{
				/* TODO 20150401 : make helper definition compatible with FormElement one
				$settingColumn['options']['helper'] = $setting['helper']['name'];
				*/
			}

			switch($type)
			{
				case "boolean":
				case "bool":
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "array":
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "date":
					if(!isset($settingColumn['options']['validators']['date']))
					{
						$settingColumn['options']['validators']['date'] = array('Date',false,array('Y-m-d'));
					}
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "datetime":
					if(!isset($settingColumn['options']['validators']['date']))
					{
						$settingColumn['options']['validators']['date'] = array('Date',false,array('Y-m-d H:i:s'));
					}
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "time":
					if(!isset($settingColumn['options']['validators']['date']))
					{
						$settingColumn['options']['validators']['date'] = array('Date',false,array('H:i:s'));
					}
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "uint":
				case "int":
					@$settingColumn['options']['validators'][] = 'Int';
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "float":
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "email":
					@$settingColumn['options']['validators'][] = 'EmailAddress';
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "host":
					@$settingColumn['options']['validators'][] = 'Hostname';
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "text":
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->elementDecorators;
					}
					break;
				case "hidden":
					if(!isset($settingColumn['options']['decorators']))
					{
						$settingColumn['options']['decorators'] = $form->hiddenDecorators;
					}
					break;
				default:
					debug_assert(false !== array_search($type, self::$types), "Unknown Form Type `{$type}`");
					break;
			}

			if(isset($setting['formType']))
			{
				$settingColumn['type'] = $setting['formType'];
			}
			else
			{
				$settingColumn['type'] = $this->_getFormType($type);
			}
			if(isset($setting['unique']) && $setting['unique'] == true)
			{
				if(!isset($settingColumn['options']['validators']))
				{
					$settingColumn['options']['validators'] = array();
				}
				if(!isset($settingColumn['options']['validators']['unique']))
				{
					$settingColumn['options']['validators']['unique'] = array('Db_RecordNotExistOrIsUnique', false, array(array(
						'table' => $this->getTable(),
						'field' => $column,
						'primary_key' => $this->getPrimaryKey()
					)));
				}
			}
			if(isset($setting['required']) && $setting['required'] == true)
			{
				$settingColumn['options']['required'] = true;
			}

			if(isset($setting['multiOptions']))
			{
				$multiOptions = $setting['multiOptions'];
				if($settingColumn['type'] == 'select' || (isset($settingColumn['formType']) && $settingColumn['formType'] == 'select'))
				{
					$multiOptions = array('' => 'LABEL_SELECT') + $multiOptions;
				}
				$settingColumn['options']['multiOptions'] = $multiOptions;

				if(isset($setting['otherMultioption']) && $setting['formType'] == 'multiCheckbox')
				{
					$settingColumn['options']['otherMultioption'] = $setting['otherMultioption'];
				}
			}

			if(isset($setting['hidden']) && $setting['hidden'] == true)
			{
				$settingColumn['options']['decorators'] = $form->hiddenDecorators;
				$settingColumn['type'] = 'hidden';
			}

			$elements[$column] = $settingColumn;
		}

		$form->setOptions([
			'elements' => $elements
		]);
		$form->setDisableLoadDefaultDecorators(true);

		return $form;
	}
76376
function($form) {
        var $form = $form, _id = null;
        if ( typeof($form) == 'undefined' ) {
            if ( typeof(this.target) != 'undefined' ) {
                _id = this.target.getAttribute('id');
            } else {
                _id = this.getAttribute('id');
            }

            $form = instance.$forms[_id]
        } else if ( typeof($form) == 'string' ) {
            _id = $form;
            _id = _id.replace(/\#/, '');

            if ( typeof(instance.$forms[_id]) == 'undefined') {
                throw new Error('[ FormValidator::resetErrorsDisplay([formId]) ] `'+$form+'` not found')
            }

            $form = instance.$forms[_id]
        }

        if ($form.defaultFields) {

            var elId        = null
                , $element  = null
                , type      = null;

            for (var f in $form.defaultFields) {

                $element    = document.getElementById(f)
                type        = $element.tagName.toLowerCase();

                if (type == 'input') {
                    $element.value = $form.defaultFields[f];
                } else if ( type == 'select' ) {
                    $element.options[ $form.defaultFields[f] ].selected = true;
                    $element.setAttribute('data-value',  $element.options[ $form.defaultFields[f] ].value);
                }
            }
        }

        return $form
    }
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();
    }
1023791
public function callbackSubmit()
    {
        // These return a single value
        // Type checkbox returns true if checked
        $elements = [
            "text", "password", "hidden", "file", "textarea", "select",
            "radio", "checkbox",
        ];
        foreach ($elements as $name) {
            $this->form->addOutput(
                "$name has value: "
                . $this->form->value($name)
                . "</br>"
            );
        }

        // Select multiple returns an array
        $elements = [
            "selectm",
        ];
        foreach ($elements as $name) {
            $this->form->addOutput(
                "$name has value: "
                . implode($this->form->value($name), ", ")
                . "</br>"
            );
        }

        // Remember values during resubmit, useful when failing (retunr false)
        // and asking the user to resubmit the form.
        $this->form->rememberValues();

        return true;
    }
1117383
public function prepare_data_for_form() {
        $data = $this->to_record();
        foreach (configuration::get_defaultable_keys() as $key) {
            $data->$key = $this->get_config($key, configuration::get_default_value($key));
        }

        return $data;
    }
570799
protected function getFormActions()
    {
        $actions = new FieldList();

        if ($this->record->ID !== 0) { // existing record
            if ($this->record->canEdit()) {
                $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save'))
                    ->setUseButtonTag(true)
                    ->addExtraClass('btn-primary font-icon-save'));
            }

            if ($this->record->canDelete()) {
                $actions->push(FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete'))
                    ->setUseButtonTag(true)
                    ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete'));
            }

            $gridState = $this->getRequest()->requestVar('gridState');
            $this->gridField->getState(false)->setValue($gridState);
            $actions->push(HiddenField::create('gridState', null, $gridState));

            $actions->push($this->getRightGroupField());
        } else { // adding new record
            //Change the Save label to 'Create'
            $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create'))
                ->setUseButtonTag(true)
                ->addExtraClass('btn-primary font-icon-plus-thin'));

            // Add a Cancel link which is a button-like link and link back to one level up.
            $crumbs = $this->Breadcrumbs();
            if ($crumbs && $crumbs->count() >= 2) {
                $oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2);
                $text = sprintf(
                    "<a class=\"%s\" href=\"%s\">%s</a>",
                    "crumb btn btn-secondary cms-panel-link", // CSS classes
                    $oneLevelUp->Link, // url
                    _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label
                );
                $actions->push(new LiteralField('cancelbutton', $text));
            }
        }

        $this->extend('updateFormActions', $actions);

        return $actions;
    }
635622
protected function defaultOptions()
    {
        $this->options = ArrayHelper::merge($this->options, $this->module->widgetOptions);
        $this->clientOptions = ArrayHelper::merge($this->clientOptions, $this->module->widgetClientOptions);
        if (!isset($this->options['id'])) {
            if ($this->hasModel()) {
                $this->options['id'] = Html::getInputId($this->model, $this->attribute);
            } else {
                $this->options['id'] = $this->getId();
            }
        }
        Html::addCssClass($this->options, 'form-control');

        $this->setOptionsKey('imageUpload', $this->module->imageUploadRoute);
        $this->setOptionsKey('fileUpload', $this->module->fileUploadRoute);

        $this->clientOptions['imageUploadErrorCallback'] = ArrayHelper::getValue($this->clientOptions, 'imageUploadErrorCallback', new JsExpression("function(json){alert(json.error);}"));
        $this->clientOptions['fileUploadErrorCallback'] = ArrayHelper::getValue($this->clientOptions, 'fileUploadErrorCallback', new JsExpression("function(json){alert(json.error);}"));

        if (isset($this->clientOptions['plugins']) && array_search('imagemanager', $this->clientOptions['plugins']) !== false) {
            $this->setOptionsKey('imageManagerJson', $this->module->imageManagerJsonRoute);
        }
        if (isset($this->clientOptions['plugins']) && array_search('filemanager', $this->clientOptions['plugins']) !== false) {
            $this->setOptionsKey('fileManagerJson', $this->module->fileManagerJsonRoute);
        }
    }
1044118
public function formAction()
    {
        $repository = $this->repositories->get('Applications/Application');
        
        $mode  = $this->params()->fromQuery('mode', 'new');
        $appId = $this->params()->fromQuery('id');
        /* @var \Applications\Entity\Application $application */
        $application = $repository->find($appId);

        $viewModel = new ViewModel();
        if ('edit' == $mode) {
            $comment = $repository->findComment($appId);
        } else {
            $comment = new Comment();
            $comment->setUser($this->auth()->getUser());
        }
        
        $this->acl($application, 'read');
        
        $form = $this->formManager->get('Applications/CommentForm');
        $form->bind($comment);
        
        if ($this->getRequest()->isPost()) {
            $form->setData($_POST);
            
            if ($form->isValid()) {
                if ('new' == $mode) {
                    $application = $repository->find($appId);
                    $application->getComments()->add($comment);
                    $application->changeStatus(
                        $application->getStatus(),
                        sprintf(
                                    /* @translate */ 'Application was rated by %s',
                                     $this->auth()->getUser()->getInfo()->getDisplayName()
                    )
                        );
                }
                $viewModel->setVariable('isSaved', true);
            }
        }
       
        $viewModel->setVariables(
            array(
            'mode' => $mode,
            'identifier' => $appId,
            'commentForm' => $form,
            )
        );
        return $viewModel;
    }
60385
public function saveUploadedFiles()
    {
        try
        {
            if(($xUploadPlugin = $this->getPluginManager()->getRequestPlugin(self::FILE_UPLOAD)) == null)
            {
                throw new Exception($this->trans('errors.upload.plugin'));
            }
            elseif(!$xUploadPlugin->canProcessRequest())
            {
                throw new Exception($this->trans('errors.upload.request'));
            }
            // Save uploaded files
            $sKey = $xUploadPlugin->saveUploadedFiles();
            $sResponse = '{"code": "success", "upl": "' . $sKey . '"}';
            $return = true;
        }
        catch(Exception $e)
        {
            $sResponse = '{"code": "error", "msg": "' . addslashes($e->getMessage()) . '"}';
            $return = false;
        }
        // Send the response back to the browser
        echo '<script>var res = ', $sResponse, '; </script>';
        if(($this->getOption('core.process.exit')))
        {
            exit();
        }
        return $return;
    }
113813
private function beforeForm() {
    // Add Bootstrap CSS if is enabled
    $form_class = "";
    if ( $this -> isUsingBootstrap() ) {
      echo $this -> constants -> getBootstrapCSS();
      if( $this -> bootstrap_form_orientation == "horizontal" ){
        $form_class = "form-horizontal";
      }else if( $this -> bootstrap_form_orientation = "inline" ){
        $form_class = "form-inline";
      }
    }

    // Render form header
    echo "<form method='" . $this -> form_method . "' action='" . $this -> form_action . "' class='" . $form_class . "'>";
  }