Show the form to edit a record.

@return \Illuminate\Http\Response
357663
public function edit($entity, $id, $child = null, $record = null)
    {
        if (!$record && !$child && ($entityObject = Entity::fromYamlFile($entity))) {
            // Get the record from the database, or fail if it is not found
            $entityClass = $entityObject->class;
            $record = $entityClass::findOrFail($id);

            $form = new Form($entityObject, $record, Session::get('errors'));

            return $form->view();
        } elseif (($parentEntity = Entity::fromYamlFile($entity)) && ($entityObject = Entity::fromYamlFile($child))) {
            // Get parent's record
            $parentRecord = $parentEntity->class::findOrFail($id);

            // Get the record from the database, or fail if it is not found
            $entityClass = $entityObject->class;
            $childObject = $entityClass::findOrFail($record);

            $form = new Form($entityObject, $childObject, Session::get('errors'), $parentEntity, $parentRecord);

            return $form->view();
        } else {
            abort(404);
        }
    }
155349
public function recordEditForm()
    {
        //clone current request : used to figure out what record we are asking
        $request = clone $this->request;
        $recordInfo = $request->shift();

        //shift request till we find the requested field
        while ($recordInfo) {
            if ($unescapedRecordInfo = $this->unEscapeFieldName($recordInfo)) {
                $id = $unescapedRecordInfo['id'];
                $fieldName = $unescapedRecordInfo['name'];

                $action = $request->shift();
                break;
            } else {
                $recordInfo = $request->shift();
            }
        }

        //generate a form with only that requested record's fields
        if ($id) {
            $modelClass = $this->gridField->getModelClass();
            $record = DataObject::get_by_id($modelClass, $id);

            $cmsFields = $record->getCMSFields();
            $recordEditingFields = $this->getRecordEditingFields($record);

            return Form::create(
                $this->gridField,
                'recordEditForm',
                FieldList::create($recordEditingFields),
                FieldList::create()
            );
        }
    }
752294
public function getEditForm()
    {
        if (null === $this->editForm) {
            $this->setEditForm($this->getServiceLocator()->get('dlccategory_editcategory_form'));
        }
        return $this->editForm;
    }
