コード例 #1
1
 /**
  * Removes an existing formfield instance by its name.
  *
  * @param string $fieldName
  */
 public function removeFieldByName($fieldName)
 {
     $this->fields->removeByName($fieldName);
 }
コード例 #2
0
 public function __construct($name, $title = null, $value = '', $extension = null, $areaCode = null, $countryCode = null)
 {
     $this->areaCode = $areaCode;
     $this->ext = $extension;
     $this->countryCode = $countryCode;
     // Build fields
     $fields = new FieldList();
     if ($this->countryCode !== null) {
         $countryField = NumericField::create($name . '[Country]', false, $countryCode, 4)->addExtraClass('phonenumber-field__country');
         $fields->push($countryField);
     }
     if ($this->areaCode !== null) {
         $areaField = NumericField::create($name . '[Area]', false, $areaCode, 4)->addExtraClass('phonenumber-field__area');
         $fields->push($areaField);
     }
     $numberField = NumericField::create($name . '[Number]', false, null, 10)->addExtraClass('phonenumber-field__number');
     $fields->push($numberField);
     if ($this->ext !== null) {
         $extensionField = NumericField::create($name . '[Extension]', false, $extension, 6)->addExtraClass('phonenumber-field__extension');
         $fields->push($extensionField);
     }
     parent::__construct($title, $fields);
     $this->setName($name);
     if (isset($value)) {
         $this->setValue($value);
     }
 }
コード例 #3
0
 public function __construct(Controller $controller, $name)
 {
     // Set default fields
     $fields = new FieldList(HiddenField::create("AuthenticationMethod", null, $this->authenticator_class, $this), HiddenField::create('tempid', null, $controller->getRequest()->requestVar('tempid')), PasswordField::create("Password", _t('Member.PASSWORD', 'Password')), LiteralField::create('forgotPassword', sprintf('<p id="ForgotPassword"><a href="%s" target="_top">%s</a></p>', $this->getExternalLink('lostpassword'), _t('CMSMemberLoginForm.BUTTONFORGOTPASSWORD', "Forgot password?"))));
     if (Security::config()->autologin_enabled) {
         $fields->push(CheckboxField::create("Remember", _t('Member.REMEMBERME', "Remember me next time?")));
     }
     // Determine returnurl to redirect to parent page
     $logoutLink = $this->getExternalLink('logout');
     if ($returnURL = $controller->getRequest()->requestVar('BackURL')) {
         $logoutLink = Controller::join_links($logoutLink, '?BackURL=' . urlencode($returnURL));
     }
     // Make actions
     $actions = new FieldList(FormAction::create('dologin', _t('CMSMemberLoginForm.BUTTONLOGIN', "Log back in")), LiteralField::create('doLogout', sprintf('<p id="doLogout"><a href="%s" target="_top">%s</a></p>', $logoutLink, _t('CMSMemberLoginForm.BUTTONLOGOUT', "Log out"))));
     parent::__construct($controller, $name, $fields, $actions);
 }
コード例 #4
0
 /**
  * Return the default button that should be clicked when another one isn't
  * available.
  *
  * @return FormAction
  */
 public function defaultAction()
 {
     if ($this->hasDefaultAction && $this->actions) {
         return $this->actions->first();
     }
     return null;
 }
コード例 #5
0
 /**
  * Returns the root field set that this belongs to
  *
  * @return FieldList|FormField
  */
 public function rootFieldList()
 {
     if ($this->containerField) {
         return $this->containerField->rootFieldList();
     }
     return $this;
 }
コード例 #6
0
 /**
  * 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);
 }
コード例 #7
0
 /**
  * Transform the named field into a readonly feld.
  *
  * @param string|FormField
  * @return bool
  */
 public function makeFieldReadonly($field)
 {
     $fieldName = $field instanceof FormField ? $field->getName() : $field;
     // Iterate on items, looking for the applicable field
     foreach ($this->children as $i => $item) {
         if ($item instanceof CompositeField) {
             if ($item->makeFieldReadonly($fieldName)) {
                 return true;
             }
         } elseif ($item instanceof FormField && $item->getName() == $fieldName) {
             // Once it's found, use FormField::transform to turn the field into a readonly version of itself.
             $this->children->replaceField($fieldName, $item->transform(new ReadonlyTransformation()));
             // A true results indicates that the field was found
             return true;
         }
     }
     return false;
 }
