The form fields used can be configured by setting the value in {@link setDisplayFields()} to one of the following forms: - A Closure which returns the field instance. - An array with a callback key pointing to a function which returns the field. - An array with a field key->response specifying the field class to use.
Inheritance: extends GridFieldDataColumns, implements GridField_HTMLProvider, implements GridField_SaveHandler, implements GridField_URLHandler
示例#1
0
 /**
  * Gets the field editor, for adding and removing EditableFormFields.
  *
  * @return GridField
  */
 public function getFieldEditorGrid()
 {
     Requirements::javascript(USERFORMS_DIR . '/javascript/FieldEditor.js');
     $fields = $this->Fields();
     $editableColumns = new GridFieldEditableColumns();
     $fieldClasses = singleton('EditableFormField')->getEditableFieldClasses();
     $editableColumns->setDisplayFields(array('ClassName' => function ($record, $column, $grid) use($fieldClasses) {
         if ($record instanceof EditableFormField) {
             return $record->getInlineClassnameField($column, $fieldClasses);
         }
     }, 'Title' => function ($record, $column, $grid) {
         if ($record instanceof EditableFormField) {
             return $record->getInlineTitleField($column);
         }
     }));
     $config = GridFieldConfig::create()->addComponents($editableColumns, new GridFieldButtonRow(), GridFieldAddClassesButton::create('EditableTextField')->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD', 'Add Field'))->setButtonClass('ss-ui-action-constructive'), GridFieldAddClassesButton::create('EditableFormStep')->setButtonName(_t('UserFormFieldEditorExtension.ADD_PAGE_BREAK', 'Add Page Break')), GridFieldAddClassesButton::create(array('EditableFieldGroup', 'EditableFieldGroupEnd'))->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD_GROUP', 'Add Field Group')), new GridFieldEditButton(), new GridFieldDeleteAction(), new GridFieldToolbarHeader(), new GridFieldDetailForm());
     $fieldEditor = GridField::create('Fields', _t('UserDefinedForm.FIELDS', 'Fields'), $fields, $config)->addExtraClass('uf-field-editor');
     if (Config::inst()->get('UserFormFieldEditorExtension', 'showAddEdit')) {
         $addFieldAction->setTitle(_t('UserFormFieldEditorExtension.ADD_EDIT_FIELD', 'Add & Edit Field'));
         $fields = $addFieldAction->getClasses($fieldEditor);
         $fields = array_diff_key($fields, array_flip(array('EditableFormStep', 'EditableFieldGroup', 'EditableFieldGroupEnd')));
         asort($fields);
         $addFieldAction->setClasses($fields);
     }
     return $fieldEditor;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->removeByName('Capacity');
     $fields->removeByName('Registrations');
     $fields->removeByName('Tickets');
     $fields->removeByName('EmailReminder');
     $fields->removeByName('RemindDays');
     $fields->removeByName('PaymentID');
     $fields->removeByName('ReminderJobID');
     if (!$this->isInDB()) {
         $fields->push(new LiteralField('RegistrationNote', '<p>You can configure registration once ' . 'you save for the first time.</p>'));
         return $fields;
     }
     $fields->push(new GridField('Tickets', _t('EventManagement.AVAILABLE_TICKETS', 'Available Tickets'), $this->Tickets(), GridFieldConfig::create()->addComponent(new GridFieldButtonRow('before'))->addComponent(new GridFieldToolbarHeader())->addComponent($add = new GridFieldAddExistingSearchButton())->addComponent(new GridFieldTitleHeader())->addComponent(new GridFieldOrderableRows('Sort'))->addComponent($editable = new GridFieldEditableColumns())->addComponent(new GridFieldDeleteAction(true))));
     $fields->push($capacity = new NumericField('Capacity', _t('EventManagement.CAPACITY', 'Capacity')));
     $editable->setDisplayFields(array('Title' => array('title' => 'Title', 'field' => 'ReadonlyField'), 'StartSummary' => 'Sales Start', 'PriceSummary' => 'Price', 'Available' => array('field' => 'NumericField')));
     $add->setTitle(_t('EventManagement.ADD_TICKET_TYPE', 'Add Ticket Type'));
     $capacity->setDescription('Set to 0 for unlimited capacity.');
     if (class_exists('AbstractQueuedJob')) {
         if ($this->ReminderJobID && $this->ReminderJob()->StepsProcessed) {
             $fields->push(new LiteralField('RemindersAlreadySent', '<p>Reminder emails have already been sent out.</p>'));
         } else {
             $fields->push(new CheckboxField('EmailReminder', _t('EventManagement.SEND_REMINDER_EMAIL', 'Send the registered attendees a reminder email?')));
             $fields->push($remindDays = new NumericField('RemindDays', _t('EventManagement.SEND_REMINDER', 'Send reminder')));
             $remindDays->setDescription(_t('EventManagement.DAYS_BEFORE_EVENT', 'Days before the event starts.'));
         }
     }
     return $fields;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->removeByName('LinkedFromCities');
     $grid = new GridField('LinkedToCities', $this->fieldLabel('LinkedToCities'), $this->LinkedToCities(), GridFieldConfig::create()->addComponent(new GridFieldDetailForm())->addComponent(new GridFieldButtonRow())->addComponent($GridFieldAddExistingSearchButton = new GridFieldAddExistingSearchButton('buttons-before-right'))->addComponent($GridFieldAddExistingAutocompleter = new GridFieldAddExistingAutocompleter('buttons-before-right'))->addComponent(new GridFieldToolbarHeader())->addComponent(new GridFieldTitleHeader())->addComponent($comp = new GridFieldEditableColumns())->addComponent(new GridFieldEditButton())->addComponent(new GridFieldDeleteAction('unlinkrelation'))->addComponent(new GridFieldDeleteAction())->addComponent($GridFieldAddNewInlineButton = new GridFieldAddNewInlineButton()));
     $GridFieldAddNewInlineButton->setTitle(_t(__CLASS__ . '.AddNewCity', 'Add new city'));
     $GridFieldAddExistingSearchButton->setTitle(_t(__CLASS__ . '.SearchAndAddExistingCity', 'Search and add existing city'));
     $LinkTargetField = MapaelCountryPageExtension::getTargetField($this, 'LinkTarget');
     $LinkTargetField->setTitle(_t(__CLASS__ . '.LinkTarget', 'Link target'));
     $field_names = array_keys(array_merge($this->summaryFields(), self::$many_many_extraFields['LinkedToCities']));
     $arr = array();
     foreach ($field_names as $name) {
         preg_match('/(TooltipContent|Href|Target)$/', $name, $matches);
         $title = $this->fieldLabel($name);
         $arr[$name] = $title;
         if ($matches) {
             $arr[$name] = array('title' => $title, 'callback' => function ($record, $column, $grid) {
                 preg_match('/(TooltipContent|Href|Target)$/', $column, $matches);
                 return MapaelCountryPageExtension::getAttrField($record, $matches[1], $column);
             });
         }
     }
     $comp->setDisplayFields($arr);
     $fields->replaceField('LinkedToCities', $grid);
     $fields->replaceField('Target', MapaelCountryPageExtension::getTargetField($this));
     $fields->replaceField('Href', MapaelCountryPageExtension::getHrefField($this));
     $fields->replaceField('TooltipContent', MapaelCountryPageExtension::getTooltipContentField($this));
     return $fields;
 }
 private function getRowTemplate(GridField $grid, GridFieldEditableColumns $editable)
 {
     $columns = new ArrayList();
     $handled = array_keys($editable->getDisplayFields($grid));
     if ($grid->getList()) {
         $record = Object::create($grid->getModelClass());
     } else {
         $record = null;
     }
     $fields = $editable->getFields($grid, $record);
     foreach ($grid->getColumns() as $column) {
         if (in_array($column, $handled)) {
             $field = $fields->dataFieldByName($column);
             $field->setName(sprintf('%s[%s][{%%=o.num%%}][%s]', $grid->getName(), __CLASS__, $field->getName()));
             $content = $field->Field();
         } else {
             $content = null;
         }
         $attrs = '';
         foreach ($grid->getColumnAttributes($record, $column) as $attr => $val) {
             $attrs .= sprintf(' %s="%s"', $attr, Convert::raw2att($val));
         }
         $columns->push(new ArrayData(array('Content' => $content, 'Attributes' => $attrs, 'IsActions' => $column == 'Actions')));
     }
     return $columns->renderWith('GridFieldAddNewInlineRow');
 }
    public function __construct($canAdd = true, $canEdit = true, $canDelete = true, $editableRows = false, $aboveOrBelow = false)
    {
        parent::__construct();
        $this->blockManager = Injector::inst()->get('BlockManager');
        $controllerClass = Controller::curr()->class;
        // Get available Areas (for page) or all in case of ModelAdmin
        if ($controllerClass == 'CMSPageEditController') {
            $currentPage = Controller::curr()->currentPage();
            $areasFieldSource = $this->blockManager->getAreasForPageType($currentPage->ClassName);
        } else {
            $areasFieldSource = $this->blockManager->getAreasForTheme();
        }
        // EditableColumns only makes sense on Saveable parenst (eg Page), or inline changes won't be saved
        if ($editableRows) {
            $this->addComponent($editable = new GridFieldEditableColumns());
            $displayfields = array('TypeForGridfield' => array('title' => _t('Block.BlockType', 'Block Type'), 'field' => 'LiteralField'), 'Title' => array('title' => _t('Block.Title', 'Title'), 'field' => 'ReadonlyField'), 'BlockArea' => array('title' => _t('Block.BlockArea', 'Block Area') . '
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'callback' => function () use($areasFieldSource) {
                return DropdownField::create('BlockArea', 'Block Area', $areasFieldSource)->setHasEmptyDefault(true);
            }), 'isPublishedNice' => array('title' => _t('Block.IsPublishedField', 'Published'), 'field' => 'ReadonlyField'), 'UsageListAsString' => array('title' => _t('Block.UsageListAsString', 'Used on'), 'field' => 'LiteralField'));
            if ($aboveOrBelow) {
                $displayfields['AboveOrBelow'] = array('title' => _t('GridFieldConfigBlockManager.AboveOrBelow', 'Above or Below'), 'callback' => function () {
                    return DropdownField::create('AboveOrBelow', _t('GridFieldConfigBlockManager.AboveOrBelow', 'Above or Below'), BlockSet::config()->get('above_or_below_options'));
                });
            }
            $editable->setDisplayFields($displayfields);
        } else {
            $this->addComponent($dcols = new GridFieldDataColumns());
            $displayfields = array('singular_name' => _t('Block.BlockType', 'Block Type'), 'Title' => _t('Block.Title', 'Title'), 'BlockArea' => _t('Block.BlockArea', 'Block Area'), 'isPublishedNice' => _t('Block.IsPublishedField', 'Published'), 'UsageListAsString' => _t('Block.UsageListAsString', 'Used on'));
            $dcols->setDisplayFields($displayfields);
            $dcols->setFieldCasting(array('UsageListAsString' => 'HTMLText->Raw'));
        }
        $this->addComponent(new GridFieldButtonRow('before'));
        $this->addComponent(new GridFieldToolbarHeader());
        $this->addComponent(new GridFieldDetailForm());
        $this->addComponent($sort = new GridFieldSortableHeader());
        $this->addComponent($filter = new GridFieldFilterHeader());
        $this->addComponent(new GridFieldDetailForm());
        if ($controllerClass == 'BlockAdmin' && class_exists('GridFieldCopyButton')) {
            $this->addComponent(new GridFieldCopyButton());
        }
        $filter->setThrowExceptionOnBadDataType(false);
        $sort->setThrowExceptionOnBadDataType(false);
        if ($canAdd) {
            $multiClass = new GridFieldAddNewMultiClass();
            $classes = $this->blockManager->getBlockClasses();
            $multiClass->setClasses($classes);
            $this->addComponent($multiClass);
            //$this->addComponent(new GridFieldAddNewButton());
        }
        if ($canEdit) {
            $this->addComponent(new GridFieldEditButton());
        }
        if ($canDelete) {
            $this->addComponent(new GridFieldDeleteAction(true));
        }
        return $this;
    }