1004288
public function edit(): void
    {
        $oUri   = Factory::service('Uri');
        $oInput = Factory::service('Input');

        if ($oUri->segment(5) != activeUser('id') && !userHasPermission('admin:auth:accounts:editOthers')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        /**
         * Get the user's data; loaded early because it's required for the user_meta_cols
         * (we need to know the group of the user so we can pull up the correct cols/rules)
         */

        $oSession   = Factory::service('Session', 'nails/module-auth');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $oUser      = $oUserModel->getById($oUri->segment(5));

        if (!$oUser) {
            $oSession->setFlashData('error', lang('accounts_edit_error_unknown_id'));
            $this->returnToIndex();
        }

        //  Non-superusers editing superusers is not cool
        if (!$oUserModel->isSuperuser() && userHasPermission('superuser', $oUser)) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/dashboard';
            redirect($sReturnTo);
        }

        //  Is this user editing someone other than themselves? If so, do they have permission?
        if (activeUser('id') != $oUser->id && !userHasPermission('admin:auth:accounts:editOthers')) {
            $oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
            $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/dashboard';
            redirect($sReturnTo);
        }

        // --------------------------------------------------------------------------

        /**
         * Load the user_meta_cols; loaded here because it's needed for both the view
         * and the form validation
         */

        $oDb           = Factory::service('Database');
        $oConfig       = Factory::service('Config');
        $aUserMetaCols = $oConfig->item('user_meta_cols');
        $iGroupId      = (int) $oInput->post('group_id') ?: $oUser->group_id;

        if (isset($aUserMetaCols[$iGroupId])) {
            $this->data['user_meta_cols'] = $aUserMetaCols[$oUser->group_id];
        } else {
            $this->data['user_meta_cols'] = null;
        }

        //  Set fields to ignore by default
        $this->data['ignored_fields'] = [
            'id',
            'user_id',
        ];

        /**
         * If no cols were found, DESCRIBE the user_meta_app table - where possible you
         * should manually set columns, including datatypes
         */

        if (is_null($this->data['user_meta_cols'])) {

            $aResult                      = $oDb->query('DESCRIBE `' . NAILS_DB_PREFIX . 'user_meta_app`')->result();
            $this->data['user_meta_cols'] = [];

            foreach ($aResult as $col) {

                //  Always ignore some fields
                if (array_search($col->Field, $this->data['ignored_fields']) !== false) {
                    continue;
                }

                // --------------------------------------------------------------------------

                //  Attempt to detect datatype
                $sDataType = 'string';
                $type      = 'text';

                switch (strtolower($col->Type)) {

                    case 'text':
                        $type = 'textarea';
                        break;

                    case 'date':
                        $sDataType = 'date';
                        break;

                    case 'tinyint(1) unsigned':
                        $sDataType = 'bool';
                        break;
                }

                // --------------------------------------------------------------------------

                $this->data['user_meta_cols'][$col->Field] = [
                    'datatype' => $sDataType,
                    'type'     => $type,
                    'label'    => ucwords(str_replace('_', ' ', $col->Field)),
                ];
            }
        }

        // --------------------------------------------------------------------------

        //  Validate if we're saving, otherwise get the data and display the edit form
        if ($oInput->post()) {

            //  Load validation library
            $oFormValidation = Factory::service('FormValidation');

            // --------------------------------------------------------------------------

            //  Define user table rules
            $oFormValidation->set_rules('first_name', '', 'trim|required');
            $oFormValidation->set_rules('last_name', '', 'trim|required');
            $oFormValidation->set_rules('gender', '', 'required');
            $oFormValidation->set_rules('dob', '', 'valid_date');
            $oFormValidation->set_rules('timezone', '', 'required');
            $oFormValidation->set_rules('datetime_format_date', '', 'required');
            $oFormValidation->set_rules('datetime_format_time', '', 'required');

            // --------------------------------------------------------------------------

            //  Define user_meta table rules
            foreach ($this->data['user_meta_cols'] as $col => $value) {

                $sDataType = isset($value['datatype']) ? $value['datatype'] : 'string';
                $label     = isset($value['label']) ? $value['label'] : ucwords(str_replace('_', ' ', $col));

                //  Some data types require different handling
                switch ($sDataType) {

                    case 'date':
                        //  Dates must validate
                        if (isset($value['validation'])) {
                            $oFormValidation->set_rules($col, $label, $value['validation'] . '|valid_date[' . $col . ']');
                        } else {
                            $oFormValidation->set_rules($col, $label, 'valid_date[' . $col . ']');
                        }
                        break;

                    // --------------------------------------------------------------------------

                    case 'file':
                    case 'upload':
                    case 'string':
                    default:
                        if (isset($value['validation'])) {
                            $oFormValidation->set_rules($col, $label, $value['validation']);
                        }
                        break;
                }
            }

            // --------------------------------------------------------------------------

            //  Set messages
            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('min_length', lang('fv_min_length'));
            $oFormValidation->set_message('alpha_dash_period', lang('fv_alpha_dash_period'));
            $oFormValidation->set_message('is_natural_no_zero', lang('fv_required'));
            $oFormValidation->set_message('valid_date', lang('fv_valid_date'));
            $oFormValidation->set_message('valid_datetime', lang('fv_valid_datetime'));

            // --------------------------------------------------------------------------

            //  Data is valid; ALL GOOD :]
            if ($oFormValidation->run()) {

                //  Define the data var
                $aData = [];

                // --------------------------------------------------------------------------

                //  If we have a profile image, attempt to upload it
                if (isset($_FILES['profile_img']) && $_FILES['profile_img']['error'] != UPLOAD_ERR_NO_FILE) {

                    $oCdn   = Factory::service('Cdn', 'nails/module-cdn');
                    $object = $oCdn->objectReplace($oUser->profile_img, 'profile-images', 'profile_img');

                    if ($object) {

                        $aData['profile_img'] = $object->id;

                    } else {

                        $this->data['upload_error'] = $oCdn->getErrors();
                        $this->data['error']        = lang('accounts_edit_error_profile_img');
                    }
                }

                // --------------------------------------------------------------------------

                if (!isset($this->data['upload_error'])) {

                    //  Set basic data

                    $aData['temp_pw']              = stringToBoolean($oInput->post('temp_pw', true));
                    $aData['reset_mfa_question']   = stringToBoolean($oInput->post('reset_mfa_question', true));
                    $aData['reset_mfa_device']     = stringToBoolean($oInput->post('reset_mfa_device', true));
                    $aData['first_name']           = $oInput->post('first_name', true);
                    $aData['last_name']            = $oInput->post('last_name', true);
                    $aData['username']             = $oInput->post('username', true);
                    $aData['gender']               = $oInput->post('gender', true);
                    $aData['dob']                  = $oInput->post('dob', true);
                    $aData['dob']                  = !empty($aData['dob']) ? $aData['dob'] : null;
                    $aData['timezone']             = $oInput->post('timezone', true);
                    $aData['datetime_format_date'] = $oInput->post('datetime_format_date', true);
                    $aData['datetime_format_time'] = $oInput->post('datetime_format_time', true);

                    if ($oInput->post('password', true)) {
                        $aData['password'] = $oInput->post('password', true);
                    }

                    //  Set meta data
                    foreach ($this->data['user_meta_cols'] as $col => $value) {

                        $mValue = $oInput->post($col, true);

                        //  Should the field be made null on empty?
                        if (!empty($value['nullOnEmpty']) && empty($mValue)) {
                            $mValue = null;
                        }

                        switch ($value['datatype']) {

                            case 'bool':
                            case 'boolean':
                                //  Convert all to boolean from string
                                $aData[$col] = stringToBoolean($mValue);
                                break;

                            case 'file':
                            case 'upload':
                                //  File uploads should be an integer, or if empty, null
                                $aData[$col] = (int) $mValue ?: null;
                                break;

                            default:
                                $aData[$col] = $mValue;
                                break;
                        }
                    }

                    // --------------------------------------------------------------------------

                    //  Update account
                    if ($oUserModel->update($oInput->post('id'), $aData)) {

                        $name                  = $oInput->post('first_name', true) . ' ' . $oInput->post('last_name', true);
                        $this->data['success'] = lang('accounts_edit_ok', [title_case($name)]);
                        // --------------------------------------------------------------------------

                        //  Set Admin changelogs
                        $name = '#' . number_format($oInput->post('id'));

                        if ($aData['first_name']) {
                            $name .= ' ' . $aData['first_name'];
                        }

                        if ($aData['last_name']) {
                            $name .= ' ' . $aData['last_name'];
                        }

                        foreach ($aData as $field => $value) {
                            if (isset($oUser->$field)) {
                                $this->oChangeLogModel->add(
                                    'updated',
                                    'a',
                                    'user',
                                    $oInput->post('id'),
                                    $name,
                                    'admin/auth/accounts/edit/' . $oInput->post('id'),
                                    $field,
                                    $oUser->$field,
                                    $value,
                                    false
                                );
                            }
                        }

                        // --------------------------------------------------------------------------

                        //  refresh the user object
                        $oUser = $oUserModel->getById($oInput->post('id'));

                        //  The account failed to update, feedback to user
                    } else {

                        $this->data['error'] = lang(
                            'accounts_edit_fail',
                            implode(', ', $oUserModel->getErrors())
                        );
                    }
                }

                //  Update failed for another reason
            } else {

                $this->data['error'] = lang('fv_there_were_errors');
            }
        }
        //  End POST() check

        // --------------------------------------------------------------------------

        //  Get the user's meta data
        if ($this->data['user_meta_cols']) {

            $oDb->select(implode(',', array_keys($this->data['user_meta_cols'])));
            $oDb->where('user_id', $oUser->id);
            $aUserMeta = (array) $oDb->get(NAILS_DB_PREFIX . 'user_meta_app')->row();

        } else {
            $aUserMeta = [];
        }

        // --------------------------------------------------------------------------

        //  Get the user's email addresses
        $this->data['user_emails'] = $oUserModel->getEmailsForUser($oUser->id);

        // --------------------------------------------------------------------------

        $this->data['user_edit'] = $oUser;
        $this->data['user_meta'] = $aUserMeta;

        //  Page Title
        $this->data['page']->title = lang(
            'accounts_edit_title',
            title_case($oUser->first_name . ' ' . $oUser->last_name)
        );

        //  Get the groups, timezones and languages
        $oUserGroupModel      = Factory::model('UserGroup', 'nails/module-auth');
        $this->data['groups'] = $oUserGroupModel->getAll();

        $oLanguageService        = Factory::service('Language');
        $this->data['languages'] = $oLanguageService->getAllEnabledFlat();

        $oDateTimeService               = Factory::service('DateTime');
        $this->data['timezones']        = $oDateTimeService->getAllTimezone();
        $this->data['date_formats']     = $oDateTimeService->getAllDateFormat();
        $this->data['time_formats']     = $oDateTimeService->getAllTimeFormat();
        $this->data['default_timezone'] = $oDateTimeService->getTimezoneDefault();

        //  Fetch any user uploads
        if (Components::exists('nails/module-cdn')) {
            $oCdn                       = Factory::service('Cdn', 'nails/module-cdn');
            $this->data['user_uploads'] = $oCdn->getObjectsForUser($oUser->id);
        }

        // --------------------------------------------------------------------------

        if (activeUser('id') == $oUser->id) {

            switch (strtolower(activeUser('gender'))) {

                case 'male':
                    $this->data['notice'] = lang('accounts_edit_editing_self_m');
                    break;

                case 'female':
                    $this->data['notice'] = lang('accounts_edit_editing_self_f');
                    break;

                default:
                    $this->data['notice'] = lang('accounts_edit_editing_self_u');
                    break;
            }
        }

        $oUserPasswordModel          = Factory::model('UserPassword', 'nails/module-auth');
        $this->data['passwordRules'] = $oUserPasswordModel->getRulesAsString($oUser->group_id);

        // --------------------------------------------------------------------------

        //  Load views
        Helper::loadView('edit');
    }
