drupal template.php - drupal

how should i know which variables and objects can be used directly in this file.(eg:$node,$term....) thank you.

In template.php
/**
* Override or insert PHPTemplate variables into the templates.
*/
function phptemplate_preprocess_node(&$vars) {
_vdump(get_defined_vars(), 1);
}
/**
* Override or insert PHPTemplate variables into the templates.
*/
function phptemplate_preprocess_page(&$vars) {
_vdump(get_defined_vars(), 1);
}
And add dump function to custom module
/*
* Custom dump function
*
* #param $vars
* An string or array containing the data.
* #param $keys
* If true6 function will return keys of $vars array
* #return a dump of $vars as drupal message.
*/
function _vdump($var, $keys = FALSE) {
if($keys){
drupal_set_message('<pre>' . print_r(array_keys($var), 1) . '</pre>');
}
else {
drupal_set_message('<pre>' . print_r($var, 1) . '</pre>');
}
}

I'm guessing you're talking about creating/modifying a theme. You could use most of the standard Drupal globals. You can always use get_defined_vars to see if any other variables have been defined.

There is no such variables in the template.php file.
Do you think of $node, $terms, ... that you find on page.tpl.php or node.tpl.php ?
If yes, those variables are generated in the preprocess functions.
Modules can implements those hook to define new variables that you can directly use in those file, or template.php can also define some new variables.
Please have a look in the documentation about the preprocess

Related

How to show content of a custom block using PHP code format in Drupal 8

I have added some custom code in a block using PHP code format to show that block on a specific page. I have checked all the things working fine on Devel PHP page but contents are not showing on page. The code below fetches the field value of a destination node.
$refer = $_SERVER[HTTP_REFERER];
$parsed = parse_url($refer);
$alias = array_pop($parsed);
$dst = \Drupal::service('path.alias_manager')->getPathByAlias($alias , $langcode);
$nid = array_pop(explode('/', $dst));
$dest_node = node_load($nid);
$body = $dest_node->get('body')->getValue();
print $body; //have tried other printing methods also but invain
Hope this clarifies the question.
Thanks
Are you sure that it works in Devel? I've just tried to execute your code, and this line:
$body = $dest_node->get('body')->getValue();
returns Array.
Try to use this one instead:
$body = $dest_node->body->value;
First of all, your first block of code (getting current node) can be replaced with just one line:
$node = \Drupal::service('current_route_match')->getParameter('node');
And the whole block can be changed in the following way:
if ($node = \Drupal::service('current_route_match')->getParameter('node')) {
print $node->body->value;
}
P.S. And it's definitely a bad idea to use PHP text filter. You may easily write your own custom module providing required block. The simplest block plugin requires several lines of code:
/**
* #file
* Contains \Drupal\my_module\Plugin\Block\MyBlock.
*/
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides my super block.
*
* #Block(
* id = "my_module_block",
* admin_label = #Translation("My Block"),
* category = #Translation("My Module"),
* )
*/
class MyBlock extends BlockBase{
/**
* Builds and returns the renderable array for this block plugin.
*
* #return array
* A renderable array representing the content of the block.
*
* #see \Drupal\block\BlockViewBuilder
*/
public function build() {
if ($node = \Drupal::service('current_route_match')->getParameter('node')) {
return [ '#markup' => $node->body->value ];
}
}
}
This file MyBlock.php must be placed in /src/Plugin/Block/ directory inside your custom module named my_module.

Missing file doc comment?

I used drupal coder module to check my code and always get missing file doc as an error.
I used the following file doc comment but still showing error. Can you please guide me what am i doing wrong.
Edit:
<?php
/**
* #file
* Description
*/
/**
* Implements hook_menu().
*
* Description
*
* #return array An array of menu items
*/
function hook_menu() {
//My code
}
Typical first 15 lines of a file:
<?php
/**
* #file
* Description of what this module (or file) is doing.
*/
/**
* Implements hook_help().
*/
function yourmodule_help($path, $arg) {
// or any other hook...
}
Don't forget to also comment the first function of you file with /** or else coder will believe that your #file comment is your first function's comment.

setting variable in header.php but not seen in footer.php

