class Table

Same name in this branch
  1. 11.x core/lib/Drupal/Core/Render/Element/Table.php \Drupal\Core\Render\Element\Table
Same name in other branches
  1. 9 core/modules/views/src/Plugin/views/style/Table.php \Drupal\views\Plugin\views\style\Table
  2. 9 core/lib/Drupal/Core/Render/Element/Table.php \Drupal\Core\Render\Element\Table
  3. 8.9.x core/modules/views/src/Plugin/views/style/Table.php \Drupal\views\Plugin\views\style\Table
  4. 8.9.x core/lib/Drupal/Core/Render/Element/Table.php \Drupal\Core\Render\Element\Table
  5. 10 core/modules/views/src/Plugin/views/style/Table.php \Drupal\views\Plugin\views\style\Table
  6. 10 core/lib/Drupal/Core/Render/Element/Table.php \Drupal\Core\Render\Element\Table

Style plugin to render each item as a row in a table.

Hierarchy

Expanded class hierarchy of Table

Related topics

1 file declares its use of Table
BulkForm.php in core/modules/views/src/Plugin/views/field/BulkForm.php
75 string references to 'Table'
BookAdminEditForm::bookAdminTableTree in core/modules/book/src/Form/BookAdminEditForm.php
Helps build the main table in the book administration page form.
BookAdminEditForm::submitForm in core/modules/book/src/Form/BookAdminEditForm.php
Form submission handler.
ckeditor5.ckeditor5.yml in core/modules/ckeditor5/ckeditor5.ckeditor5.yml
core/modules/ckeditor5/ckeditor5.ckeditor5.yml
ckeditor5.ckeditor5.yml in core/modules/ckeditor5/ckeditor5.ckeditor5.yml
core/modules/ckeditor5/ckeditor5.ckeditor5.yml
claro_preprocess_file_widget_multiple in core/themes/claro/claro.theme
Implements hook_preprocess_HOOK() for file_widget_multiple.

... See full list

File

core/modules/views/src/Plugin/views/style/Table.php, line 18

Namespace

Drupal\views\Plugin\views\style
View source
class Table extends StylePluginBase implements CacheableDependencyInterface {
    
    /**
     * Does the style plugin for itself support to add fields to its output.
     *
     * @var bool
     */
    protected $usesFields = TRUE;
    
    /**
     * {@inheritdoc}
     */
    protected $usesRowPlugin = FALSE;
    
    /**
     * Does the style plugin support custom css class for the rows.
     *
     * @var bool
     */
    protected $usesRowClass = TRUE;
    
    /**
     * Should field labels be enabled by default.
     *
     * @var bool
     */
    protected $defaultFieldLabels = TRUE;
    
    /**
     * Contains the current active sort column.
     * @var string
     */
    public $active;
    
