Conditional script execution in Drupal 7 Views

We continue to pervert with different versions of Drupal and this time on the seven in the view it became necessary to execute the script through a condition with PHP.

Initially, there was the following task - in the nodes, the selection list, with a certain selected value, it was necessary to hide several buttons displayed in the custom text field in the view.

So add a global PHP field in the view

<?php 
   $node = node_load($row->nid);
   $aviable = $node->field_select_aviable['und']['0']['value'];
   if ($aviable == 'notaviable'){
      echo '
	<script>
	   (function($){
	      $(document).ready(function() {
		$(\'.tax_node_button_'.$row->nid.'\').addClass(\'hide_buttons\');
		});
	      })(jQuery);
        </script>
      ';
   }
?>

Let's look a little at what is stuffed in this crutch. First line

$node = node_load($row->nid);

we get the array of the current node by the id field - $row->nid.

In the second line, we get the set value of the node field, in our case, the value of the set list selection

$aviable = $node->field_select_aviable['und']['0']['value'];

Next comes the usual condition check. We need to hide the buttons if the field value is notaviable

if ($aviable == 'notaviable'){

And if the node has this value, we execute a script that adds another class to the block with the tax_node_button_% id-node% class - hide_buttons

$(\'.tax_node_button_'.$row->nid.'\').addClass(\'hide_buttons\');

In styles, this class can be set to display: none.

Thus, the script will be executed only for nodes with the same field value.

Also, it may come in handy, the version of the script fell off, which was looking for the hidden text of our notaviable field on the page, and if there was such a text, the required class was added to the element.

<script>
   (function($){
      $(document).ready(function() {
	var content = document.body.textContent || document.body.innerText;
	var hasText = content.indexOf("notaviable")!==-1;
	   if(hasText){
	      $('.tax_node_button').addClass('hide_buttons');
           }
	});
   })(jQuery);
</script>

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.