811847
public function processUpdateAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth($this->resourceCode, $this->getModuleCode(), AccessManager::UPDATE)) {
            return $response;
        }

        // Error (Default: false)
        $error_msg = false;

        // Create the Form from the request
        $changeForm = $this->getUpdateForm($this->getRequest());

        try {
            // Check the form against constraints violations
            $form = $this->validateForm($changeForm, "POST");

            // Get the form field values
            $data = $form->getData();

            // Create a new event object with the modified fields
            $changeEvent = $this->getUpdateEvent($data);
            $changeEvent->bindForm($form);

            // Dispatch Update Event
            $this->dispatch($this->updateEventIdentifier, $changeEvent);

            // Check if object exist
            if (! $this->eventContainsObject($changeEvent)) {
                throw new \LogicException(
                    $this->getTranslator()->trans("No %obj was updated.", ['%obj' => $this->objectName])
                );
            }

            // Log object modification
            if (null !== $changedObject = $this->getObjectFromEvent($changeEvent)) {
                $this->adminLogAppend(
                    $this->resourceCode,
                    AccessManager::UPDATE,
                    sprintf(
                        "%s %s (ID %s) modified",
                        ucfirst($this->objectName),
                        $this->getObjectLabel($changedObject),
                        $this->getObjectId($changedObject)
                    ),
                    $this->getObjectId($changedObject)
                );
            }

            // Execute additional Action
            $response = $this->performAdditionalUpdateAction($changeEvent);

            if ($response == null) {
                // If we have to stay on the same page, do not redirect to the successUrl,
                // just redirect to the edit page again.
                if ($this->getRequest()->get('save_mode') == 'stay') {
                    return $this->redirectToEditionTemplate($this->getRequest());
                }

                // Redirect to the success URL
                return $this->generateSuccessRedirect($changeForm);
            } else {
                return $response;
            }
        } catch (FormValidationException $ex) {
            // Form cannot be validated
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
        } catch (\Exception $ex) {
            // Any other error
            $error_msg = $ex->getMessage();
        }

        if (false !== $error_msg) {
            // At this point, the form has errors, and should be redisplayed.
            $this->setupFormErrorContext(
                $this->getTranslator()->trans("%obj modification", ['%obj' => $this->objectName]),
                $error_msg,
                $changeForm,
                $ex
            );

            return $this->renderEditionTemplate();
        }
    }
