PhpDefault.php in Views Contextual Range Filter 8
File
src/Plugin/views/argument_default/PhpDefault.php
View source
<?php
namespace Drupal\contextual_range_filter\Plugin\views\argument_default;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\argument_default\ArgumentDefaultPluginBase;
class PhpDefault extends ArgumentDefaultPluginBase implements CacheableDependencyInterface {
protected function defineOptions() {
$options = parent::defineOptions();
$options['code'] = [
'default' => '',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$warning = $this
->t('In order to use this feature you must 1) have the "Use PHP code for default contextual filter" permission and 2) know what you are doing.');
$help1 = $this
->t('Enter PHP code that returns a single text or number to use for this filter. Do <em>not</em> use <code><?php ?></code>');
$help2 = $this
->t("Depending on the page you're on some entity objects are available as <code>\$entity['node'], \$entity['user']</code> etc.");
$example1 = $this
->t("<strong>Example</strong>: if the View is a block displayed on <em>node/*</em> pages and the View has a field named <em>Price</em>, then you can return items cheaper than the main node shown, using a snippet like this:");
$code1 = "<code>return '--' . \$entity['node']->field_price->getString();</code>";
$help3 = $this
->t("<code>--</code> (double hyphen) is the range operator. In the above example there is no lower limit to the range, only an upper limit.");
$form['code'] = [
'#type' => 'textarea',
'#title' => $this
->t('PHP contextual filter code -- experienced users only'),
'#default_value' => $this->options['code'],
'#description' => "{$warning}<br/>{$help1}<br/>{$help2}<br/>{$example1}<br/>{$code1}<br/>{$help3}<br/>",
];
$this
->checkAccess($form, 'code');
}
public function access() {
return \Drupal::currentUser()
->hasPermission('use views php code contextual filter');
}
public function getArgument() {
$entity = [];
foreach ($params = \Drupal::routeMatch()
->getParameters() as $type => $param) {
if ($param instanceof EntityInterface) {
$entity[$type] = $param;
}
}
ob_start();
$result = eval($this->options['code']);
ob_end_clean();
return $result;
}
public function getCacheMaxAge() {
return Cache::PERMANENT;
}
public function getCacheContexts() {
return [];
}
}
Classes
Name |
Description |
PhpDefault |
Default argument plugin to execute PHP code to return default argument value. |