    /**
     * Contains the current active sort order, either desc or asc.
     * @var string
     */
    public $order;
    protected function defineOptions() {
        $options = parent::defineOptions();
        $options['columns'] = [
            'default' => [],
        ];
        $options['default'] = [
            'default' => '',
        ];
        $options['info'] = [
            'default' => [],
        ];
        $options['override'] = [
            'default' => TRUE,
        ];
        $options['sticky'] = [
            'default' => FALSE,
        ];
        $options['order'] = [
            'default' => 'asc',
        ];
        $options['caption'] = [
            'default' => '',
        ];
        $options['summary'] = [
            'default' => '',
        ];
        $options['description'] = [
            'default' => '',
        ];
        $options['empty_table'] = [
            'default' => FALSE,
        ];
        return $options;
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildSort() {
        $order = $this->view
            ->getRequest()->query
            ->get('order');
        if (!isset($order) && ($this->options['default'] == -1 || empty($this->view->field[$this->options['default']]))) {
            return TRUE;
        }
        // If a sort we don't know anything about gets through, exit gracefully.
        if (isset($order) && empty($this->view->field[$order])) {
            return TRUE;
        }
        // Let the builder know whether or not we're overriding the default sorts.
        return empty($this->options['override']);
    }
    
    /**
     * Add our actual sort criteria.
     */
    public function buildSortPost() {
        $query = $this->view
            ->getRequest()->query;
        $order = $query->get('order');
        if (!isset($order)) {
            // Check for a 'default' clickSort. If there isn't one, exit gracefully.
            if (empty($this->options['default'])) {
                return;
            }
            $sort = $this->options['default'];
            if (!empty($this->options['info'][$sort]['default_sort_order'])) {
                $this->order = $this->options['info'][$sort]['default_sort_order'];
            }
            else {
                $this->order = !empty($this->options['order']) ? $this->options['order'] : 'asc';
            }
        }
        else {
            $sort = $order;
            // Store the $order for later use.
            $request_sort = $query->get('sort');
            $this->order = !empty($request_sort) ? strtolower($request_sort) : 'asc';
        }
        // If a sort we don't know anything about gets through, exit gracefully.
        if (empty($this->view->field[$sort])) {
            return;
        }
        // Ensure $this->order is valid.
        if ($this->order != 'asc' && $this->order != 'desc') {
            $this->order = 'asc';
        }
        // Store the $sort for later use.
        $this->active = $sort;
        // Tell the field to click sort.
        $this->view->field[$sort]
            ->clickSort($this->order);
    }
    
    /**
     * Sanitizes the columns.
     *
     * Normalize a list of columns based upon the fields that are
     * available. This compares the fields stored in the style handler
     * to the list of fields actually in the view, removing fields that
     * have been removed and adding new fields in their own column.
     *
     * - Each field must be in a column.
     * - Each column must be based upon a field, and that field
     *   is somewhere in the column.
     * - Any fields not currently represented must be added.
     * - Columns must be re-ordered to match the fields.
     *
     * @param $columns
     *   An array of all fields; the key is the id of the field and the
     *   value is the id of the column the field should be in.
     * @param $fields
     *   The fields to use for the columns. If not provided, they will
     *   be requested from the current display. The running render should
     *   send the fields through, as they may be different than what the
     *   display has listed due to access control or other changes.
     *
     * @return array
     *   An array of all the sanitized columns.
     */
    public function sanitizeColumns($columns, $fields = NULL) {
        $sanitized = [];
        if ($fields === NULL) {
            $fields = $this->displayHandler
                ->getOption('fields');
        }
        // Pre-configure the sanitized array so that the order is retained.
        foreach ($fields as $field => $info) {
            // Set to itself so that if it isn't touched, it gets column
            // status automatically.
            $sanitized[$field] = $field;
        }
        foreach ($columns as $field => $column) {
            // first, make sure the field still exists.
            if (!isset($sanitized[$field])) {
                continue;
            }
            // If the field is the column, mark it so, or the column
            // it's set to is a column, that's ok
            if ($field == $column || $columns[$column] == $column && !empty($sanitized[$column])) {
                $sanitized[$field] = $column;
            }
            // Since we set the field to itself initially, ignoring
            // the condition is ok; the field will get its column
            // status back.
        }
        return $sanitized;
    }
    
    /**
     * Render the given style.
     */
    public function buildOptionsForm(&$form, FormStateInterface $form_state) {
        parent::buildOptionsForm($form, $form_state);
        $handlers = $this->displayHandler
            ->getHandlers('field');
        if (empty($handlers)) {
            $form['error_markup'] = [
                '#markup' => '<div class="messages messages--error">' . $this->t('You need at least one field before you can configure your table settings') . '</div>',
            ];
            return;
        }
        $form['override'] = [
            '#type' => 'checkbox',
            '#title' => $this->t('Override normal sorting if click sorting is used'),
            '#default_value' => !empty($this->options['override']),
        ];
        $form['sticky'] = [
            '#type' => 'checkbox',
            '#title' => $this->t('Enable Drupal style "sticky" table headers'),
            '#default_value' => !empty($this->options['sticky']),
            '#description' => $this->t('(Sticky header effects will not be active for preview below, only on live output.)'),
        ];
        $form['caption'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Caption for the table'),
            '#description' => $this->t('A title semantically associated with your table for increased accessibility.'),
            '#default_value' => $this->options['caption'],
            '#maxlength' => 255,
        ];
        $form['accessibility_details'] = [
            '#type' => 'details',
            '#title' => $this->t('Table details'),
        ];
        $form['summary'] = [
            '#title' => $this->t('Summary title'),
            '#type' => 'textfield',
            '#default_value' => $this->options['summary'],
            '#fieldset' => 'accessibility_details',
        ];
        $form['description'] = [
            '#title' => $this->t('Table description'),
            '#type' => 'textarea',
            '#description' => $this->t('Provide additional details about the table to increase accessibility.'),
            '#default_value' => $this->options['description'],
            '#states' => [
                'visible' => [
                    'input[name="style_options[summary]"]' => [
                        'filled' => TRUE,
                    ],
                ],
            ],
            '#fieldset' => 'accessibility_details',
        ];
        // Note: views UI registers this theme handler on our behalf. Your module
        // will have to register your theme handlers if you do stuff like this.
        $form['#theme'] = 'views_ui_style_plugin_table';
        $columns = $this->sanitizeColumns($this->options['columns']);
        // Create an array of allowed columns from the data we know:
        $field_names = $this->displayHandler
            ->getFieldLabels();
        if (isset($this->options['default'])) {
            $default = $this->options['default'];
            if (!isset($columns[$default])) {
                $default = -1;
            }
        }
        else {
            $default = -1;
        }
        foreach ($columns as $field => $column) {
            $column_selector = ':input[name="style_options[columns][' . $field . ']"]';
            $form['columns'][$field] = [
                '#title' => $this->t('Columns for @field', [
                    '@field' => $field,
                ]),
                '#title_display' => 'invisible',
                '#type' => 'select',
                '#options' => $field_names,
                '#default_value' => $column,
            ];
            if ($handlers[$field]->clickSortable()) {
                $form['info'][$field]['sortable'] = [
                    '#title' => $this->t('Sortable for @field', [
                        '@field' => $field,
                    ]),
                    '#title_display' => 'invisible',
                    '#type' => 'checkbox',
                    '#default_value' => !empty($this->options['info'][$field]['sortable']),
                    '#states' => [
                        'visible' => [
                            $column_selector => [
                                'value' => $field,
                            ],
                        ],
                    ],
                ];
                $form['info'][$field]['default_sort_order'] = [
                    '#title' => $this->t('Default sort order for @field', [
                        '@field' => $field,
                    ]),
                    '#title_display' => 'invisible',
                    '#type' => 'select',
                    '#options' => [
                        'asc' => $this->t('Ascending'),
                        'desc' => $this->t('Descending'),
                    ],
                    '#default_value' => !empty($this->options['info'][$field]['default_sort_order']) ? $this->options['info'][$field]['default_sort_order'] : 'asc',
                    '#states' => [
                        'visible' => [
                            $column_selector => [
                                'value' => $field,
                            ],
                            ':input[name="style_options[info][' . $field . '][sortable]"]' => [
                                'checked' => TRUE,
                            ],
                        ],
                    ],
                ];
                // Provide an ID so we can have such things.
                $radio_id = Html::getUniqueId('edit-default-' . $field);
                $form['default'][$field] = [
                    '#title' => $this->t('Default sort for @field', [
                        '@field' => $field,
                    ]),
                    '#title_display' => 'invisible',
                    '#type' => 'radio',
                    '#return_value' => $field,
                    '#parents' => [
                        'style_options',
                        'default',
                    ],
                    '#id' => $radio_id,
                    // Because 'radio' doesn't fully support '#id' =(
'#attributes' => [
                        'id' => $radio_id,
                    ],
                    '#default_value' => $default,
                    '#states' => [
                        'visible' => [
                            $column_selector => [
                                'value' => $field,
                            ],
                        ],
                    ],
                ];
            }
            $form['info'][$field]['align'] = [
                '#title' => $this->t('Alignment for @field', [
                    '@field' => $field,
                ]),
                '#title_display' => 'invisible',
                '#type' => 'select',
                '#default_value' => !empty($this->options['info'][$field]['align']) ? $this->options['info'][$field]['align'] : '',
                '#options' => [
                    '' => $this->t('None'),
                    'views-align-left' => $this->t('Left', [], [
                        'context' => 'Text alignment',
                    ]),
                    'views-align-center' => $this->t('Center', [], [
                        'context' => 'Text alignment',
                    ]),
                    'views-align-right' => $this->t('Right', [], [
                        'context' => 'Text alignment',
                    ]),
                ],
                '#states' => [
                    'visible' => [
                        $column_selector => [
                            'value' => $field,
                        ],
                    ],
                ],
            ];
            $form['info'][$field]['separator'] = [
                '#title' => $this->t('Separator for @field', [
                    '@field' => $field,
                ]),
                '#title_display' => 'invisible',
                '#type' => 'textfield',
                '#size' => 10,
                '#default_value' => $this->options['info'][$field]['separator'] ?? '',
                '#states' => [
                    'visible' => [
                        $column_selector => [
                            'value' => $field,
                        ],
                    ],
                ],
            ];
            $form['info'][$field]['empty_column'] = [
                '#title' => $this->t('Hide empty column for @field', [
                    '@field' => $field,
                ]),
                '#title_display' => 'invisible',
                '#type' => 'checkbox',
                '#default_value' => $this->options['info'][$field]['empty_column'] ?? FALSE,
                '#states' => [
                    'visible' => [
                        $column_selector => [
                            'value' => $field,
                        ],
                    ],
                ],
            ];
            $form['info'][$field]['responsive'] = [
                '#title' => $this->t('Responsive setting for @field', [
                    '@field' => $field,
                ]),
                '#title_display' => 'invisible',
                '#type' => 'select',
                '#default_value' => $this->options['info'][$field]['responsive'] ?? '',
                '#options' => [
                    '' => $this->t('High'),
                    RESPONSIVE_PRIORITY_MEDIUM => $this->t('Medium'),
                    RESPONSIVE_PRIORITY_LOW => $this->t('Low'),
                ],
                '#states' => [
                    'visible' => [
                        $column_selector => [
                            'value' => $field,
                        ],
                    ],
                ],
            ];
            // Markup for the field name
            $form['info'][$field]['name'] = [
                '#markup' => $field_names[$field],
            ];
        }
        // Provide a radio for no default sort
        $form['default'][-1] = [
            '#title' => $this->t('No default sort'),
            '#title_display' => 'invisible',
            '#type' => 'radio',
            '#return_value' => -1,
            '#parents' => [
                'style_options',
                'default',
            ],
            '#id' => 'edit-default-0',
            '#default_value' => $default,
        ];
        $form['empty_table'] = [
            '#type' => 'checkbox',
            '#title' => $this->t('Show the empty text in the table'),
            '#default_value' => $this->options['empty_table'],
            '#description' => $this->t('Per default the table is hidden for an empty view. With this option it is possible to show an empty table with the text in it.'),
        ];
        $form['description_markup'] = [
            '#markup' => '<div class="js-form-item form-item description">' . $this->t('Place fields into columns; you may combine multiple fields into the same column. If you do, the separator in the column specified will be used to separate the fields. Check the sortable box to make that column click sortable, and check the default sort radio to determine which column will be sorted by default, if any. You may control column order and field labels in the fields section.') . '</div>',
        ];
    }
    public function evenEmpty() {
        return parent::evenEmpty() || !empty($this->options['empty_table']);
    }
    public function wizardSubmit(&$form, FormStateInterface $form_state, WizardInterface $wizard, &$display_options, $display_type) {
        // If any of the displays use the table style, make sure that the fields
        // always have a labels by unsetting the override.
        foreach ($display_options['default']['fields'] as &$field) {
            unset($field['label']);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCacheMaxAge() {
        return Cache::PERMANENT;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCacheContexts() {
        $contexts = [];
        foreach ($this->options['info'] as $info) {
            if (!empty($info['sortable'])) {
                // The rendered link needs to play well with any other query parameter
                // used on the page, like pager and exposed filter.
                $contexts[] = 'url.query_args';
                break;
            }
        }
        return $contexts;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getCacheTags() {
        return [];
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DerivativeInspectionInterface::getBaseId public function Gets the base_plugin_id of the plugin instance. 1
DerivativeInspectionInterface::getDerivativeId public function Gets the derivative_id of the plugin instance. 1
PluginBase::$definition public property Plugins&#039; definition.
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$position public property The handler position.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$view public property The top object of a view. 1
PluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 14
PluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 61
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::submitOptionsForm public function Handle any special handling on the validate form. Overrides ViewsPluginInterface::submitOptionsForm 16
PluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides ViewsPluginInterface::summaryTitle 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::unpackOptions public function Unpacks options over our existing defaults. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::viewsTokenReplace protected function Replaces Views&#039; tokens in a given string. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
PluginBase::__construct public function Constructs a PluginBase object. 19
PluginInspectionInterface::getPluginDefinition public function Gets the definition of the plugin implementation. 6
PluginInspectionInterface::getPluginId public function Gets the plugin ID of the plugin instance. 2
StylePluginBase::$groupingTheme protected property The theme function used to render the grouping set.
StylePluginBase::$rendered_fields protected property
StylePluginBase::$render_tokens public property
StylePluginBase::$rowTokens protected property Store all available tokens row rows.
StylePluginBase::$usesGrouping protected property Does the style plugin support grouping of rows. 3
StylePluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. Overrides PluginBase::$usesOptions
StylePluginBase::defaultFieldLabels public function Return TRUE if this style enables field labels by default. 1
StylePluginBase::destroy public function Clears a plugin. Overrides PluginBase::destroy
StylePluginBase::elementPreRenderRow public function #pre_render callback for view row field rendering.
StylePluginBase::getField public function Gets a rendered field.
StylePluginBase::getFieldValue public function Get the raw field value.
StylePluginBase::getRowClass public function Return the token replaced row class for the specified row.
StylePluginBase::init public function Overrides \Drupal\views\Plugin\views\PluginBase::init(). Overrides PluginBase::init
StylePluginBase::preRender public function Allow the style to do stuff before each row is rendered.
StylePluginBase::query public function Add anything to the query that we might need to. Overrides PluginBase::query 1
StylePluginBase::render public function Render the display in this style. 7
StylePluginBase::renderFields protected function Renders all of the fields for a given style and store them on the object.
StylePluginBase::renderGrouping public function Group records as needed for rendering.
StylePluginBase::renderGroupingSets public function Render the grouping sets.
StylePluginBase::renderRowGroup protected function Renders a group of rows of the grouped view.
StylePluginBase::tokenizeValue public function Take a value and apply token replacement logic to it.
StylePluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides PluginBase::trustedCallbacks
StylePluginBase::usesFields public function Return TRUE if this style also uses fields. 3
StylePluginBase::usesGrouping public function Returns the usesGrouping property. 3
StylePluginBase::usesRowClass public function Returns the usesRowClass property. 3
StylePluginBase::usesRowPlugin public function Returns the usesRowPlugin property. 11
StylePluginBase::usesTokens public function Return TRUE if this style uses tokens.
StylePluginBase::validate public function Validate that the plugin is correct and can be saved. Overrides PluginBase::validate
StylePluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm
Table::$active public property Contains the current active sort column.
Table::$defaultFieldLabels protected property Should field labels be enabled by default. Overrides StylePluginBase::$defaultFieldLabels
Table::$order public property Contains the current active sort order, either desc or asc.
Table::$usesFields protected property Does the style plugin for itself support to add fields to its output. Overrides StylePluginBase::$usesFields
Table::$usesRowClass protected property Does the style plugin support custom css class for the rows. Overrides StylePluginBase::$usesRowClass
Table::$usesRowPlugin protected property Whether or not this style uses a row plugin. Overrides StylePluginBase::$usesRowPlugin
Table::buildOptionsForm public function Render the given style. Overrides StylePluginBase::buildOptionsForm
Table::buildSort public function Determines if the style handler should interfere with sorts. Overrides StylePluginBase::buildSort
Table::buildSortPost public function Add our actual sort criteria. Overrides StylePluginBase::buildSortPost
Table::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides StylePluginBase::defineOptions
Table::evenEmpty public function Determines if the style plugin is rendered even if the view is empty. Overrides StylePluginBase::evenEmpty
Table::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
Table::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
Table::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
Table::sanitizeColumns public function Sanitizes the columns.
Table::wizardSubmit public function Alter the options of a display before they are added to the view. Overrides StylePluginBase::wizardSubmit
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.