示例#6
0
 public static function makeEditable($name, $label = '', $source, $sortable = true, $fields = null)
 {
     $grid = self::make($name, $label, $source, $sortable);
     $config = $grid->getConfig();
     $fieldEditor = new \GridFieldEditableColumns();
     $btnInlineAdd = new \GridFieldAddNewInlineButton();
     if (!empty($fields)) {
         $fieldEditor->setDisplayFields($fields);
     }
     $config->removeComponentsByType('GridFieldAddNewButton')->addComponents($fieldEditor, $btnInlineAdd);
     return $grid;
 }
 /**
  * Generate a gridfield config for editing filter rules
  *
  * @return GridFieldConfig
  */
 protected function getRulesConfig()
 {
     $formFields = $this->getFormParent()->Fields();
     $config = GridFieldConfig::create()->addComponents(new GridFieldButtonRow('before'), new GridFieldToolbarHeader(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction(), $columns = new GridFieldEditableColumns());
     $columns->setDisplayFields(array('ConditionFieldID' => function ($record, $column, $grid) use($formFields) {
         return DropdownField::create($column, false, $formFields->map('ID', 'Title'));
     }, 'ConditionOption' => function ($record, $column, $grid) {
         $options = UserDefinedForm_EmailRecipientCondition::config()->condition_options;
         return DropdownField::create($column, false, $options);
     }, 'ConditionValue' => function ($record, $column, $grid) {
         return TextField::create($column);
     }));
     return $config;
 }
 /**
  * @return FieldList
  */
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $editableColumns = new GridFieldEditableColumns();
     $editableColumns->setDisplayFields(array('Title' => array('title' => 'Title', 'callback' => function ($record, $column, $grid) {
         return TextField::create($column);
     }), 'Default' => array('title' => _t('EditableMultipleOptionField.DEFAULT', 'Selected by default?'), 'callback' => function ($record, $column, $grid) {
         return CheckboxField::create($column);
     })));
     $optionsConfig = GridFieldConfig::create()->addComponents(new GridFieldToolbarHeader(), new GridFieldTitleHeader(), $editableColumns, new GridFieldButtonRow(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction());
     $optionsGrid = GridField::create('Options', _t('EditableFormField.CUSTOMOPTIONS', 'Options'), $this->Options(), $optionsConfig);
     $fields->insertAfter(new Tab('Options'), 'Main');
     $fields->addFieldToTab('Root.Options', $optionsGrid);
     return $fields;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $contentMsg = 'Insert the $Items keyword to display the item list';
     $fields->addFieldToTab('Root.Main', LiteralField::create('ContentMsg', "<strong>{$contentMsg}</strong>"), 'Content');
     $config = GridFieldConfig::create()->addComponent(new GridFieldButtonRow('before'))->addComponent(new GridFieldAddNewButton('buttons-before-left'))->addComponent(new GridFieldDetailForm())->addComponent(new GridFieldToolbarHeader())->addComponent(new GridFieldTitleHeader())->addComponent($cols = new GridFieldEditableColumns())->addComponent(new GridFieldOrderableRows())->addComponent(new GridFieldEditButton())->addComponent(new GridFieldDeleteAction());
     $display = array('Title' => true, 'Content' => function ($record, $col, $grid) {
         return HtmlEditorField::create('Content', 'Content')->setRows(8);
     });
     $cols->setDisplayFields($display);
     $gf = GridField::create('Questions', 'Questions', $this->Questions(), $config);
     $fields->addFieldToTab('Root.Questions', $gf);
     $msg = 'Please note that changes to the questions here will not appear on the published site until the page is published';
     $notice = LiteralField::create('FaqNotice', "<strong>{$msg}</strong>");
     $fields->addFieldToTab('Root.Questions', $notice, 'Questions');
     return $fields;
 }
 /**
  * Gets the field editor, for adding and removing EditableFormFields.
  *
  * @return GridField
  */
 public function getFieldEditorGrid()
 {
     Requirements::javascript('pageblockbuilder/javascript/FieldEditor.js');
     $editableColumns = new GridFieldEditableColumns();
     $fieldClasses = singleton('EditableFormField')->getEditableFieldClasses();
     $editableColumns->setDisplayFields(array('ClassName' => function ($record, $column, $grid) use($fieldClasses) {
         if ($record instanceof EditableFormField) {
             return $record->getInlineClassnameField($column, $fieldClasses);
         }
     }, 'Title' => function ($record, $column, $grid) {
         if ($record instanceof EditableFormField) {
             return $record->getInlineTitleField($column);
         }
     }));
     $config = GridFieldConfig::create()->addComponents($editableColumns, new GridFieldButtonRow(), GridFieldAddClassesButton::create('EditableTextField')->setButtonName('Add Block')->setButtonClass('ss-ui-action-constructive'), new GridFieldEditButton(), new GridFieldDeleteAction(), new GridFieldToolbarHeader(), new GridFieldOrderableRows('SortOrder'), new GridFieldDetailForm());
     $fieldEditor = GridField::create('Fields', 'Fields', $this->owner->Blocks(), $config)->addExtraClass('uf-field-editor');
     return $fieldEditor;
 }
 function updateCMSFields(FieldList $fields)
 {
     $fields->insertAfter($tabset = new TabSet('ColoredImages'), 'Image');
     $tabset->push($uploadtab = new Tab('UploadImages'));
     $tabset->push($attributetab = new Tab('AssignAttribute'));
     $uploadtab->push($uf = new UploadField('Images', 'Images'));
     $uf->setDescription('Note: The product must be saved before attributes can be assigned to new uploaded images.');
     $attributetab->push($gf = GridField::create("ImageAttributes", "Images", $this->owner->Images(), GridFieldConfig_RelationEditor::create()->removeComponentsByType("GridFieldAddNewButton")->removeComponentsByType("GridFieldEditButton")->removeComponentsByType("GridFieldDataColumns")->removeComponentsByType("GridFieldDeleteAction")->addComponent($cols = new GridFieldEditableColumns())->addComponent(new GridFieldOrderableRows('Sort'))));
     $displayfields = array('Title' => array('title' => 'Title', 'field' => new ReadonlyField("Name")));
     //add drop-down color selection
     $colors = $this->owner->getColors();
     if ($colors->exists()) {
         $displayfields['ColorID'] = function ($record, $col, $grid) use($colors) {
             return DropdownField::create($col, "Color", $colors->map('ID', 'Value')->toArray())->setHasEmptyDefault(true);
         };
     }
     $cols->setDisplayFields($displayfields);
 }
 /**
  * @return FieldList
  */
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     // get current user form fields
     $currentFromFields = $this->Parent()->Fields()->map('Name', 'Title')->toArray();
     // check for any lists
     $fieldsStatus = true;
     if ($this->getLists()->Count() > 0) {
         $fieldsStatus = false;
     }
     $fields->addFieldsToTab("Root.Main", array(LiteralField::create("CampaignMonitorStart", "<h4>Campaign Monitor Configuration</h4>")->setAttribute("disabled", $fieldsStatus), DropdownField::create("ListID", 'Subscripers List', $this->getLists()->map("ListID", "Name"))->setEmptyString("Choose a Campaign Monitor List")->setAttribute("disabled", $fieldsStatus), DropdownField::create("EmailField", 'Email Field', $currentFromFields)->setAttribute("disabled", $fieldsStatus), DropdownField::create("FirstNameField", 'First Name Field', $currentFromFields)->setAttribute("disabled", $fieldsStatus), DropdownField::create("LastNameField", 'Last Name Field', $currentFromFields)->setAttribute("disabled", $fieldsStatus), LiteralField::create("CampaignMonitorEnd", "<h4>Other Configuration</h4>")), 'Type');
     $editableColumns = new GridFieldEditableColumns();
     $editableColumns->setDisplayFields(array('Title' => array('title' => 'Title', 'callback' => function ($record, $column, $grid) {
         return TextField::create($column);
     }), 'Default' => array('title' => _t('EditableMultipleOptionField.DEFAULT', 'Selected by default?'), 'callback' => function ($record, $column, $grid) {
         return CheckboxField::create($column);
     })));
     $optionsConfig = GridFieldConfig::create()->addComponents(new GridFieldToolbarHeader(), new GridFieldTitleHeader(), $editableColumns, new GridFieldButtonRow(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction());
     $optionsGrid = GridField::create('CustomOptions', 'CustomOptions', $this->CustomOptions(), $optionsConfig);
     $fields->insertAfter(new Tab('CustomOptions'), 'Main');
     $fields->addFieldToTab('Root.CustomOptions', $optionsGrid);
     return $fields;
 }
    public function __construct($canAdd = true, $canEdit = true, $canDelete = true, $editableRows = false, $aboveOrBelow = false)
    {
        parent::__construct();
        $this->blockManager = Injector::inst()->get('BlockManager');
        $controllerClass = Controller::curr()->class;
        // Get available Areas (for page) or all in case of ModelAdmin
        if ($controllerClass == 'CMSPageEditController') {
            $currentPage = Controller::curr()->currentPage();
            $areasFieldSource = $this->blockManager->getAreasForPageType($currentPage->ClassName);
        } else {
            $areasFieldSource = $this->blockManager->getAreasForTheme();
        }
        // EDIT
        $blockTypeArray = $this->blockManager->getBlockClasses();
        // /EDIT
        // EditableColumns only makes sense on Saveable parenst (eg Page), or inline changes won't be saved
        if ($editableRows) {
            // set project-dir in cookie to be accessible as fallback from js
            Cookie::set('js-project-dir', project(), 90, null, null, false, false);
            $this->addComponent($editable = new GridFieldEditableColumns());
            $displayfields = array('ClassName' => array('title' => _t('Block.BlockType', 'Block Type') . '
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'callback' => function () use($blockTypeArray) {
                return DropdownField::create('ClassName', 'Block Type', $blockTypeArray)->addExtraClass('select2blocktype')->setAttribute('data-project-dir', project());
            }), 'Title' => array('title' => _t('Block.TitleName', 'Block Name'), 'field' => 'TextField'), 'BlockArea' => array('title' => _t('Block.BlockArea', 'Block Area') . '
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'callback' => function () use($areasFieldSource) {
                return DropdownField::create('BlockArea', 'Block Area', $areasFieldSource)->setHasEmptyDefault(true);
            }), 'isPublishedNice' => array('title' => _t('Block.IsPublishedField', 'Published'), 'field' => 'ReadonlyField'), 'UsageListAsString' => array('title' => _t('Block.UsageListAsString', 'Used on'), 'field' => 'ReadonlyField'));
            if ($aboveOrBelow) {
                $displayfields['AboveOrBelow'] = array('title' => _t('GridFieldConfigBlockManager.AboveOrBelow', 'Above or Below'), 'callback' => function () {
                    return DropdownField::create('AboveOrBelow', _t('GridFieldConfigBlockManager.AboveOrBelow', 'Above or Below'), BlockSet::config()->get('above_or_below_options'));
                });
            }
            $editable->setDisplayFields($displayfields);
            // EDIT
            $this->addComponent($erow = new EditableBlockRow());
            // /EDIT
        } else {
            $this->addComponent($dcols = new GridFieldDataColumns());
            $displayfields = array('singular_name' => _t('Block.BlockType', 'Block Type'), 'Title' => _t('Block.TitleName', 'Block Name'), 'BlockArea' => _t('Block.BlockArea', 'Block Area'), 'isPublishedNice' => _t('Block.IsPublishedField', 'Published'), 'UsageListAsString' => _t('Block.UsageListAsString', 'Used on'));
            $dcols->setDisplayFields($displayfields);
            $dcols->setFieldCasting(array('UsageListAsString' => 'HTMLText->Raw'));
        }
        $this->addComponent(new GridFieldButtonRow('before'));
        // EDIT
        $this->addComponent(new GridFieldButtonRow('after'));
        // /EDIT
        $this->addComponent(new GridFieldToolbarHeader());
        $this->addComponent(new GridFieldDetailForm());
        // EDIT
        //$this->addComponent($sort = new GridFieldSortableHeader());
        //$this->addComponent($filter = new GridFieldFilterHeader());
        //$this->addComponent(new GridFieldDetailForm());
        //$filter->setThrowExceptionOnBadDataType(false);
        //$sort->setThrowExceptionOnBadDataType(false);
        // load enhancements module (eg inline editing etc, needs save action @TODO: move to SiteTree only?
        if (class_exists('GF_BlockEnhancements')) {
            $this->addComponent(new GF_BlockEnhancements());
        }
        // stuff only for BlockAdmin
        if ($controllerClass == 'BlockAdmin') {
            $this->addComponent($sort = new GridFieldSortableHeader());
            $sort->setThrowExceptionOnBadDataType(false);
            $this->addComponent($filter = new GridFieldFilterHeader());
            $filter->setThrowExceptionOnBadDataType(false);
        } else {
            // only for GF on SiteTree
            $this->addComponent(new GridFieldTitleHeader());
            $this->addComponent(new GridFieldFooter());
            // groupable
            $this->addComponent(new GridFieldGroupable('BlockArea', 'Area', 'none', $areasFieldSource));
            //            var_dump($areasFieldSource);
            //            // Get available Areas (for page) enhancements inactive when in ModelAdmin/BlockAdmin
            //            if (Controller::curr() && Controller::curr()->class == 'CMSPageEditController') {
            //                // Provide defined blockAreas to JS
            //                $blockManager = Injector::inst()->get('BlockManager');
            ////            $blockAreas = $blockManager->getAreasForPageType( Controller::curr()->currentPage()->ClassName );
            //                $blockAreas = $blockManager->getAreasForPageType( Controller::curr()->currentPage()->ClassName );
            //            }
        }
        if ($canAdd) {
            $multiClass = new GridFieldAddNewMultiClass('after');
            $classes = $this->blockManager->getBlockClasses();
            $multiClass->setClasses($classes);
            $this->addComponent($multiClass);
            //$this->addComponent(new GridFieldAddNewButton());
        }
        // /EDIT
        if ($controllerClass == 'BlockAdmin' && class_exists('GridFieldCopyButton')) {
            $this->addComponent(new GridFieldCopyButton());
        }
        if ($canEdit) {
            $this->addComponent(new GridFieldEditButton());
        }
        if ($canDelete) {
            $this->addComponent(new GridFieldDeleteAction(true));
        }
        return $this;
    }
 /**
  * @return FieldList
  */
 public function getCMSFields()
 {
     $fields = new FieldList(new TabSet('Root'));
     // Main tab
     $fields->addFieldsToTab('Root.Main', array(ReadonlyField::create('Type', _t('EditableFormField.TYPE', 'Type'), $this->i18n_singular_name()), LiteralField::create('MergeField', _t('EditableFormField.MERGEFIELDNAME', '<div class="field readonly">' . '<label class="left">Merge field</label>' . '<div class="middleColumn">' . '<span class="readonly">$' . $this->Name . '</span>' . '</div>' . '</div>')), TextField::create('Title'), TextField::create('Default', _t('EditableFormField.DEFAULT', 'Default value')), TextField::create('RightTitle', _t('EditableFormField.RIGHTTITLE', 'Right title')), SegmentField::create('Name')->setModifiers(array(UnderscoreSegmentFieldModifier::create()->setDefault('FieldName'), DisambiguationSegmentFieldModifier::create()))->setPreview($this->Name)));
     // Custom settings
     if (!empty(self::$allowed_css)) {
         $cssList = array();
         foreach (self::$allowed_css as $k => $v) {
             if (!is_array($v)) {
                 $cssList[$k] = $v;
             } elseif ($k === $this->ClassName) {
                 $cssList = array_merge($cssList, $v);
             }
         }
         $fields->addFieldToTab('Root.Main', DropdownField::create('ExtraClass', _t('EditableFormField.EXTRACLASS_TITLE', 'Extra Styling/Layout'), $cssList)->setDescription(_t('EditableFormField.EXTRACLASS_SELECT', 'Select from the list of allowed styles')));
     } else {
         $fields->addFieldToTab('Root.Main', TextField::create('ExtraClass', _t('EditableFormField.EXTRACLASS_Title', 'Extra CSS classes'))->setDescription(_t('EditableFormField.EXTRACLASS_MULTIPLE', 'Separate each CSS class with a single space')));
     }
     // Validation
     $validationFields = $this->getFieldValidationOptions();
     if ($validationFields) {
         $fields->addFieldsToTab('Root.Validation', $this->getFieldValidationOptions());
     }
     $allowedClasses = array_keys($this->getEditableFieldClasses(false));
     $self = $this;
     $editableColumns = new GridFieldEditableColumns();
     $editableColumns->setDisplayFields(array('Display' => '', 'ConditionFieldID' => function ($record, $column, $grid) use($allowedClasses, $self) {
         return DropdownField::create($column, '', EditableFormField::get()->filter(array('ParentID' => $self->ParentID, 'ClassName' => $allowedClasses))->exclude(array('ID' => $self->ID))->map('ID', 'Title'));
     }, 'ConditionOption' => function ($record, $column, $grid) {
         $options = Config::inst()->get('EditableCustomRule', 'condition_options');
         return DropdownField::create($column, '', $options);
     }, 'FieldValue' => function ($record, $column, $grid) {
         return TextField::create($column);
     }, 'ParentID' => function ($record, $column, $grid) use($self) {
         return HiddenField::create($column, '', $self->ID);
     }));
     // Custom rules
     $customRulesConfig = GridFieldConfig::create()->addComponents($editableColumns, new GridFieldButtonRow(), new GridFieldToolbarHeader(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction());
     $fields->addFieldsToTab('Root.DisplayRules', array(CheckboxField::create('ShowOnLoad')->setDescription(_t('EditableFormField.SHOWONLOAD', 'Initial visibility before processing these rules')), GridField::create('DisplayRules', _t('EditableFormField.CUSTOMRULES', 'Custom Rules'), $this->DisplayRules(), $customRulesConfig)));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 public function allowLinkToActAsMenu($fields, $form = null, $relation = 'MenuLinks', $parent = null, $controller = null, $item = null)
 {
     if (!$this->owner->config()->always_use_selection_group) {
         $this->updateFields($fields);
     }
     if (!$item) {
         $item = $this->owner;
     }
     $fields->removeByName($relation);
     if (!($typeField = $fields->fieldByName('Root.Main.Type')) || !$typeField instanceof \TabbedSelectionGroup) {
         $fields->addFieldsToTab('Root.Main', [$fieldsForForm[] = \HeaderField::create('HEADING-LINK_TO', _t('Link.LINK_TO', 'Link to:'), 3), $fieldsForForm[] = \FormMessageField::create('MSG-LINK_TO', _t('Link.MSG-LINK_TO', 'When as user clicks on this link in the menu, where does it go?'), 'info')->cms()], 'Type');
     }
     if ($item->exists()) {
         $fieldsForForm[] = $links = \GridField::create($relation, _t('Link.LINKS', 'Links'), $item->{$relation}(), $config = \GridFieldConfig_RecordEditor::create()->addComponent(new \GridFieldDeleteAction(true), 'GridFieldDeleteAction')->addComponent(new \GridFieldTitleHeader())->removeComponentsByType('GridFieldFilterHeader')->removeComponentsByType('GridFieldSortableHeader')->removeComponentsByType('GridFieldPageCount')->removeComponentsByType('GridFieldPaginator')->removeComponentsByType('GridFieldDataColumns')->removeComponentsByType('GridFieldAddNewButton')->addComponent($ec = new \GridFieldEditableColumns(), 'GridFieldEditButton')->addComponent(new \Milkyway\SS\GridFieldUtils\EditableRow(), 'GridFieldEditableColumns')->addComponents(new \GridFieldOrderableRows(), new \GridFieldAddExistingSearchButton('buttons-before-right'), new MinorActionsHolder(), $addNewExtended = new AddNewInlineExtended('actions-buttons-before-left')));
         $addNewExtended->openToggleByDefault = true;
         $model = singleton($item->{$relation}()->dataClass());
         $ec->setDisplayFields($model->EditableColumnsForMenuLinks($links));
         foreach ($model->hasOne() as $hasOneName => $hasOneClass) {
             $config->addComponent((new AddExistingPicker('actions-buttons-before-left'))->setTitle(_t('LinkableMenus.LINK_TO_HAS_ONE', 'Link to a {item}', ['item' => singleton($hasOneClass)->i18n_singular_name()]))->setSearchList(DataList::create($hasOneClass))->setUrlSegment('add-a-' . strtolower($hasOneName))->setAddHandler(function ($request, $grid, $button, $acquireItems) use($model, $hasOneClass, $hasOneName) {
                 $items = $acquireItems($request);
                 if (!$items) {
                     return;
                 }
                 foreach ($items as $item) {
                     $link = $model->create();
                     $link->Type = $hasOneName;
                     $link->{$hasOneName . 'ID'} = $item->ID;
                     $link->write();
                     $grid->getList()->add($link);
                 }
             })->setUndoHandler(function ($request, $grid, $button, $acquireItems) use($model, $hasOneName) {
                 $items = $acquireItems($request);
                 if (!$items) {
                     return;
                 }
                 foreach ($items as $item) {
                     if ($link = $grid->getList()->sort('Created DESC')->filter($hasOneName . 'ID', $item->ID)->first()) {
                         $link->delete();
                     }
                 }
             }));
         }
         if ($item && ($item instanceof \LinkableMenu || $item->Type == 'SiteTree')) {
             if ($item->Type == 'SiteTree') {
                 $config->addComponent(new CopyChildrenFromCurrentPage('actions-buttons-before-left'));
             }
             $config->addComponents((new AddExistingPicker('actions-buttons-before-left'))->setTitle(_t('LinkableMenus.COPY_CHILDREN_FROM', 'Copy children from other {item}', ['item' => singleton('SiteTree')->i18n_singular_name()]))->setSearchList(DataList::create('SiteTree'))->setUrlSegment('copy-links-from-sitetree')->setAddHandler(function ($request, $grid, $button, $acquireItems) use($model) {
                 $items = $acquireItems($request);
                 if (!$items) {
                     return;
                 }
                 foreach ($items as $item) {
                     $children = $item->Children();
                     foreach ($children as $child) {
                         $link = $model->create();
                         $link->Type = 'SiteTree';
                         $link->SiteTreeID = $child->ID;
                         $link->write();
                         $grid->getList()->add($link);
                     }
                 }
             })->setUndoHandler(function ($request, $grid, $button, $acquireItems) use($model) {
                 $items = $acquireItems($request);
                 if (!$items) {
                     return;
                 }
                 foreach ($items as $item) {
                     if ($links = $grid->getList()->Relation('SiteTree')->sort('Created DESC')->filter('ParentID', $item->ID)) {
                         $links->delete();
                     }
                 }
             }), new CopyChildrenFromRoot('actions-buttons-before-left'));
         }
         if ($detailForm = $config->getComponentByType('GridFieldDetailForm')) {
             $detailForm->setItemEditFormCallback(function ($form, $controller) use($item) {
                 if (isset($controller->record)) {
                     $record = $controller->record;
                 } elseif ($form->Record) {
                     $record = $form->Record;
                 } else {
                     $record = null;
                 }
                 if ($record && $record instanceof \Link) {
                     $record->allowLinkToActAsMenu($form->Fields(), $form, 'MenuLinks', $item, $controller);
                 }
             });
         }
     } else {
         $fieldsForForm[] = $links = \FormMessageField::create('ERR-SAVE_FIRST', _t('LinkableMenus.SAVE_FIRST', 'Please save before adding any sub-menu links'), 'warning')->cms();
     }
     $fields->addFieldsToTab('Root.Main', [$fieldsForForm[] = \LiteralField::create('HR-SUB_MENU', '<p><br /></p>'), $fieldsForForm[] = \HeaderField::create('HEADING-SUB_MENU', _t('Link.SUB_MENU', 'Sub-menu'), 3), $links]);
     if ($form) {
         foreach ($fieldsForForm as $field) {
             $field->setForm($form);
         }
     }
     $this->owner->extend('updateLinkThatCanActAsMenuFields', $fields, $form, $relation, $parent, $controller, $item);
 }
 function updateCMSFields(\FieldList $fields)
 {
     $fields->addFieldToTab('Root.Configuration', new TextField('BaseFolder', _t('SubsiteExtra.BaseFolder', 'Base folder')));
     // Profiles
     $profiles = ClassInfo::subclassesFor('SubsiteProfile');
     array_shift($profiles);
     if (!empty($profiles)) {
         $profiles = array('' => '') + $profiles;
         $fields->insertAfter(new DropdownField('Profile', _t('SubsiteExtra.SubsiteProfile', 'Subsite profile'), $profiles), 'Title');
     }
     // Better gridfield
     if (class_exists('GridFieldEditableColumns')) {
         $DomainsGridField = GridFieldConfig::create()->addComponent(new GridFieldButtonRow('before'))->addComponent(new GridFieldTitleHeader())->addComponent($editableCols = new GridFieldEditableColumns())->addComponent(new GridFieldDeleteAction())->addComponent($addNew = new GridFieldAddNewInlineButton());
         $addNew->setTitle(_t('SubsitesExtra.ADD_NEW', "Add a new subdomain"));
         $editableColsFields = array();
         $editableColsFields['IsPrimary'] = array('title' => _t('SubsiteExtra.IS_PRIMARY', 'Is Primary'), 'callback' => function ($record, $column, $grid) {
             $field = new CheckboxField($column);
             return $field;
         });
         $editableColsFields['Domain'] = array('title' => _t('SubsitesExtra.TITLE', "Domain"), 'callback' => function ($record, $column, $grid) {
             $field = new TextField($column);
             $field->setAttribute('placeholder', 'mydomain.ext');
             return $field;
         });
         $editableCols->setDisplayFields($editableColsFields);
         $DomainsGridField = new GridField("Domains", _t('Subsite.DomainsListTitle', "Domains"), $this->owner->Domains(), $DomainsGridField);
         if ($fields->dataFieldByName('Domains')) {
             $fields->replaceField('Domains', $DomainsGridField);
         }
     }
 }
 /**
  * @return FieldList
  */
 public function getCMSFields()
 {
     /** =========================================
          * Requirements
         ===========================================*/
     Requirements::css('roster/css/rosterAdmin.css');
     $fields = parent::getCMSFields();
     $endDate = $this->EndDate;
     $startDate = $this->StartDate;
     /** =========================================
         * Date
         ==========================================*/
     /** @var MultiDateField $holidayField */
     $holidayField = MultiDateField::create('Holidays');
     $holidayField->setConfig('dateformat', 'dd-MM-yyyy');
     $holidayField->setConfig('showcalendar', true);
     $holidayField->setConfig('separator', ', ');
     $holidayField->setConfig('min', $startDate);
     $holidayField->setConfig('max', $endDate);
     /** @var DateField $dateField */
     $dateField = DateField::create('StartDate');
     $dateField->setConfig('dateformat', 'dd-MM-yyyy');
     $fields->addFieldsToTab('Root.Main', array($dateField, $holidayField));
     /** @var $dateField DateField */
     $dateField->setConfig('showcalendar', true);
     /** =========================================
          * Staff Roster
         ===========================================*/
     $fields->removeByName(array('WeeklyRosters', 'StaffLeave', 'EndDate'));
     /** -----------------------------------------
          * Variables
         -------------------------------------------*/
     $roles = JobRole::get();
     $numberOfDays = Config::inst()->get('Roster', 'number_of_days') ?: 5;
     /** @var DataList $staffMembers */
     $staffMembers = Group::get()->filter(array('Code' => 'staff-members'))->first()->Members();
     $staffMap = $staffMembers->count() ? $staffMembers->map('ID', 'Initials')->toArray() : array();
     /** -----------------------------------------
          * Fields
         -------------------------------------------*/
     if ($roles->count()) {
         /** -----------------------------------------
              * Weekly Rosters
             -------------------------------------------*/
         if ($this->WeeklyRosters()->count()) {
             $editableColumns = new GridFieldEditableColumns();
             $editableColumns->setDisplayFields(array('Title' => array('title' => 'Role', 'field' => 'ReadonlyField'), 'StaffAm0' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'AM', $staffMap)->setMultiple(true);
             }, 'StaffPm0' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'PM', $staffMap)->setMultiple(true);
             }, 'StaffAm1' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'AM', $staffMap)->setMultiple(true);
             }, 'StaffPm1' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'PM', $staffMap)->setMultiple(true);
             }, 'StaffAm2' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'AM', $staffMap)->setMultiple(true);
             }, 'StaffPm2' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'PM', $staffMap)->setMultiple(true);
             }, 'StaffAm3' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'AM', $staffMap)->setMultiple(true);
             }, 'StaffPm3' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'PM', $staffMap)->setMultiple(true);
             }, 'StaffAm4' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'AM', $staffMap)->setMultiple(true);
             }, 'StaffPm4' => function ($record, $column, $grid) use($staffMap) {
                 return ListboxField::create($column, 'PM', $staffMap)->setMultiple(true);
             }));
             // Adjust the WeeklyRoster gridfield
             $grid = GridField::create('WeeklyRosters', sprintf('Weekly Roster for %s - %s', $this->dbObject('StartDate')->Format('D jS M'), $this->dbObject('EndDate')->Format('D jS M')), $this->WeeklyRosters(), GridFieldConfig::create()->addComponent(new GridFieldToolbarHeader())->addComponent(new RosterGridFieldTitleHeader($this->dbObject('StartDate'), $this->getHolidayArray()))->addComponent($editableColumns))->addExtraClass('roster-gridfield');
             $fields->addFieldToTab('Root.Main', $grid);
         } else {
             $fields->addFieldToTab('Root.Main', LiteralField::create('', sprintf('<div class="message notice"><p>%s</p></div>', _t('Roster.SaveFirstNotice', 'Choose a starting date, then press the green "Save" button at the bottom of the screen.'))));
             $this->WeeklyRosters()->addMany($roles);
         }
         /** -----------------------------------------
              * Staff Leave
             -------------------------------------------*/
         if ($this->StaffLeave()->count()) {
             $editableColumns = new GridFieldEditableColumns();
             $editableColumns->setDisplayFields(array('Title' => array('title' => 'Staff Member', 'field' => 'ReadonlyField'), 'Leave' => function ($record, $column, $grid) use($staffMap, $startDate, $endDate) {
                 return MultiDateField::create($column)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('showcalendar', true)->setConfig('separator', ', ')->setConfig('min', $startDate)->setConfig('max', $endDate);
             }));
             $grid = GridField::create('StaffLeave', sprintf('Staff Leave for %s - %s', $this->dbObject('StartDate')->Format('D jS M'), $this->dbObject('EndDate')->Format('D jS M')), $this->StaffLeave(), GridFieldConfig::create()->addComponent(new GridFieldToolbarHeader())->addComponent(new GridFieldTitleHeader())->addComponent($editableColumns))->addExtraClass('staff-leave-gridfield');
             $fields->addFieldToTab('Root.Main', $grid);
         } else {
             $this->StaffLeave()->addMany($staffMembers);
         }
     } else {
         // If no job roles exist, display a warning
         $fields->addFieldToTab('Root.Main', LiteralField::create('', sprintf('<div class="message warning"><p>%s</p></div>', _t('Roster.NoRoleWarning', 'Can&apos;t create roster; no job roles exist. Add new roles under the "Job Roles" tab.'))));
     }
     return $fields;
 }