/** * Gets the heading, or label, for the interface, e.g. "Select the categories for this product" * * @return string */ public function getHeading() { if (!$this->get('Heading')) { return FormField::name_to_label($this->getParentNode()->transform("BedrockComponent")->getName()); } return $this->get('Heading'); }
public function updateCMSFields(FieldList $fields) { $extFields = self::$db; $fields->removeByName(array_keys($extFields)); if (!$this->owner->WordpressID) { return; } $compositeFields = array(); foreach ($extFields as $name => $type) { $value = $this->owner->getField($name); $compositeFields[$name] = ReadonlyField::create($name . '_Readonly', FormField::name_to_label($name), $value); } if ($compositeFields) { $wordpressCompositeField = ToggleCompositeField::create('WordpressCompositeField', 'Wordpress', $compositeFields)->setHeadingLevel(4); if ($fields->fieldByName('Metadata')) { $fields->insertBefore($wordpressCompositeField, 'Metadata'); } else { if ($fields->fieldByName('Root')) { $fields->addFieldToTab('Root.Main', $wordpressCompositeField); } else { $fields->push($wordpressCompositeField); } } } }
protected function handlePost(array $data, $settings = []) { $post = ['ID' => isset($data['id']) && isset($data['id']['videoId']) ? $data['id']['videoId'] : '0', 'Author' => isset($data['snippet']) && isset($data['snippet']['channelTitle']) ? \FormField::name_to_label($data['snippet']['channelTitle']) : '', 'AuthorID' => isset($data['snippet']) && isset($data['snippet']['channelId']) ? $data['snippet']['channelId'] : 0, 'AuthorURL' => isset($data['snippet']) && isset($data['snippet']['channelId']) ? \Controller::join_links($this->url, 'channel', $data['snippet']['channelId']) : '', 'Title' => isset($data['snippet']) && isset($data['snippet']['title']) ? $data['snippet']['title'] : '', 'Content' => isset($data['snippet']) && isset($data['snippet']['description']) ? $this->textParser()->text($data['snippet']['description']) : '', 'Priority' => isset($data['snippet']) && isset($data['snippet']['publishedAt']) ? strtotime($data['snippet']['publishedAt']) : 0, 'Posted' => isset($data['snippet']) && isset($data['snippet']['publishedAt']) ? \DBField::create_field('SS_Datetime', strtotime($data['snippet']['publishedAt'])) : null]; if (isset($data['snippet']) && isset($data['snippet']['thumbnails'])) { if (isset($data['snippet']['thumbnails']['high']) && isset($data['snippet']['thumbnails']['high']['url'])) { $post['Cover'] = $data['snippet']['thumbnails']['high']['url']; } else { if (isset($data['snippet']['thumbnails']['medium']) && isset($data['snippet']['thumbnails']['medium']['url'])) { $post['Cover'] = $data['snippet']['thumbnails']['medium']['url']; } else { if (isset($data['snippet']['thumbnails']['default']) && isset($data['snippet']['thumbnails']['default']['url'])) { $post['Cover'] = $data['snippet']['thumbnails']['default']['url']; } } } } if ($post['ID']) { $params = (array) singleton('env')->get('Youtube.video_params'); if (isset($settings['videoParams'])) { $params = array_merge($params, (array) $settings['videoParams']); } $params['v'] = $post['ID']; $post['Link'] = \Controller::join_links($this->url, 'watch', '?' . http_build_query($params)); $this->setFromEmbed($post); } if (isset($post['ObjectDescription']) && $post['ObjectDescription'] == $post['Content']) { unset($post['ObjectDescription']); } if (isset($post['Description']) && $post['Description'] == $post['Content']) { unset($post['Description']); } return $post; }
/** * @param string $name Identifier * @param string $title (Optional) Natural language title of the tabset * @param Tab|TabSet $unknown All further parameters are inserted as children into the TabSet */ public function __construct($name) { $args = func_get_args(); $name = array_shift($args); if (!is_string($name)) { user_error('TabSet::__construct(): $name parameter to a valid string', E_USER_ERROR); } $this->name = $name; $this->id = $name; // Legacy handling: only assume second parameter as title if its a string, // otherwise it might be a formfield instance if (isset($args[0]) && is_string($args[0])) { $title = array_shift($args); } $this->title = isset($title) ? $title : FormField::name_to_label($name); if ($args) { foreach ($args as $tab) { $isValidArg = is_object($tab) && (!$tab instanceof Tab || !$tab instanceof TabSet); if (!$isValidArg) { user_error('TabSet::__construct(): Parameter not a valid Tab instance', E_USER_ERROR); } $tab->setTabSet($this); } } parent::__construct($args); }
/** * Gets an array of all areas defined for the current theme that are compatible * with pages of type $class * @param string $class * @return array $areas **/ public function getAreasForPageType($class) { $areas = $this->getAreasForTheme(null, false); if (!$areas) { return false; } foreach ($areas as $area => $config) { if (!is_array($config)) { continue; } if (isset($config['except'])) { $except = $config['except']; if (is_array($except) ? in_array($class, $except) : $except == $class) { unset($areas[$area]); continue; } } if (isset($config['only'])) { $only = $config['only']; if (is_array($only) ? !in_array($class, $only) : $only != $class) { unset($areas[$area]); continue; } } } if (count($areas)) { foreach ($areas as $k => $v) { $areas[$k] = FormField::name_to_label($k); } return $areas; } else { return $areas; } }
public function updateFieldLabels(&$labels) { foreach (array('db', 'has_one', 'has_many', 'many_many', 'belongs_many_many') as $type) { if (property_exists(__CLASS__, $type)) { foreach (self::${$type} as $name => $val) { $labels[$name] = _t(__CLASS__ . ".{$type}_{$name}", FormField::name_to_label($name)); } } } }
/** * @param FieldList $fields * @return FieldList */ public function updateCMSFields(FieldList $fields) { if ($this->currencyService instanceof CurrencyServiceInterface) { foreach ($this->currencyService->getCurrencies() as $currency) { $columnName = $this->getColumnName($currency); $fields->removeByName($columnName); $fields->addFieldToTab('Root.Prices', new NumericField($columnName, \FormField::name_to_label($columnName))); } } return $fields; }
public function __construct($name) { Requirements::css(RIGHTSIDEBAR_DIR . '/css/cms.css'); Requirements::javascript(RIGHTSIDEBAR_DIR . '/js/cms.js'); $args = func_get_args(); $name = array_shift($args); if (!is_string($name)) { user_error('RightSidebar::__construct(): $name parameter to a valid string', E_USER_ERROR); } $this->name = $name; $this->id = preg_replace('/[^0-9A-Za-z]+/', '', $name); $this->title = isset($title) ? $title : FormField::name_to_label($name); parent::__construct($args); }
/** * Generates the edit lock warning message displayed to the user * @return String **/ public function getLockedMessage() { $editor = $this->Editor(); $editorString = $editor->getTitle(); if ($editor->Email) { $editorString .= " <<a href='mailto:{$editor->Email}'>{$editor->Email}</a>>"; } $message = sprintf(_t('RecordBeingEdited.LOCKEDMESSAGE', 'Sorry, this %s is currently being edited by %s. To avoid conflicts and data loss, editing will be locked until they are finished.'), FormField::name_to_label($this->RecordClass), $editorString); if ($this->canEditAnyway()) { $editAnywayLink = Controller::join_links(Controller::curr()->getRequest()->requestVar('url'), '?editanyway=1'); $message .= "<span style='float:right'>"; $message .= sprintf(_t('RecordBeingEdited.EDITANYWAY', 'I understand the risks, %s edit anyway %s'), "<a href='{$editAnywayLink}'>", "</a>"); $message .= "</span>"; } return $message; }
/** * @uses FormField::name_to_label() * * @param string $name Identifier of the tab, without characters like dots or spaces * @param string $title Natural language title of the tab. If its left out, * the class uses {@link FormField::name_to_label()} to produce a title from the {@link $name} parameter. * @param FormField All following parameters are inserted as children to this tab */ public function __construct($name) { $args = func_get_args(); $name = array_shift($args); if (!is_string($name)) { user_error('TabSet::__construct(): $name parameter to a valid string', E_USER_ERROR); } $this->name = $name; $this->id = preg_replace('/[^0-9A-Za-z]+/', '', $name); // Legacy handling: only assume second parameter as title if its a string, // otherwise it might be a formfield instance if (isset($args[0]) && is_string($args[0])) { $title = array_shift($args); } $this->title = isset($title) ? $title : FormField::name_to_label($name); parent::__construct($args); }
public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab('Root', new TabSet('Profile', _t('MemberProfiles.PROFILE', 'Profile'))); $fields->addFieldToTab('Root', new Tab('ContentBlocks', _t('MemberProfiles.CONTENTBLOCKS', 'Content Blocks'))); $fields->addFieldToTab('Root', new Tab('Email', _t('MemberProfiles.Email', 'Email'))); $fields->fieldByName('Root.Main')->setTitle(_t('MemberProfiles.MAIN', 'Main')); $fields->addFieldsToTab('Root.Profile', array(new Tab('Fields', _t('MemberProfiles.FIELDS', 'Fields'), new GridField('Fields', _t('MemberProfiles.PROFILEFIELDS', 'Profile Fields'), $this->Fields(), $grid = GridFieldConfig_RecordEditor::create()->removeComponentsByType('GridFieldDeleteAction')->removeComponentsByType('GridFieldAddNewButton'))), new Tab('Groups', _t('MemberProfiles.GROUPS', 'Groups'), $groups = new TreeMultiselectField('Groups', _t('MemberProfiles.GROUPS', 'Groups'), 'Group'), $selectable = new TreeMultiselectField('SelectableGroups', _t('MemberProfiles.SELECTABLEGROUPS', 'Selectable Groups'), 'Group')), new Tab('PublicProfile', _t('MemberProfiles.PUBLICPROFILE', 'Public Profile'), new GridField('Sections', _t('MemberProfiles.PROFILESECTIONS', 'Profile Sections'), $this->Sections(), GridFieldConfig_RecordEditor::create()->removeComponentsByType('GridFieldAddNewButton')->addComponent(new MemberProfilesAddSectionAction()))))); $grid->getComponentByType('GridFieldDataColumns')->setFieldFormatting(array('Unique' => function ($val, $obj) { return $obj->dbObject('Unique')->Nice(); }, 'Required' => function ($val, $obj) { return $obj->dbObject('Required')->Nice(); })); if (class_exists('GridFieldOrderableRows')) { $grid->addComponent(new GridFieldOrderableRows('Sort')); } elseif (class_exists('GridFieldSortableRows')) { $grid->addComponent(new GridFieldSortableRows('Sort')); } if (!$this->AllowProfileViewing) { $disabledNote = new LiteralField('PublisProfileDisabledNote', sprintf('<p class="message notice">%s</p>', _t('MemberProfiles.PUBLICPROFILEDISABLED', 'Public profiles are currently disabled, you can enable them ' . 'in the "Settings" tab.'))); $fields->insertBefore($disabledNote, 'Sections'); } $groups->setDescription(_t('MemberProfiles.GROUPSNOTE', 'Any users registering via this page will always be added to ' . 'these groups (if registration is enabled). Conversely, a member ' . 'must belong to these groups in order to edit their profile on ' . 'this page.')); $selectable->setDescription(_t('MemberProfiles.SELECTABLENOTE', 'Users can choose to belong to these groups, if the "Groups" field ' . 'is enabled in the "Fields" tab.')); $fields->removeByName('Content', true); $contentFields = array(); if ($this->AllowRegistration) { $contentFields[] = 'Registration'; $contentFields[] = 'AfterRegistration'; } if ($this->AllowProfileEditing) { $contentFields[] = 'Profile'; } foreach ($contentFields as $type) { $fields->addFieldToTab("Root.ContentBlocks", new ToggleCompositeField("{$type}Toggle", _t('MemberProfiles.' . strtoupper($type), FormField::name_to_label($type)), array(new TextField("{$type}Title", _t('MemberProfiles.TITLE', 'Title')), $content = new HtmlEditorField("{$type}Content", _t('MemberProfiles.CONTENT', 'Content'))))); $content->setRows(15); } $fields->addFieldsToTab('Root.Email', array(new OptionsetField('EmailType', _t('MemberProfiles.EMAILSETTINGS', 'Email Settings'), array('Validation' => _t('MemberProfiles.EMAILVALIDATION', 'Require email validation'), 'Confirmation' => _t('MemberProfiles.EMAILCONFIRMATION', 'Send a confirmation email'), 'None' => _t('MemberProfiles.NONE', 'None'))), new ToggleCompositeField('EmailContentToggle', _t('MemberProfiles.EMAILCONTENT', 'Email Content'), array(new TextField('EmailSubject', _t('MemberProfiles.EMAILSUBJECT', 'Email subject')), new TextField('EmailFrom', _t('MemberProfiles.EMAILFROM', 'Email from')), new TextareaField('EmailTemplate', _t('MemberProfiles.EMAILTEMPLATE', 'Email template')), new LiteralField('TemplateNote', sprintf('<div class="field">%s</div>', MemberConfirmationEmail::TEMPLATE_NOTE)))), new ToggleCompositeField('ConfirmationContentToggle', _t('MemberProfiles.CONFIRMCONTENT', 'Confirmation Content'), array(new TextField('ConfirmationTitle', _t('MemberProfiles.TITLE', 'Title')), $confContent = new HtmlEditorField('ConfirmationContent', _t('MemberProfiles.CONTENT', 'Content')))))); $confContent->setRows(15); return $fields; }
/** * A wildcard method for accepting any FormField object as a method. * Ex: text(), currency(), dropdown(), treeDropdown(), htmlEditor() * * @param string The method being called * @param array The arguments to the method * @return FieldList */ public function __call($method, $args) { $formFieldClass = ucfirst($method) . "Field"; $getter = "get" . ucfirst($method); if ($this->owner->hasMethod($getter)) { return $this->owner->{$getter}(); } if (is_subclass_of($formFieldClass, "FormField")) { if (!isset($args[0])) { user_error("FieldList::{$method} -- Missing argument 1 for field name", E_ERROR); } if (!isset($args[1])) { $args[1] = FormField::name_to_label($args[0]); } $field = Injector::inst()->createWithArgs($formFieldClass, $args); $this->add($field); $this->field = $field; $field->FieldList = $this->owner; return $this->owner; } else { user_error("FieldList::{$method} -- {$formFieldClass} is not a FormField.", E_ERROR); } }
public function collectFromEntityProviders($filePath, $module = null) { $entities = []; // HACK Ugly workaround to avoid "Cannot redeclare class PHPUnit_Framework_TestResult" error // when running text collector with PHPUnit 3.4. There really shouldn't be any dependencies // here, but the class reflection enforces autloading of seemingly unrelated classes. // The main problem here is the CMSMenu class, which iterates through test classes, // which in turn trigger autoloading of PHPUnit. $phpunitwrapper = PhpUnitWrapper::inst(); $phpunitwrapper->init(); $classes = ClassInfo::classes_for_file($filePath); if ($classes) { foreach ($classes as $class) { // Not all classes can be instanciated without mandatory arguments, // so entity collection doesn't work for all SilverStripe classes currently // Requires PHP 5.1+ if (class_exists($class) && in_array('i18nEntityProvider', class_implements($class))) { $reflectionClass = new ReflectionClass($class); if ($reflectionClass->isAbstract()) { continue; } $obj = singleton($class); $entities = array_merge($entities, (array) $obj->provideI18nEntities()); if ($obj->is_a('DataObject')) { foreach (['db', 'has_one', 'has_many', 'many_many', 'belongs_many_many'] as $type) { foreach ((array) Config::inst()->get($obj->class, $type, Config::UNINHERITED) as $name => $spec) { $entities["{$obj->class}.{$type}_{$name}"] = [FormField::name_to_label($name)]; } } } } } } ksort($entities); return $entities; }
/** * Add a new provider (triggered by the ExternalContentAdmin_left template) * * @return unknown_type */ public function addprovider() { // Providers are ALWAYS at the root $parent = 0; $name = isset($_REQUEST['Name']) ? basename($_REQUEST['Name']) : _t('ExternalContent.NEWCONNECTOR', "New Connector"); $type = $_REQUEST['ProviderType']; $providerClasses = ClassInfo::subclassesFor(self::$tree_class); if (!in_array($type, $providerClasses)) { throw new Exception("Invalid connector type"); } $parentObj = null; // Create object $record = new $type(); $record->ParentID = $parent; $record->Name = $record->Title = $name; // if (isset($_REQUEST['returnID'])) { // return $p->ID; // } else { // return $this->returnItemToUser($p); // } try { $record->write(); } catch (ValidationException $ex) { $form->sessionMessage($ex->getResult()->message(), 'bad'); return $this->getResponseNegotiator()->respond($this->request); } singleton('CMSPageEditController')->setCurrentPageID($record->ID); Session::set("FormInfo.Form_EditForm.formError.message", sprintf(_t('ExternalContent.SourceAdded', 'Successfully created %s'), $type)); Session::set("FormInfo.Form_EditForm.formError.type", 'good'); $msg = "New " . FormField::name_to_label($type) . " created"; $this->response->addHeader('X-Status', rawurlencode(_t('ExternalContent.PROVIDERADDED', $msg))); return $this->getResponseNegotiator()->respond($this->request); }
public function getDashletsList() { if ($this->allowedDashlets) { return $this->allowedDashlets; } $dashlets = self::get_allowed_dashlets(); // prune any that have specific requirements foreach ($dashlets as $cls => $title) { $clazz = is_int($cls) ? $title : $cls; $dummy = singleton($clazz); if (!$dummy->canCreate()) { unset($dashlets[$cls]); } } $keys = array_keys($dashlets); if (count($keys) && is_int($keys[0])) { foreach (array_values($dashlets) as $dashletClass) { $title = Config::inst()->get($dashletClass, 'title'); if (!$title) { FormField::name_to_label($dashletClass); } $this->allowedDashlets[$dashletClass] = $title; } } else { $this->allowedDashlets = $dashlets; } return $this->allowedDashlets; }
public static function getHrefField(DataObject $do, $property = 'Href') { /** @var MapaelCountryPageExtension|MapaelCity $do */ return new TextField($property, _t(__CLASS__ . '.db_Href', FormField::name_to_label($property)), $do->{$property}); }
/** * @todo Explain different source data that can be used with this field, * e.g. SQLMap, DataObjectSet or an array. * * @todo Should use CheckboxField FieldHolder rather than constructing own markup. */ function Field() { Requirements::css(NEWSLETTER_DIR . '/css/CheckboxSetWithExtraField.css'); $source = $this->source; $values = $this->value; // Get values from the join, if available if (is_object($this->form)) { $record = $this->form->getRecord(); if (!$values && $record && $record->hasMethod($this->name)) { $funcName = $this->name; $join = $record->{$funcName}(); if ($join) { foreach ($join as $joinItem) { $values[] = $joinItem->ID; } } } } // Source is not an array if (!is_array($source) && !is_a($source, 'SQLMap')) { if (is_array($values)) { $items = $values; } else { // Source and values are DataObject sets. if ($values && is_a($values, 'DataObjectSet')) { foreach ($values as $object) { if (is_a($object, 'DataObject')) { $items[] = $object->ID; } } } elseif ($values && is_string($values)) { $items = explode(',', $values); $items = str_replace('{comma}', ',', $items); } } } else { // Sometimes we pass a singluar default value thats ! an array && !DataObjectSet if (is_a($values, 'DataObjectSet') || is_array($values)) { $items = $values; } else { $items = explode(',', $values); $items = str_replace('{comma}', ',', $items); } } if (is_array($source)) { unset($source['']); } $odd = 0; $options = ''; if ($source == null) { $source = array(); $options = "<tr><td>No options available</td></tr>"; } else { $header = "<thead><tr><th>Checked?</th>"; $footer = "<tfoot><tr><td>Checked?</td>"; if (!empty($this->extra)) { foreach ($this->extra as $label => $type) { $fieldLabel = FormField::name_to_label($label); $header .= "<th>{$fieldLabel}</th>"; $footer .= "<td>{$fieldLabel}</td>"; } } //add a column for drag&drop icon if ($this->tragable) { $header .= "<th></th>"; $footer .= "<td></td>"; } $header .= "</tr></thead>"; $footer .= "</tr></tfoot>"; foreach ($source as $index => $item) { if (is_a($item, 'DataObject')) { $key = $item->ID; $value = $item->Title; } else { $key = $index; $value = $item; } $odd = ($odd + 1) % 2; $extraClass = $odd ? 'odd' : 'even'; $extraClass .= ' val' . str_replace(' ', '', $key); $itemID = $this->id() . '_' . ereg_replace('[^a-zA-Z0-9]+', '', $key); $checked = ''; if (isset($items)) { $checked = in_array($key, $items) ? ' checked="checked"' : ''; } $disabled = isset($this->cellDisabled[$key]) && in_array('Value', $this->cellDisabled[$key]) ? $disabled = ' disabled="disabled"' : ''; $options .= "<tr class=\"{$extraClass}\">\n\t\t\t\t<td>\n\t\t\t\t<input id=\"{$itemID}\" name=\"{$this->name}[{$key}][Value]\" type=\"checkbox\" value=\"{$key}\"{$checked} {$disabled} class=\"checkbox\" /> {$value}\n\t\t\t\t</td>"; if (!empty($this->extraValue)) { foreach ($this->extraValue as $label => $val) { if ($val) { $extraValue[$label] = Convert::json2array($val); } } } if (!empty($this->extra)) { foreach ($this->extra as $label => $fieldType) { $value = ""; if (isset($extraValue[$label][$key])) { $value = $extraValue[$label][$key]; } $dbField = DBField::create($fieldType, $value, $this->name . "[" . $key . "][" . $label . "]"); $extraField = $dbField->scaffoldFormField($this->name . "[" . $key . "][" . $label . "]"); $extraField->setValue($value); if (isset($this->cellDisabled[$key]) && in_array($label, $this->cellDisabled[$key])) { $extraField->setDisabled(true); } $options .= "<td>" . $extraField->Field() . "</td>"; } } $options .= "<td class=\"dragHandle\"></td>"; $options .= "</tr>"; } } return "<table id=\"{$this->id()}\" class=\"optionset checkboxsetwithextrafield{$this->extraClass()}\">" . $header . $footer . $options . "</table>\n"; }
/** * Present translatable form fields in a more readable fashion * @see DataExtension::updateFieldLabels() * @inheritdoc */ public function updateFieldLabels(&$labels) { parent::updateFieldLabels($labels); $statics = self::$collectorCache[$this->ownerBaseClass]; foreach ($statics as $field => $type) { $parts = explode(TRANSLATABLE_COLUMN_SEPARATOR, $field); $labels[$field] = FormField::name_to_label($parts[0]) . ' (' . $parts[1] . ')'; } }
public function getCMSFields() { $this->beforeExtending('updateCMSFields', function ($fields) { $fields->removeByName('Automated'); $fields->removeByName('AuthorID'); $fields->removeByName('OrderID'); $fields->removeByName('Changes'); $fields->removeByName('FirstRead'); // Disables the default firing of sent to customer flag $fields->removeByName('SentToCustomer'); // Status Field $allSuggestedStatuses = (array) $this->config()->status_list; $statusesWithIcons = $otherStatuses = []; // Check if readonly $editable = $this->canEdit(); $simplified = !Permission::check('ADMIN') && $this->Automated && !in_array($this->Status, static::$DETAILED_STATUS); $dataFields = $fields->dataFields(); if ($editable) { $fields->removeByName('Status'); foreach ($allSuggestedStatuses as $status => $options) { if (is_array($options) && !empty($options['icon'])) { $statusesWithIcons[$status] = isset($options['title']) ? $options['icon'] . ' ' . $options['title'] : $options['icon'] . ' ' . $status; } else { if (is_array($options) && !empty($options['title'])) { $otherStatuses[$status] = $options['title']; } else { $otherStatuses[$status] = $options; } } } $otherStatuses = array_merge($otherStatuses, $this->get()->exclude('Status', array_merge(array_keys($allSuggestedStatuses)))->sort('Status', 'ASC')->map('Status', 'Status')->toArray()); $statuses = ['Common Statuses' => $statusesWithIcons]; if (!empty($otherStatuses)) { asort($otherStatuses); $statuses['Other Status'] = $otherStatuses; foreach ($statuses['Other Status'] as $status => $title) { $statuses['Other Status'][$status] = FormField::name_to_label($title); } } $fields->insertBefore($statusField = Select2Field::create('Status', 'Status', '', $statuses)->setMinimumSearchLength(0)->setEmptyString('You can select from suggested statuses, or create a new status')->setAttribute('data-format-searching', _t('OrderLog.SEARCHING-Status', 'Loading statuses...')), 'Title'); $statusField->requireSelection = false; if (!Permission::check('ADMIN')) { $statusField->disabledOptions = $this->config()->disallowed_multiple_statuses; } if ($this->exists() && !Permission::check('ADMIN') && ($this->Automated || $this->AuthorID != Member::currentUserID())) { $statusField->setAttribute('disabled', 'disabled'); } elseif ($editable) { $statusField->setDescription(_t('OrderLog.DESC-Status', 'Note: {updated} is a special status. If there are more than {limit} logs for an order, it will automatically delete statuses classed as {updated}, so use with caution.', ['updated' => implode(', ', (array) static::$GENERIC_STATUS), 'limit' => $this->config()->max_records_per_order])); } $statusField->allowHTML = true; $statusField->prefetch = true; } elseif (isset($dataFields['Status'])) { $fields->removeByName('Status'); $fields->insertBefore('Title', $dataFields['Status']); } if (isset($dataFields['Title']) && $editable) { $dataFields['Title']->setDescription(_t('OrderLog.DESC-Title', 'If not set, will automatically use the Status above')); } elseif (!$editable && $this->Title == $this->Status) { $fields->removeByName('Title'); } $lastField = 'Title'; if (!$editable && !$this->Note) { $fields->removeByName('Note'); } elseif ($editable && isset($dataFields['Note']) && $dataFields['Note'] instanceof TextareaField) { $dataFields['Note']->setRows(2); $lastField = 'Note'; } else { $lastField = 'Note'; } $fieldSet = []; foreach (['Public', 'Unread'] as $field) { if (isset($dataFields[$field])) { $fieldSet[$field] = $dataFields[$field]; $fields->removeByName($field); } } if (!empty($fieldSet)) { if (isset($fieldSet['Public'])) { $fieldSet['Public']->setTitle($fieldSet['Public']->Title() . ' (' . _t('OrderLog.DESC-Public', 'If checked, user can view this log on the front-end when checking the status of their orders') . ')'); } if ($this->FirstRead) { $fieldSet['FirstRead'] = DatetimeField::create('FirstRead'); } $fields->insertAfter(FieldGroup::create($fieldSet)->setTitle('Public Visibility')->setName('PublicFields')->addExtraClass('hero-unit stacked-items'), $lastField); $fieldSet = []; $lastField = 'PublicFields'; } foreach (['DispatchTicket', 'DispatchedBy', 'DispatchedOn'] as $field) { if (($simplified || !$editable) && !$this->{$field}) { $fields->removeByName($field); continue; } if (isset($dataFields[$field])) { $fieldSet[$field] = $dataFields[$field]; $fields->removeByName($field); if ($fieldSet[$field] instanceof DateField) { $fieldSet[$field]->setConfig('showcalendar', true); } if ($field == 'DispatchTicket') { $fieldSet[$field]->setTitle(_t('OrderLog.TRACKING_ID', 'Tracking ID')); } elseif ($field == 'DispatchedBy') { $fieldSet[$field]->setTitle(_t('OrderLog.VIA', 'via')); } elseif ($field == 'DispatchedOn') { $fieldSet[$field]->setTitle(_t('OrderLog.ON', 'on')); } } } if (!empty($fieldSet)) { $fields->removeByName('DispatchUri'); $fields->insertAfter($dispatched = CompositeField::create(FieldGroup::create($fieldSet)->setTitle('Dispatched')->setName('DispatchedDetails'))->setName('Dispatched')->addExtraClass('hero-unit'), $lastField); if ($editable || $this->DispatchUri) { $dispatched->push(TextField::create('DispatchUri', _t('OrderLog.DispatchUri', 'Tracking URL'))->setDescription(_t('OrderLog.DESC-DispatchUri', 'If none provided, will attempt to use the URL of the carrier'))); } $fieldSet = []; $lastField = 'Dispatched'; } elseif (($simplified || !$editable) && !$this->DispatchUri) { $fields->removeByName('DispatchUri'); } foreach (['PaymentCode', 'PaymentOK'] as $field) { if (($simplified || !$editable) && !$this->{$field}) { $fields->removeByName($field); continue; } if (isset($dataFields[$field])) { $fieldSet[$field] = $dataFields[$field]; $fields->removeByName($field); if ($field == 'PaymentCode') { $fieldSet[$field]->setTitle(_t('OrderLog.CODE', 'Code')); } } } if (!empty($fieldSet)) { $fields->insertAfter(FieldGroup::create($fieldSet)->setTitle('Payment')->setName('Payment')->addExtraClass('hero-unit'), $lastField); $fieldSet = []; } // Email Fields $fields->removeByName('Send_To'); $fields->removeByName('Send_Subject'); $fields->removeByName('Send_Body'); $fields->removeByName('Send_From'); $fields->removeByName('Send_HideOrder'); $fields->removeByName('Send'); $fields->removeByName('Sent'); if (($simplified || !$editable) && !$this->Sent) { return; } $fields->addFieldsToTab('Root', [Tab::create('Email', _t('OrderLog.EMAIL', 'Email'))]); $emailFields = ['Send_To' => TextField::create('Send_To', _t('OrderLog.Send_To', 'Send to')), 'Send_From' => TextField::create('Send_From', _t('OrderLog.Send_From', 'From')), 'Send_Subject' => TextField::create('Send_Subject', _t('OrderLog.Send_Subject', 'Subject'))->setAttribute('placeholder', _t('Order.RECEIPT_SUBJECT', 'Web Order - {reference}', ['reference' => $this->Order()->Reference])), 'Send_HideOrder' => CheckboxField::create('Send_HideOrder', _t('OrderLog.Send_HideOrder', 'Hide order from email')), 'Send_Body' => HTMLEditorField::create('Send_Body', _t('OrderLog.Send_Body', 'Body'))->setRows(2)->addExtraClass('limited limited-with-source limited-with-links')->setDescription(_t('OrderLog.DESC-Send_Body', 'If no body is provided, will use the log notes (as seen below)')), 'EmailPreview' => DataObjectPreviewField::create(get_class($this) . '_EmailPreview', new Preview($this), new DataObjectPreviewer(new Preview($this)))]; if ($this->Sent || !$editable) { $readOnlyEmailFields = []; unset($emailFields['Send_HideOrder']); foreach ($emailFields as $emailField) { if ($emailField->Name != 'Send_Body' && !$emailField instanceof DataObjectPreviewField) { $readOnlyEmailFields[] = $emailField->performReadonlyTransformation(); } elseif ($emailField instanceof DataObjectPreviewField) { $readOnlyEmailFields[] = $emailField; } } unset($emailFields); $fields->addFieldsToTab('Root.Email', array_merge([ReadonlyField::create('READONLY_Sent', _t('OrderLog.Sent', 'Sent'), $this->obj('Sent')->Nice())], $readOnlyEmailFields)); } else { $fields->addFieldsToTab('Root.Email', [$selectionGroup = TabbedSelectionGroup::create('Send', [SelectionGroup_Item::create(0, CompositeField::create(), _t('OrderLog.Send-NO', 'No')), SelectionGroup_Item::create(1, CompositeField::create($emailFields), _t('OrderLog.Send-YES', 'Yes'))])->addExtraClass('selectionGroup--minor')->showAsDropdown(true)->setTitle(_t('OrderLog.Send', 'Send as an email?'))]); } }); return parent::getCMSFields(); }
public function RenderForm() { if ($form_fields = $this->FormFields()) { $fields = new FieldList(); if ($form_error = Session::get('FormError')) { Session::set('FormError', false); $fields->push(new LiteralField('form_error', '<p class="form-error">' . $form_error . '</p>')); } $validator = new RequiredFields(); $utils = new FormUtilities(); $fieldGroups = array(); foreach ($form_fields as $FieldName => $data) { if ($data['Value'] && is_string($data['Value'])) { $method_home = method_exists($this, $data['Value']) ? $this : (method_exists($utils, $data['Value']) ? $utils : false); $data['Value'] = $method_home ? $method_home->{$data}['Value']() : $data['Value']; } $Label = $data['Group'] ? '' : ($data['Label'] ? $data['Label'] : FormField::name_to_label($FieldName)); $field = new $data['FieldType']($FieldName, $Label, $data['Value'] ? $data['Value'] : null, $data['Default'] ? $data['Default'] : null); if ($data['ExtraClass']) { $field->addExtraClass($data['ExtraClass']); } if ($data['Config'] && is_array($data['Config'])) { foreach ($data['Config'] as $key => $value) { $field->setConfig($key, $value); } } if ($data['Required']) { $validator->addRequiredField($FieldName); $field->addExtraClass('required'); } if ($data['Group']) { if (!isset(${$data['Group']})) { ${$data['Group']} = new FieldGroup($data['Group']); $fields->push(${$data['Group']}); ${$data['Group']}->FieldCount = 0; $fieldGroups[] = ${$data['Group']}; } $field->setRightTitle($data['Label'] ? $data['Label'] : FormField::name_to_label($FieldName)); ${$data['Group']}->push($field); ${$data['Group']}->FieldCount++; } else { $fields->push($field); } } // update the class on the field groups to properly display the grouped fields horizontally foreach ($fieldGroups as $fieldGroup) { $fieldGroup->addExtraClass('stacked col' . $fieldGroup->FieldCount); } $submitText = "Submit"; if ($config = $this->FormConfig()) { $submitText = $config['submitText'] ? $config['submitText'] : $submitText; } $actions = new FieldList(new FormAction('SubmitForm', $submitText)); $form = new Form($this, 'RenderForm', $fields, $actions, $validator); if ($defaults = Session::get("FormInfo.Form_RenderForm.data")) { $form->loadDataFrom($defaults); Session::set("FormInfo.Form_RenderForm.data", false); } return $form; } return false; }
/** * Get a human-readable label for a single field, * see {@link fieldLabels()} for more details. * * @uses fieldLabels() * @uses FormField::name_to_label() * * @param string $name Name of the field * @return string Label of the field */ public function fieldLabel($name) { $labels = $this->fieldLabels(); return isset($labels[$name]) ? $labels[$name] : FormField::name_to_label($name); }
/** * @return FieldSet */ public function getCMSFields() { $fields = parent::getCMSFields(); /* @var FieldSet $fields */ $fields->replaceField('Content', new HtmlEditorField('Content', _t('ListingPage.CONTENT', 'Content (enter $Listing to display the listing)'))); $templates = DataObject::get('ListingTemplate'); if ($templates) { $templates = $templates->map(); } else { $templates = array(); } $fields->addFieldToTab('Root.ListingSettings', new DropdownField('ListingTemplateID', _t('ListingPage.CONTENT_TEMPLATE', 'Listing Template'), $templates)); $fields->addFieldToTab('Root.ListingSettings', new NumericField('PerPage', _t('ListingPage.PER_PAGE', 'Items Per Page'))); $fields->addFieldToTab('Root.ListingSettings', new DropdownField('SortDir', _t('ListingPage.SORT_DIR', 'Sort Direction'), $this->dbObject('SortDir')->enumValues())); $listType = $this->ListType ? $this->ListType : 'Page'; $objFields = $this->getSelectableFields($listType); $fields->addFieldToTab('Root.ListingSettings', new DropdownField('SortBy', _t('ListingPage.SORT_BY', 'Sort By'), $objFields)); // $fields->addFieldToTab('Root.Content.Main', new TextField('CustomSort', _t('ListingPage.CUSTOM_SORT', 'Custom sort field'))); $types = ClassInfo::subclassesFor('DataObject'); array_shift($types); $source = array_combine($types, $types); asort($source); $optionsetField = new DropdownField('ListType', _t('ListingPage.PAGE_TYPE', 'List items of type'), $source, 'Any'); $fields->addFieldToTab('Root.ListingSettings', $optionsetField); $fields->addFieldToTab('Root.ListingSettings', new CheckboxField('StrictType', _t('ListingPage.STRICT_TYPE', 'List JUST this type, not descendents'))); $sourceType = $this->effectiveSourceType(); $parentType = $this->parentType($sourceType); if ($sourceType && $parentType) { $fields->addFieldToTab('Root.ListingSettings', new DropdownField('Depth', _t('ListingPage.DEPTH', 'Depth'), array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5))); $fields->addFieldToTab('Root.ListingSettings', new TreeDropdownField('ListingSourceID', _t('ListingPage.LISTING_SOURCE', 'Source of content for listing'), $parentType)); $fields->addFieldToTab('Root.ListingSettings', new CheckboxField('ClearSource', _t('ListingPage.CLEAR_SOURCE', 'Clear listing source value'))); } $contentTypes = array('' => 'In Theme', 'text/html; charset=utf-8' => 'HTML Fragment', 'text/xml; charset=utf-8' => 'XML', 'application/rss+xml; charset=utf-8' => 'RSS (xml)', 'application/rdf+xml; charset=utf-8' => 'RDF (xml)', 'application/atom+xml; charset=utf-8' => 'ATOM (xml)'); $fields->addFieldToTab('Root.ListingSettings', new DropdownField('ContentType', _t('ListingPage.CONTENT_TYPE', 'Content Type'), $contentTypes)); $fields->addFieldToTab('Root.ListingSettings', new TextField('CustomContentType', _t('ListingPage.CUSTOM_CONTENT_TYPE', 'Custom Content Type'))); if ($this->ListType) { $componentsManyMany = singleton($this->ListType)->config()->many_many; if (!is_array($componentsManyMany)) { $componentsManyMany = array(); } $componentNames = array(); foreach ($componentsManyMany as $componentName => $className) { $componentNames[$componentName] = FormField::name_to_label($componentName) . ' (' . $className . ')'; } $fields->addFieldToTab('Root.ListingSettings', DropdownField::create('ComponentFilterName', _t('ListingPage.RELATION_COMPONENT_NAME', 'Filter by Relation'), $componentNames)->setEmptyString('(Select)')->setRightTitle('Will cause this page to list items based on the last URL part. (ie. ' . $this->AbsoluteLink() . '{$componentFieldName})')); $fields->addFieldToTab('Root.ListingSettings', $componentColumnField = DropdownField::create('ComponentFilterColumn', 'Filter by Relation Field')->setEmptyString('(Must select a relation and save)')); $fields->addFieldToTab('Root.ListingSettings', $componentListingField = DropdownField::create('ComponentListingTemplateID', _t('ListingPage.COMPONENT_CONTENT_TEMPLATE', 'Relation Listing Template'))->setEmptyString('(Must select a relation and save)')); if ($this->ComponentFilterName) { $componentClass = isset($componentsManyMany[$this->ComponentFilterName]) ? $componentsManyMany[$this->ComponentFilterName] : ''; if ($componentClass) { $componentFields = array(); foreach ($this->getSelectableFields($componentClass) as $columnName => $type) { $componentFields[$columnName] = $columnName; } $componentColumnField->setSource($componentFields); $componentColumnField->setEmptyString('(Select)'); $componentListingField->setSource($templates); $componentListingField->setHasEmptyDefault(false); if (class_exists('KeyValueField')) { $fields->addFieldToTab('Root.ListingSettings', KeyValueField::create('ComponentFilterWhere', 'Constrain Relation By', $componentFields)->setRightTitle("Filter '{$this->ComponentFilterName}' with these properties.")); } } } } return $fields; }