793347
public function edit() {
		HtmlEditorField::include_js();
//		Requirements::javascript('simplewiki/javascript/sslinks/editor_plugin_src.js');

		$existing = $this->getEditingLocks($this->data(), true);
		// oops, we've somehow got here even though we shouldn't have
		if ($existing && $existing['user'] != Member::currentUser()->Email) {
			return $this->redirect($this->data()->Link());
		}

		if (!$this->data()->canEdit()) {
			return Security::permissionFailure($this);
		}

		$this->form = $this->EditForm();

		// check who's editing and whether or not we should bail out
		return $this->renderWith(array('WikiPage', 'Page'));
	}
1030597
public function editAction()
    {
        $leaderboardId = $this->getEvent()->getRouteMatch()->getParam('leaderboardId');
        $leaderboard = $this->getLeaderboardTypeService()->findById($leaderboardId);

        $form = $this->getServiceLocator()->get('playgroundreward_leaderboard_form');

        $request = $this->getRequest();

        $form->bind($leaderboard);

        if ($request->isPost()) {
            $data = array_merge(
                $request->getPost()->toArray(),
                $request->getFiles()->toArray()
            );

            $leaderboard = $this->getLeaderboardTypeService()->edit(
                $data,
                $leaderboard,
                'playgroundreward_leaderboard_form'
            );

            if ($leaderboard) {
                $this->flashMessenger()->addMessage('The leaderboard "'.$leaderboard->getName().'" has been updated');

                return $this->redirect()->toRoute('admin/leaderboardtype/list');
            } else {
                $this->flashMessenger()->addMessage('The leaderboard was not updated');

                return $this->redirect()->toRoute('admin/leaderboardtype/list');
            }
        }

        $viewModel = new ViewModel();
        $viewModel->setTemplate('playground-reward/leader-board-type/leaderboardtype');

        return $viewModel->setVariables(array('form' => $form));
    }
579667
protected function execUpdateForm()
    {
        // form translations
        $this->loadTranslations('form', sprintf('private/global/locales/%s/form.ini', LANGUAGE));
        // get record
        $this->templateParameters['record'] = $this->getByPrimaryKey($this->primaryKeyValue);
        // render template
        $this->renderTemplate(sprintf('%s/%s/save-form', AREA, $this->name));
    }
96429
public function updateAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth($this->resourceCode, $this->getModuleCode(), AccessManager::UPDATE)) {
            return $response;
        }

        // Load object if exist
        if (null !== $object = $this->getExistingObject()) {
            // Hydrate the form abd pass it to the parser
            $changeForm = $this->hydrateObjectForm($object);

            // Pass it to the parser
            $this->getParserContext()->addForm($changeForm);
        }

        // Render the edition template.
        return $this->renderEditionTemplate();
    }
1017139
public function getRecord() {
		$form = $this->getForm();
		if (!$this->record && $form) {
			if (($record = $form->getRecord()) && ($record instanceof DataObject)) {
				$this->record = $record;
			} elseif (($controller = $form->Controller())
				&& $controller->hasMethod('data')
				&& ($record = $controller->data())
				&& ($record instanceof DataObject)
			) {
				$this->setRecord($record);
			}
		}
		return $this->record;
	}
1186631
public function view($request) {
        if(!$this->record->canView()) {
            $this->httpError(403);
        }
        
        $controller=$this->getToplevelController();
        $form=$this->ItemEditForm($this->gridField, $request);
        $form->makeReadonly();
        
        
        return $controller->customise(array(
                                            'Title'=>($this->record && $this->record->ID ? $this->record->Title:sprintf(_t('GridField.NewRecord', 'New %s'), $this->record->i18n_singular_name())),
                                            'ItemEditForm'=>$form
                                        ))->renderWith($this->template);
    }
