0

I am not able to add custom class in custom module, I need to add class "ajax-link" in the anchor link to make it ajax based page load .

function hook_node_view(array &$build, \Drupal\node\Entity\Node 
$node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, 
 $view_mode) {

 if ($display->getComponent('prevnext_next')) {
$build['prevnext_next'] = [
  '#theme' => 'prevnext',
  '#direction' => 'next',
  '#text' => t('Next'),
  '#nid' => $previous_next['next'],
  '#attributes' => array(
  'class' => array(
  'ajax-link' 
      ),
    ),
  '#url' => Url::fromUserInput('/node/' . $previous_next['next']."?an=left")->toString(),
  '#void' => empty($previous_next['next']),
];
 }
   }

What am I doing wrong in the code ?

I want to create link something like this:

<a class="ajax-link" href="node/nid?an=left">Next</a>
  • 1
    What does your prevnext theme / template code look like? – CG Monroe Aug 21 '18 at 13:09
  • theme_prevnext isn't making use of #attributes, it's pretty much that simple – Clive Aug 21 '18 at 13:35
  • I am not getting you @clive , so what should i use instead of #attributes to add class. – user84266 Aug 21 '18 at 13:40
  • 1
    What @Clive means is that theme function doesn't use an "attributes" variable so putting that key in there has no effect. If all you want is an A tag you could use a #type link instead. See. drupal.stackexchange.com/a/187780/13727 – Alfred Armstrong Aug 21 '18 at 15:08
0

you can try code :

  $url = Url::fromRoute('entity.node.canonical', ['node' => $previous_next['next'],'an'=>'left']);
  $url->setOptions([
      'attributes' => [
          'class' => ['ajax-link custom-class']
      ],
  ]);

  $build['prevnext_next'] = [
      '#type' => 'link',
      '#title' => t('Next'),
      '#url' =>  $url,
  ];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.