public function scaffoldFormField($title = null, $params = null)
 {
     if (empty($this->object)) {
         return null;
     }
     $relationName = substr($this->name, 0, -2);
     $hasOneClass = DataObject::getSchema()->hasOneComponent(get_class($this->object), $relationName);
     if (empty($hasOneClass)) {
         return null;
     }
     $hasOneSingleton = singleton($hasOneClass);
     if ($hasOneSingleton instanceof File) {
         $field = new UploadField($relationName, $title);
         if ($hasOneSingleton instanceof Image) {
             $field->setAllowedFileCategories('image/supported');
         }
         return $field;
     }
     // Build selector / numeric field
     $titleField = $hasOneSingleton->hasField('Title') ? "Title" : "Name";
     $list = DataList::create($hasOneClass);
     // Don't scaffold a dropdown for large tables, as making the list concrete
     // might exceed the available PHP memory in creating too many DataObject instances
     if ($list->count() < 100) {
         $field = new DropdownField($this->name, $title, $list->map('ID', $titleField));
         $field->setEmptyString(' ');
     } else {
         $field = new NumericField($this->name, $title);
     }
     return $field;
 }
 public function scaffoldSearchField($title = null)
 {
     $anyText = _t('Boolean.ANY', 'Any');
     $source = array(1 => _t('Boolean.YESANSWER', 'Yes'), 0 => _t('Boolean.NOANSWER', 'No'));
     $field = new DropdownField($this->name, $title, $source);
     $field->setEmptyString("({$anyText})");
     return $field;
 }
 public function testValidation()
 {
     $field = CompositeField::create($fieldOne = DropdownField::create('A'), $fieldTwo = TextField::create('B'));
     $validator = new RequiredFields();
     $this->assertFalse($field->validate($validator), "Validation fails when child is invalid");
     $fieldOne->setEmptyString('empty');
     $this->assertTrue($field->validate($validator), "Validates when children are valid");
 }
 protected function getFormFieldAttributesTab($record, $context = [])
 {
     /** @var Tab $tab */
     $tab = parent::getFormFieldAttributesTab($record, $context);
     $alignments = array('leftAlone' => _t('AssetAdmin.AlignmentLeftAlone', 'On the left, on its own.'), 'center' => _t('AssetAdmin.AlignmentCenter', 'Centered, on its own.'), 'left' => _t('AssetAdmin.AlignmentLeft', 'On the left, with text wrapping around.'), 'right' => _t('AssetAdmin.AlignmentRight', 'On the right, with text wrapping around.'));
     $tab->push(DropdownField::create('Alignment', _t('AssetAdmin.Alignment', 'Alignment'), $alignments));
     $tab->push(FieldGroup::create(_t('AssetAdmin.ImageSpecs', 'Dimensions'), TextField::create('InsertWidth', _t('AssetAdmin.ImageWidth', 'Width'))->setMaxLength(5)->addExtraClass('flexbox-area-grow'), TextField::create('InsertHeight', _t('AssetAdmin.ImageHeight', 'Height'))->setMaxLength(5)->addExtraClass('flexbox-area-grow'))->addExtraClass('fill-width'));
     $tab->insertBefore('Caption', TextField::create('AltText', _t('AssetAdmin.AltText', 'Alternative text (alt)'))->setDescription(_t('AssetAdmin.AltTextDescription', 'Shown to screen readers or if image can\'t be displayed')));
     $tab->insertAfter('AltText', TextField::create('TitleTooltip', _t('AssetAdmin.TitleTooltip', 'Title text (tooltip)'))->setDescription(_t('AssetAdmin.TitleTooltipDescription', 'For additional information about the image'))->setValue($record->Title));
     return $tab;
 }
 /**
  * Build a potentially nested fieldgroup
  *
  * @param mixed $valueOrGroup Value of item, or title of group
  * @param string|array $titleOrOptions Title of item, or options in grouip
  * @return ArrayData Data for this item
  */
 protected function getFieldOption($valueOrGroup, $titleOrOptions)
 {
     // Return flat option
     if (!is_array($titleOrOptions)) {
         return parent::getFieldOption($valueOrGroup, $titleOrOptions);
     }
     // Build children from options list
     $options = new ArrayList();
     foreach ($titleOrOptions as $childValue => $childTitle) {
         $options->push($this->getFieldOption($childValue, $childTitle));
     }
     return new ArrayData(array('Title' => $valueOrGroup, 'Options' => $options));
 }
 public function Field($properties = array())
 {
     $source = $this->getSource();
     // Default value to best availabel locale
     $value = $this->Value();
     if ($this->config()->default_to_locale && (!$value || !isset($source[$value])) && $this->locale()) {
         $locale = new Zend_Locale();
         $locale->setLocale($this->locale());
         $value = $locale->getRegion();
         $this->setValue($value);
     }
     // Default to default country otherwise
     if (!$value || !isset($source[$value])) {
         $this->setValue($this->config()->default_country);
     }
     return parent::Field($properties);
 }
 /**
  * @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;
 }
 public function scaffoldFormField($title = null, $params = null)
 {
     $selectBox = new DropdownField($this->name, $title);
     $selectBox->setSource($this->getDefaultOptions());
     return $selectBox;
 }
 public function testValidation()
 {
     $field = DropdownField::create('Test', 'Testing', array("One" => "One", "Two" => "Two", "Five" => "Five"));
     $validator = new RequiredFields();
     /** @skipUpgrade */
     $form = new Form($this, 'Form', new FieldList($field), new FieldList(), $validator);
     $field->setValue("One");
     $this->assertTrue($field->validate($validator));
     $field->setName("TestNew");
     //try changing name of field
     $this->assertTrue($field->validate($validator));
     //non-existent value should make the field invalid
     $field->setValue("Three");
     $this->assertFalse($field->validate($validator));
     //empty string shouldn't validate
     $field->setValue('');
     $this->assertFalse($field->validate($validator));
     //empty field should validate after being set
     $field->setEmptyString('Empty String');
     $field->setValue('');
     $this->assertTrue($field->validate($validator));
     //disabled items shouldn't validate
     $field->setDisabledItems(array('Five'));
     $field->setValue('Five');
     $this->assertFalse($field->validate($validator));
 }
 /**
  * Builds a Form that mirrors the parent editForm, but with an extra field to collect the ChangeSet ID
  *
  * @param DataObject $object The object we're going to be adding to whichever ChangeSet is chosen
  * @return Form
  */
 public function Form($object)
 {
     $inChangeSets = array_unique(ChangeSetItem::get_for_object($object)->column('ChangeSetID'));
     $changeSets = $this->getAvailableChangeSets()->map();
     $campaignDropdown = DropdownField::create('Campaign', '', $changeSets);
     $campaignDropdown->setEmptyString(_t('Campaigns.AddToCampaignFormFieldLabel', 'Select a Campaign'));
     $campaignDropdown->addExtraClass('noborder');
     $campaignDropdown->addExtraClass('no-chosen');
     $campaignDropdown->setDisabledItems($inChangeSets);
     $fields = new FieldList([$campaignDropdown, HiddenField::create('ID', null, $this->data['ID']), HiddenField::create('ClassName', null, $this->data['ClassName'])]);
     $form = new Form($this->controller, $this->name, $fields, new FieldList($action = AddToCampaignHandler_FormAction::create()));
     $action->addExtraClass('add-to-campaign__action');
     $form->setHTMLID('Form_EditForm_AddToCampaign');
     $form->loadDataFrom($this->data);
     $form->getValidator()->addRequiredField('Campaign');
     $form->addExtraClass('form--no-dividers add-to-campaign__form');
     return $form;
 }
 /**
  * @return FieldList
  */
 public function getFields()
 {
     $fields = new FieldList(CompositeField::create(CompositeField::create(LiteralField::create("ImageFull", $this->getPreview()))->setName("FilePreviewImage")->addExtraClass('cms-file-info-preview'), CompositeField::create($this->getDetailFields())->setName("FilePreviewData")->addExtraClass('cms-file-info-data'))->setName("FilePreview")->addExtraClass('cms-file-info'), TextField::create('CaptionText', _t('HTMLEditorField.CAPTIONTEXT', 'Caption text')), DropdownField::create('CSSClass', _t('HTMLEditorField.CSSCLASS', 'Alignment / style'), array('leftAlone' => _t('HTMLEditorField.CSSCLASSLEFTALONE', 'On the left, on its own.'), 'center' => _t('HTMLEditorField.CSSCLASSCENTER', 'Centered, on its own.'), 'left' => _t('HTMLEditorField.CSSCLASSLEFT', 'On the left, with text wrapping around.'), 'right' => _t('HTMLEditorField.CSSCLASSRIGHT', 'On the right, with text wrapping around.'))), FieldGroup::create(_t('HTMLEditorField.IMAGEDIMENSIONS', 'Dimensions'), TextField::create('Width', _t('HTMLEditorField.IMAGEWIDTHPX', 'Width'), $this->getInsertWidth())->setMaxLength(5), TextField::create('Height', " x " . _t('HTMLEditorField.IMAGEHEIGHTPX', 'Height'), $this->getInsertHeight())->setMaxLength(5))->addExtraClass('dimensions last'), HiddenField::create('URL', false, $this->getURL()), HiddenField::create('FileID', false, $this->getFileID()));
     return $fields;
 }
 /**
  * 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;
 }
 /**
  * Get the search context from {@link File}, used to create the search form
  * as well as power the /search API endpoint.
  *
  * @return SearchContext
  */
 public function getSearchContext()
 {
     $context = File::singleton()->getDefaultSearchContext();
     // Customize fields
     $dateHeader = HeaderField::create('Date', _t('CMSSearch.FILTERDATEHEADING', 'Date'), 4);
     $dateFrom = DateField::create('CreatedFrom', _t('CMSSearch.FILTERDATEFROM', 'From'))->setConfig('showcalendar', true);
     $dateTo = DateField::create('CreatedTo', _t('CMSSearch.FILTERDATETO', 'To'))->setConfig('showcalendar', true);
     $dateGroup = FieldGroup::create($dateHeader, $dateFrom, $dateTo);
     $context->addField($dateGroup);
     /** @skipUpgrade */
     $appCategories = array('archive' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryArchive', 'Archive'), 'audio' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryAudio', 'Audio'), 'document' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryDocument', 'Document'), 'flash' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryFlash', 'Flash', 'The fileformat'), 'image' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryImage', 'Image'), 'video' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryVideo', 'Video'));
     $context->addField($typeDropdown = new DropdownField('AppCategory', _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Filetype', 'File type'), $appCategories));
     $typeDropdown->setEmptyString(' ');
     $currentfolderLabel = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.CurrentFolderOnly', 'Limit to current folder?');
     $context->addField(new CheckboxField('CurrentFolderOnly', $currentfolderLabel));
     $context->getFields()->removeByName('Title');
     return $context;
 }