in wordpress ,
i set a variable in header.php
<?php
$var= 'anything'
?>
but in footer.php when I echo it
<?php
echo $var;
?>
I got no thing printed ... why !>
You're not in the same scope, as the header and footer files are included in a function's body. So you are declaring a local variable, and referring to another local variable (from another function).
So just declare your variable as global:
$GLOBALS[ 'var' ] = '...';
Then:
echo $GLOBALS[ 'var' ];
I know you've already accepted the answer to this question; however, I think there's a much better approach to the variable scope problem than passing vars into the $GLOBALS array.
Take the functions.php file in your theme for example. This file is included outside the scope of the get_header() and get_footer() functions. In fact it supersedes anything else you might be doing in your theme (and I believe in the plugin scope as well--though I'd have to check that.)
If you want to set a variable that you'd like to use in your header/footer files, you should do it in your functions.php file rather than polluting $GLOBALS array. If you have more variables that you want to sure, consider using a basic Registry object with getters/setters. This way your variables will be better encapsulated in a scope you can control.
Registry
Here's a sample Registry class to get you started if:
<?php
/**
* Registry
*
* #author Made By Me
* #version v0.0.1
*/
class Registry
{
# +------------------------------------------------------------------------+
# MEMBERS
# +------------------------------------------------------------------------+
private $properties = array();
# +------------------------------------------------------------------------+
# ACCESSORS
# +------------------------------------------------------------------------+
/**
* #set mixed Objects
* #param string $index A unique index
* #param mixed $value Objects to be stored in the registry
* #return void
*/
public function __set($index, $value)
{
$this->properties[ $index ] = $value;
}
/**
* #get mixed Objects stored in the registry
* #param string $index A unique ID for the object
* #return object Returns a object used by the core application.
*/
public function __get($index)
{
return $this->properties[ $index ];
}
# +------------------------------------------------------------------------+
# CONSTRUCTOR
# +------------------------------------------------------------------------+
public function __construct()
{
}
}
Save this class in your theme somewhere, e.g. /classes/registry.class.php Include the file at the top of your functions.php file: include( get_template_directory() . '/classes/registry.class.php');
Example Usage
Storing variables:
$registry = new Registry();
$registry->my_variable_name = "hello world";
Retrieving variables:
echo '<h1>' . $registry->my_variable_name . '</h1>'
The registry will accept any variable type.
Note: I normally use SplObjectStorage as the internal datastore, but I've swapped it out for a regular ole array for this case.
I know this is a bit old question and with a solution voted but I though I should share another option and just found a better solution (that works) without using Globals
function fn_your_var_storage( $var = NULL )
{
static $internal;
if ( NULL !== $var )
{
$internal = $var;
}
return $internal;
}
// store the value
fn_your_var_storage( 'my_value' );
// retrieve value
echo fn_your_var_storage(); // print my_value
try this code
first define your initial variable
$var="something";
then use the $_GLOBALS
$_GLOBALS['myvar']=$var;
and finally use the global variable in anywhere you want
global $myvar;
define string inside the $_GLOBALS as taken as global variable name or use the $_GLOBALS['myvar'] direct into the code without using the global
In wordpress Header, any template, Footer is different functions so you have to declare any varible as a global variable then you can access it .
/** header.php **/
<?php
global $xyz;
$xyz="123456"; ?>
/** Template.php or Footer.php **/
<?php
echo $xyz; ///return 123456
?>

preprocess function for cck node types

(Note: I originally posted this on drupal.org before remembering that I never get a response over there. So, sorry for the cross-posting)
Hello, is there a way (built-in or otherwise) to add preprocessing functions for particular cck node types? I am looking to do some preprocessing of a field within my cck node type. Currently I can either use theme_preprocess_node and then do a switch on the $node->type or use a theming function for a particular field name (and still do a switch to make sure the current field usage is within the node type i'm looking for). What I am suggesting is to have a function like this...
theme_preprocess_mynodetype(&$vars) {
// Now I can preprocess a field without testing whether the field is within the target content type
}
...but I can't figure out if I can suggest preprocess functions the same way I can suggest template files
Thanks! Rob
See this function in content.module of cck:
/**
* Theme preprocess function for field.tpl.php.
*
* The $variables array contains the following arguments:
* - $node
* - $field
* - $items
* - $teaser
* - $page
*
* #see field.tpl.php
*
* TODO : this should live in theme/theme.inc, but then the preprocessor
* doesn't get called when the theme overrides the template. Bug in theme layer ?
*/
function content_preprocess_content_field(&$variables) {
$element = $variables['element'];
...
I think that you're looking for this post. There's no magic per-node preprocess, only per theme/template engine, but you do have access to the node type in the $vars parameter so you can switch on it there.
Hope that helps!

Is there a way (other than sql) to get the mlid for a given nid in drupal?

I've got a node, I want it's menu. As far as I can tell, node_load doesn't include it. Obviously, it's trivial to write a query to find it based on the path node/nid, but is there a Drupal Way to do it?
if the menu tree has multiple levels sql seems a better option.
a sample for drupal 7 is given bellow where path is something like 'node/x'
function _get_mlid($path, $menu_name) {
$mlid = db_select('menu_links' , 'ml')
->condition('ml.link_path' , $path)
->condition('ml.menu_name',$menu_name)
->fields('ml' , array('mlid'))
->execute()
->fetchField();
return $mlid;
}
The Menu Node module exposes an API to do this.
You can read the documentation (Doxygen) in the code. I think the functionality you need is provided by the menu_node_get_links($nid, $router = FALSE) method:
/**
* Get the relevant menu links for a node.
* #param $nid
* The node id.
* #param $router
* Boolean flag indicating whether to attach the menu router item to the $item object.
* If set to TRUE, the router will be set as $item->menu_router.
* #return
* An array of complete menu_link objects or an empy array on failure.
*/
An associative array of mlid => menu object is returned. You probably only need the first one so it might look like something like this:
$arr = menu_node_get_links(123);
list($mlid) = array_keys($arr);
Otherwise, you can try out the suggestion in a thread in the Drupal Forums:
Use node/[nid] as the $path argument for:
function _get_mlid($path) {
$mlid = null;
$tree = menu_tree_all_data('primary-links');
foreach($tree as $item) {
if ($item['link']['link_path'] == $path) {
$mlid = $item['link']['mlid'];
break;
}
}
return $mlid;
}

Resources