Created
May 22, 2017 07:42
-
-
Save fago/f51fe8861919a40c753a03c79a134848 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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