For my use case, I want to filter pages than are older than current page.
Contextual filter cannot work as we don't have access to the operator : @see Is there a specific reason that views contextual filters lack the ability to specify the operator?
So I have for my work around:
1x contextual filter:
- Use content Id from URL + content validator content (exclude from results)
1x normal views filter:
- filter by created date is less than current with dummy value "2020-10-20 00:00:00"
On the block layout -> block settings I use "Content: ID Node from ID".
Then in the theme layer to override "2020-10-20 00:00:00" with node created date:
use Drupal\Core\Plugin\ContextAwarePluginInterface;
/**
* Implements hook_preprocess_block__views_block__VIEW_ID__DISPLAY_ID().
*/
function mytheme_preprocess_block__views_block__alumni_hub_previous_lessons_block_1(&$variables, $hook) {
if (!isset($variables['elements']['#plugin_id'])
|| !isset($variables['elements']['#configuration'])) {
return;
}
$block_manager = \Drupal::service('plugin.manager.block');
// Plugin ID format is: views_block:VIEW_ID-DISPLAY_ID.
$plugin_block = $block_manager->createInstance($variables['elements']['#plugin_id'], $variables['elements']['#configuration']);
// Inject runtime contexts.
if ($plugin_block instanceof ContextAwarePluginInterface) {
$contexts = \Drupal::service('context.repository')->getRuntimeContexts($plugin_block->getContextMapping());
\Drupal::service('context.handler')->applyContextMapping($plugin_block, $contexts);
// Get the node entity from the contextual value now.
$contextual_values = $plugin_block->getContextValues();
if (isset($contextual_values['nid'])
&& $contextual_values['nid']->hasField('created')
&& !$contextual_values['nid']->get('created')->isEmpty()) {
$date_timestamp = $contextual_values['nid']->created->value;
$plugin_view = $plugin_block->getViewExecutable();
$filter = $plugin_view->display_handler->getHandler('filter', 'created');
// Actually line that changes stuff.
// Set filter to show nodes earlier than current ndoe.
$filter->value['value'] = \Drupal::service('date.formatter')->format($date_timestamp, 'custom', 'Y-m-d H:i:s');
// Good to change options too.
$filter->options['value'] = $filter->value;
// Override render array.
$variables['content'] = $plugin_block->build();
}
}
}