Skip to content

Instantly share code, notes, and snippets.

@fago
Created May 22, 2017 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fago/f51fe8861919a40c753a03c79a134848 to your computer and use it in GitHub Desktop.
Save fago/f51fe8861919a40c753a03c79a134848 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\module\Plugin\Block;
use Drupal\contextual_views\Plugin\Block\ContextualViewsBlock;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;
/**
* Provides a 'NewsByChannel' block.
*
* @Block(
* id = "views_block:news-news_by_channel",
* admin_label = @Translation("News by channel"),
* category = @Translation("News"),
* context = {
* "node" = @ContextDefinition("entity:node", required = FALSE)
* }
* )
*/
class NewsByChannel extends ContextualViewsBlock {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'channel' => '',
] + parent::defaultConfiguration();
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
// @todo: This should make use of a data selector.
$form['channel'] = [
'#type' => 'textfield',
'#title' => $this->t('Channel field'),
'#description' => $this->t('The field on the node (context) containing the channel.'),
'#default_value' => $this->configuration['channel'],
'#weight' => '10',
'#required' => TRUE,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
parent::blockSubmit($form, $form_state);
$this->configuration['channel'] = $form_state->getValue('channel');
}
/**
* {@inheritdoc}
*/
public function build() {
$node = $this->getContextValue('node');
assert($node instanceof NodeInterface);
$channel = NULL;
$field_name = $this->configuration['channel'];
if ($node->hasField($field_name)) {
$channel = $node->get($field_name)->entity ? $node->get($field_name)->entity->id() : NULL;
}
$this->view->setArguments([$channel]);
return parent::build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment