Drupal : Create variable from custom .module to custom .tpl.php - php

I create a custom module and I want use the complete_url of my future website in the template who used/created by my module.
I tried several ways and searched Google but I don't find a solution.
However this issue seems very simply, that became me crazy x)
So, I must create a variable in my .module and add her when I return the array in the main_socialtag_theme function. Where/How can I do that ?
My .module:
function main_socialtag_block_info(){
$block['main_socialtag']=array(
'info' => t('Main socialtag'),
'cache' => DRUPAL_NO_CACHE,
);
return $block;
}
function main_socialtag_theme(){
return array(
'main_socialtag_block' => array(
'template' => 'theme/main_socialtag_block',
'variables' => array(),
),
);
}
function main_socialtag_block_view($delta=''){
if ($delta == 'main_socialtag'){
return array(
'subject' => '',
'content' => array(
'#theme' => 'main_socialtag_block',
)
);
}
}
Thanks for help, and sorry for my bad english writing !

If you are looking for a way to add, modify and call variables. Check variable_get and variable_set.
To add or modify a variable value:
variable_set("my_variable_name", "value");
To retrieve the value:
$myVal = variable_get("my_variable_name", "");
For hook_theme Implementation, kindly check this question.

Related

DRUPAL-7: hook declaration missing

Goodmorning everyone,
I'm new in Drupal.
I hope don't ask a stupid question.
I'm working with Drupal 7 and I need to edit a custom module for my company developed by another developer.
This is a piece of code where I use "theme" function.
This code is under "sites/all/modules/gestione_attivita_attivita/gestione_attivita_attivita.module"
function gestione_attivita_attivita_block_search_attivita($tipo_ricerca) {
$block['subject'] = "";
$ricerca = gestione_attivita_ricerca_fetchAll($tipo_ricerca);
$block['content'] = theme('ricerca_attivita', array(
'items' => $ricerca,
'tipo_ricerca' => $tipo_ricerca
));
return $block;
}
I know that should exist "ricerca_attivita" hook declared somehere in my files.
I'v been looking for something like "['ricerca_attivita'] = array(" or similar words or sub-words in all my files of my site folder but it doesn't exist.
The only thing I know is that under :"sites/all/themes/customModuleOfmyCompany/templates" there are several tpl files and in particular one called "ricerca_attivita.tpl.php" that work and receives data from theme function but I don't know how this is possible.
I don't know who tell to theme call to go on another folder on another path and use "ricerca_attivita.tpl.php" and not foo.tpl.php for example.
Is there anyone that can help me?
Another thing:
Going under includes/theme.inc and debugginng it I have this printing hook info:
array (
'template' => 'ricerca_attivita',
'path' => 'sites/all/themes/customtheme/templates',
'type' => 'theme_engine',
'theme path' => 'sites/all/themes/customtheme',
'preprocess functions' =>
array (
0 => 'template_preprocess',
1 => 'contextual_preprocess',
),
'process functions' =>
array (
0 => 'template_process',
1 => 'ctools_process',
2 => 'rdf_process',
),
)
but I don't know who is that declare it
I think you should use the developer module for themers https://www.drupal.org/project/devel_themer
And about theming function, did you search for this function inside the themes folder?
Hope that helps.

How to output html from content array property?

