Is there a way to get the name of the module you are working within? I have a large set of modules (about 35) with some common functionality. Long story short is that I would like to be able to get the module name without hard-coding it in a string. Hopefully this isn't necessary, but here's an idea of what I'm trying for:
function MYMODULE_mycustom_hook($args) {
$sCurrModule = 'MYMODULE';
// Operations using $sCurrModule...
}
Essentially, I can replace 'MYMODULE' with the module name and be done with it, but I'm wondering if there is a way to get that value programmatically. I'm using Drupal 7.
This does not apply to Drupal 8.
If your module file is sites/default/modules/MYMODULE/MYMODULE.module then module name is MYMODULE.
You can get it programmatically inside MYMODULE.module file using following command:
$module_name = basename(__FILE__, '.module');
Although OP was asking regarding D7, here's the solution for Drupal 8 (D8) as well:
/** #var \Drupal\Core\Extension\ModuleHandlerInterface $module_handler */
$module_handler = \Drupal::service('module_handler');
/** #var \Drupal\Core\Extension\Extension $module_object */
$module_object = $module_handler->getModule(basename(__FILE__, '.module'));
$module_name = $module_object->getName();
Of course, you can chain these calls if necessary:
\Drupal::service('module_handler')->getModule(basename(__FILE__, '.module'))->getName()
As correctly said in comments
basename(__FILE__, '.module');
only works inside an actual .module file.
Answering to question:
inside your MYMODULE.module
function print_current_module_name() {
return basename(__FILE__, '.module');
}
from everywhere in Drupal >8
$module_name = print_current_module_name();
echo "module name is : " . $module_name
Not sure this will work on Drupal 7 as well
Related
I'm using hook_theme_suggestions_HOOK_alter() to add theme hook suggestions for page.html.twig based on the content type:
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
$node = \Drupal::request()->attributes->get('node');
$suggestions[] = 'page--node--' . $node->getType();
}
Now my twig debug mode picks this up:
<!-- FILE NAME SUGGESTIONS:
* page--node--case.html.twig (new suggestion based on content type 'case')
* page--node--3.html.twig
* page--node--%.html.twig
* page--node.html.twig
x page.html.twig
-->
However, when I make a file called page--node--case.html.twig, it is not being rendered. Instead, page.html.twig is being used.
Anyone know what's going on?
I found out what was going wrong.
Apparently, when defining new suggestions, Drupal needs underscores instead of dashes. Then Drupal converts these underscores into dashes so that the actual file name will still be page--node--case.html.twig
So:
$suggestions [] = 'page--node--'.$node->gettype();
Should be: $suggestions [] = 'page__node__'.$node->gettype();
Documentation:
https://www.drupal.org/node/2186401
I'm new to Drupal. I looked here and on google for a while before asking, but I'm sure I can't find the answer because I don't know how to ask the question.
Here is what's going on. I'm using a custom module to load certain entities and then output them in a specific format for an application to access. The problem is that the NODE BODY contains special information and media files that should be converted. My goal is to obtain the HTML output that would normally be used on this field.
// Execute an EntityFieldQuery
$result = $query->execute();
if (isset($result['node'])) {
$article_items_nids = array_keys($result['node']);
$article_items = entity_load('node', $news_items_nids);
}
// Loop through each article
foreach ($article_items as $article) {
return $article->body[LANGUAGE_NONE]['0']['value'];
}
All of this works great. The only problem is that I get things like this in the output:
[[{"type":"media","view_mode":"media_original","fid":"283","attributes":{"alt":"","class":"media-image","data-thmr":"thmr_32","height":"400","width":"580"}}]]
or
*protoss_icon*
My goal is to find a way that these items are converted just like they are when these articles are viewed normally.
I've tried doing things such as:
render(field_view_field('node', $article, 'body'));
or
render($article->body[LANGUAGE_NONE]['0']['value']);
without success. Thanks for any help, I'm learning so I don't have a complete grasp of the process drupal uses to build output.
You can try something like this (this works only with nodes not with other custom entity types):
$node = node_load($nid);
$field = field_get_items('node', $node, 'your_field_name');
$output = field_view_value('node', $node, 'your_field_name', $field[$delta]);
the field_view_value returns a renderable array for a single field value. (from drupal api documentation)
How can I use the localization mechanism in WordPress to get access to an existing but not-current language string?
Background: I have a custom theme where I use locale 'en_US' as the default locale and translate through a PO file to locale 'es_ES' (Spanish).
Let us say I use the construction
__('Introduction', 'my_domain');
in my code, and that I have translated 'Introduction' to the Spanish 'Introducción´ in my PO file. All this works fine.
Now to the problem: I want to insert n records in my database with all existing translations of the string 'Introduction' - one for each language; so, n = 2 in my example.
Ideally, I would write something like this:
$site_id = 123;
// Get an array of all defined locales: ['en_US', 'es_ES']
$locales = util::get_all_locales();
// Add one new record in table details for each locale with the translated target string
foreach ($locales as $locale) {
db::insert_details($site_id, 'intro',
__('Introduction', 'my_domain', $locale), $locale);
}
Only, that the 3rd parameter in __() above is pure fantasy on my part. You can only validly write
__('Introduction', 'my_domain');
to get either 'Introduction' or 'Introducción' depending on the current locale.
The outcome of the code above would ideally be that I end up with two records in my table:
SITE_ID CAT TEXT LOCALE
123 intro Introduction en_US
123 intro Introducción es_ES
I am aware that I want something that requires loading all the MO files, where normally, only the MO file for the current language is required. Maybe use of the WordPress function load_textdomain is necessary - I was just hoping there already exists a solution.
Expanding on the question by including the plugin PolyLang: is it possible to use Custom Strings to achieve the above functionality? E.g. conceptually:
pll_('Introduction', $locale)
Old question I know, but here goes -
Starting with a simple example where you know exactly what locales to load and exactly where the MO files are, you could use the MO loader directly:
<?php
$locales = array( 'en_US', 'es_ES' );
foreach( $locales as $tmp_locale ){
$mo = new MO;
$mofile = get_template_directory().'/languages/'.$tmp_locale.'.mo';
$mo->import_from_file( $mofile );
// get what you need directly
$translation = $mo->translate('Introduction');
}
This assumes your MO files are all under the theme. If you wanted to put more of this logic through the WordPress's environment you could, but it's a bit nasty. Example:
<?php
global $locale;
// pull list of installed language codes
$locales = get_available_languages();
$locales[] = 'en_US';
// we need to know the Text Domain and path of what we're translating
$domain = 'my_domain';
$mopath = get_template_directory() . '/languages';
// iterate over locales, finally restoring the original en_US
foreach( $locales as $switch_locale ){
// hack the global locale variable (better to use a filter though)
$locale = $switch_locale;
// critical to unload domain before loading another
unload_textdomain( $domain );
// call the domain loader - here using the specific theme utility
load_theme_textdomain( $domain, $mopath );
// Use translation functions as normal
$translation = __('Introduction', $domain );
}
This method is nastier because it hacks globals and requires restoring your original locale afterwards, but it has the advantage of using WordPress's internal logic for loading your theme's translations. That would be useful if they were in different locations, or if their locations were subject to filters.
I also used get_available_languages in this example, but note that you'll need the core language packs to be installed for this. It won't pick up Spanish in your theme unless you've also installed the core Spanish files.
I'm using sluggable behavior in my Symfony2 project, but now I would like to make many slugs for one page, based on different texts (current title, old title(s), users text from form input), and keep it in another table. And my question is - how to manually use doctrine extensions for any text? I can't find it anywhere. Perfect would be something like:
/* careful - it's not a real, working code! */
$sluggable = new DoctrineSluggable();
$slug = $sluggable->generate('My own text!');
echo $slug; // my-own-text
I found solution by accident here.
Code:
use Gedmo\Sluggable\Util as Sluggable;
$string = 'My own text!';
$slug = Sluggable\Urlizer::urlize($string, '-');
if(empty($slug)) // if $string is like '=))' or 'トライアングル・サービス' an empty slug will be returned, that causes troubles and throws no exception
echo 'error, empty slug!!!';
else
echo $slug;
Find the doctrine code for generating a slug here: l3pp4rd/DoctrineExtensions. Playing around with that class could do as you desire but you will probable need to create your own service to implement an easy use as you want. See the Service Container section of the docs for more details about services.
The Sluggable\Urlizer::urlize seems to replace ' with -.
I had to use Sluggable\Urlizer::transliterate to be closer to the SluggableListener behaviour.
I've made a view with an exposed filter. This filter is taxonomy based, and I'm using Hierarchical Select as the widget because this taxonomy is deeply nested.
This question is greatly similar to:
How to change the label of the default value (-Any-) of an exposed filter in Drupal Views?
However, the poster of that question was not using HS, and so I cannot use the answers there, specifically this one: https://stackoverflow.com/a/5975294/443219
Where exactly should I place the '#options' key in the $form array when using hook_form_alter, to make this work? I've tried pasting the relevant line of code blindly in different places throughout the array, but I believe HS works a tad different to FAPI...
I have a horrible answer to this.
I changed line 402 in sites/all/modules/hierarchical_select/hs_taxonomy_views.module from:
$any_label = variable_get('views_exposed_filter_any_label', 'old_any') === 'old_any' ? '<'. t('Any') .'>' : '- '. t('Any') .' -';
to
$any_label = variable_get('views_exposed_filter_any_label', 'old_any') === 'old_any' ? 'Worldwide' : '- '. t('Any') .' -';
This works because: in this site, I need the filter on only view - and nowhere else.
This can never be a general solution because:
The unholy sin of hacking the core of a module will haunt me forever because I cannot ever use drush to update this module again.
If I ever make another view in this site, and decide to have a hs taxonomy exposed filter, it's "Any" option will be displayed as "Worldwide", even if there is no such context: weird.
I would greatly appreciate if anyone can point me in a direction that will allow me to solve this cleanly. But I'm going with my hack for now.
You can use following code any drupal module. this will work.
/**
* hook_views_pre_view
* #param type $view
* #param type $display_id
* #param type $args
*/
function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
if ($view->name == 'VIEW_NAME') {
$filters = $view->display_handler->get_option('filters');
$view->display_handler->override_option('filters', $filters);
}
}
/**
* hook__views_pre_build
* #param type $view
* #return type
*/
function MODULE_NAME_views_pre_build($view) {
if ($view->name=='VIEW_NAME') {
$view->display['page']->handler->handlers['filter']['filter_field']->value['value'] = 8;
return $view;
}
}