/** * Similar to {@link groupBy()}, but returns * the data in a format which is suitable for usage in templates. * * @param string $index * @param string $children Name of the control under which children can be iterated on * @return ArrayList */ public function GroupedBy($index, $children = 'Children') { $grouped = $this->groupBy($index); $result = new ArrayList(); foreach ($grouped as $indVal => $list) { $list = GroupedList::create($list); $result->push(new ArrayData(array($index => $indVal, $children => $list))); } return $result; }
public function testRSSFeedWithShortcode() { $list = new ArrayList(); $list->push(new RSSFeedTest_ItemD()); $rssFeed = new RSSFeed($list, "http://www.example.com", "Test RSS Feed", "Test RSS Feed Description"); $content = $rssFeed->outputToBrowser(); $this->assertContains('<link>http://www.example.org/item-d.html</link>', $content); $this->assertContains('<title>ItemD</title>', $content); $this->assertContains('<description><![CDATA[<p>ItemD Content test shortcode output</p>]]></description>', $content); }
public function Times() { $output = new ArrayList(); for ($i = 0; $i < $this->value; $i++) { $output->push(new ArrayData(array('Number' => $i + 1))); } return $output; }
/** * 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)); }
/** * Gets the list of options to render in this formfield * * @return ArrayList */ public function getOptions() { $selectedValues = $this->getValueArray(); $defaultItems = $this->getDefaultItems(); // Generate list of options to display $odd = 0; $formID = $this->ID(); $options = new ArrayList(); foreach ($this->getSource() as $itemValue => $title) { $itemID = Convert::raw2htmlid("{$formID}_{$itemValue}"); $odd = ($odd + 1) % 2; $extraClass = $odd ? 'odd' : 'even'; $extraClass .= ' val' . preg_replace('/[^a-zA-Z0-9\\-\\_]/', '_', $itemValue); $itemChecked = in_array($itemValue, $selectedValues) || in_array($itemValue, $defaultItems); $itemDisabled = $this->isDisabled() || in_array($itemValue, $defaultItems); $options->push(new ArrayData(array('ID' => $itemID, 'Class' => $extraClass, 'Name' => "{$this->name}[{$itemValue}]", 'Value' => $itemValue, 'Title' => $title, 'isChecked' => $itemChecked, 'isDisabled' => $itemDisabled))); } $this->extend('updateGetOptions', $options); return $options; }
/** * Push a single field onto the end of this FieldList instance. * * @param FormField $item The FormField to add */ public function push($item) { $this->onBeforeInsert($item); $item->setContainerFieldList($this); return parent::push($item); }
/** * Generate a CSV import form for a single {@link DataObject} subclass. * * @return Form */ public function ImportForm() { $modelSNG = singleton($this->modelClass); $modelName = $modelSNG->i18n_singular_name(); // check if a import form should be generated if (!$this->showImportForm || is_array($this->showImportForm) && !in_array($this->modelClass, $this->showImportForm)) { return false; } $importers = $this->getModelImporters(); if (!$importers || !isset($importers[$this->modelClass])) { return false; } if (!$modelSNG->canCreate(Member::currentUser())) { return false; } $fields = new FieldList(new HiddenField('ClassName', _t('ModelAdmin.CLASSTYPE'), $this->modelClass), new FileField('_CsvFile', false)); // get HTML specification for each import (column names etc.) $importerClass = $importers[$this->modelClass]; $importer = new $importerClass($this->modelClass); $spec = $importer->getImportSpec(); $specFields = new ArrayList(); foreach ($spec['fields'] as $name => $desc) { $specFields->push(new ArrayData(array('Name' => $name, 'Description' => $desc))); } $specRelations = new ArrayList(); foreach ($spec['relations'] as $name => $desc) { $specRelations->push(new ArrayData(array('Name' => $name, 'Description' => $desc))); } $specHTML = $this->customise(array('ClassName' => $this->sanitiseClassName($this->modelClass), 'ModelName' => Convert::raw2att($modelName), 'Fields' => $specFields, 'Relations' => $specRelations))->renderWith('Includes/ModelAdmin_ImportSpec'); $fields->push(new LiteralField("SpecFor{$modelName}", $specHTML)); $fields->push(new CheckboxField('EmptyBeforeImport', _t('ModelAdmin.EMPTYBEFOREIMPORT', 'Replace data'), false)); $actions = new FieldList(new FormAction('import', _t('ModelAdmin.IMPORT', 'Import from CSV'))); $form = new Form($this, "ImportForm", $fields, $actions); $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'ImportForm')); $this->extend('updateImportForm', $form); return $form; }
/** * Returns all components extending a certain class, or implementing a certain interface. * * @param string $type Class name or interface * @return ArrayList Of GridFieldComponent */ public function getComponentsByType($type) { $components = new ArrayList(); foreach ($this->components as $component) { if ($component instanceof $type) { $components->push($component); } } return $components; }
/** * Return this field's linked items */ public function getItems() { // If the value has been set, use that if ($this->value != 'unchanged' && is_array($this->sourceObject)) { $items = array(); $values = is_array($this->value) ? $this->value : preg_split('/ *, */', trim($this->value)); foreach ($values as $value) { $item = new stdClass(); $item->ID = $value; $item->Title = $this->sourceObject[$value]; $items[] = $item; } return $items; // Otherwise, look data up from the linked relation } if ($this->value != 'unchanged' && is_string($this->value)) { $items = new ArrayList(); $ids = explode(',', $this->value); foreach ($ids as $id) { if (!is_numeric($id)) { continue; } $item = DataObject::get_by_id($this->sourceObject, $id); if ($item) { $items->push($item); } } return $items; } else { if ($this->form) { $fieldName = $this->name; $record = $this->form->getRecord(); if (is_object($record) && $record->hasMethod($fieldName)) { return $record->{$fieldName}(); } } } }
/** * Retrieves a customised list of all File records to ensure they are * properly viewable when rendered in the field template. * * @return SS_List[ViewableData_Customised] */ public function getCustomisedItems() { $customised = new ArrayList(); foreach ($this->getItems() as $file) { $customised->push($this->customiseFile($file)); } return $customised; }
/** * Get the RSS feed entries * * @return SS_List Returns the {@link RSSFeed_Entry} objects. */ public function Entries() { $output = new ArrayList(); if (isset($this->entries)) { foreach ($this->entries as $entry) { $output->push(RSSFeed_Entry::create($entry, $this->titleField, $this->descriptionField, $this->authorField)); } } return $output; }
/** * Render server configuration file from a template file * * @param string $template * @return DBHTMLText Rendered results */ protected function renderTemplate($template) { // Build allowed extensions $allowedExtensions = new ArrayList(); foreach (\File::config()->allowed_extensions as $extension) { if ($extension) { $allowedExtensions->push(new \ArrayData(array('Extension' => preg_quote($extension)))); } } $viewer = new \SSViewer(array($template)); return (string) $viewer->process(new \ArrayData(array('AllowedExtensions' => $allowedExtensions))); }
/** * Return all the parents of this class in a set ordered from the lowest to highest parent. * * @return ArrayList */ public function getAncestors() { $ancestors = new ArrayList(); $object = $this->owner; while ($object = $object->getParent()) { $ancestors->push($object); } return $ancestors; }
/** * Returns all of the children for the CMS Tree. * Filters to only those groups that the current user can edit */ public function AllChildrenIncludingDeleted() { /** @var Hierarchy $extInstance */ $extInstance = $this->getExtensionInstance('SilverStripe\\ORM\\Hierarchy\\Hierarchy'); $extInstance->setOwner($this); $children = $extInstance->AllChildrenIncludingDeleted(); $extInstance->clearOwner(); $filteredChildren = new ArrayList(); if ($children) { foreach ($children as $child) { if ($child->canView()) { $filteredChildren->push($child); } } } return $filteredChildren; }
public function obj($fieldName, $arguments = null, $cache = false, $cacheName = null) { $childName = $this->argedName($fieldName, $arguments); // Special field name Loop### to create a list if (preg_match('/^Loop([0-9]+)$/', $fieldName, $matches)) { $output = new ArrayList(); for ($i = 0; $i < $matches[1]; $i++) { $output->push(new SSViewerTestFixture($childName)); } return $output; } else { if (preg_match('/NotSet/i', $fieldName)) { return new ViewableData(); } else { return new SSViewerTestFixture($childName); } } }
/** * Get a SS_List of the changed fields. * Each element is an array data containing * - Name: The field name * - Title: The human-readable field title * - Diff: An HTML diff showing the changes * - From: The older version of the field * - To: The newer version of the field */ public function ChangedFields() { $changedFields = new ArrayList(); if ($this->fromRecord) { $base = $this->fromRecord; $fields = array_keys($this->fromRecord->toMap()); } else { $base = $this->toRecord; $fields = array_keys($this->toRecord->toMap()); } foreach ($fields as $field) { if (in_array($field, $this->ignoredFields)) { continue; } if (!$this->fromRecord || $this->fromRecord->{$field} != $this->toRecord->{$field}) { // Only show HTML diffs for fields which allow HTML values in the first place $fieldObj = $this->toRecord->dbObject($field); if ($this->fromRecord) { $fieldDiff = Diff::compareHTML($this->fromRecord->{$field}, $this->toRecord->{$field}, !$fieldObj || $fieldObj->stat('escape_type') != 'xml'); } else { if ($fieldObj && $fieldObj->stat('escape_type') == 'xml') { $fieldDiff = "<ins>" . $this->toRecord->{$field} . "</ins>"; } else { $fieldDiff = "<ins>" . Convert::raw2xml($this->toRecord->{$field}) . "</ins>"; } } $changedFields->push(new ArrayData(array('Name' => $field, 'Title' => $base->fieldLabel($field), 'Diff' => $fieldDiff, 'From' => $this->fromRecord ? $this->fromRecord->{$field} : null, 'To' => $this->toRecord ? $this->toRecord->{$field} : null))); } } return $changedFields; }
/** * Return a list of all the versions available. * * @param string $filter * @param string $sort * @param string $limit * @param string $join Deprecated, use leftJoin($table, $joinClause) instead * @param string $having * @return ArrayList */ public function allVersions($filter = "", $sort = "", $limit = "", $join = "", $having = "") { // Make sure the table names are not postfixed (e.g. _Live) $oldMode = static::get_reading_mode(); static::set_stage(static::DRAFT); $owner = $this->owner; $list = DataObject::get(get_class($owner), $filter, $sort, $join, $limit); if ($having) { $list->having($having); } $query = $list->dataQuery()->query(); foreach ($query->getFrom() as $table => $tableJoin) { if (is_string($tableJoin) && $tableJoin[0] == '"') { $baseTable = str_replace('"', '', $tableJoin); } elseif (is_string($tableJoin) && substr($tableJoin, 0, 5) != 'INNER') { $query->setFrom(array($table => "LEFT JOIN \"{$table}\" ON \"{$table}\".\"RecordID\"=\"{$baseTable}_versions\".\"RecordID\"" . " AND \"{$table}\".\"Version\" = \"{$baseTable}_versions\".\"Version\"")); } $query->renameTable($table, $table . '_versions'); } // Add all <basetable>_versions columns foreach (Config::inst()->get('SilverStripe\\ORM\\Versioning\\Versioned', 'db_for_versions_table') as $name => $type) { $query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name); } $query->addWhere(array("\"{$baseTable}_versions\".\"RecordID\" = ?" => $owner->ID)); $query->setOrderBy($sort ? $sort : "\"{$baseTable}_versions\".\"LastEdited\" DESC, \"{$baseTable}_versions\".\"Version\" DESC"); $records = $query->execute(); $versions = new ArrayList(); foreach ($records as $record) { $versions->push(new Versioned_Version($record)); } Versioned::set_reading_mode($oldMode); return $versions; }
/** * @param bool $unlinked * @return ArrayList */ public function Breadcrumbs($unlinked = false) { $items = new ArrayList(array(new ArrayData(array('Title' => $this->menu_title(), 'Link' => $unlinked ? false : $this->Link())))); $record = $this->currentPage(); if ($record && $record->exists()) { if ($record->hasExtension(Hierarchy::class)) { $ancestors = $record->getAncestors(); $ancestors = new ArrayList(array_reverse($ancestors->toArray())); $ancestors->push($record); foreach ($ancestors as $ancestor) { $items->push(new ArrayData(array('Title' => $ancestor->MenuTitle ? $ancestor->MenuTitle : $ancestor->Title, 'Link' => $unlinked ? false : Controller::join_links($this->Link('show'), $ancestor->ID)))); } } else { $items->push(new ArrayData(array('Title' => $record->MenuTitle ? $record->MenuTitle : $record->Title, 'Link' => $unlinked ? false : Controller::join_links($this->Link('show'), $record->ID)))); } } return $items; }
/** * Return a SS_List of ArrayData objects containing the following pieces of info * about each batch action: * - Link * - Title * * @return ArrayList */ public function batchActionList() { $actions = $this->batchActions(); $actionList = new ArrayList(); foreach ($actions as $urlSegment => $action) { $actionObj = $this->buildAction($action['class']); if ($actionObj->canView()) { $actionDef = new ArrayData(array("Link" => Controller::join_links($this->Link(), $urlSegment), "Title" => $actionObj->getActionTitle())); $actionList->push($actionDef); } } return $actionList; }
/** * Pushes an item onto the end of this list. * * @param array|object $item * @param array $extraFields */ public function push($item, $extraFields = null) { if (is_object($item) && !$item instanceof $this->dataClass || !is_object($item) && !is_numeric($item)) { throw new InvalidArgumentException("UnsavedRelationList::add() expecting a {$this->dataClass} object, or ID value", E_USER_ERROR); } if (is_object($item) && $item->ID) { $item = $item->ID; } $this->extraFields[] = $extraFields; parent::push($item); }
/** * Export core. * * @param GridField $gridField * @return ArrayData */ public function generatePrintData(GridField $gridField) { $printColumns = $this->getPrintColumnsForGridField($gridField); $header = null; if ($this->printHasHeader) { $header = new ArrayList(); foreach ($printColumns as $field => $label) { $header->push(new ArrayData(array("CellString" => $label))); } } $items = $gridField->getManipulatedList(); $itemRows = new ArrayList(); /** @var DataObject $item */ foreach ($items->limit(null) as $item) { $itemRow = new ArrayList(); foreach ($printColumns as $field => $label) { $value = $gridField->getDataFieldValue($item, $field); if ($item->escapeTypeForField($field) != 'xml') { $value = Convert::raw2xml($value); } $itemRow->push(new ArrayData(array("CellString" => $value))); } $itemRows->push(new ArrayData(array("ItemRow" => $itemRow))); if ($item->hasMethod('destroy')) { $item->destroy(); } } $ret = new ArrayData(array("Title" => $this->getTitle($gridField), "Header" => $header, "ItemRows" => $itemRows, "Datetime" => DBDatetime::now(), "Member" => Member::currentUser())); return $ret; }
/** * Returns a summarised pagination which limits the number of pages shown * around the current page for visually balanced. * * Example: 25 pages total, currently on page 6, context of 4 pages * [prev] [1] ... [4] [5] [[6]] [7] [8] ... [25] [next] * * Example template usage: * <code> * <% if MyPages.MoreThanOnePage %> * <% if MyPages.NotFirstPage %> * <a class="prev" href="$MyPages.PrevLink">Prev</a> * <% end_if %> * <% loop MyPages.PaginationSummary(4) %> * <% if CurrentBool %> * $PageNum * <% else %> * <% if Link %> * <a href="$Link">$PageNum</a> * <% else %> * ... * <% end_if %> * <% end_if %> * <% end_loop %> * <% if MyPages.NotLastPage %> * <a class="next" href="$MyPages.NextLink">Next</a> * <% end_if %> * <% end_if %> * </code> * * @param int $context The number of pages to display around the current * page. The number should be event, as half the number of each pages * are displayed on either side of the current one. * @return SS_List */ public function PaginationSummary($context = 4) { $result = new ArrayList(); $current = $this->CurrentPage(); $total = $this->TotalPages(); // Make the number even for offset calculations. if ($context % 2) { $context--; } // If the first or last page is current, then show all context on one // side of it - otherwise show half on both sides. if ($current == 1 || $current == $total) { $offset = $context; } else { $offset = floor($context / 2); } $left = max($current - $offset, 1); $range = range($current - $offset, $current + $offset); if ($left + $context > $total) { $left = $total - $context; } for ($i = 0; $i < $total; $i++) { $link = HTTP::setGetVar($this->getPaginationGetVar(), $i * $this->getPageLength()); $num = $i + 1; $emptyRange = $num != 1 && $num != $total && ($num == $left - 1 || $num == $left + $context + 1); if ($emptyRange) { $result->push(new ArrayData(array('PageNum' => null, 'Link' => null, 'CurrentBool' => false))); } elseif ($num == 1 || $num == $total || in_array($num, $range)) { $result->push(new ArrayData(array('PageNum' => $num, 'Link' => $link, 'CurrentBool' => $current == $num))); } } return $result; }
/** * @param $arr Array containing ID and ClassName maps * @return ArrayList */ protected function mapToArrayList($arr) { $set = new ArrayList(); foreach ($arr as $arrItem) { $obj = DataObject::get_by_id($arrItem['ClassName'], $arrItem['ID']); $obj->_BulkLoaderMessage = $arrItem['Message']; if ($obj) { $set->push($obj); } } return $set; }