366219
public function editAction()
    {
        $id = $this->params()->fromRoute('id');
        $ids = [];
        if (! empty($id) && ! is_array($id)) {
            $ids = explode(',', $id);
        }
        if (empty($ids)) {
            $this->flashMessenger()->addMessage(
                $this->scTranslate('The file ID(s) was not specified.')
            );
            return $this->redirect()
                ->toRoute('sc-admin/content-manager')
                ->setStatusCode(303);
        }

        try {
            $filesList = $this->getFileService()->getFilesList($ids);
        } catch (RuntimeException $e) {
            $this->flashMessenger()->addMessage($e->getMessage());
            return $this->redirect()
                ->toRoute('sc-admin/content-manager')
                ->setStatusCode(303);
        }
        if ($filesList->isEmpty()) {
            $this->flashMessenger()->addMessage(
                $this->scTranslate('No files, available for editing.')
            );
            return $this->redirect()
                ->toRoute('sc-admin/content-manager')
                ->setStatusCode(303);
        }

        $form = $this->getFileEditForm();
        $form->setAttribute(
            'action',
            $this->url()->fromRoute(
                'sc-admin/file/edit',
                ['id' => $id]
            )
        );
        $form->bind($filesList);
        if ($this->getRequest()->isPost()) {
            $form->setData($this->params()->fromPost());
            if ($form->isValid()) {
                $this->getFileService()->saveFiles($filesList);
            }
        }
        return new ViewModel([
            'form' => $form
        ]);
    }
924641
public function edit(int $id)
    {
        if ($objectInfo = $this->model->findFirst($id)) {
            //update
            if ($objectInfo->update($this->request->getPut(), $this->updateFields)) {
                return $this->response($objectInfo->toArray());
            } else {
                //didnt work
                throw new Exception($objectInfo->getMessages()[0]);
            }
        } else {
            throw new Exception('Record not found');
        }
    }
225780
public function edit() {
        if ($this->request->is('post') && !empty($this->request->data)) {
            if (isset($this->request->data['data'])) {
                foreach ($this->request->data['data'] ?? [] as $attribute => $value) {
                    $this->request->data[$attribute] = $value;
                    unset($this->request->data['data'][$attribute]);
                }
                if (empty($this->request->data['data'])) {
                    unset($this->request->data['data']);
                }
            }

            $data = $this->request->data ?? [];

            $moduleClass = $this->request->data('meta.moduleId');
            /** @var Module $form */
            $form = new $moduleClass();

            $formSubmitted = $this->request->data('fetch') !== '1';

            if (!$formSubmitted) {
                $this->_renderModule($form);
            } else if ($form->execute($data)) {
                $formData = $form->process($data);
                $this->set([
                    'module' => $formData,
                    '_serialize' => ['module']
                ]);
            } else {
                $this->Flash->error($this->formErrorMessage, 'module');
                $this->_renderModule($form, true);
            }
        }
    }
835605
public function editAction()
    {
        $this->view->disable();
        $id     = $this->request->getPost('hidden_id');    
        $user   = Users::findFirstById($id);
        $msg    = "";
        if (!$user) {
            $alert = "sukses";
            $msg .= "User was not found";
        }

        if ($this->request->isPost()) {

            $user->assign([
                'name' => $this->request->getPost('name', 'striptags'),
                'profilesId' => $this->request->getPost('profile', 'int'),
                'email' => $this->request->getPost('email', 'email'),
                'banned' => $this->request->getPost('banned'),
                'suspended' => $this->request->getPost('suspended'),
                'active' => $this->request->getPost('active')
            ]);
            
            if (!$user->save()) {
                $alert = "error";
                foreach($user->getMessages() as $message)
                {
                    $msg .= $message ." ";
                }
            } else {
                $alert = "sukses";
                $msg .= "User was updated successfully";
            }
        }

        $response = new \Phalcon\Http\Response();
        $response->setContentType('application/json', 'UTF-8');
        $response->setJsonContent(array('_id' => $this->request->getPost("name"),'alert' => $alert, 'msg' => $msg ));
        return $response->send();
    }
