public function testGetFormFields()
 {
     $fields = singleton('FormScaffolderTest_Article')->getFrontEndFields();
     $form = new Form(new Controller(), 'TestForm', $fields, new FieldList());
     $form->loadDataFrom(singleton('FormScaffolderTest_Article'));
     $this->assertFalse($fields->hasTabSet(), 'getFrontEndFields() doesnt produce a TabSet by default');
 }
 /**
  * Attempt to find and authenticate member if possible from the given data
  *
  * @param array $data
  * @param Form $form
  * @param bool &$success Success flag
  * @return Member Found member, regardless of successful login
  */
 protected static function authenticate_member($data, $form, &$success)
 {
     // Default success to false
     $success = false;
     // Attempt to identify by temporary ID
     $member = null;
     $email = null;
     if (!empty($data['tempid'])) {
         // Find user by tempid, in case they are re-validating an existing session
         $member = Member::member_from_tempid($data['tempid']);
         if ($member) {
             $email = $member->Email;
         }
     }
     // Otherwise, get email from posted value instead
     /** @skipUpgrade */
     if (!$member && !empty($data['Email'])) {
         $email = $data['Email'];
     }
     // Check default login (see Security::setDefaultAdmin())
     $asDefaultAdmin = $email === Security::default_admin_username();
     if ($asDefaultAdmin) {
         // If logging is as default admin, ensure record is setup correctly
         $member = Member::default_admin();
         $success = !$member->isLockedOut() && Security::check_default_admin($email, $data['Password']);
         //protect against failed login
         if ($success) {
             return $member;
         }
     }
     // Attempt to identify user by email
     if (!$member && $email) {
         // Find user by email
         $member = Member::get()->filter(Member::config()->unique_identifier_field, $email)->first();
     }
     // Validate against member if possible
     if ($member && !$asDefaultAdmin) {
         $result = $member->checkPassword($data['Password']);
         $success = $result->valid();
     } else {
         $result = new ValidationResult(false, _t('Member.ERRORWRONGCRED'));
     }
     // Emit failure to member and form (if available)
     if (!$success) {
         if ($member) {
             $member->registerFailedLogin();
         }
         if ($form) {
             $form->sessionMessage($result->message(), 'bad');
         }
     } else {
         if ($member) {
             $member->registerSuccessfulLogin();
         }
     }
     return $member;
 }
 /**
  * @param Form $form
  *
  * @return string
  */
 public function generateFormID($form)
 {
     if ($id = $form->getHTMLID()) {
         return Convert::raw2htmlid($id);
     }
     $reflection = new ReflectionClass($form);
     $shortName = str_replace(array('.', '/'), '', $form->getName());
     return Convert::raw2htmlid($reflection->getShortName() . '_' . $shortName);
 }
 public function testFormValidation()
 {
     /** @skipUpgrade */
     $form = new Form(new Controller(), 'Form', new FieldList($field = new ConfirmedPasswordField('Password')), new FieldList());
     $form->loadDataFrom(array('Password' => array('_Password' => '123', '_ConfirmPassword' => '999')));
     $this->assertEquals('123', $field->children->first()->Value());
     $this->assertEquals('999', $field->children->last()->Value());
     $this->assertNotEquals($field->children->first()->Value(), $field->children->last()->Value());
 }
 public function testGetStateWithFieldValidationErrors()
 {
     $fields = new FieldList(new TextField('Title'));
     $actions = new FieldList();
     $validator = new RequiredFields('Title');
     $form = new Form(new Controller(), 'TestForm', $fields, $actions, $validator);
     $form->loadDataFrom(['Title' => null]);
     $this->assertFalse($form->validate());
     $formSchema = new FormSchema();
     $expected = ['id' => 'Form_TestForm', 'fields' => [['id' => 'Form_TestForm_Title', 'value' => null, 'message' => ['value' => ['html' => '"Title" is required'], 'type' => 'required'], 'data' => [], 'name' => 'Title'], ['id' => 'Form_TestForm_SecurityID', 'value' => $form->getSecurityToken()->getValue(), 'message' => null, 'data' => [], 'name' => 'SecurityID']], 'valid' => false, 'messages' => []];
     $state = $formSchema->getState($form);
     $this->assertInternalType('array', $state);
     $this->assertJsonStringEqualsJsonString(json_encode($expected), json_encode($state));
 }
 public function __construct($controller, $name, $fields = null, $actions = null, $validator = null)
 {
     if (!$fields) {
         $helpHtml = _t('MemberImportForm.Help1', '<p>Import users in <em>CSV format</em> (comma-separated values).' . ' <small><a href="#" class="toggle-advanced">Show advanced usage</a></small></p>');
         $helpHtml .= _t('MemberImportForm.Help2', '<div class="advanced">' . '<h4>Advanced usage</h4>' . '<ul>' . '<li>Allowed columns: <em>%s</em></li>' . '<li>Existing users are matched by their unique <em>Code</em> property, and updated with any new values from ' . 'the imported file.</li>' . '<li>Groups can be assigned by the <em>Groups</em> column. Groups are identified by their <em>Code</em> property, ' . 'multiple groups can be separated by comma. Existing group memberships are not cleared.</li>' . '</ul>' . '</div>');
         $importer = new MemberCsvBulkLoader();
         $importSpec = $importer->getImportSpec();
         $helpHtml = sprintf($helpHtml, implode(', ', array_keys($importSpec['fields'])));
         $fields = new FieldList(new LiteralField('Help', $helpHtml), $fileField = new FileField('CsvFile', DBField::create_field('HTMLFragment', _t('SecurityAdmin_MemberImportForm.FileFieldLabel', 'CSV File <small>(Allowed extensions: *.csv)</small>'))));
         $fileField->getValidator()->setAllowedExtensions(array('csv'));
     }
     if (!$actions) {
         $action = new FormAction('doImport', _t('SecurityAdmin_MemberImportForm.BtnImport', 'Import from CSV'));
         $action->addExtraClass('btn btn-secondary-outline ss-ui-button');
         $actions = new FieldList($action);
     }
     if (!$validator) {
         $validator = new RequiredFields('CsvFile');
     }
     parent::__construct($controller, $name, $fields, $actions, $validator);
     Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/vendor.js');
     Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/MemberImportForm.js');
     Requirements::css(FRAMEWORK_ADMIN_DIR . '/client/dist/styles/bundle.css');
     $this->addExtraClass('cms');
     $this->addExtraClass('import-form');
 }
 /**
  * Constructor
  *
  * @param Controller $controller The parent controller, necessary to create the appropriate form action tag.
  * @param string $name The method on the controller that will return this form object.
  * @param FieldList|FormField $fields All of the fields in the form - a {@link FieldList} of
  * {@link FormField} objects.
  * @param FieldList|FormAction $actions All of the action buttons in the form - a {@link FieldList} of
  */
 public function __construct($controller, $name, $fields = null, $actions = null)
 {
     if (isset($_REQUEST['BackURL'])) {
         $backURL = $_REQUEST['BackURL'];
     } else {
         $backURL = Session::get('BackURL');
     }
     if (!$fields) {
         $fields = new FieldList();
         // Security/changepassword?h=XXX redirects to Security/changepassword
         // without GET parameter to avoid potential HTTP referer leakage.
         // In this case, a user is not logged in, and no 'old password' should be necessary.
         if (Member::currentUser()) {
             $fields->push(new PasswordField("OldPassword", _t('Member.YOUROLDPASSWORD', "Your old password")));
         }
         $fields->push(new PasswordField("NewPassword1", _t('Member.NEWPASSWORD', "New Password")));
         $fields->push(new PasswordField("NewPassword2", _t('Member.CONFIRMNEWPASSWORD', "Confirm New Password")));
     }
     if (!$actions) {
         $actions = new FieldList(new FormAction("doChangePassword", _t('Member.BUTTONCHANGEPASSWORD', "Change Password")));
     }
     if (isset($backURL)) {
         $fields->push(new HiddenField('BackURL', 'BackURL', $backURL));
     }
     parent::__construct($controller, $name, $fields, $actions);
 }
 /**
  * Build the file selection form.
  *
  * @skipUpgrade
  * @return Form
  */
 public function Form()
 {
     // Find out the requested folder ID.
     $folderID = $this->parent->getRequest()->requestVar('ParentID');
     if ($folderID === null && $this->parent->getDisplayFolderName()) {
         $folder = Folder::find_or_make($this->parent->getDisplayFolderName());
         $folderID = $folder ? $folder->ID : 0;
     }
     // Construct the form
     $action = new FormAction('doAttach', _t('UploadField.AttachFile', 'Attach file(s)'));
     $action->addExtraClass('ss-ui-action-constructive icon-accept');
     $form = new Form($this, 'Form', new FieldList($this->getListField($folderID)), new FieldList($action));
     // Add a class so we can reach the form from the frontend.
     $form->addExtraClass('uploadfield-form');
     return $form;
 }
 /**
  * @return bool
  */
 public function Required()
 {
     if ($this->form && ($validator = $this->form->getValidator())) {
         return $validator->fieldIsRequired($this->name);
     }
     return false;
 }
 /**
  * Test different scenarii for a failed upload : an error occured, no files where provided
  */
 public function testUploadMissingRequiredFile()
 {
     /** @skipUpgrade */
     $form = new Form(new Controller(), 'Form', new FieldList($fileField = new FileField('cv', 'Upload your CV')), new FieldList(), new RequiredFields('cv'));
     // All fields are filled but for some reason an error occured when uploading the file => fails
     $fileFieldValue = array('name' => 'aCV.txt', 'type' => 'application/octet-stream', 'tmp_name' => '/private/var/tmp/phpzTQbqP', 'error' => 1, 'size' => 3471);
     $fileField->setValue($fileFieldValue);
     $this->assertFalse($form->validate(), 'An error occured when uploading a file, but the validator returned true');
     // We pass an empty set of parameters for the uploaded file => fails
     $fileFieldValue = array();
     $fileField->setValue($fileFieldValue);
     $this->assertFalse($form->validate(), 'An empty array was passed as parameter for an uploaded file, but the validator returned true');
     // We pass an null value for the uploaded file => fails
     $fileFieldValue = null;
     $fileField->setValue($fileFieldValue);
     $this->assertFalse($form->validate(), 'A null value was passed as parameter for an uploaded file, but the validator returned true');
 }
 /**
  * Test that data loaded in via Form::loadDataFrom(DataObject) will populate the field correctly,
  * and can format the database value appropriately for the frontend
  *
  * @param string $locale
  * @param array $tests
  */
 public function checkDataFormatting($locale, $tests)
 {
     i18n::set_locale($locale);
     $field = new NumericField('Number');
     /** @skipUpgrade */
     $form = new Form(new Controller(), 'Form', new FieldList($field), new FieldList());
     $dataObject = new NumericFieldTest_Object();
     foreach ($tests as $input => $output) {
         // Given a dataobject as a context, the field should assume the field value is not localised
         $dataObject->Number = (string) $input;
         $form->loadDataFrom($dataObject, Form::MERGE_CLEAR_MISSING);
         // Test value
         $this->assertEquals($input, $field->dataValue(), "Expected {$input} loaded via dataobject to be left intact in locale {$locale}");
         // Test expected formatted value (Substitute nbsp for spaces)
         $this->assertEquals($this->clean($output), $field->Value(), "Expected {$input} to be formatted as {$output} in locale {$locale}");
     }
 }
 public function testValidation()
 {
     $field = OptionsetField::create('Test', 'Testing', array("One" => "One", "Two" => "Two", "Five" => "Five"));
     $validator = new RequiredFields('Test');
     /** @skipUpgrade */
     $form = new Form($this, 'Form', new FieldList($field), new FieldList(), $validator);
     $field->setValue("One");
     $this->assertTrue($field->validate($validator));
     //non-existent value should make the field invalid
     $field->setValue("Three");
     $this->assertFalse($field->validate($validator));
     //empty string should pass field-level validation...
     $field->setValue('');
     $this->assertTrue($field->validate($validator));
     // ... but should not pass "RequiredFields" validation
     $this->assertFalse($form->validate());
     //disabled items shouldn't validate
     $field->setDisabledItems(array('Five'));
     $field->setValue('Five');
     $this->assertFalse($field->validate($validator));
 }
 /**
  * Gets the current state of this form as a nested array.
  *
  * @param Form $form
  * @return array
  */
 public function getState(Form $form)
 {
     // Ensure that session errors are populated within form field messages
     $form->setupFormErrors();
     // @todo - Replace with ValidationResult handling
     // Currently tri-state; null (unsubmitted), true (submitted-valid), false (submitted-invalid)
     $errors = Session::get("FormInfo.{$form->FormName()}.errors");
     $valid = isset($errors) ? empty($errors) : null;
     $state = ['id' => $form->FormName(), 'fields' => [], 'valid' => $valid, 'messages' => []];
     // flattened nested fields are returned, rather than only top level fields.
     $state['fields'] = array_merge($this->getFieldStates($form->Fields()), $this->getFieldStates($form->Actions()));
     if ($message = $form->Message()) {
         $state['messages'][] = ['value' => ['html' => $message], 'type' => $form->MessageType()];
     }
     return $state;
 }
 public function getForm(Controller $controller, $name = FormFactory::DEFAULT_NAME, $context = [])
 {
     // Validate context
     foreach ($this->getRequiredContext() as $required) {
         if (!isset($context[$required])) {
             throw new InvalidArgumentException("Missing required context {$required}");
         }
     }
     $fields = $this->getFormFields($controller, $name, $context);
     $actions = $this->getFormActions($controller, $name, $context);
     $validator = new RequiredFields('Name');
     $form = Form::create($controller, $name, $fields, $actions, $validator);
     // Extend form
     $this->invokeWithExtensions('updateForm', $form, $controller, $name, $context);
     // Populate form from record
     $form->loadDataFrom($context['Record']);
     return $form;
 }
 public function __construct($controller, $name, $fields = null, $actions = null, $validator = null)
 {
     if (!$fields) {
         $helpHtml = _t('GroupImportForm.Help1', '<p>Import one or more groups in <em>CSV</em> format (comma-separated values).' . ' <small><a href="#" class="toggle-advanced">Show advanced usage</a></small></p>');
         $helpHtml .= _t('GroupImportForm.Help2', '<div class="advanced">' . '<h4>Advanced usage</h4>' . '<ul>' . '<li>Allowed columns: <em>%s</em></li>' . '<li>Existing groups are matched by their unique <em>Code</em> value, and updated with any new values from the ' . 'imported file</li>' . '<li>Group hierarchies can be created by using a <em>ParentCode</em> column.</li>' . '<li>Permission codes can be assigned by the <em>PermissionCode</em> column. Existing permission codes are not ' . 'cleared.</li>' . '</ul>' . '</div>');
         $importer = new GroupCsvBulkLoader();
         $importSpec = $importer->getImportSpec();
         $helpHtml = sprintf($helpHtml, implode(', ', array_keys($importSpec['fields'])));
         $fields = new FieldList(new LiteralField('Help', $helpHtml), $fileField = new FileField('CsvFile', DBField::create_field('HTMLFragment', _t('SecurityAdmin_MemberImportForm.FileFieldLabel', 'CSV File <small>(Allowed extensions: *.csv)</small>'))));
         $fileField->getValidator()->setAllowedExtensions(array('csv'));
     }
     if (!$actions) {
         $action = new FormAction('doImport', _t('SecurityAdmin_MemberImportForm.BtnImport', 'Import from CSV'));
         $action->addExtraClass('ss-ui-button');
         $actions = new FieldList($action);
     }
     if (!$validator) {
         $validator = new RequiredFields('CsvFile');
     }
     parent::__construct($controller, $name, $fields, $actions, $validator);
     $this->addExtraClass('cms');
     $this->addExtraClass('import-form');
 }
 public function submit($data, Form $form)
 {
     $record = $this->getRecord();
     $form->saveInto($record);
     $record->write();
     return json_encode($record->toMap());
 }
 function Form()
 {
     $form = new Form($this, 'Form', new FieldList(new EmailField('Email')), new FieldList(new FormAction('doSubmit')), new RequiredFields('Email'));
     // Disable CSRF protection for easier form submission handling
     $form->disableSecurityToken();
     return $form;
 }
 public function getExtraFields()
 {
     $fields = parent::getExtraFields();
     $fields->push(new CheckboxField('ExtraFieldCheckbox', 'Extra Field Checkbox', 1));
     return $fields;
 }
 /**
  * @return Form
  */
 public function BatchActionsForm()
 {
     $actions = $this->batchactions()->batchActionList();
     $actionsMap = array('-1' => _t('LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...'));
     // Placeholder action
     foreach ($actions as $action) {
         $actionsMap[$action->Link] = $action->Title;
     }
     $form = new Form($this, 'BatchActionsForm', new FieldList(new HiddenField('csvIDs'), DropdownField::create('Action', false, $actionsMap)->setAttribute('autocomplete', 'off')->setAttribute('data-placeholder', _t('LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...'))), new FieldList(new FormAction('submit', _t('Form.SubmitBtnLabel', "Go"))));
     $form->addExtraClass('cms-batch-actions form--no-dividers');
     $form->unsetValidator();
     $this->extend('updateBatchActionsForm', $form);
     return $form;
 }
 /**
  * This is the action that gets executed when a GridField_AlterAction gets clicked.
  *
  * @param array $data
  * @param Form $form
  * @param HTTPRequest $request
  *
  * @return string
  */
 public function gridFieldAlterAction($data, $form, HTTPRequest $request)
 {
     $data = $request->requestVars();
     // Protection against CSRF attacks
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         $this->httpError(400, _t("Form.CSRF_FAILED_MESSAGE", "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again."));
     }
     $name = $this->getName();
     $fieldData = null;
     if (isset($data[$name])) {
         $fieldData = $data[$name];
     }
     $state = $this->getState(false);
     /** @skipUpgrade */
     if (isset($fieldData['GridState'])) {
         $state->setValue($fieldData['GridState']);
     }
     foreach ($data as $dataKey => $dataValue) {
         if (preg_match('/^action_gridFieldAlterAction\\?StateID=(.*)/', $dataKey, $matches)) {
             $stateChange = Session::get($matches[1]);
             $actionName = $stateChange['actionName'];
             $arguments = array();
             if (isset($stateChange['args'])) {
                 $arguments = $stateChange['args'];
             }
             $html = $this->handleAlterAction($actionName, $arguments, $data);
             if ($html) {
                 return $html;
             }
         }
     }
     if ($request->getHeader('X-Pjax') === 'CurrentField') {
         return $this->FieldHolder();
     }
     return $form->forTemplate();
 }
 /**
  * @param Form $form
  */
 public function updateImageForm($form)
 {
     self::$update_called = true;
     self::$fields = $form->Fields();
 }
 /**
  * Imports the submitted CSV file based on specifications given in
  * {@link self::model_importers}.
  * Redirects back with a success/failure message.
  *
  * @todo Figure out ajax submission of files via jQuery.form plugin
  *
  * @param array $data
  * @param Form $form
  * @param HTTPRequest $request
  * @return bool|HTTPResponse
  */
 public function import($data, $form, $request)
 {
     if (!$this->showImportForm || is_array($this->showImportForm) && !in_array($this->modelClass, $this->showImportForm)) {
         return false;
     }
     $importers = $this->getModelImporters();
     /** @var BulkLoader $loader */
     $loader = $importers[$this->modelClass];
     // File wasn't properly uploaded, show a reminder to the user
     if (empty($_FILES['_CsvFile']['tmp_name']) || file_get_contents($_FILES['_CsvFile']['tmp_name']) == '') {
         $form->sessionMessage(_t('ModelAdmin.NOCSVFILE', 'Please browse for a CSV file to import'), 'good');
         $this->redirectBack();
         return false;
     }
     if (!empty($data['EmptyBeforeImport']) && $data['EmptyBeforeImport']) {
         //clear database before import
         $loader->deleteExistingRecords = true;
     }
     $results = $loader->load($_FILES['_CsvFile']['tmp_name']);
     $message = '';
     if ($results->CreatedCount()) {
         $message .= _t('ModelAdmin.IMPORTEDRECORDS', "Imported {count} records.", array('count' => $results->CreatedCount()));
     }
     if ($results->UpdatedCount()) {
         $message .= _t('ModelAdmin.UPDATEDRECORDS', "Updated {count} records.", array('count' => $results->UpdatedCount()));
     }
     if ($results->DeletedCount()) {
         $message .= _t('ModelAdmin.DELETEDRECORDS', "Deleted {count} records.", array('count' => $results->DeletedCount()));
     }
     if (!$results->CreatedCount() && !$results->UpdatedCount()) {
         $message .= _t('ModelAdmin.NOIMPORT', "Nothing to import");
     }
     $form->sessionMessage($message, 'good');
     return $this->redirectBack();
 }
 /**
  * Return a {@link Form} instance allowing a user to
  * add images and flash objects to the TinyMCE content editor.
  *
  * @return Form
  */
 public function MediaForm()
 {
     // TODO Handle through GridState within field - currently this state set too late to be useful here (during
     // request handling)
     $parentID = $this->getAttachParentID();
     $fileFieldConfig = GridFieldConfig::create()->addComponents(new GridFieldSortableHeader(), new GridFieldFilterHeader(), new GridFieldDataColumns(), new GridFieldPaginator(7), new GridFieldDeleteAction(), new GridFieldDetailForm());
     $fileField = GridField::create('Files', false, null, $fileFieldConfig);
     $fileField->setList($this->getFiles($parentID));
     $fileField->setAttribute('data-selectable', true);
     $fileField->setAttribute('data-multiselect', true);
     /** @var GridFieldDataColumns $columns */
     $columns = $fileField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
     $columns->setDisplayFields(array('StripThumbnail' => false, 'Title' => _t('File.Title'), 'Created' => File::singleton()->fieldLabel('Created')));
     $columns->setFieldCasting(array('Created' => 'DBDatetime->Nice'));
     $fromCMS = new CompositeField($select = TreeDropdownField::create('ParentID', "", 'SilverStripe\\Assets\\Folder')->addExtraClass('noborder')->setValue($parentID), $fileField);
     $fromCMS->addExtraClass('content ss-uploadfield htmleditorfield-from-cms');
     $select->addExtraClass('content-select');
     $URLDescription = _t('HTMLEditorField.URLDESCRIPTION', 'Insert videos and images from the web into your page simply by entering the URL of the file. Make sure you have the rights or permissions before sharing media directly from the web.<br /><br />Please note that files are not added to the file store of the CMS but embeds the file from its original location, if for some reason the file is no longer available in its original location it will no longer be viewable on this page.');
     $fromWeb = new CompositeField($description = new LiteralField('URLDescription', '<div class="url-description">' . $URLDescription . '</div>'), $remoteURL = new TextField('RemoteURL', 'http://'), new LiteralField('addURLImage', '<button type="button" class="action ui-action-constructive ui-button field font-icon-plus add-url">' . _t('HTMLEditorField.BUTTONADDURL', 'Add url') . '</button>'));
     $remoteURL->addExtraClass('remoteurl');
     $fromWeb->addExtraClass('content ss-uploadfield htmleditorfield-from-web');
     Requirements::css(ltrim(FRAMEWORK_ADMIN_DIR . '/client/dist/styles/AssetUploadField.css', '/'));
     $computerUploadField = UploadField::create('AssetUploadField', '');
     $computerUploadField->setConfig('previewMaxWidth', 40);
     $computerUploadField->setConfig('previewMaxHeight', 30);
     $computerUploadField->addExtraClass('toolbar toolbar--content ss-assetuploadfield htmleditorfield-from-computer');
     $computerUploadField->removeExtraClass('ss-uploadfield');
     $computerUploadField->setTemplate('SilverStripe\\Forms\\HTMLEditorField_UploadField');
     $computerUploadField->setFolderName(Upload::config()->get('uploads_folder'));
     $defaultPanel = new CompositeField($computerUploadField, $fromCMS);
     $fromWebPanel = new CompositeField($fromWeb);
     $defaultPanel->addExtraClass('htmleditorfield-default-panel');
     $fromWebPanel->addExtraClass('htmleditorfield-web-panel');
     $allFields = new CompositeField($defaultPanel, $fromWebPanel, $editComposite = new CompositeField(new LiteralField('contentEdit', '<div class="content-edit ss-uploadfield-files files"></div>')));
     $allFields->addExtraClass('ss-insert-media');
     $headings = new CompositeField(new LiteralField('Heading', sprintf('<h3 class="htmleditorfield-mediaform-heading insert">%s</h3>', _t('HTMLEditorField.INSERTMEDIA', 'Insert media from')) . sprintf('<h3 class="htmleditorfield-mediaform-heading update">%s</h3>', _t('HTMLEditorField.UpdateMEDIA', 'Update media'))));
     $headings->addExtraClass('cms-content-header');
     $editComposite->addExtraClass('ss-assetuploadfield');
     $fields = new FieldList($headings, $allFields);
     $form = new Form($this->controller, "{$this->name}/MediaForm", $fields, new FieldList());
     $form->unsetValidator();
     $form->disableSecurityToken();
     $form->loadDataFrom($this);
     $form->addExtraClass('htmleditorfield-form htmleditorfield-mediaform cms-dialog-content');
     // Allow other people to extend the fields being added to the imageform
     $this->extend('updateMediaForm', $form);
     return $form;
 }
 public function __construct()
 {
     parent::__construct(Controller::curr(), __CLASS__, new FieldList(new TextField('Email'), new TextField('Surname'), new TextField('ID'), new TextField('FirstName')), new FieldList(new FormAction('someAction')));
 }
 public function testLoadDataFromObject()
 {
     $article = $this->objFromFixture('CheckboxSetFieldTest_Article', 'articlewithouttags');
     $articleWithTags = $this->objFromFixture('CheckboxSetFieldTest_Article', 'articlewithtags');
     $tag1 = $this->objFromFixture('CheckboxSetFieldTest_Tag', 'tag1');
     $tag2 = $this->objFromFixture('CheckboxSetFieldTest_Tag', 'tag2');
     $field = new CheckboxSetField("Tags", "Test field", DataObject::get("CheckboxSetFieldTest_Tag")->map());
     /** @skipUpgrade */
     $form = new Form(new Controller(), 'Form', new FieldList($field), new FieldList());
     $form->loadDataFrom($articleWithTags);
     $value = $field->Value();
     sort($value);
     $this->assertEquals(array($tag1->ID, $tag2->ID), $value, 'CheckboxSetField loads data from a manymany relationship in an object through Form->loadDataFrom()');
 }
 public function getEditForm($id = null, $fields = null)
 {
     // TODO Duplicate record fetching (see parent implementation)
     if (!$id) {
         $id = $this->currentPageID();
     }
     $form = parent::getEditForm($id);
     // TODO Duplicate record fetching (see parent implementation)
     $record = $this->getRecord($id);
     if ($record && !$record->canView()) {
         return Security::permissionFailure($this);
     }
     $memberList = GridField::create('Members', false, Member::get(), $memberListConfig = GridFieldConfig_RecordEditor::create()->addComponent(new GridFieldButtonRow('after'))->addComponent(new GridFieldExportButton('buttons-after-left')))->addExtraClass("members_grid");
     if ($record && method_exists($record, 'getValidator')) {
         $validator = $record->getValidator();
     } else {
         $validator = Member::singleton()->getValidator();
     }
     /** @var GridFieldDetailForm $detailForm */
     $detailForm = $memberListConfig->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDetailForm');
     $detailForm->setValidator($validator);
     $groupList = GridField::create('Groups', false, Group::get(), GridFieldConfig_RecordEditor::create());
     /** @var GridFieldDataColumns $columns */
     $columns = $groupList->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
     $columns->setDisplayFields(array('Breadcrumbs' => Group::singleton()->fieldLabel('Title')));
     $columns->setFieldFormatting(array('Breadcrumbs' => function ($val, $item) {
         /** @var Group $item */
         return Convert::raw2xml($item->getBreadcrumbs(' > '));
     }));
     $fields = new FieldList($root = new TabSet('Root', $usersTab = new Tab('Users', _t('SecurityAdmin.Users', 'Users'), new LiteralField('MembersCautionText', sprintf('<div class="alert alert-warning" role="alert">%s</div>', _t('SecurityAdmin.MemberListCaution', 'Caution: Removing members from this list will remove them from all groups and the database'))), $memberList), $groupsTab = new Tab('Groups', singleton('SilverStripe\\Security\\Group')->i18n_plural_name(), $groupList)), new HiddenField('ID', false, 0));
     // Add import capabilities. Limit to admin since the import logic can affect assigned permissions
     if (Permission::check('ADMIN')) {
         $fields->addFieldsToTab('Root.Users', array(new HeaderField('ImportUsersHeader', _t('SecurityAdmin.IMPORTUSERS', 'Import users'), 3), new LiteralField('MemberImportFormIframe', sprintf('<iframe src="%s" id="MemberImportFormIframe" width="100%%" height="330px" frameBorder="0">' . '</iframe>', $this->Link('memberimport')))));
         $fields->addFieldsToTab('Root.Groups', array(new HeaderField('ImportGroupsHeader', _t('SecurityAdmin.IMPORTGROUPS', 'Import groups'), 3), new LiteralField('GroupImportFormIframe', sprintf('<iframe src="%s" id="GroupImportFormIframe" width="100%%" height="330px" frameBorder="0">' . '</iframe>', $this->Link('groupimport')))));
     }
     // Tab nav in CMS is rendered through separate template
     $root->setTemplate('SilverStripe\\Forms\\CMSTabSet');
     // Add roles editing interface
     $rolesTab = null;
     if (Permission::check('APPLY_ROLES')) {
         $rolesField = GridField::create('Roles', false, PermissionRole::get(), GridFieldConfig_RecordEditor::create());
         $rolesTab = $fields->findOrMakeTab('Root.Roles', _t('SecurityAdmin.TABROLES', 'Roles'));
         $rolesTab->push($rolesField);
     }
     $actionParam = $this->getRequest()->param('Action');
     if ($actionParam == 'groups') {
         $groupsTab->addExtraClass('ui-state-active');
     } elseif ($actionParam == 'users') {
         $usersTab->addExtraClass('ui-state-active');
     } elseif ($actionParam == 'roles' && $rolesTab) {
         $rolesTab->addExtraClass('ui-state-active');
     }
     $actions = new FieldList();
     $form = Form::create($this, 'EditForm', $fields, $actions)->setHTMLID('Form_EditForm');
     $form->addExtraClass('cms-edit-form fill-height');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     // Tab nav in CMS is rendered through separate template
     if ($form->Fields()->hasTabSet()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('SilverStripe\\Forms\\CMSTabSet');
     }
     $form->addExtraClass('ss-tabset cms-tabset ' . $this->BaseCSSClasses());
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $this->extend('updateEditForm', $form);
     return $form;
 }
 /**
  * Returns any errors there may be.
  *
  * @return null|array
  */
 public function validate()
 {
     $this->errors = null;
     $this->php($this->form->getData());
     return $this->errors;
 }
 /**
  * @param Form $form
  * @param string $message
  */
 protected function setFormMessage($form, $message)
 {
     $form->sessionMessage($message, 'good', false);
     $controller = $this->getToplevelController();
     if ($controller->hasMethod('getEditForm')) {
         $backForm = $controller->getEditForm();
         $backForm->sessionMessage($message, 'good', false);
     }
 }
 /**
  * @todo Use GridFieldDetailForm once it can handle structured data and form schemas
  *
  * @param int $id
  * @return Form
  */
 public function getDetailEditForm($id)
 {
     // Get record-specific fields
     $record = null;
     if ($id) {
         $record = ChangeSet::get()->byID($id);
         if (!$record || !$record->canView()) {
             return null;
         }
     }
     if (!$record) {
         $record = ChangeSet::singleton();
     }
     $fields = $record->getCMSFields();
     // Add standard fields
     $fields->push(HiddenField::create('ID'));
     $form = Form::create($this, 'DetailEditForm', $fields, FieldList::create(FormAction::create('save', _t('CMSMain.SAVE', 'Save'))->setIcon('save'), FormAction::create('cancel', _t('LeftAndMain.CANCEL', 'Cancel'))->setUseButtonTag(true)));
     // Load into form
     if ($id && $record) {
         $form->loadDataFrom($record);
     }
     $form->getValidator()->addRequiredField('Name');
     // Configure form to respond to validation errors with form schema
     // if requested via react.
     $form->setValidationResponseCallback(function () use($form, $record) {
         $schemaId = Controller::join_links($this->Link('schema/DetailEditForm'), $record->exists() ? $record->ID : '');
         return $this->getSchemaResponse($form, $schemaId);
     });
     return $form;
 }
 /**
  * @param array $data
  * @param Form $form
  * @param HTTPRequest $request
  * @return DBHTMLText
  */
 public function doEdit(array $data, Form $form, HTTPRequest $request)
 {
     // Check form field state
     if ($this->parent->isDisabled() || $this->parent->isReadonly()) {
         return $this->httpError(403);
     }
     // Check item permissions
     $item = $this->getItem();
     if (!$item) {
         return $this->httpError(404);
     }
     if ($item instanceof Folder) {
         return $this->httpError(403);
     }
     if (!$item->canEdit()) {
         return $this->httpError(403);
     }
     $form->saveInto($item);
     $item->write();
     $form->sessionMessage(_t('UploadField.Saved', 'Saved'), 'good');
     return $this->edit($request);
 }