I create a page within my custom module with the following code:  function mymodule_menu(){     $items['product-detail'] = array(         'title' =&gt; t('Product detail'),         'page callback' =&gt; '_mymodule_product_detail',         'variables' =&gt; array('var1' =&gt; "Hello World Attempt #1"),         'type' =&gt; MENU_CALLBACK,         'access callback' =&gt; TRUE,      );   function _mymodule_product_detail(){       // global $var1 = "Hello Workd Attempt #3";       return array('variables' =&gt; array("var1" =&gt; "Hello World Attempt #2") , '#markup' =&gt; '&lt;p&gt;This is some markup content displayed correctly in the page&lt;/p&gt;');  } // function   It renders the template, sets the title and display the markup (content of the page). However, I would like to fill some variables defined in the page.tpl.php and I don't know how to send these parameters, I tried with the variables key in the code but nothing is written. I want to display the message "Hello World Attempt #?" in the place in page.tpl.php where I have the code &lt;?php if(isset($var1)) print $var1; ?&gt;  I have been able to reach my goal with the following code, but using GLOBAL, which is not adequate:  function mymodule_preprocess_page(&amp;$variables) {    global $var1; if(isset($var1) &amp;&amp; $var1 != "") $variables["var1"] = $var1;  }   The global $var1 is set to $var1 = "HELLO WORLD Attempt #3" in the _mymodule_product_detail() function above (lines commented).
121922
Unifying the questions below, I want to check if the problem and solution is correct:  Problem: I want to create a page with hook_menu from my custom module. This page will have a different template to the other pages. Some of the dynamic content of the page will be retrieved by my custom module.  Solution: the code below, with these convoluted steps:   hook_menu with callback function callback function returns empty array. Based on path, hook_preprocess_page retrieves data and send to page. theme suggestion is set, based on path.   What I don't understand is why 3. and 4. cannot be accessed directly from callback function, avoiding to guess what page we are accesing via path.  Code:  function hook_menu(){     $items['product-detail'] = array(        'page callback' =&gt; '_hook_product_detail',        'type' =&gt; MENU_CALLBACK,        'access callback' =&gt; TRUE, );  function _hook_product_detail(){    return array("#markup" =&gt; ""); } // function  function hook_preprocess_page(&amp;$variables) {    $cp = current_path();    $cp_arr = explode("/", $cp);    if($cp_arr[0] == "product-detail"){        $variables['theme_hook_suggestion'] = 'page__product_detail';        // ... get data to populate var1, used in page--product_detail.tpl.php        $variables["var1"] = $var1;    } // if   }      Questions unified:  and
7928
I wanted to add custom JavaScript code on certain nodes. I have written this code in the html.tpl.php template, but this doesn't work. (donate is the path alias for a node.) &lt;?php if(arg(0) == 'DONATE'): ?&gt;   &lt;script&gt;     (function() {       // ...     );   &lt;/script&gt; &lt;?php endif; ?&gt;
29317
I'm setting up a child theme in WordPress and I can't make add_action to be fired within functions.php.  Functions.php is called and I can run code from within. Any idea on what I'm doing wrong?  $debug_msg = "Hi there!";  function test_function() {     error_log($debug_msg, 0);  } add_action('init', 'test_function', 20);
120697
I'd like to provide template implementation in my module and allow themes to override it. Basically, I add a suggestion by this simplified code:  function attach_preprocess_node(&amp;$vars) {   $vars['theme_hook_suggestions'][] = 'node__test'; }   (I don't want to use hook_theme to add a new theme because I want to reuse preprocess node functions. The theme name are awkward but I don't want to write node_attach_% to avoid confusion with node type.)  Then I use hook_theme_registry_alter() to add module path:  function attach_theme_registry_alter(&amp;$theme_registry) {   $path = drupal_get_path('module', 'attach') . '/themes';   $theme_registry_copy = $theme_registry;   _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'node', drupal_get_path('module', 'node'));   $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);   if (!isset($theme_registry['node']['theme paths'])) {     $theme_registry['node']['theme paths'] = array();   }   if (!isset($theme_registry['node']['theme paths'])) {     $first_element = array_shift($theme_registry['node']['theme paths']);     if ($first_element) {       array_unshift($theme_registry['node']['theme paths'], $first_element, $path);     }     else {       array_unshift($theme_registry['node']['theme paths'], $path);     }   } }   However it does not work. That means: the file themes/node--super.tpl.php is not used. It is used only if I copied it to the theme folder.
87273
I have a PHP file that does some task in consistent intervals.   I have placed that PHP file inside a custom module folder, but I found that Drupal functions like drupal_set_message() are not available inside the PHP file.   How do I include Drupal functions inside this PHP file? How do I set up this php file to be run as a cron job?
5401
I'm trying to define a custom template file for a specific node, using the node ID. I read a lot of topics saying to create a node--X.tpl.php file in the templates folder.  That's what I did; unfortunately, even after flushing the theme cache many times, nothing changes.  Is there anything more I have to do?  I am using Drupal 7.
1728
I created a custom module, It generate a custom Form in a page. When I submit my form, I create a new node. So, I am redirect to the form page but I would like be redirect to the new node page.  I add this line at the end of my submitForm function :   $form_state-&gt;setRedirect('node/'.$mynewnode-&gt;id());   But when I submit my form from the website, I get the empty-white-screen-of-the-death. My apache log :   ... Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "node/153" does not exist. ...   And then, when I go manually to the node/153 page, there isn't any problem. The page work well.   My question : where is my mistake ? How can I set the redirection after create the new node ? Is it possible from the submitForm function ?
112689
I'm trying to add an "add more" field to a form in my custom module. I've been looking at the examples module, with no luck.   Here's what I have so far:  $form['#tree'] = TRUE;   $form['names_fieldset'] = array(   '#type' =&gt; 'fieldset',   '#title' =&gt; t('People coming to the picnic'),   // Set up the wrapper so that AJAX will be able to replace the fieldset.   '#prefix' =&gt; '&lt;div id="names-fieldset-wrapper"&gt;',   '#suffix' =&gt; '&lt;/div&gt;', );  if (empty($form_state['num_names'])) {   $form_state['num_names'] = 1; }  for ($i = 0; $i &lt; $form_state['num_names']; $i++) {   $form['names_fieldset']['name'][$i] = array(     '#type' =&gt; 'textfield',     '#title' =&gt; t('Name'),   ); }  $form['names_fieldset']['add_name'] = array(   '#type' =&gt; 'submit',   '#value' =&gt; t('Add one more'),   '#submit' =&gt; array('spower_add_more_add_one'),   // See the examples in ajax_example.module for more details on the   // properties of #ajax.   '#ajax' =&gt; array(     'callback' =&gt; 'spower_add_more_callback',     'wrapper' =&gt; 'names-fieldset-wrapper',   ), );  if ($form_state['num_names'] &gt; 1) {   $form['names_fieldset']['remove_name'] = array(     '#type' =&gt; 'submit',     '#value' =&gt; t('Remove one'),     '#submit' =&gt; array('spower_add_more_remove_one'),     '#ajax' =&gt; array(       'callback' =&gt; 'spower_add_more_callback',       'wrapper' =&gt; 'names-fieldset-wrapper',     ),   ); }     function spower_theme($existing, $type, $theme, $path) {   $base = array(     'render element' =&gt; 'form',   );    return array(     'spower_my_form' =&gt; $base + array(       'template' =&gt; 'spower',     ),   ); }  function spower_add_more_callback($form, $form_state) {   return $form['names_fieldset']; }  /**  * Submit handler for the "add-one-more" button.  *  * Increments the max counter and causes a rebuild.  */ function spower_add_more_add_one($form, &amp;$form_state) {   $form_state['num_names']++;   $form_state['rebuild'] = TRUE; }  /**  * Submit handler for the "remove one" button.  *  * Decrements the max counter and causes a form rebuild.  */ function spower_add_more_remove_one($form, &amp;$form_state) {   if ($form_state['num_names'] &gt; 1) {     $form_state['num_names']--;   }   $form_state['rebuild'] = TRUE; }   The problem is that when I click "add more", the entire form is submitted.   If the above isn't clear, I've added the module at  and the spower_elements.inc at .  Thanks for the help.
50648
In my current project I need to alter node templates depending on previously visited landing page. My idea is that, when a visitor visits one of these landing pages, a cookie will be set, and subsequent node templates will be altered depending on that cookie.  I've got three view pages serving as entry points for my visitors: myproject.com/tv myproject.com/mobile myproject.com/infopoint    In theme preprocess I'm checking/setting a cookie and assigning a template variable. The Twig templates do minor modifications depending on that variable:  function MYTHEME_preprocess(array &amp;$variables, $hook) {   $router = \Drupal::routeMatch();    if ($route = $router-&gt;getRouteObject()) {     $view_id = $route-&gt;getDefault('view_id');     $display_id = $route-&gt;getDefault('display_id');     $view_display_plugin = $route-&gt;getOption('_view_display_plugin_id');      if ($view_id &amp;&amp; $view_display_plugin === 'page') {       if ($view_id == 'slide') {         user_cookie_save(['device' =&gt; 'tv']);         $variables['MYTHEME']['device'] = 'tv';       }       elseif ($view_id == 'tile' &amp;&amp; $display_id == 'mobile') {         user_cookie_save(['device' =&gt; 'mobile']);         $variables['MYTHEME']['device'] = 'mobile';       }       elseif ($view_id == 'tile' &amp;&amp; $display_id == 'infopoint') {         user_cookie_save(['device' =&gt; 'infopoint']);         $variables['MYTHEME']['device'] = 'infopoint';       }     }   }    // user_cookie_save prefixes all cookie names with 'Drupal.visitor.'   if (isset($_COOKIE['Drupal.visitor.device']) &amp;&amp;      in_array($_COOKIE['Drupal.visitor.device'], ['tv', 'mobile', 'infopoint'])) {          // I'm doing design modifications in my Twig templates depending on this variable         $variables['MYTHEME']['device'] = $_COOKIE['Drupal.visitor.device'];     }   } }   In services.yml I've activated the cookies cache context  parameters:   renderer.config:     required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'url.site', 'cookies:Drupal.visitor.device']   In my Twig templates I've got multiple code pieces like this:  {% if MYTHEME.device == 'tv' %}    &lt;!-- code here --&gt; {% else %}    &lt;!-- other design here --&gt; {% endif %}   Sadly the code doesn't really work. On the entry pages, the device theme variable is always correct, but the cookie is not updated (seems as if only first uncached hit sets the cookie. I even have the weird situation that cookie and twig variable aren't equal.). On node templates the theme variable isn't set correctly at all.  Any ideas how to get the code above working?  PS: Due slow views with geo-distance calculations disabling cache is not an option, I need to provide cached pages also for anonymous users.
48996
I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...  &lt;html&gt;     &lt;head&gt;     &lt;/head&gt;     &lt;body&gt;         &lt;pre style="word-wrap: break-word; white-space: pre-wrap;"&gt; {json here}&lt;/pre&gt;     &lt;/body&gt; &lt;/html&gt;   I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...  &lt;?php  /**  * Implementation of hook_menu()  */ function content_relation_menu() {     $items = array();     $items['api'] = array(         'title' =&gt; 'Search',         'page callback' =&gt; 'content_relation_get',         'access callback' =&gt; TRUE,         'type' =&gt; MENU_CALLBACK,     );      return $items; }  function content_relation_get($term = '') {     drupal_add_http_header('Content-Type', 'application/javascript; utf-8');     $var = json_encode(         db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" =&gt; $term.'%'))-&gt;fetchAll()     );     echo $var;     exit(0); }   How can I return JUST raw JSON?
98071
I have a view page that requires a dynamic page title. It is a simple substitution of the label field.  If I use {{ label }} it works fine for the title displayed on the page, but it doesn't substitute the label for the actual page title (in meta)  I was able to fix this by using hook_views_post_render using the following code  // Set the route title. $route = \Drupal::routeMatch()-&gt;getCurrentRouteMatch()-&gt;getRouteObject(); $route-&gt;setDefault('_title', $title);  $view-&gt;setTitle($title);   However, the title only works if the page is not cached. For the cached pages, the page title is missing. This feels like a bug in drupal, but I am hoping that there is a simple way to get this done.
23786
I'm trying to define a static variable for use in my custom module. I want it to let me pass a number from function to function. I'm using drupal_static() but I can't get it to work. How do I do this?  This is the code I'm using to define my static variable.  $var = &amp;drupal_static(__FUNCTION__); if (!isset($var)) {   // generate contents of static variable   $var = '8'; } return $var;   I've tried putting it in a custom module.    function viewusercontact_locateuser($value, $key, &amp;$counter) {    global $user;     /**********In here***********/     if ($value['uid'] == $user-&gt;uid) {       ........    } }   I can't seem to get it to work. What am I doing wrong?  (I got my code from the following guides)
48930
I read about Drupal behaviors today, and I tried writing the following code.  (function ($) {    Drupal.behaviors.mymodule = {     attach: function (context, settings) {       $('#mymodule_id', context).change(function () {         alert('Handler for .change() called.');       });     }   };  }(jQuery));    Is Drupal.behaviors.mymodule the namespace? What are the context and settings parameters passed to the Drupal behavior? Is this the equivalent of document.ready()?   Can I attach any number of functions?  Can I define JavaScript functions which will be called somewhere?
101680
If I want to show the current node title in page.html.twig (by default it seems to only be available in node.html.twig) I have to create a preprocess function like so:  function theme_preprocess_page(&amp;$variables, $hook) {   // Set our page title so we can access it in page.html.twig   if ($node = \Drupal::routeMatch()-&gt;getParameter('node')) {     $variables['my_node_title'] = $node-&gt;title-&gt;value;   } }   And then I have to overwrite page-title.html.twig by copying it into my current theme folder and commenting out everything.  This doesn't seem "right".  Is there a better way?
89533
I need Drupal to use a custom page template if the URL contains a particular _GET parameter.  In D7 I would do something like this in the theme's template.php:  function mytheme_preprocess_page(&amp;$variables) {       if($_GET['isCustomTpl'] == true)         $variables['theme_hook_suggestions'][] =  'page__myCustomTpl'; }   It doesn't work in D8 though (I would have been surprised by the opposite, considering all the architectural changes in the theme layer).  Any ideas?  Bonus question: is it possible to define such a function in a module, so that i can release it publicly without having the users to edit their themes?
98458
I am trying to write a batch. And I have a problem that none of the batch operations callback functions are getting called.  I wrote drupal_set_message at the start of each callback and none of the messages are displayed.  I can get the batch page, but the callback ops aren't called at all.  Here's the code I used:  function mymdoule_node_batch() {     $batch = array(         'title'         =&gt; t("Migrating"),         'operations'    =&gt; array(             array('mycallback_001'),             array('mycallback_002'),         ),         'finished'      =&gt; 'mycallback_finished',         'init_message'  =&gt; t('Initializing...'),         'error_message' =&gt; t('An error occurred.'),     );      batch_set($batch);     drupal_set_message("step: 0"); // this is the only message the system returns }   function mycallback_001(&amp;$context) {     drupal_set_message("step: 1");     $nids = db_select("node", "n")             -&gt;fields("n", array("nid"))             -&gt;orderBy("nid", "ASC")             -&gt;execute()             -&gt;fetchCol(); }  function mycallback_002(&amp;$context) {     drupal_set_message("step: 2");     $nids = db_select("node", "n")             -&gt;fields("n", array("nid"))             -&gt;orderBy("nid", "ASC")             -&gt;execute()             -&gt;fetchCol(); }   P.s. The batch is getting called in form submission.  What's wrong in that?
81854
When I define an object of a class using new like this  $blah = new Whatever();   I get autocomplete for $blah. But how do I do it when I have $blah as a function parameter? Without autocomplete I am incomplete.  Edit: How do I do it if it's in an include and PDT or Netbeans can't figure it out? Is there any way to declare types for variables in PHP?