796555
private function edit()
    {
        $item = Eresus_CMS::getLegacyKernel()->db->selectItem('users', "`id`='".arg('id')."'");
        $form = array(
            'name' => 'UserForm',
            'caption' => admUsersChangeUser.' №'.$item['id'],
            'width' => '400px',
            'fields' => array (
                array('type'=>'hidden','name'=>'update', 'value'=>$item['id']),
                array('type'=>'edit','name'=>'name','label'=>admUsersName,'maxlength'=>32,'width'=>'100%',
                    'value'=>$item['name'], 'pattern'=>'/.+/', 'errormsg'=>admUsersNameInvalid),
                array('type'=>'edit','name'=>'login','label'=>admUsersLogin,'maxlength'=>16,'width'=>'100%',
                    'value'=>$item['login'], 'pattern'=>'/^[a-z\d_]+$/', 'errormsg'=>admUsersLoginInvalid,
                    'access'=>ADMIN),
                array('type'=>'select','name'=>'access','label'=>admAccessLevel,
                    'values'=>array('2','3','4'),'items'=>array(ACCESSLEVEL2, ACCESSLEVEL3, ACCESSLEVEL4),
                    'value'=>$item['access'], 'disabled'=>$item['access'] == ROOT, 'access'=>ADMIN),
                array('type'=>'checkbox','name'=>'active','label'=>admUsersAccountState,
                    'value'=>$item['active'], 'access'=>ADMIN),
                array('type'=>'edit','name'=>'loginErrors','label'=>admUsersLoginErrors,'maxlength'=>2,
                    'width'=>'30px','value'=>$item['loginErrors'], 'access'=>ADMIN),
                array('type' => 'edit', 'name' => 'mail', 'label' => admUsersMail,
                    'maxlength' => 32, 'width' => '100%', 'value' => $item['mail'],
                    'access' => ADMIN),
            ),
            'buttons' => array(UserRights($this->access)?'ok':'', 'apply', 'cancel'),
        );

        $pswd = array(
            'name' => 'PasswordForm',
            'caption' => admUsersChangePassword,
            'width' => '400px',
            'fields' => array (
                array('type'=>'hidden','name'=>'password', 'value'=>$item['id']),
                array('type'=>'password','name'=>'pswd1','label'=>admUsersPassword,'maxlength'=>32,
                    'width'=>'100%'),
                array('type'=>'password','name'=>'pswd2','label'=>admUsersConfirmation,'maxlength'=>32,
                    'width'=>'100%', 'equal'=>'pswd1', 'errormsg'=>admUsersConfirmInvalid),
            ),
            'buttons' => array(UserRights($this->access)?'ok':'apply', 'cancel'),
        );

        /** @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $result = $page->renderForm($form) . "<br />\n" . $page->renderForm($pswd);
        return $result;
    }
348764
public function VersionsForm()
    {
        $id = $this->currentPageID();
        $page = $this->getRecord($id);
        $versionsHtml = '';

        $action = $this->getRequest()->param('Action');
        $versionID = $this->getRequest()->param('VersionID');
        $otherVersionID = $this->getRequest()->param('OtherVersionID');

        $showUnpublishedChecked = 0;
        $compareModeChecked = ($action == "compare");

        if ($page) {
            $versions = $page->allVersions();
            $versionID = (!$versionID) ? $page->Version : $versionID;

            if ($versions) {
                foreach ($versions as $k => $version) {
                    $active = false;

                    if ($version->Version == $versionID || $version->Version == $otherVersionID) {
                        $active = true;

                        if (!$version->WasPublished) {
                            $showUnpublishedChecked = 1;
                        }
                    }

                    $version->Active = ($active);
                }
            }

            $vd = new ViewableData();

            $versionsHtml = $vd->customise(array(
                'Versions' => $versions
            ))->renderWith($this->getTemplatesWithSuffix('_versions'));
        }

        $fields = new FieldList(
            new CheckboxField(
                'ShowUnpublished',
                _t('SilverStripe\\CMS\\Controllers\\CMSPageHistoryController.SHOWUNPUBLISHED', 'Show unpublished versions'),
                $showUnpublishedChecked
            ),
            new CheckboxField(
                'CompareMode',
                _t('SilverStripe\\CMS\\Controllers\\CMSPageHistoryController.COMPAREMODE', 'Compare mode (select two)'),
                $compareModeChecked
            ),
            new LiteralField('VersionsHtml', $versionsHtml),
            $hiddenID = new HiddenField('ID', false, "")
        );

        $form = Form::create(
            $this,
            'VersionsForm',
            $fields,
            new FieldList()
        )->setHTMLID('Form_VersionsForm');
        $form->loadDataFrom($this->getRequest()->requestVars());
        $hiddenID->setValue($id);
        $form->unsetValidator();

        $form
            ->addExtraClass('cms-versions-form') // placeholder, necessary for $.metadata() to work
            ->setAttribute('data-link-tmpl-compare', Controller::join_links($this->Link('compare'), '%s', '%s', '%s'))
            ->setAttribute('data-link-tmpl-show', Controller::join_links($this->Link('show'), '%s', '%s'));

        return $form;
    }