コード例 #8
0
 public function getCMSFields()
 {
     $path = '/' . dirname($this->getFilename());
     $previewLink = Convert::raw2att($this->PreviewLink());
     $image = "<img src=\"{$previewLink}\" class=\"editor__thumbnail\" />";
     $link = $this->Link();
     $statusTitle = $this->getStatusTitle();
     $statusFlag = "<span class=\"editor__status-flag\">{$statusTitle}</span>";
     $content = Tab::create('Main', HeaderField::create('TitleHeader', $this->Title, 1)->addExtraClass('editor__heading'), LiteralField::create("ImageFull", $image)->addExtraClass('editor__file-preview'), TabSet::create('Editor', Tab::create('Details', TextField::create("Title", $this->fieldLabel('Title')), TextField::create("Name", $this->fieldLabel('Filename')), ReadonlyField::create("Path", _t('AssetTableField.PATH', 'Path'), ($path !== '/.' ? $path : '') . '/'), HTMLReadonlyField::create('ClickableURL', _t('AssetTableField.URL', 'URL'), sprintf('<i class="%s"></i><a href="%s" target="_blank">%s</a>', 'font-icon-link btn--icon-large form-control-static__icon', $link, $link))), Tab::create('Usage', DatetimeField::create("Created", _t('AssetTableField.CREATED', 'First uploaded'))->setReadonly(true), DatetimeField::create("LastEdited", _t('AssetTableField.LASTEDIT', 'Last changed'))->setReadonly(true))), HiddenField::create('ID', $this->ID));
     if ($dimensions = $this->getDimensions()) {
         $content->insertAfter('TitleHeader', LiteralField::create("DisplaySize", sprintf('<div class="editor__specs">%spx, %s %s</div>', $dimensions, $this->getSize(), $statusFlag)));
     } else {
         $content->insertAfter('TitleHeader', LiteralField::create('StatusFlag', $statusFlag));
     }
     $fields = FieldList::create(TabSet::create('Root', $content));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
コード例 #9
0
 public function getCMSFields()
 {
     $fields = new FieldList(new TabSet('Root'));
     if ($this->IsInferred) {
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('Name', $this->fieldLabel('Name')));
     } else {
         $fields->addFieldToTab('Root.Main', TextField::create('Name', $this->fieldLabel('Name')));
     }
     if ($this->isInDB()) {
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('State', $this->fieldLabel('State')));
     }
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
コード例 #10
0
 /**
  * @inheritdoc
  */
 public function updateCMSFields(FieldList $fields)
 {
     $analyticsFields = FieldList::create(TextField::create("GoogleAnalyticsTrackingID", "Google Analytics Tracking ID")->setDescription("e.g. UA-XXXXXX-X"), TextareaField::create("GoogleAnalyticsParameters", "Additional Parameters")->setDescription("<strong>Advanced users only.</strong>\n\t\t\t\t\tIf you do not know what this field does, please leave it blank."), TextareaField::create("GoogleAnalyticsConstructorParameters", "Constructor Parameters")->setDescription("<strong>Advanced users only.</strong>\n\t\t\t\t\tIf you do not know what this field does, please leave it blank. An object to be\n\t\t\t\t\tpassed as an argument to ga.create()"));
     $fields->addFieldToTab('Root', Tab::create('GoogleAnalytics')->setChildren($analyticsFields));
 }
コード例 #11
0
 /**
  * Generate a CSV import form for a single {@link DataObject} subclass.
  *
  * @return Form|false
  */
 public function ImportForm()
 {
     $modelSNG = singleton($this->modelClass);
     $modelName = $modelSNG->i18n_singular_name();
     // check if a import form should be generated
     if (!$this->showImportForm || is_array($this->showImportForm) && !in_array($this->modelClass, $this->showImportForm)) {
         return false;
     }
     $importers = $this->getModelImporters();
     if (!$importers || !isset($importers[$this->modelClass])) {
         return false;
     }
     if (!$modelSNG->canCreate(Member::currentUser())) {
         return false;
     }
     $fields = new FieldList(new HiddenField('ClassName', _t('ModelAdmin.CLASSTYPE'), $this->modelClass), new FileField('_CsvFile', false));
     // get HTML specification for each import (column names etc.)
     $importerClass = $importers[$this->modelClass];
     /** @var BulkLoader $importer */
     $importer = new $importerClass($this->modelClass);
     $spec = $importer->getImportSpec();
     $specFields = new ArrayList();
     foreach ($spec['fields'] as $name => $desc) {
         $specFields->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
     }
     $specRelations = new ArrayList();
     foreach ($spec['relations'] as $name => $desc) {
         $specRelations->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
     }
     $specHTML = $this->customise(array('ClassName' => $this->sanitiseClassName($this->modelClass), 'ModelName' => Convert::raw2att($modelName), 'Fields' => $specFields, 'Relations' => $specRelations))->renderWith($this->getTemplatesWithSuffix('_ImportSpec'));
     $fields->push(new LiteralField("SpecFor{$modelName}", $specHTML));
     $fields->push(new CheckboxField('EmptyBeforeImport', _t('ModelAdmin.EMPTYBEFOREIMPORT', 'Replace data'), false));
     $actions = new FieldList(new FormAction('import', _t('ModelAdmin.IMPORT', 'Import from CSV')));
     $form = new Form($this, "ImportForm", $fields, $actions);
     $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'ImportForm'));
     $this->extend('updateImportForm', $form);
     return $form;
 }
コード例 #12
0
 /**
  * @param FieldList $fields
  */
 public function updateCMSFields(FieldList $fields)
 {
     // remove the version field from the CMS as this should be left
     // entirely up to the extension (not the cms user).
     $fields->removeByName('Version');
 }
