code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
protected function modifyButtons($name, $offset, $del = 0, $add = null) { foreach ($this->buttons as &$buttons) { if (($idx = array_search($name, $buttons ?? [])) !== false) { if ($add) { array_splice($buttons, $idx + $offset, $del, $add); } else { array_splice($buttons, $idx + $offset, $del); } return true; } } return false; }
Internal function for adding and removing buttons related to another button @param string $name The name of the button to modify @param int $offset The offset relative to that button to perform an array_splice at. 0 for before $name, 1 for after. @param int $del The number of buttons to remove at the position given by index(string) + offset @param mixed $add An array or single item to insert at the position given by index(string) + offset, or null for no insertion @return bool True if $name matched a button, false otherwise
modifyButtons
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function insertButtonsBefore($before, $buttons) { if (func_num_args() > 2) { $buttons = func_get_args(); array_shift($buttons); } if (!is_array($buttons)) { $buttons = [$buttons]; } return $this->modifyButtons($before, 0, 0, $buttons); }
Insert buttons before the first occurrence of another button @param string $before the name of the button to insert other buttons before @param string ...$buttons a string, or several strings, or a single array of strings. The button names to insert before that button @return bool True if insertion occurred, false if it did not (because the given button name was not found)
insertButtonsBefore
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function insertButtonsAfter($after, $buttons) { if (func_num_args() > 2) { $buttons = func_get_args(); array_shift($buttons); } if (!is_array($buttons)) { $buttons = [$buttons]; } return $this->modifyButtons($after, 1, 0, $buttons); }
Insert buttons after the first occurrence of another button @param string $after the name of the button to insert other buttons before @param string ...$buttons a string, or several strings, or a single array of strings. The button names to insert after that button @return bool True if insertion occurred, false if it did not (because the given button name was not found)
insertButtonsAfter
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function getContentCSS() { // Prioritise instance specific content if (isset($this->contentCSS)) { return $this->contentCSS; } // Add standard editor.css $editor = []; $editorCSSFiles = $this->config()->get('editor_css'); if ($editorCSSFiles) { foreach ($editorCSSFiles as $editorCSS) { $editor[] = $editorCSS; } } // Themed editor.css $themes = HTMLEditorConfig::getThemes() ?: SSViewer::get_themes(); $themedEditor = ThemeResourceLoader::inst()->findThemedCSS('editor', $themes); if ($themedEditor) { $editor[] = $themedEditor; } return $editor; }
Get list of resource paths to css files. Will default to `editor_css` config, as well as any themed `editor.css` files. Use setContentCSS() to override. @return string[]
getContentCSS
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function setContentCSS($css) { $this->contentCSS = $css; return $this; }
Set explicit set of CSS resources to use for `content_css` option. Note: If merging with default paths, you should call getContentCSS() and merge prior to assignment. @param string[] $css Array of resource paths. Supports module prefix, e.g. `silverstripe/admin:client/dist/styles/editor.css` @return $this
setContentCSS
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function getScriptURL() { $generator = Injector::inst()->get(TinyMCEScriptGenerator::class); return $generator->getScriptURL($this); }
Generate gzipped TinyMCE configuration including plugins and languages. This ends up "pre-loading" TinyMCE bundled with the required plugins so that multiple HTTP requests on the client don't need to be made. @return string @throws Exception
getScriptURL
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public static function get_tinymce_lang() { $lang = static::config()->get('tinymce_lang'); $locale = i18n::get_locale(); if (isset($lang[$locale])) { return $lang[$locale]; } return 'en'; }
Get the current tinyMCE language @return string Language
get_tinymce_lang
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function getTinyMCEResourcePath() { $resource = $this->getTinyMCEResource(); if ($resource instanceof ModuleResource) { return $resource->getPath(); } return Director::baseFolder() . '/' . $resource; }
Returns the full filesystem path to TinyMCE resources (which could be different from the original tinymce location in the module). Path will be absolute. @return string @throws Exception
getTinyMCEResourcePath
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function getTinyMCEResourceURL() { $resource = $this->getTinyMCEResource(); if ($resource instanceof ModuleResource) { return $resource->getURL(); } return $resource; }
Get front-end url to tinymce resources @return string @throws Exception
getTinyMCEResourceURL
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function getTinyMCEResource() { $configDir = static::config()->get('base_dir'); if ($configDir) { return ModuleResourceLoader::singleton()->resolveResource($configDir); } throw new Exception(sprintf( 'If the silverstripe/admin module is not installed you must set the TinyMCE path in %s.base_dir', __CLASS__ )); }
Get resource root for TinyMCE, either as a string or ModuleResource instance Path will be relative to BASE_PATH if string. @return ModuleResource|string @throws Exception
getTinyMCEResource
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCEConfig.php
BSD-3-Clause
public function setAssetHandler(GeneratedAssetHandler $assetHandler) { $this->assetHandler = $assetHandler; return $this; }
Assign backend store for generated assets @param GeneratedAssetHandler $assetHandler @return $this
setAssetHandler
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
protected function getFileContents($file) { if ($file instanceof ModuleResource) { $path = $file->getPath(); } else { $path = Director::baseFolder() . '/' . $file; } if (!file_exists($path ?? '')) { return null; } $content = file_get_contents($path ?? ''); // Remove UTF-8 BOM if (substr($content ?? '', 0, 3) === pack("CCC", 0xef, 0xbb, 0xbf)) { $content = substr($content ?? '', 3); } return $content; }
Returns the contents of the script file if it exists and removes the UTF-8 BOM header if it exists. @param string|ModuleResource $file File to load. @return string File contents or empty string if it doesn't exist.
getFileContents
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
protected function checkName(TinyMCEConfig $config) { $configs = HTMLEditorConfig::get_available_configs_map(); foreach ($configs as $id => $name) { if (HTMLEditorConfig::get($id) === $config) { return $id; } } return 'custom'; }
Check if this config is registered under a given key @param TinyMCEConfig $config @return string
checkName
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
public function generateFilename(TinyMCEConfig $config) { $hash = substr(sha1(json_encode($config->getAttributes()) ?? ''), 0, 10); $name = $this->checkName($config); $url = str_replace( ['{name}', '{hash}'], [$name, $hash], $this->config()->get('filename_base') ?? '' ); return $url; }
Get filename to use for this config @param TinyMCEConfig $config @return mixed
generateFilename
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
public static function flush() { $dir = dirname(static::config()->get('filename_base') ?? ''); static::singleton()->getAssetHandler()->removeContent($dir); }
This function is triggered early in the request if the "flush" query parameter has been set. Each class that implements Flushable implements this function which looks after it's own specific flushing functionality. @see FlushMiddleware
flush
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
protected function resolveRelativeResource($base, $resource) { // Return resource path based on relative resource path foreach (['', '.min.js', '.js'] as $ext) { // Map resource if ($base instanceof ModuleResource) { $next = $base->getRelativeResource($resource . $ext); } else { $next = rtrim($base ?? '', '/') . '/' . $resource . $ext; } // Ensure resource exists if ($this->resourceExists($next)) { return $next; } } return null; }
Get relative resource for a given base and string @param ModuleResource|string $base @param string $resource @return ModuleResource|string
resolveRelativeResource
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
protected function resourceExists($resource) { if (!$resource) { return false; } if ($resource instanceof ModuleResource) { return $resource->exists(); } $base = rtrim(Director::baseFolder() ?? '', '/'); return file_exists($base . '/' . $resource); }
Check if the given resource exists @param string|ModuleResource $resource @return bool
resourceExists
php
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php
BSD-3-Clause
public function setThrowExceptionOnBadDataType($throwExceptionOnBadDataType) { Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality'); $this->throwExceptionOnBadDataType = $throwExceptionOnBadDataType; return $this; }
Determine what happens when this component is used with a list that isn't {@link SS_Filterable}. - true: An exception is thrown - false: This component will be ignored - it won't make any changes to the GridField. By default, this is set to true so that it's clearer what's happening, but the predefined {@link GridFieldConfig} subclasses set this to false for flexibility. @param bool $throwExceptionOnBadDataType @return $this @deprecated 5.2.0 Will be removed without equivalent functionality
setThrowExceptionOnBadDataType
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldSortableHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldSortableHeader.php
BSD-3-Clause
protected function checkDataType($dataList) { if ($dataList instanceof Sortable) { return true; } else { // This will be changed to always throw an exception in a future major release. if ($this->throwExceptionOnBadDataType) { throw new LogicException( static::class . " expects an SS_Sortable list to be passed to the GridField." ); } return false; } }
Check that this dataList is of the right data type. Returns false if it's a bad data type, and if appropriate, throws an exception. @param SS_List $dataList @return bool
checkDataType
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldSortableHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldSortableHeader.php
BSD-3-Clause
public function setFieldSorting($sorting) { $this->fieldSorting = $sorting; return $this; }
Specify sorting with fieldname as the key, and actual fieldname to sort as value. Example: array("MyCustomTitle"=>"Title", "MyCustomBooleanField" => "ActualBooleanField") @param array $sorting @return $this
setFieldSorting
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldSortableHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldSortableHeader.php
BSD-3-Clause
public function getManipulatedData(GridField $gridField, SS_List $dataList) { if (!$this->checkDataType($dataList)) { return $dataList; } $state = $this->getState($gridField); if ($state->SortColumn == "") { return $dataList; } // Prevent SQL Injection by validating that SortColumn exists $columns = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class); $fields = $columns->getDisplayFields($gridField); if (!array_key_exists($state->SortColumn, $fields) && !in_array($state->SortColumn, $this->getFieldSorting()) ) { throw new LogicException('Invalid SortColumn: ' . $state->SortColumn); } return $dataList->sort($state->SortColumn, $state->SortDirection('asc')); }
Returns the manipulated (sorted) DataList. Field names will simply add an 'ORDER BY' clause, relation names will add appropriate joins to the {@link DataQuery} first. @param GridField $gridField @param SS_List&Sortable $dataList @return SS_List
getManipulatedData
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldSortableHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldSortableHeader.php
BSD-3-Clause
public function getManipulatedData(GridField $gridField, SS_List $dataList) { // If we are lazy loading an empty the list if ($this->isLazy($gridField)) { if ($dataList instanceof Filterable) { // If our original list can be filtered, filter out all results. $dataList = $dataList->byIDs([-1]); } else { // If not, create an empty list instead. $dataList = ArrayList::create([]); } } return $dataList; }
Empty $datalist if the current request should be lazy loadable. @param GridField $gridField @param SS_List $dataList @return SS_List
getManipulatedData
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldLazyLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldLazyLoader.php
BSD-3-Clause
public function getHTMLFragments($gridField) { $gridField->addExtraClass($this->isLazy($gridField) ? 'grid-field--lazy-loadable' : 'grid-field--lazy-loaded'); return []; }
Apply an appropriate CSS class to `$gridField` based on whatever the current request is lazy loadable or not. @param GridField $gridField @return array
getHTMLFragments
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldLazyLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldLazyLoader.php
BSD-3-Clause
private function isLazy(GridField $gridField) { return $gridField->getRequest()->getHeader('X-Pjax') !== 'CurrentField' && $this->isInTabSet($gridField); }
Detect if the current request should include results. @param GridField $gridField @return bool
isLazy
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldLazyLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldLazyLoader.php
BSD-3-Clause
private function isInTabSet(FormField $field) { $list = $field->getContainerFieldList(); if ($list && $containerField = $list->getContainerField()) { // Classes that extends TabSet might not have the expected JS to lazy load. return get_class($containerField) === TabSet::class ?: $this->isInTabSet($containerField); } return false; }
Recursively check if $field is inside a TabSet. @param FormField $field @return bool
isInTabSet
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldLazyLoader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldLazyLoader.php
BSD-3-Clause
public function getHTMLFragments($gridField) { $button = new GridField_FormAction( $gridField, 'print', _t('SilverStripe\\Forms\\GridField\\GridField.Print', 'Print'), 'print', null ); $button->setForm($gridField->getForm()); $button->addExtraClass('font-icon-print grid-print-button btn btn-secondary'); return [ $this->targetFragment => $button->Field(), ]; }
Place the print button in a <p> tag below the field @param GridField $gridField @return array
getHTMLFragments
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPrintButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPrintButton.php
BSD-3-Clause
public function getURLHandlers($gridField) { return [ 'print' => 'handlePrint', ]; }
Print is accessible via the url @param GridField $gridField @return array
getURLHandlers
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPrintButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPrintButton.php
BSD-3-Clause
public function handlePrint($gridField, $request = null) { set_time_limit(60); Requirements::clear(); $data = $this->generatePrintData($gridField); $this->extend('updatePrintData', $data); if ($data) { return $data->renderWith([ get_class($gridField) . '_print', GridField::class . '_print', ]); } return null; }
Handle the print, for both the action button and the URL @param GridField $gridField @param HTTPRequest $request @return DBHTMLText
handlePrint
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPrintButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPrintButton.php
BSD-3-Clause
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { switch ($actionName) { case 'addto': if (isset($data['relationID']) && $data['relationID']) { $gridField->State->GridFieldAddRelation = $data['relationID']; } break; } }
Manipulate the state to add a new relation @param GridField $gridField @param string $actionName Action identifier, see {@link getActions()}. @param array $arguments Arguments relevant for this @param array $data All form data
handleAction
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldAddExistingAutocompleter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldAddExistingAutocompleter.php
BSD-3-Clause
public function getManipulatedData(GridField $gridField, SS_List $dataList) { $dataClass = $gridField->getModelClass(); if (!is_a($dataClass, DataObject::class, true)) { throw new LogicException(__CLASS__ . " must be used with DataObject subclasses. Found '$dataClass'"); } $objectID = $gridField->State->GridFieldAddRelation(null); if (empty($objectID)) { return $dataList; } $gridField->State->GridFieldAddRelation = null; $object = DataObject::get_by_id($dataClass, $objectID); if ($object) { if (!$object->canView()) { throw new HTTPResponse_Exception(null, 403); } $dataList->add($object); } return $dataList; }
If an object ID is set, add the object to the list @param GridField $gridField @param SS_List $dataList @return SS_List
getManipulatedData
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldAddExistingAutocompleter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldAddExistingAutocompleter.php
BSD-3-Clause
public function setSearchList(SS_List $list) { $this->searchList = $list; return $this; }
Sets the base list instance which will be used for the autocomplete search. @param SS_List $list
setSearchList
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldAddExistingAutocompleter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldAddExistingAutocompleter.php
BSD-3-Clause
public function scaffoldSearchFields($dataClass) { if (!is_a($dataClass, DataObject::class, true)) { throw new LogicException(__CLASS__ . " must be used with DataObject subclasses. Found '$dataClass'"); } $obj = DataObject::singleton($dataClass); $fields = null; if ($fieldSpecs = $obj->searchableFields()) { $customSearchableFields = $obj->config()->get('searchable_fields'); foreach ($fieldSpecs as $name => $spec) { if (is_array($spec) && array_key_exists('filter', $spec ?? [])) { // The searchableFields() spec defaults to PartialMatch, // so we need to check the original setting. // If the field is defined $searchable_fields = array('MyField'), // then default to StartsWith filter, which makes more sense in this context. if (!$customSearchableFields || array_search($name, $customSearchableFields ?? []) !== false) { $filter = 'StartsWith'; } else { $filterName = $spec['filter']; // It can be an instance if ($filterName instanceof SearchFilter) { $filterName = get_class($filterName); } // It can be a fully qualified class name if (strpos($filterName ?? '', '\\') !== false) { $filterNameParts = explode("\\", $filterName ?? ''); // We expect an alias matching the class name without namespace, see #coresearchaliases $filterName = array_pop($filterNameParts); } $filter = preg_replace('/Filter$/', '', $filterName ?? ''); } $fields[] = "{$name}:{$filter}"; } else { $fields[] = $name; } } } if (is_null($fields)) { if ($obj->hasDatabaseField('Title')) { $fields = ['Title']; } elseif ($obj->hasDatabaseField('Name')) { $fields = ['Name']; } } return $fields; }
Detect searchable fields and searchable relations. Falls back to {@link DataObject->summaryFields()} if no custom search fields are defined. @param string $dataClass The class name @return array|null names of the searchable fields
scaffoldSearchFields
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldAddExistingAutocompleter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldAddExistingAutocompleter.php
BSD-3-Clause
public function getResultsLimit() { return $this->resultsLimit; }
Gets the maximum number of autocomplete results to display. @return int
getResultsLimit
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldAddExistingAutocompleter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldAddExistingAutocompleter.php
BSD-3-Clause
public function getComponentsByType($type) { $components = new ArrayList(); foreach ($this->components as $component) { if ($component instanceof $type) { $components->push($component); } } return $components; }
Returns all components extending a certain class, or implementing a certain interface. @template T of GridFieldComponent @param class-string<T> $type Class name or interface @return ArrayList<T>
getComponentsByType
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldConfig.php
BSD-3-Clause
public function getComponentByType($type) { foreach ($this->components as $component) { if ($component instanceof $type) { return $component; } } return null; }
Returns the first available component with the given class or interface. @template T of GridFieldComponent @param class-string<T> $type ClassName @return T|null
getComponentByType
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldConfig.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldConfig.php
BSD-3-Clause
public function augmentColumns($gridField, &$columns) { $baseColumns = array_keys($this->getDisplayFields($gridField) ?? []); foreach ($baseColumns as $col) { $columns[] = $col; } $columns = array_unique($columns ?? []); }
Modify the list of columns displayed in the table. See {@link GridFieldDataColumns->getDisplayFields()} and {@link GridFieldDataColumns}. @param GridField $gridField @param array $columns List reference of all column names. (by reference)
augmentColumns
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function getColumnsHandled($gridField) { return array_keys($this->getDisplayFields($gridField) ?? []); }
Names of all columns which are affected by this component. @param GridField $gridField @return array
getColumnsHandled
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function setDisplayFields($fields) { if (!is_array($fields)) { throw new InvalidArgumentException( 'Arguments passed to GridFieldDataColumns::setDisplayFields() must be an array' ); } $this->displayFields = $fields; return $this; }
Override the default behaviour of showing the models summaryFields with these fields instead Example: array( 'Name' => 'Members name', 'Email' => 'Email address') @param array $fields @return $this
setDisplayFields
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function setFieldCasting($casting) { $this->fieldCasting = $casting; return $this; }
Specify castings with fieldname as the key, and the desired casting as value. Example: array("MyCustomDate"=>"Date","MyShortText"=>"Text->FirstSentence") @param array $casting @return $this
setFieldCasting
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function setFieldFormatting($formatting) { $this->fieldFormatting = $formatting; return $this; }
Specify custom formatting for fields, e.g. to render a link instead of pure text. Caution: Make sure to escape special php-characters like in a normal php-statement. Example: "myFieldName" => '<a href=\"custom-admin/$ID\">$ID</a>'. Alternatively, pass a anonymous function, which takes two parameters: The value and the original list item. Formatting is applied after field casting, so if you're modifying the string to include further data through custom formatting, ensure it's correctly escaped. @param array $formatting @return $this
setFieldFormatting
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function getColumnContent($gridField, $record, $columnName) { // Find the data column for the given named column $columns = $this->getDisplayFields($gridField); $columnInfo = array_key_exists($columnName, $columns ?? []) ? $columns[$columnName] : null; // Allow callbacks if (is_array($columnInfo) && isset($columnInfo['callback'])) { $method = $columnInfo['callback']; $value = $method($record, $columnName, $gridField); // This supports simple FieldName syntax } else { $value = $gridField->getDataFieldValue($record, $columnName); } // Turn $value, whatever it is, into a HTML embeddable string $value = $this->castValue($gridField, $columnName, $value); // Make any formatting tweaks $value = $this->formatValue($gridField, $record, $columnName, $value); // Do any final escaping $value = $this->escapeValue($gridField, $value); return $value; }
HTML for the column, content of the <td> element. @param GridField $gridField @param ViewableData $record Record displayed in this row @param string $columnName @return string HTML for the column. Return NULL to skip.
getColumnContent
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function getColumnMetadata($gridField, $column) { $columns = $this->getDisplayFields($gridField); $title = null; if (is_string($columns[$column])) { $title = $columns[$column]; } elseif (is_array($columns[$column]) && isset($columns[$column]['title'])) { $title = $columns[$column]['title']; } return [ 'title' => $title, ]; }
Additional metadata about the column which can be used by other components, e.g. to set a title for a search column header. @param GridField $gridField @param string $column @return array Map of arbitrary metadata identifiers to their values.
getColumnMetadata
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
protected function getValueFromRelation($record, $columnName) { Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it.'); $fieldNameParts = explode('.', $columnName ?? ''); $tmpItem = clone($record); for ($idx = 0; $idx < sizeof($fieldNameParts ?? []); $idx++) { $methodName = $fieldNameParts[$idx]; // Last mmethod call from $columnName return what that method is returning if ($idx == sizeof($fieldNameParts ?? []) - 1) { return $tmpItem->XML_val($methodName); } // else get the object from this $methodName $tmpItem = $tmpItem->$methodName(); } return null; }
Translate a Object.RelationName.ColumnName $columnName into the value that ColumnName returns @param ViewableData $record @param string $columnName @return string|null - returns null if it could not found a value @deprecated 5.4.0 Will be removed without equivalent functionality to replace it.
getValueFromRelation
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDataColumns.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDataColumns.php
BSD-3-Clause
public function setModelClass($modelClassName) { $this->modelClassName = $modelClassName; return $this; }
Set the modelClass (data object) that this field will get it column headers from. If no $displayFields has been set, the display fields will be $summary_fields. @see GridFieldDataColumns::getDisplayFields() @param string $modelClassName @return $this
setModelClass
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getModelClass() { if ($this->modelClassName) { return $this->modelClassName; } /** @var DataList|ArrayList $list */ $list = $this->list; if ($list && $list->hasMethod('dataClass')) { $class = $list->dataClass(); if ($class) { return $class; } } throw new LogicException( 'GridField doesn\'t have a modelClassName, so it doesn\'t know the columns of this grid.' ); }
Returns the class name of the record type that this GridField should contain. @return string @throws LogicException
getModelClass
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function setReadonlyComponents(array $components) { $this->readonlyComponents = $components; }
Overload the readonly components for this gridfield. @param array $components an array map of component class references to whitelist for a readonly version.
setReadonlyComponents
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getReadonlyComponents() { return $this->readonlyComponents; }
Return the readonly components @return array a map of component classes.
getReadonlyComponents
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function performReadonlyTransformation() { $copy = clone $this; $copy->setReadonly(true); $copyConfig = $copy->getConfig(); $hadEditButton = $copyConfig->getComponentByType(GridFieldEditButton::class) !== null; // get the whitelist for allowable readonly components $allowedComponents = $this->getReadonlyComponents(); foreach ($this->getConfig()->getComponents() as $component) { // if a component doesn't exist, remove it from the readonly version. if (!in_array(get_class($component), $allowedComponents ?? [])) { $copyConfig->removeComponent($component); } } // If the edit button has been removed, replace it with a view button if one is allowed if ($hadEditButton && !$copyConfig->getComponentByType(GridFieldViewButton::class)) { $viewButtonClass = null; foreach ($allowedComponents as $componentClass) { if (is_a($componentClass, GridFieldViewButton::class, true)) { $viewButtonClass = $componentClass; break; } } if ($viewButtonClass) { $copyConfig->addComponent($viewButtonClass::create()); } } $copy->extend('afterPerformReadonlyTransformation', $this); return $copy; }
Custom Readonly transformation to remove actions which shouldn't be present for a readonly state. @return GridField
performReadonlyTransformation
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function performDisabledTransformation() { parent::performDisabledTransformation(); return $this->performReadonlyTransformation(); }
Disabling the gridfield should have the same affect as making it readonly (removing all action items). @return GridField
performDisabledTransformation
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getCastedValue($value, $castingDefinition) { $castingParams = []; if (is_array($castingDefinition)) { $castingParams = $castingDefinition; array_shift($castingParams); $castingDefinition = array_shift($castingDefinition); } if (strpos($castingDefinition ?? '', '->') === false) { $castingFieldType = $castingDefinition; $castingField = DBField::create_field($castingFieldType, $value); return call_user_func_array([$castingField, 'XML'], $castingParams ?? []); } list($castingFieldType, $castingMethod) = explode('->', $castingDefinition ?? ''); $castingField = DBField::create_field($castingFieldType, $value); return call_user_func_array([$castingField, $castingMethod], $castingParams ?? []); }
Cast an arbitrary value with the help of a $castingDefinition. @param mixed $value @param string|array $castingDefinition @return mixed
getCastedValue
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getState($getData = true) { // Initialise state on first call. This ensures it's evaluated after components have been added if (!$this->state) { $this->initState(); } if ($getData) { return $this->state->getData(); } return $this->state; }
Get the current GridState_Data or the GridState. @param bool $getData @return GridState_Data|GridState
getState
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getColumns() { $columns = []; foreach ($this->getComponents() as $item) { if ($item instanceof GridField_ColumnProvider) { $item->augmentColumns($this, $columns); } } return $columns; }
Get the columns of this GridField, they are provided by attached GridField_ColumnProvider. @return array
getColumns
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function addDataFields($fields) { if ($this->customDataFields) { $this->customDataFields = array_merge($this->customDataFields, $fields); } else { $this->customDataFields = $fields; } }
Add additional calculated data fields to be used on this GridField @param array $fields a map of fieldname to callback. The callback will be passed the record as an argument.
addDataFields
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getDataFieldValue($record, $fieldName) { if (isset($this->customDataFields[$fieldName])) { $callback = $this->customDataFields[$fieldName]; return $callback($record); } if ($record->hasMethod('relField')) { return $record->relField($fieldName); } if ($record->hasMethod($fieldName)) { return $record->$fieldName(); } return $record->$fieldName; }
Get the value of a named field on the given record. Use of this method ensures that any special rules around the data for this gridfield are followed. @param ViewableData $record @param string $fieldName @return mixed
getDataFieldValue
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function getColumnCount() { if (!$this->columnDispatch) { $this->buildColumnDispatch(); } return count($this->columnDispatch ?? []); }
Return how many columns the grid will have. @return int
getColumnCount
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
protected function buildColumnDispatch() { $this->columnDispatch = []; foreach ($this->getComponents() as $item) { if ($item instanceof GridField_ColumnProvider) { $columns = $item->getColumnsHandled($this); foreach ($columns as $column) { $this->columnDispatch[$column][] = $item; } } } }
Build an columnDispatch that maps a GridField_ColumnProvider to a column for reference later.
buildColumnDispatch
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function gridFieldAlterAction($data, $form, HTTPRequest $request) { $data = $request->requestVars(); // Protection against CSRF attacks $token = $this ->getForm() ->getSecurityToken(); if (!$token->checkRequest($request)) { $this->httpError(400, _t( "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE", "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again." )); } $name = $this->getName(); $fieldData = null; if (isset($data[$name])) { $fieldData = $data[$name]; } $state = $this->getState(false); if (isset($fieldData['GridState'])) { $state->setValue($fieldData['GridState']); } // Fetch the store for the "state" of actions (not the GridField) /** @var StateStore $store */ $store = Injector::inst()->create(StateStore::class . '.' . $this->getName()); foreach ($data as $dataKey => $dataValue) { if (preg_match('/^action_gridFieldAlterAction\?StateID=(.*)/', $dataKey ?? '', $matches)) { $stateChange = $store->load($matches[1]); $actionName = $stateChange['actionName']; $arguments = []; if (isset($stateChange['args'])) { $arguments = $stateChange['args']; }; $html = $this->handleAlterAction($actionName, $arguments, $data); if ($html) { return $html; } } } if ($request->getHeader('X-Pjax') === 'CurrentField') { if ($this->getState()->Readonly === true) { $this->performDisabledTransformation(); } return $this->FieldHolder(); } return $form->forTemplate(); }
This is the action that gets executed when a GridField_AlterAction gets clicked. @param array $data @param Form $form @param HTTPRequest $request @return string
gridFieldAlterAction
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function handleAlterAction($actionName, $arguments, $data) { $actionName = strtolower($actionName ?? ''); foreach ($this->getComponents() as $component) { if ($component instanceof GridField_ActionProvider) { $actions = array_map('strtolower', (array) $component->getActions($this)); if (in_array($actionName, $actions ?? [])) { return $component->handleAction($this, $actionName, $arguments, $data); } } } throw new InvalidArgumentException(sprintf( 'Can\'t handle action "%s"', $actionName )); }
Pass an action on the first GridField_ActionProvider that matches the $actionName. @param string $actionName @param mixed $arguments @param array $data @return mixed @throws InvalidArgumentException
handleAlterAction
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
public function handleRequest(HTTPRequest $request) { if ($this->brokenOnConstruct) { user_error( sprintf( "parent::__construct() needs to be called on %s::__construct()", __CLASS__ ), E_USER_WARNING ); } $this->setRequest($request); $fieldData = $this->getRequest()->requestVar($this->getName()); if ($fieldData && isset($fieldData['GridState'])) { $this->getState(false)->setValue($fieldData['GridState']); } foreach ($this->getComponents() as $component) { if ($component instanceof GridField_URLHandler && $urlHandlers = $component->getURLHandlers($this)) { foreach ($urlHandlers as $rule => $action) { if ($params = $request->match($rule, true)) { // Actions can reference URL parameters. // e.g. '$Action/$ID/$OtherID' → '$Action' if ($action[0] == '$') { $action = $params[substr($action, 1)]; } if (!method_exists($component, 'checkAccessAction') || $component->checkAccessAction($action)) { if (!$action) { $action = "index"; } if (!is_string($action)) { throw new LogicException(sprintf( 'Non-string method name: %s', var_export($action, true) )); } try { $this->extend('beforeCallActionURLHandler', $request, $action); $result = $component->$action($this, $request); $this->extend('afterCallActionURLHandler', $request, $action, $result); } catch (HTTPResponse_Exception $responseException) { $result = $responseException->getResponse(); } if ($result instanceof HTTPResponse && $result->isError()) { return $result; } if ($this !== $result && !$request->isEmptyPattern($rule) && ($result instanceof RequestHandler || $result instanceof HasRequestHandler) ) { if ($result instanceof HasRequestHandler) { $result = $result->getRequestHandler(); } $returnValue = $result->handleRequest($request); if (is_array($returnValue)) { throw new LogicException( 'GridField_URLHandler handlers can\'t return arrays' ); } return $returnValue; } if ($request->allParsed()) { return $result; } return $this->httpError( 404, sprintf( 'I can\'t handle sub-URLs of a %s object.', get_class($result) ) ); } } } } } return parent::handleRequest($request); }
Custom request handler that will check component handlers before proceeding to the default implementation. @param HTTPRequest $request @return array|RequestHandler|HTTPResponse|string @throws HTTPResponse_Exception
handleRequest
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField.php
BSD-3-Clause
protected function getCreateContext() { $gridField = $this->gridField; $context = []; if ($gridField->getList() instanceof RelationList) { $record = $gridField->getForm()->getRecord(); if ($record && $record instanceof DataObject) { $context['Parent'] = $record; } } return $context; }
Build context for verifying canCreate @see GridFieldAddNewButton::getHTMLFragments() @return array
getCreateContext
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
protected function getFormActions() { $manager = $this->getStateManager(); $actions = FieldList::create(); $majorActions = CompositeField::create()->setName('MajorActions'); $majorActions->setFieldHolderTemplate(get_class($majorActions) . '_holder_buttongroup'); $actions->push($majorActions); if ($this->record->ID !== null && $this->record->ID !== 0) { // existing record if ($this->record->hasMethod('canEdit') && $this->record->canEdit()) { if (!($this->record instanceof DataObjectInterface)) { throw new LogicException(get_class($this->record) . ' must implement ' . DataObjectInterface::class); } $noChangesClasses = 'btn-outline-primary font-icon-tick'; $majorActions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save')) ->addExtraClass($noChangesClasses) ->setAttribute('data-btn-alternate-add', 'btn-primary font-icon-save') ->setAttribute('data-btn-alternate-remove', $noChangesClasses) ->setUseButtonTag(true) ->setAttribute('data-text-alternate', _t('SilverStripe\\CMS\\Controllers\\CMSMain.SAVEDRAFT', 'Save'))); } if ($this->record->hasMethod('canDelete') && $this->record->canDelete()) { if (!($this->record instanceof DataObjectInterface)) { throw new LogicException(get_class($this->record) . ' must implement ' . DataObjectInterface::class); } $actions->insertAfter('MajorActions', FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete')) ->setUseButtonTag(true) ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete')); } $gridState = $this->gridField->getState(false); $actions->push(HiddenField::create($manager->getStateKey($this->gridField), null, $gridState)); $actions->push($this->getRightGroupField()); } else { // adding new record //Change the Save label to 'Create' $majorActions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create')) ->setUseButtonTag(true) ->addExtraClass('btn-primary font-icon-plus-thin')); // Add a Cancel link which is a button-like link and link back to one level up. $crumbs = $this->Breadcrumbs(); if ($crumbs && $crumbs->count() >= 2) { $oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2); $text = sprintf( "<a class=\"%s\" href=\"%s\">%s</a>", "crumb btn btn-secondary cms-panel-link", // CSS classes $oneLevelUp->Link, // url _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label ); $actions->insertAfter('MajorActions', LiteralField::create('cancelbutton', $text)); } } $this->extend('updateFormActions', $actions); return $actions; }
Build the set of form field actions for the record being handled @return FieldList
getFormActions
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
protected function getToplevelController() { $c = $this->popupController; while ($c && $c instanceof GridFieldDetailForm_ItemRequest) { $c = $c->getController(); } return $c; }
Traverse the nested RequestHandlers until we reach something that's not GridFieldDetailForm_ItemRequest. This allows us to access the Controller responsible for invoking the top-level GridField. This should be equivalent to getting the controller off the top of the controller stack via Controller::curr(), but allows us to avoid accessing the global state. GridFieldDetailForm_ItemRequests are RequestHandlers, and as such they are not part of the controller stack. @return Controller
getToplevelController
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
public function getEditLink($id) { $link = Controller::join_links( $this->gridField->Link(), 'item', $id ); return $this->gridField->addAllStateToUrl($link); }
Gets the edit link for a record @param int $id The ID of the record in the GridField @return string
getEditLink
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
public function getPreviousRecordID() { return $this->getAdjacentRecordID(-1); }
Gets the ID of the previous record in the list. @return int
getPreviousRecordID
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
public function getNextRecordID() { return $this->getAdjacentRecordID(1); }
Gets the ID of the next record in the list. @return int
getNextRecordID
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
protected function saveFormIntoRecord($data, $form) { $list = $this->gridField->getList(); // Check object matches the correct classname if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) { $newClassName = $data['ClassName']; // The records originally saved attribute was overwritten by $form->saveInto($record) before. // This is necessary for newClassInstance() to work as expected, and trigger change detection // on the ClassName attribute $this->record->setClassName($this->record->ClassName); // Replace $record with a new instance $this->record = $this->record->newClassInstance($newClassName); } // Save form and any extra saved data into this record. // Set writeComponents = true to write has-one relations / join records $form->saveInto($this->record); // https://github.com/silverstripe/silverstripe-assets/issues/365 $this->record->write(); $this->extend('onAfterSave', $this->record); $extraData = $this->getExtraSavedData($this->record, $list); $list->add($this->record, $extraData); return $this->record; }
Loads the given form data into the underlying record and relation @param array $data @param Form $form @throws ValidationException On error @return ViewableData&DataObjectInterface Saved record
saveFormIntoRecord
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
public function Breadcrumbs($unlinked = false) { if (!$this->popupController->hasMethod('Breadcrumbs')) { return null; } /** @var ArrayList<ArrayData> $items */ $items = $this->popupController->Breadcrumbs($unlinked); if (!$items) { $items = ArrayList::create(); } if ($this->record && $this->record->ID) { $title = ($this->record->Title) ? $this->record->Title : "#{$this->record->ID}"; $items->push(ArrayData::create([ 'Title' => $title, 'Link' => $this->Link() ])); } else { $items->push(ArrayData::create([ 'Title' => _t('SilverStripe\\Forms\\GridField\\GridField.NewRecord', 'New {type}', ['type' => $this->getModelName()]), 'Link' => false ])); } foreach ($items as $item) { if ($item->Link) { $item->Link = $this->gridField->addAllStateToUrl($item->Link); } } $this->extend('updateBreadcrumbs', $items); return $items; }
CMS-specific functionality: Passes through navigation breadcrumbs to the template, and includes the currently edited record (if any). see {@link LeftAndMain->Breadcrumbs()} for details. @param boolean $unlinked @return ArrayList<ArrayData>
Breadcrumbs
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php
BSD-3-Clause
public function nameEncode($value) { return (string)preg_replace_callback('/[^\w]/', [$this, '_nameEncode'], $value ?? ''); }
Encode all non-word characters. @param string $value @return string
nameEncode
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField_FormAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField_FormAction.php
BSD-3-Clause
protected function getNameFromParent() { $base = $this->gridField; $name = []; do { array_unshift($name, $base->getName()); $base = $base->getForm(); } while ($base && !($base instanceof Form)); return implode('.', $name); }
Calculate the name of the gridfield relative to the form. @return string
getNameFromParent
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridField_FormAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridField_FormAction.php
BSD-3-Clause
public function __construct($name = null, $showPagination = null, $showAdd = null) { $this->setName($name ?: 'DetailForm'); $this->setShowPagination($showPagination); $this->setShowAdd($showAdd); }
Create a popup component. The two arguments will specify how the popup form's HTML and behaviour is created. The given controller will be customised, putting the edit form into the template with the given name. The arguments are experimental API's to support partial content to be passed back to whatever controller who wants to display the getCMSFields @param string $name The name of the edit form to place into the pop-up form @param bool $showPagination Whether the `Previous` and `Next` buttons should display or not, leave as null to use default @param bool $showAdd Whether the `Add` button should display or not, leave as null to use default
__construct
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm.php
BSD-3-Clause
protected function getItemRequestHandler($gridField, $record, $requestHandler) { $class = $this->getItemRequestClass(); $assignedClass = $this->itemRequestClass; $this->extend('updateItemRequestClass', $class, $gridField, $record, $requestHandler, $assignedClass); /** @var GridFieldDetailForm_ItemRequest $handler */ $handler = Injector::inst()->createWithArgs( $class, [$gridField, $this, $record, $requestHandler, $this->name] ); if ($template = $this->getTemplate()) { $handler->setTemplate($template); } $this->extend('updateItemRequestHandler', $handler); return $handler; }
Build a request handler for the given record @param GridField $gridField @param ViewableData $record @param RequestHandler $requestHandler @return GridFieldDetailForm_ItemRequest
getItemRequestHandler
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDetailForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDetailForm.php
BSD-3-Clause
protected function getGridPagerState(GridField $gridField) { return $gridField->State->GridFieldPaginator; }
Retrieves/Sets up the state object used to store and retrieve information about the current paging details of this GridField @param GridField $gridField @return GridState_Data
getGridPagerState
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPaginator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPaginator.php
BSD-3-Clause
public function getTemplateParameters(GridField $gridField) { if (!$this->checkDataType($gridField->getList())) { return null; } $state = $this->getGridPagerState($gridField); // Figure out which page and record range we're on $totalRows = $this->totalItems; if (!$totalRows) { return null; } $totalPages = 1; $firstShownRecord = 1; $lastShownRecord = $totalRows; if ($itemsPerPage = $this->getItemsPerPage()) { $totalPages = (int)ceil($totalRows / $itemsPerPage); if ($totalPages == 0) { $totalPages = 1; } $firstShownRecord = ($state->currentPage - 1) * $itemsPerPage + 1; if ($firstShownRecord > $totalRows) { $firstShownRecord = $totalRows; } $lastShownRecord = $state->currentPage * $itemsPerPage; if ($lastShownRecord > $totalRows) { $lastShownRecord = $totalRows; } } // If there is only 1 page for all the records in list, we don't need to go further // to sort out those first page, last page, pre and next pages, etc // we are not render those in to the paginator. if ($totalPages === 1) { return new ArrayData([ 'OnlyOnePage' => true, 'FirstShownRecord' => $firstShownRecord, 'LastShownRecord' => $lastShownRecord, 'NumRecords' => $totalRows, 'NumPages' => $totalPages ]); } else { // First page button $firstPage = new GridField_FormAction($gridField, 'pagination_first', 'First', 'paginate', 1); $firstPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-left ss-gridfield-pagination-action ss-gridfield-firstpage'); if ($state->currentPage == 1) { $firstPage = $firstPage->performDisabledTransformation(); } // Previous page button $previousPageNum = $state->currentPage <= 1 ? 1 : $state->currentPage - 1; $previousPage = new GridField_FormAction( $gridField, 'pagination_prev', 'Previous', 'paginate', $previousPageNum ); $previousPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-left ss-gridfield-pagination-action ss-gridfield-previouspage'); if ($state->currentPage == 1) { $previousPage = $previousPage->performDisabledTransformation(); } // Next page button $nextPageNum = $state->currentPage >= $totalPages ? $totalPages : $state->currentPage + 1; $nextPage = new GridField_FormAction( $gridField, 'pagination_next', 'Next', 'paginate', $nextPageNum ); $nextPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-right ss-gridfield-pagination-action ss-gridfield-nextpage'); if ($state->currentPage == $totalPages) { $nextPage = $nextPage->performDisabledTransformation(); } // Last page button $lastPage = new GridField_FormAction($gridField, 'pagination_last', 'Last', 'paginate', $totalPages); $lastPage->addExtraClass('btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-right ss-gridfield-pagination-action ss-gridfield-lastpage'); if ($state->currentPage == $totalPages) { $lastPage = $lastPage->performDisabledTransformation(); } // Render in template return new ArrayData([ 'OnlyOnePage' => false, 'FirstPage' => $firstPage, 'PreviousPage' => $previousPage, 'CurrentPageNum' => $state->currentPage, 'NumPages' => $totalPages, 'NextPage' => $nextPage, 'LastPage' => $lastPage, 'FirstShownRecord' => $firstShownRecord, 'LastShownRecord' => $lastShownRecord, 'NumRecords' => $totalRows ]); } }
Determines arguments to be passed to the template for building this field @param GridField $gridField @return ArrayData If paging is available this will be an ArrayData object of paging details with these parameters: <ul> <li>OnlyOnePage: boolean - Is there only one page?</li> <li>FirstShownRecord: integer - Number of the first record displayed</li> <li>LastShownRecord: integer - Number of the last record displayed</li> <li>NumRecords: integer - Total number of records</li> <li>NumPages: integer - The number of pages</li> <li>CurrentPageNum (optional): integer - If OnlyOnePage is false, the number of the current page</li> <li>FirstPage (optional): GridField_FormAction - Button to go to the first page</li> <li>PreviousPage (optional): GridField_FormAction - Button to go to the previous page</li> <li>NextPage (optional): GridField_FormAction - Button to go to the next page</li> <li>LastPage (optional): GridField_FormAction - Button to go to last page</li> </ul>
getTemplateParameters
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPaginator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPaginator.php
BSD-3-Clause
public function getGroup($gridField, $record, $columnName) { if (!$this->canUnlink($record)) { return null; } return parent::getGroup($gridField, $record, $columnName); }
Get the ActionMenu group (not related to Member group) @param GridField $gridField @param DataObject $record @param $columnName @return null|string
getGroup
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldGroupDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldGroupDeleteAction.php
BSD-3-Clause
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { $record = $gridField->getList()->find('ID', $arguments['RecordID']); if (!$record || !$actionName == 'unlinkrelation' || $this->canUnlink($record)) { parent::handleAction($gridField, $actionName, $arguments, $data); return; } throw new ValidationException( _t(__CLASS__ . '.UnlinkSelfFailure', 'Cannot remove yourself from this group, you will lose admin rights') ); }
Handle the actions and apply any changes to the GridField @param GridField $gridField @param string $actionName @param array $arguments @param array $data Form data @throws ValidationException
handleAction
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldGroupDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldGroupDeleteAction.php
BSD-3-Clause
public function getColumnAttributes($gridField, $record, $columnName) { return ['class' => 'grid-field__col-compact']; }
Return any special attributes that will be used for FormField::create_tag() @param GridField $gridField @param DataObjectInterface&ViewableData $record @param string $columnName @return array
getColumnAttributes
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php
BSD-3-Clause
public function getColumnsHandled($gridField) { return ['Actions']; }
Which columns are handled by this component @param GridField $gridField @return array
getColumnsHandled
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php
BSD-3-Clause
public function getActions($gridField) { return ['deleterecord', 'unlinkrelation']; }
Which GridField actions are this component handling @param GridField $gridField @return array
getActions
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php
BSD-3-Clause
public function getRemoveRelation() { return $this->removeRelation; }
Get whether to remove or delete the relation @return bool
getRemoveRelation
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php
BSD-3-Clause
public function setRemoveRelation($removeRelation) { $this->removeRelation = (bool) $removeRelation; return $this; }
Set whether to remove or delete the relation @param bool $removeRelation @return $this
setRemoveRelation
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldDeleteAction.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldDeleteAction.php
BSD-3-Clause
public function setThrowExceptionOnBadDataType($throwExceptionOnBadDataType) { Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality'); $this->throwExceptionOnBadDataType = $throwExceptionOnBadDataType; }
Determine what happens when this component is used with a list that isn't {@link SS_Filterable}. - true: An exception is thrown - false: This component will be ignored - it won't make any changes to the GridField. By default, this is set to true so that it's clearer what's happening, but the predefined {@link GridFieldConfig} subclasses set this to false for flexibility. @param bool $throwExceptionOnBadDataType @deprecated 5.2.0 Will be removed without equivalent functionality
setThrowExceptionOnBadDataType
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function getActions($gridField) { if (!$this->checkDataType($gridField->getList())) { return []; } return ['filter', 'reset']; }
If the GridField has a filterable datalist, return an array of actions @param GridField $gridField @return array
getActions
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if (!$this->checkDataType($gridField->getList())) { return; } $state = $this->getState($gridField); $state->Columns = []; if ($actionName === 'filter') { if (isset($data['filter'][$gridField->getName()])) { foreach ($data['filter'][$gridField->getName()] as $key => $filter) { $state->Columns->$key = $filter; } } } }
If the GridField has a filterable datalist, return an array of actions @param GridField $gridField @param string $actionName @param array $data @return void
handleAction
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function getSearchContext(GridField $gridField) { if (!$this->searchContext) { $modelClass = $gridField->getModelClass(); $singleton = singleton($modelClass); if (!$singleton->hasMethod('getDefaultSearchContext')) { throw new LogicException( 'Cannot dynamically instantiate SearchContext. Pass the SearchContext to setSearchContext()' . " or implement a getDefaultSearchContext() method on $modelClass" ); } $list = $gridField->getList(); $searchContext = $singleton->getDefaultSearchContext(); // In case we are working with a list not backed by the database we need to convert the search context into a BasicSearchContext // This is because the scaffolded filters use the ORM for data searching if (!$list instanceof DataList) { $searchContext = $this->getBasicSearchContext($gridField, $searchContext); } $this->searchContext = $searchContext; } return $this->searchContext; }
Generate a search context based on the model class of the of the GridField @param GridField $gridfield @return SearchContext
getSearchContext
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function getSearchFieldSchema(GridField $gridField) { Deprecation::noticeWithNoReplacment( '5.4.0', 'Will be replaced with SilverStripe\ORM\Search\SearchContextForm::getSchemaData()' ); $schemaUrl = Controller::join_links($gridField->Link(), 'schema/SearchForm'); $inst = singleton($gridField->getModelClass()); $context = $this->getSearchContext($gridField); $params = $gridField->getRequest()->postVar('filter') ?: []; if (array_key_exists($gridField->getName(), $params ?? [])) { $params = $params[$gridField->getName()]; } if ($context->getSearchParams()) { $params = array_merge($context->getSearchParams(), $params); } $context->setSearchParams($params); $searchField = $this->getSearchField() ?: $inst->config()->get('general_search_field'); if (!$searchField) { $searchField = $context->getSearchFields()->first(); $searchField = $searchField && property_exists($searchField, 'name') ? $searchField->name : null; } // Prefix "Search__" onto the filters to match the field names in the actual form $filters = $context->getSearchParams(); if (!empty($filters)) { $filters = array_combine(array_map(function ($key) { return 'Search__' . $key; }, array_keys($filters ?? [])), $filters ?? []); } $searchAction = GridField_FormAction::create($gridField, 'filter', false, 'filter', null); $clearAction = GridField_FormAction::create($gridField, 'reset', false, 'reset', null); $schema = [ 'formSchemaUrl' => $schemaUrl, 'name' => $searchField, 'placeholder' => $this->getPlaceHolder($inst), 'filters' => $filters ?: new \stdClass, // stdClass maps to empty json object '{}' 'gridfield' => $gridField->getName(), 'searchAction' => $searchAction->getAttribute('name'), 'searchActionState' => $searchAction->getAttribute('data-action-state'), 'clearAction' => $clearAction->getAttribute('name'), 'clearActionState' => $clearAction->getAttribute('data-action-state'), ]; return json_encode($schema); }
Returns the search field schema for the component @param GridField $gridfield @return string @deprecated 5.4.0 Will be replaced with SilverStripe\ORM\Search\SearchContextForm::getSchemaData()
getSearchFieldSchema
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function getSearchFormSchema(GridField $gridField) { Deprecation::noticeWithNoReplacment( '5.4.0', 'Will be replaced with SilverStripe\Forms\FormRequestHandler::getSchema()' ); $form = $this->getSearchForm($gridField); // If there are no filterable fields, return a 400 response if (!$form) { return new HTTPResponse(_t(__CLASS__ . '.SearchFormFaliure', 'No search form could be generated'), 400); } $parts = $gridField->getRequest()->getHeader(FormSchema::SCHEMA_HEADER); $schemaID = $gridField->getRequest()->getURL(); $data = FormSchema::singleton() ->getMultipartSchema($parts, $schemaID, $form); $response = new HTTPResponse(json_encode($data)); $response->addHeader('Content-Type', 'application/json'); return $response; }
Returns the search form schema for the component @param GridField $gridfield @return HTTPResponse @deprecated 5.4.0 Will be replaced with SilverStripe\Forms\FormRequestHandler::getSchema()
getSearchFormSchema
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function getHTMLFragments($gridField) { $forTemplate = new ArrayData([]); if (!$this->canFilterAnyColumns($gridField)) { return null; } $fieldSchema = $this->getSearchFieldSchema($gridField); $forTemplate->SearchFieldSchema = $fieldSchema; $searchTemplates = SSViewer::get_templates_by_class($this, '_Search', __CLASS__); return [ 'before' => $forTemplate->renderWith($searchTemplates), 'buttons-before-right' => sprintf( '<button type="button" name="showFilter" aria-label="%s" title="%s"' . ' class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>', _t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter"), _t('SilverStripe\\Forms\\GridField\\GridField.OpenFilter', "Open search and filter") ) ]; }
Either returns the legacy filter header or the search button and field @param GridField $gridField @return array|null
getHTMLFragments
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldFilterHeader.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldFilterHeader.php
BSD-3-Clause
public function Value() { $data = $this->data ? $this->data->getChangesArray() : []; return json_encode($data, JSON_FORCE_OBJECT); }
Returns a json encoded string representation of this state. @return string
Value
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridState.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridState.php
BSD-3-Clause
public function getData($name, $default = null) { if (!array_key_exists($name, $this->data ?? [])) { $this->data[$name] = $default; } else { if (is_array($this->data[$name])) { $this->data[$name] = new GridState_Data($this->data[$name]); } } return $this->data[$name]; }
Retrieve the value for the given key @param string $name The name of the value to retrieve @param mixed $default Default value to assign if not set. Note that this *will* be included in getChangesArray() @return mixed The value associated with this key, or the value specified by $default if not set
getData
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridState_Data.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridState_Data.php
BSD-3-Clause
public function getHTMLFragments($gridField) { $button = new GridField_FormAction( $gridField, 'export', _t('SilverStripe\\Forms\\GridField\\GridField.CSVEXPORT', 'Export to CSV'), 'export', null ); $button->addExtraClass('btn btn-secondary no-ajax font-icon-down-circled action_export'); $button->setForm($gridField->getForm()); return [ $this->targetFragment => $button->Field(), ]; }
Place the export button in a <p> tag below the field @param GridField $gridField @return array
getHTMLFragments
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldExportButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldExportButton.php
BSD-3-Clause
public function handleExport($gridField, $request = null) { $now = date("d-m-Y-H-i"); $fileName = "export-$now.csv"; if ($fileData = $this->generateExportFileData($gridField)) { return HTTPRequest::send_file($fileData, $fileName, 'text/csv'); } return null; }
Handle the export, for both the action button and the URL @param GridField $gridField @param HTTPRequest $request @return HTTPResponse
handleExport
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldExportButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldExportButton.php
BSD-3-Clause
protected function getPaginator($gridField) { $paginator = $gridField->getConfig()->getComponentByType(GridFieldPaginator::class); if (!$paginator && GridFieldPageCount::config()->uninherited('require_paginator')) { throw new LogicException( static::class . " relies on a GridFieldPaginator to be added " . "to the same GridField, but none are present." ); } return $paginator; }
Retrieves an instance of a GridFieldPaginator attached to the same control @param GridField $gridField The parent gridfield @return GridFieldPaginator The attached GridFieldPaginator, if found. @throws LogicException
getPaginator
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldPageCount.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldPageCount.php
BSD-3-Clause
public function getActions($gridField) { return []; }
Which GridField actions are this component handling. @param GridField $gridField @return array
getActions
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldEditButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php
BSD-3-Clause
public function getExtraClass() { return implode(' ', array_keys($this->extraClass ?? [])); }
Get the extra HTML classes to add for edit buttons @return string
getExtraClass
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldEditButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php
BSD-3-Clause
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { }
Handle the actions and apply any changes to the GridField. @param GridField $gridField @param string $actionName @param mixed $arguments @param array $data - form data @return void
handleAction
php
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldEditButton.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/GridFieldEditButton.php
BSD-3-Clause
public function save($id, array $state) { $this->getRequest()->getSession()->set($id, $state); // This adapter does not require any additional attributes... return []; }
Save the given state against the given ID returning an associative array to be added as attributes on the form action @param string $id @param array $state @return array
save
php
silverstripe/silverstripe-framework
src/Forms/GridField/FormAction/SessionStore.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/GridField/FormAction/SessionStore.php
BSD-3-Clause
public function getState(Form $form) { $state = [ 'id' => $form->FormName(), 'fields' => [], 'messages' => [], 'notifyUnsavedChanges' => $form->getNotifyUnsavedChanges(), ]; // flattened nested fields are returned, rather than only top level fields. $state['fields'] = array_merge( $this->getFieldStates($form->Fields()), $this->getFieldStates($form->Actions()) ); if ($message = $form->getSchemaMessage()) { $state['messages'][] = $message; } return $state; }
Gets the current state of this form as a nested array. @param Form $form @return array
getState
php
silverstripe/silverstripe-framework
src/Forms/Schema/FormSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Forms/Schema/FormSchema.php
BSD-3-Clause
public static function filename2url($filename) { $filename = realpath($filename ?? ''); if (!$filename) { return null; } // Filter files outside of the webroot $base = realpath(BASE_PATH); $baseLength = strlen($base ?? ''); if (substr($filename ?? '', 0, $baseLength) !== $base) { return null; } $relativePath = ltrim(substr($filename ?? '', $baseLength ?? 0), '/\\'); return Director::absoluteURL($relativePath); }
Turns a local system filename into a URL by comparing it to the script filename. @param string $filename @return string
filename2url
php
silverstripe/silverstripe-framework
src/Control/HTTP.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php
BSD-3-Clause
public static function absoluteURLs($html) { $html = str_replace('$CurrentPageURL', Controller::curr()->getRequest()->getURL() ?? '', $html ?? ''); return HTTP::urlRewriter($html, function ($url) { //no need to rewrite, if uri has a protocol (determined here by existence of reserved URI character ":") if (preg_match('/^\w+:/', $url ?? '')) { return $url; } return Director::absoluteURL((string) $url); }); }
Turn all relative URLs in the content to absolute URLs. @param string $html @return string
absoluteURLs
php
silverstripe/silverstripe-framework
src/Control/HTTP.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php
BSD-3-Clause
public static function setGetVar($varname, $varvalue, $currentURL = null, $separator = '&') { if (!isset($currentURL)) { $request = Controller::curr()->getRequest(); $currentURL = $request->getURL(true); } $uri = $currentURL; $isRelative = false; // We need absolute URLs for parse_url() if (Director::is_relative_url($uri)) { $uri = Controller::join_links(Director::absoluteBaseURL(), $uri); $isRelative = true; } // try to parse uri $parts = parse_url($uri ?? ''); if (!$parts) { throw new InvalidArgumentException("Can't parse URL: " . $uri); } // Parse params and add new variable $params = []; if (isset($parts['query'])) { parse_str($parts['query'] ?? '', $params); } $params[$varname] = $varvalue; // Generate URI segments and formatting $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http'; $user = (isset($parts['user']) && $parts['user'] != '') ? $parts['user'] : ''; if ($user != '') { // format in either user:[email protected] or [email protected] $user .= (isset($parts['pass']) && $parts['pass'] != '') ? ':' . $parts['pass'] . '@' : '@'; } $host = (isset($parts['host'])) ? $parts['host'] : ''; $port = (isset($parts['port']) && $parts['port'] != '') ? ':' . $parts['port'] : ''; $path = (isset($parts['path']) && $parts['path'] != '') ? $parts['path'] : ''; // handle URL params which are existing / new $params = ($params) ? '?' . http_build_query($params, '', $separator) : ''; // keep fragments (anchors) intact. $fragment = (isset($parts['fragment']) && $parts['fragment'] != '') ? '#' . $parts['fragment'] : ''; // Recompile URI segments $newUri = $scheme . '://' . $user . $host . $port . $path . $params . $fragment; if ($isRelative) { return Controller::join_links(Director::baseURL(), Director::makeRelative($newUri)); } return $newUri; }
Will try to include a GET parameter for an existing URL, preserving existing parameters and fragments. If no URL is given, falls back to $_SERVER['REQUEST_URI']. Uses parse_url() to dissect the URL, and http_build_query() to reconstruct it with the additional parameter. Converts any '&' (ampersand) URL parameter separators to the more XHTML compliant '&amp;'. CAUTION: If the URL is determined to be relative, it is prepended with Director::absoluteBaseURL(). This method will always return an absolute URL because Director::makeRelative() can lead to inconsistent results. @param string $varname @param string $varvalue @param string|null $currentURL Relative or absolute URL, or HTTPRequest to get url from @param string $separator Separator for http_build_query(). @return string
setGetVar
php
silverstripe/silverstripe-framework
src/Control/HTTP.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTP.php
BSD-3-Clause