ProgRessourceLink.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Drupal\popsu_link_block\Plugin\Block;
  3. use Drupal\Core\Block\BlockBase;
  4. use Drupal\Core\Form\FormStateInterface;
  5. use Drupal\Core\Url;
  6. use Drupal\Core\Link;
  7. // use Drupal\Core\Utility\Token;
  8. /**
  9. * Provides a 'ProgRessourceLink' block.
  10. *
  11. * @Block(
  12. * id = "prog_ressource_link",
  13. * admin_label = @Translation("Prog ressource link"),
  14. * )
  15. */
  16. class ProgRessourceLink extends BlockBase {
  17. public function blockForm($form, FormStateInterface $form_state) {
  18. $form = parent::blockForm($form, $form_state);
  19. $config = $this->getConfiguration();
  20. $form['link_title_wrapper'] = [
  21. '#type' => 'container'
  22. ];
  23. $form['link_title_wrapper']['link_title'] = [
  24. '#type' => 'textfield',
  25. '#title' => 'Link title',
  26. '#default_value' => isset($config['link_title']) ? $config['link_title'] : "Ressources",
  27. '#element_validate' => array('token_element_validate'),
  28. '#token_types' => array('node'),
  29. ];
  30. $form['link_title_wrapper']['token_tree'] = array(
  31. '#theme' => 'token_tree_link',
  32. '#token_types' => array('node'),
  33. '#show_restricted' => TRUE,
  34. '#global_types' => FALSE,
  35. '#weight' => 90,
  36. );
  37. return $form;
  38. }
  39. public function blockSubmit($form, FormStateInterface $form_state)
  40. {
  41. parent::blockSubmit($form, $form_state);
  42. $values = $form_state->getValues();
  43. $link_title = $values['link_title_wrapper']['link_title'];
  44. $this->configuration['link_title'] = $link_title;
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function build() {
  50. $config = $this->getConfiguration();
  51. $build = [];
  52. $node = \Drupal::routeMatch()->getParameter('node');
  53. if ($node instanceof \Drupal\node\Entity\Node) {
  54. $nid = $node->id();
  55. // $title = $config["link_title"];
  56. $token_service = \Drupal::token();
  57. $title = $token_service->replace($config["link_title"], array('node' => $node));
  58. $url = Url::fromRoute("view.centre_de_ressources.page_1");
  59. $url->setRouteParameter("programme", $nid);
  60. $url->setOption('attributes', array("class"=>array('prog-ressources-link')));
  61. $build['prog_ressource_link'] = array(
  62. '#title' => $title,
  63. '#type' => 'link',
  64. '#url' => $url
  65. );
  66. }
  67. return $build;
  68. }
  69. }