コード例 #13
0
 /**
  * Caution: Only call on instances, not through a singleton.
  * The "root group" fields will be created through {@link SecurityAdmin->EditForm()}.
  *
  * @return FieldList
  */
 public function getCMSFields()
 {
     $fields = new FieldList(new TabSet("Root", new Tab('Members', _t('SecurityAdmin.MEMBERS', 'Members'), new TextField("Title", $this->fieldLabel('Title')), $parentidfield = DropdownField::create('ParentID', $this->fieldLabel('Parent'), Group::get()->exclude('ID', $this->ID)->map('ID', 'Breadcrumbs'))->setEmptyString(' '), new TextareaField('Description', $this->fieldLabel('Description'))), $permissionsTab = new Tab('Permissions', _t('SecurityAdmin.PERMISSIONS', 'Permissions'), $permissionsField = new PermissionCheckboxSetField('Permissions', false, 'SilverStripe\\Security\\Permission', 'GroupID', $this))));
     $parentidfield->setDescription(_t('Group.GroupReminder', 'If you choose a parent group, this group will take all it\'s roles'));
     // Filter permissions
     // TODO SecurityAdmin coupling, not easy to get to the form fields through GridFieldDetailForm
     $permissionsField->setHiddenPermissions((array) Config::inst()->get('SilverStripe\\Admin\\SecurityAdmin', 'hidden_permissions'));
     if ($this->ID) {
         $group = $this;
         $config = GridFieldConfig_RelationEditor::create();
         $config->addComponent(new GridFieldButtonRow('after'));
         $config->addComponents(new GridFieldExportButton('buttons-after-left'));
         $config->addComponents(new GridFieldPrintButton('buttons-after-left'));
         /** @var GridFieldAddExistingAutocompleter $autocompleter */
         $autocompleter = $config->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldAddExistingAutocompleter');
         /** @skipUpgrade */
         $autocompleter->setResultsFormat('$Title ($Email)')->setSearchFields(array('FirstName', 'Surname', 'Email'));
         /** @var GridFieldDetailForm $detailForm */
         $detailForm = $config->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDetailForm');
         $detailForm->setValidator(Member_Validator::create())->setItemEditFormCallback(function ($form, $component) use($group) {
             /** @var Form $form */
             $record = $form->getRecord();
             $groupsField = $form->Fields()->dataFieldByName('DirectGroups');
             if ($groupsField) {
                 // If new records are created in a group context,
                 // set this group by default.
                 if ($record && !$record->ID) {
                     $groupsField->setValue($group->ID);
                 } elseif ($record && $record->ID) {
                     // TODO Mark disabled once chosen.js supports it
                     // $groupsField->setDisabledItems(array($group->ID));
                     $form->Fields()->replaceField('DirectGroups', $groupsField->performReadonlyTransformation());
                 }
             }
         });
         $memberList = GridField::create('Members', false, $this->DirectMembers(), $config)->addExtraClass('members_grid');
         // @todo Implement permission checking on GridField
         //$memberList->setPermissions(array('edit', 'delete', 'export', 'add', 'inlineadd'));
         $fields->addFieldToTab('Root.Members', $memberList);
     }
     // Only add a dropdown for HTML editor configurations if more than one is available.
     // Otherwise Member->getHtmlEditorConfigForCMS() will default to the 'cms' configuration.
     $editorConfigMap = HTMLEditorConfig::get_available_configs_map();
     if (count($editorConfigMap) > 1) {
         $fields->addFieldToTab('Root.Permissions', new DropdownField('HtmlEditorConfig', 'HTML Editor Configuration', $editorConfigMap), 'Permissions');
     }
     if (!Permission::check('EDIT_PERMISSIONS')) {
         $fields->removeFieldFromTab('Root', 'Permissions');
     }
     // Only show the "Roles" tab if permissions are granted to edit them,
     // and at least one role exists
     if (Permission::check('APPLY_ROLES') && DataObject::get('SilverStripe\\Security\\PermissionRole')) {
         $fields->findOrMakeTab('Root.Roles', _t('SecurityAdmin.ROLES', 'Roles'));
         $fields->addFieldToTab('Root.Roles', new LiteralField("", "<p>" . _t('SecurityAdmin.ROLESDESCRIPTION', "Roles are predefined sets of permissions, and can be assigned to groups.<br />" . "They are inherited from parent groups if required.") . '<br />' . sprintf('<a href="%s" class="add-role">%s</a>', SecurityAdmin::singleton()->Link('show/root#Root_Roles'), _t('Group.RolesAddEditLink', 'Manage roles')) . "</p>"));
         // Add roles (and disable all checkboxes for inherited roles)
         $allRoles = PermissionRole::get();
         if (!Permission::check('ADMIN')) {
             $allRoles = $allRoles->filter("OnlyAdminCanApply", 0);
         }
         if ($this->ID) {
             $groupRoles = $this->Roles();
             $inheritedRoles = new ArrayList();
             $ancestors = $this->getAncestors();
             foreach ($ancestors as $ancestor) {
                 $ancestorRoles = $ancestor->Roles();
                 if ($ancestorRoles) {
                     $inheritedRoles->merge($ancestorRoles);
                 }
             }
             $groupRoleIDs = $groupRoles->column('ID') + $inheritedRoles->column('ID');
             $inheritedRoleIDs = $inheritedRoles->column('ID');
         } else {
             $groupRoleIDs = array();
             $inheritedRoleIDs = array();
         }
         $rolesField = ListboxField::create('Roles', false, $allRoles->map()->toArray())->setDefaultItems($groupRoleIDs)->setAttribute('data-placeholder', _t('Group.AddRole', 'Add a role for this group'))->setDisabledItems($inheritedRoleIDs);
         if (!$allRoles->count()) {
             $rolesField->setAttribute('data-placeholder', _t('Group.NoRoles', 'No roles found'));
         }
         $fields->addFieldToTab('Root.Roles', $rolesField);
     }
     $fields->push($idField = new HiddenField("ID"));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
コード例 #14
0
 /**
  * Adds extra fields to this form
  *
  * @param FieldList $fields
  * @param Controller $controller
  * @param string $name
  * @param array $context
  */
 public function updateFormFields(FieldList &$fields, Controller $controller, $name, $context = [])
 {
     // Add preview link
     if (empty($context['Record'])) {
         return;
     }
     $record = $context['Record'];
     if ($record->hasExtension(Versioned::class)) {
         $link = $controller->Link('preview');
         $fields->unshift(new LiteralField("PreviewLink", sprintf('<a href="%s" rel="external" target="_blank">Preview</a>', Convert::raw2att($link))));
     }
 }
コード例 #15
0
 /**
  * @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;
 }
コード例 #16
0
 /**
  * @return null|FieldList
  */
 public function rootFieldList()
 {
     if (is_object($this->containerFieldList)) {
         return $this->containerFieldList->rootFieldList();
     }
     user_error("rootFieldList() called on {$this->class} object without a containerFieldList", E_USER_ERROR);
     return null;
 }
コード例 #17
0
 /**
  * Get list of fields for previewing this records details
  *
  * @return FieldList
  */
 protected function getDetailFields()
 {
     $fields = new FieldList(ReadonlyField::create("FileType", _t('AssetTableField.TYPE', 'File type'), $this->getFileType()), HTMLReadonlyField::create('ClickableURL', _t('AssetTableField.URL', 'URL'), $this->getExternalLink()));
     // Get file size
     if ($this->getSize()) {
         $fields->insertAfter('FileType', ReadonlyField::create("Size", _t('AssetTableField.SIZE', 'File size'), $this->getSize()));
     }
     // Get modified details of local record
     if ($this->getFile()) {
         $fields->push(new DateField_Disabled("Created", _t('AssetTableField.CREATED', 'First uploaded'), $this->getFile()->Created));
         $fields->push(new DateField_Disabled("LastEdited", _t('AssetTableField.LASTEDIT', 'Last changed'), $this->getFile()->LastEdited));
     }
     return $fields;
 }
コード例 #18
0
 /**
  * Note: Doesn't call {@link FormField->setForm()}
  * on the returned {@link HiddenField}, you'll need to take
  * care of this yourself.
  *
  * @param FieldList $fieldset
  * @return HiddenField|false
  */
 public function updateFieldSet(&$fieldset)
 {
     if (!$fieldset->fieldByName($this->getName())) {
         $field = new HiddenField($this->getName(), null, $this->getValue());
         $fieldset->push($field);
         return $field;
     } else {
         return false;
     }
 }
コード例 #19
0
 public function updateCMSFields(FieldList $fields)
 {
     $fields->addFieldToTab('Root.Main', new TextField('TestMemberField', 'Test'));
 }
コード例 #20
0
 /**
  * @param FieldList $fieldset
  * @return false
  */
 public function updateFieldSet(&$fieldset)
 {
     // Remove, in case it was added beforehand
     $fieldset->removeByName($this->getName());
     return false;
 }
コード例 #21
0
 /**
  * Return the FieldList used to edit this folder in the CMS.
  * You can modify this FieldList by subclassing folder, or by creating a {@link DataExtension}
  * and implemeting updateCMSFields(FieldList $fields) on that extension.
  *
  * @return FieldList
  */
 public function getCMSFields()
 {
     // Don't show readonly path until we can implement parent folder selection,
     // it's too confusing when readonly (makes sense for files only).
     $width = (int) Image::config()->get('asset_preview_width');
     $previewLink = Convert::raw2att($this->ScaleMaxWidth($width)->getIcon());
     $image = "<img src=\"{$previewLink}\" class=\"editor__thumbnail\" />";
     $content = Tab::create('Main', HeaderField::create('TitleHeader', $this->Title, 1)->addExtraClass('editor__heading'), LiteralField::create("IconFull", $image)->addExtraClass('editor__file-preview'), TabSet::create('Editor', Tab::create('Details', TextField::create("Name", $this->fieldLabel('Filename')))), HiddenField::create('ID', $this->ID));
     $fields = FieldList::create(TabSet::create('Root', $content));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
コード例 #22
0
 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;
 }
コード例 #23
0
 public function updateCMSFields(FieldList $fields)
 {
     $fields->addFieldToTab('Root.Main', new TextField('AddedExtensionField'));
 }
コード例 #24
0
 /**
  * Set if the existing password should be required
  *
  * @param bool $show Flag to show or hide this field
  * @return $this
  */
 public function setRequireExistingPassword($show)
 {
     // Don't modify if already added / removed
     if ((bool) $show === $this->requireExistingPassword) {
         return $this;
     }
     $this->requireExistingPassword = $show;
     $name = $this->getName();
     $currentName = "{$name}[_CurrentPassword]";
     if ($show) {
         $confirmField = PasswordField::create($currentName, _t('Member.CURRENT_PASSWORD', 'Current Password'));
         $this->children->unshift($confirmField);
     } else {
         $this->children->removeByName($currentName, true);
     }
     return $this;
 }
コード例 #25
0
 protected function getFormFields(Controller $controller, $name, $context = [])
 {
     $record = $context['Record'];
     // Build standard fields for all folders / files
     /** @var File $record */
     $fields = new FieldList(HeaderField::create('TitleHeader', $record ? $record->Title : null, 1)->addExtraClass('editor__heading'), LiteralField::create("IconFull", $this->getIconMarkup($record))->addExtraClass('editor__file-preview'), $this->getFormFieldTabs($record, $context));
     if ($record) {
         $fields->push(HiddenField::create('ID', $record->ID));
     }
     $this->invokeWithExtensions('updateFormFields', $fields, $controller, $name, $context);
     return $fields;
 }
コード例 #26
0
 public function updateCMSFields(FieldList $fields)
 {
     $fields->addFieldToTab('Root.Test', new TextField('ExtendedFieldRemove'));
     $fields->addFieldToTab('Root.Test', new TextField('ExtendedFieldKeep'));
     if ($childField = $fields->dataFieldByName('ChildFieldBeforeExtension')) {
         $childField->setTitle('ChildFieldBeforeExtension: Modified Title');
     }
     if ($grandchildField = $fields->dataFieldByName('GrandchildFieldBeforeExtension')) {
         $grandchildField->setTitle('GrandchildFieldBeforeExtension: Modified Title');
     }
 }
 /**
  * Build the set of form field actions for this DataObject
  *
  * @return FieldList
  */
 protected function getFormActions()
 {
     $canEdit = $this->record->canEdit();
     $canDelete = $this->record->canDelete();
     $actions = new FieldList();
     if ($this->record->ID !== 0) {
         if ($canEdit) {
             $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
         }
         if ($canDelete) {
             $actions->push(FormAction::create('doDelete', _t('GridFieldDetailForm.Delete', 'Delete'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-destructive action-delete'));
         }
     } else {
         // adding new record
         //Change the Save label to 'Create'
         $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Create', 'Create'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'add'));
         // 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 ss-ui-button ss-ui-action-destructive cms-panel-link ui-corner-all", $oneLevelUp->Link, _t('GridFieldDetailForm.CancelBtn', 'Cancel'));
             $actions->push(new LiteralField('cancelbutton', $text));
         }
     }
     $this->extend('updateFormActions', $actions);
     return $actions;
 }
コード例 #28
0
 /**
  * Determine which properties on the DataObject are
  * searchable, and map them to their default {@link FormField}
  * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
  *
  * Some additional logic is included for switching field labels, based on
  * how generic or specific the field type is.
  *
  * Used by {@link SearchContext}.
  *
  * @param array $_params
  *   'fieldClasses': Associative array of field names as keys and FormField classes as values
  *   'restrictFields': Numeric array of a field name whitelist
  * @return FieldList
  */
 public function scaffoldSearchFields($_params = null)
 {
     $params = array_merge(array('fieldClasses' => false, 'restrictFields' => false), (array) $_params);
     $fields = new FieldList();
     foreach ($this->searchableFields() as $fieldName => $spec) {
         if ($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) {
             continue;
         }
         // If a custom fieldclass is provided as a string, use it
         $field = null;
         if ($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
             $fieldClass = $params['fieldClasses'][$fieldName];
             $field = new $fieldClass($fieldName);
             // If we explicitly set a field, then construct that
         } else {
             if (isset($spec['field'])) {
                 // If it's a string, use it as a class name and construct
                 if (is_string($spec['field'])) {
                     $fieldClass = $spec['field'];
                     $field = new $fieldClass($fieldName);
                     // If it's a FormField object, then just use that object directly.
                 } else {
                     if ($spec['field'] instanceof FormField) {
                         $field = $spec['field'];
                         // Otherwise we have a bug
                     } else {
                         user_error("Bad value for searchable_fields, 'field' value: " . var_export($spec['field'], true), E_USER_WARNING);
                     }
                 }
                 // Otherwise, use the database field's scaffolder
             } else {
                 $field = $this->relObject($fieldName)->scaffoldSearchField();
             }
         }
         // Allow fields to opt out of search
         if (!$field) {
             continue;
         }
         if (strstr($fieldName, '.')) {
             $field->setName(str_replace('.', '__', $fieldName));
         }
         $field->setTitle($spec['title']);
         $fields->push($field);
     }
     return $fields;
 }
コード例 #29
0
 /**
  * Test VisibleFields and HiddenFields
  */
 public function testVisibleAndHiddenFields()
 {
     $fields = new FieldList(new TextField("A"), new TextField("B"), new HiddenField("C"), new Tabset("Root", new Tab("D", new TextField("D1"), new HiddenField("D2"))));
     $hidden = $fields->HiddenFields();
     // Inside hidden fields, all HiddenField objects are included, even nested ones
     $this->assertNotNull($hidden->dataFieldByName('C'));
     $this->assertNotNull($hidden->dataFieldByName('D2'));
     // Visible fields are not
     $this->assertNull($hidden->dataFieldByName('B'));
     $this->assertNull($hidden->dataFieldByName('D1'));
     $visible = $fields->VisibleFields();
     // Visible fields exclude top level HiddenField objects
     $this->assertNotNull($visible->dataFieldByName('A'));
     $this->assertNull($visible->dataFieldByName('C'));
     // But they don't exclude nested HiddenField objects.  This is a limitation; you should
     // put all your HiddenFields at the top level.
     $this->assertNotNull($visible->dataFieldByName('D2'));
 }
コード例 #30
-1
    /**
     * Constructor
     *
     * @skipUpgrade
     * @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 $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
     *                                     {@link FormAction} objects
     * @param bool $checkCurrentUser If set to TRUE, it will be checked if a
     *                               the user is currently logged in, and if
     *                               so, only a logout button will be rendered
     */
    public function __construct($controller, $name, $fields = null, $actions = null, $checkCurrentUser = true)
    {
        // This is now set on the class directly to make it easier to create subclasses
        // $this->authenticator_class = $authenticatorClassName;
        $customCSS = project() . '/css/member_login.css';
        if (Director::fileExists($customCSS)) {
            Requirements::css($customCSS);
        }
        if (isset($_REQUEST['BackURL'])) {
            $backURL = $_REQUEST['BackURL'];
        } else {
            $backURL = Session::get('BackURL');
        }
        if ($checkCurrentUser && Member::currentUser() && Member::logged_in_session_exists()) {
            $fields = FieldList::create(HiddenField::create("AuthenticationMethod", null, $this->authenticator_class, $this));
            $actions = FieldList::create(FormAction::create("logout", _t('Member.BUTTONLOGINOTHER', "Log in as someone else")));
        } else {
            if (!$fields) {
                $label = Member::singleton()->fieldLabel(Member::config()->unique_identifier_field);
                $fields = FieldList::create(HiddenField::create("AuthenticationMethod", null, $this->authenticator_class, $this), $emailField = TextField::create("Email", $label, null, null, $this), PasswordField::create("Password", _t('Member.PASSWORD', 'Password')));
                if (Security::config()->remember_username) {
                    $emailField->setValue(Session::get('SessionForms.MemberLoginForm.Email'));
                } else {
                    // Some browsers won't respect this attribute unless it's added to the form
                    $this->setAttribute('autocomplete', 'off');
                    $emailField->setAttribute('autocomplete', 'off');
                }
                if (Security::config()->autologin_enabled) {
                    $fields->push(CheckboxField::create("Remember", _t('Member.KEEPMESIGNEDIN', "Keep me signed in"))->setAttribute('title', sprintf(_t('Member.REMEMBERME', "Remember me next time? (for %d days on this device)"), RememberLoginHash::config()->get('token_expiry_days'))));
                }
            }
            if (!$actions) {
                $actions = FieldList::create(FormAction::create('dologin', _t('Member.BUTTONLOGIN', "Log in")), LiteralField::create('forgotPassword', '<p id="ForgotPassword"><a href="' . Security::lost_password_url() . '">' . _t('Member.BUTTONLOSTPASSWORD', "I've lost my password") . '</a></p>'));
            }
        }
        if (isset($backURL)) {
            $fields->push(HiddenField::create('BackURL', 'BackURL', $backURL));
        }
        // Reduce attack surface by enforcing POST requests
        $this->setFormMethod('POST', true);
        parent::__construct($controller, $name, $fields, $actions);
        $this->setValidator(RequiredFields::create('Email', 'Password'));
        // Focus on the email input when the page is loaded
        $js = <<<JS
\t\t\t(function() {
\t\t\t\tvar el = document.getElementById("MemberLoginForm_LoginForm_Email");
\t\t\t\tif(el && el.focus && (typeof jQuery == 'undefined' || jQuery(el).is(':visible'))) el.focus();
\t\t\t})();
JS;
        Requirements::customScript($js, 'MemberLoginFormFieldFocus');
    }