I'm new to theming and I just inherited this code. I need to control where and how to print #output but it's always showing up at the top of the page, above the HTML tags. I looked at the renderable arrays API but I couldn't find anything specific to my problem.
In mytheme.module:
function mytheme_output_block() {
$content = array(
'#theme' => 'my_theme',
'#output' => function_that_returns_JSON();
...
function mytheme_hook_theme() {
return array(
'my_theme' => array(
'vars' => array(
'output' => '',
...
And in my_theme.tpl.php I tried:
<?php print $output; ?>
But it gets ignored. How do I control #output so I can style it?
not super sure but you might need to call the array element directly. Something like:
$theme = mytheme_hook_theme();
echo $theme['output'];
Hope it helps
Which Drupal you use? I assume D7.
Take a look at the documentation of hook_theme: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_theme/7.x
It's not vars - it's variables
You have missed the template key in your implementation
template: If specified, this theme implementation is a template, and this is the template file without an extension. Do not put .tpl.php on this file; that extension will be added automatically by the default rendering engine (which is PHPTemplate). If 'path', above, is specified, the template should also be in this path.
So what your hook should look like:
function mytheme_hook_theme() {
return array(
'my_theme' => array(
'variables' => array(
'output' => '',
),
'template' => 'my-theme',
...
Remember to clear the caches afterwards.

How to extend Parsedown to add a class to table tags

I want to write an extension for Parsedown so that I can add a default class to each of the table tags. I've found that I can successfully hack the source code by adding lines to assign attributes in the blockTable function (around line 870):
$Block = array(
'alignments' => $alignments,
'identified' => true,
'element' => array(
'name' => 'table',
'handler' => 'elements',
'attributes' => array(
'class' => 'table',
),
),
);
However, if I try to loosely follow the Change Element Markup extension tutorial I am unsuccessful (perhaps because the table parsing may be an iterative process and the example in the tutorial is a simple string replacement.)
I've tried:
class Extension extends Parsedown
{
protected function blockTable($Line, array $Block = null)
{
$Block = parent::blockTable($Line, array $Block = null);
$Block['table']['attributes']['class'] = 'table';
return $Block;
}
}
but that doesn't work.
I'm not too sure what's wrong with your code, as your code matches mine. I simply added
'attributes' => array(
'class' => 'table table-responsive'
),
to identifyTable, on line 850 so that it became
$Block = array(
'alignments' => $alignments,
'identified' => true,
'element' => array(
'name' => 'table',
'handler' => 'elements',
'attributes' => array(
'class' => 'table table-responsive',
),
),
);
which works just fine for me. But that appears to be the same for you, minus table-responsive.
What version are you using?
I know this is a very old question asked 5 years, 3 month ago, but I came across this answer on a google search, so thought it was worthwhile answering with the code which outputs table class.
class Extension extends Parsedown {
protected function blockTable($Line, ?array $Block = null)
{
$Block = parent::blockTable($Line, $Block);
if(is_null($Block)){ return; }
$Block['element']['attributes']['class'] = 'table table-responsive';
return $Block;
}
I encountered exactly the same problem with the symfony demo application.
Finally it turned out that it wasn't parsedown, because the output was cleaned up by the html-sanitizer.
Allowing the class attribute for tables solved the issue.
For symfony 4 demo app add to config/packages/html_sanitizer.yaml:
html_sanitizer:
#[...]
sanitizers:
default:
# [...]
tags:
table:
allowed_attributes:
- "class"

Dynamic function name in php

I would like to simplify the creation of "Custom Post Types" in WordPress as it is tedious to go through the same script and change all the custom post type name instances manually over and over.
It's quite simple to achieve by creating a variable containing the CPT name and use it everywhere it is needed. This way, All I have to do is declare the variable in the beginning of the script and that should take care of the rest.
The only issue is that, to make it work, I also need to prefix the CPT name in front of every function inside the script and it seems that using a variable in a function name is not easy or even recommended in PHP.
So how could I solve this?
Here is an example below to make it clear:
$prefix = 'news';
function news_custom_type_init()
{
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
add_action('init', $prefix.'_custom_type_init');
This is almost fine and could be standardized if only I could dynamically rename the function in order not to have to write the word "news" in front of it but use the "$prefix" instead.
This could have been nice but just doesn't work:
$prefix = 'news';
$functionName= $prefix."_custom_type_init";
function $functionName()
{
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
add_action('init', $prefix.'_custom_type_init');
Having to name manually the function kinda defeat the original purpose of my attempt (especially when the script embeds dozens of functions like this one).
What would be the best way to do this?
PS: I googled and "stackoverflowed" a lot about this but didn't find any working solution that fit my needs and doesn't generate a WordPress error message.
Thank you.
Simple enough, here's a similar snipped form a project:
$function = $prefix . '_custom_type_init';
if(function_exists($function)) {
$function();
}
This is an old thread but simply use anonymous functions:
add_action('init', function() use($args) {
//...
});
Then there is no need to declare so many functions.
Edit (2017-04): Anonymous functions (properly implemented) are the way to go, see answer by David Vielhuber.
This answer is ill advised, as is any approach that involves code as a string, because this invites (among other things) concatenation.
Im not sure if it is advisable to use, or if it helps you, but php allows you to create "anonymous" functions :
function generateFunction ($prefix) {
$funcname = create_function(
'/* comma separated args here */',
'/* insert code as string here, using $prefix as you please */'
);
return $funcname;
}
$func= generateFunction ("news_custom_type_init");
$func(); // runs generated function
I am assuming add_action just calls whatever function you passed.
http://php.net/manual/en/function.create-function.php
Note: create_function will not return a function with the name you want, but the contents of the function will be under your control, and the real name of the function is not important.
I think you could use
runkit_function_add
http://php.net/manual/pl/function.runkit-function-add.php
One other available method is to use eval()
This post is old, but PHP 7 may solve this question.
Try:
$prefix = 'news';
$functionName = $prefix . "_custom_type_init";
${$functionName} = function() use ($prefix) {
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add'
)
);
register_taxonomy_for_object_type( 'category', $prefix );
};
add_action('init', '$' . $functionName);
I think it should work for WordPress.
You can use string in brackets
("function_name_{$dynamic_var}")()
I'm not sure any of the above actually answer the question about dynamically creating custom post types. This works for me though:
$languages = ("English", "Spanish", "French");
foreach($languages as $language):
$example = function () use ($language) {
$labels = array(
'name' => __( $language . ' Posts' ),
'singular_name' => __( $language . ' Post' )
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
"rewrite" => array( "slug" => $language . "_posts", "with_front" => true ),
'capability_type' => 'page',
);
register_post_type( $language . "_posts", $args );
};
add_action( 'init', $example, 0 );
endforeach;
Dynamic function named in PHP as variable functions
https://www.php.net/manual/en/functions.variable-functions.php
as example
$functionName = function () {
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
you can call it by typing $functionName()
I was also looking for a way to do this, as I wanted to create a function that could make aliases for functions, just like in ruby. e.g.
function an_insanely_long_function_name($a, $b) {
// do something with $a and $b
}
// I'll go insane if I have to type that stupidly long function name every time 😵
// Aliases to the rescue :)
define_alias('shrt_nm', 'an_insanely_long_function_name');
shrt_nm('a', 'b');
I did quite a lot of research — for like 2 mins :p — and found nothing that could help me achieve that functionality.
I was about to give up and do it all manually, but then I remembered good old "eval", my long time buddy :).
Here's what you need to do:
function define_alias($alias, $function) {
if (function_exists($alias))
throw new \Exception('A function named ' . $alias . ' already exists!');
// create the function
eval("function $alias(...\$args) { $function(...\$args); }")
}
eval() is the simpliest method
https://www.php.net/manual/en/function.eval.php
$name='new_func';
$var = eval($name."();");
function new_func(){echo "It work";}

Drupal 7 Form API - Custom Select Theme

I have been searching all day but unable to find any answers - I am sure I am doing it right as worked fine in Drupal 6 and should work fine in Drupal 7.
I want to give a custom theme function to my select element in my form
$form['field_name'] = array(
'#type' => 'select',
'#title' => t('Title Here'),
'#theme' => 'custom_select',
'#options' => $values,
);
I have the theme hook right to declare the new custom theme function but my problem is when using that custom theme function as above I get an empty $variables array which just reads
Array([element] => null)
can anyone see what I may be doing wrong? cleared cache, done everything I can think of - any ideas why Drupal is not passing the element data to the theme function? thanks
well finally figured this one out incase any one else has the problem - make sure you set render element in hook_theme and not variables!
before
function hook_theme(){
return array(
'select_currency' => array(
'variables' => array('element' => null),
'file' => 'module_name.theme.inc',
));
}
after
function hook_theme(){
return array(
'select_currency' => array(
'render element' => 'element',
'file' => 'module_name.theme.inc',
));
}
I was pulling my hair out until I remembered the render element!

Categories