How to prevent a site from ever using experimental core modules? Quote from Experimental modules in Drupal 8:

  Drupal 8 core introduces the concept of experimental modules. These are modules that are provided with Drupal core for testing purposes, but that are not yet fully supported. Experimental modules are included in the Core (Experimental) package on the Extend page of a Drupal site (/admin/modules).

I do understand what "testing purposes" means, and I'm aware of best practices like having a Dev / Staging / QA / Prod configuration.

But when using Drupal 8 in a Prod environment, I'm looking for a way to ensure to a site owner something like "You can be 100% that there is no way that any of these experimental modules can ever be enabled in the prod version of your site.". Imagine it's about a business critical Drupal site where "testing in production" is not ever allowed.

So what options do I have in Drupal, apart from hacking core (which is not an option), to be 100% sure of this? And so that:

It applies for "everybody" (any user), so even user/1 should not be able to do so if (s)he'd be tempted to do so.
It doesn't matter if you're using the Admin UI, Drush, Console or anything similar

Update

There are some D8 core issues about these experimental modules, which IMO are either related, or contains some inspiring comments for finding a possible solution (work around?):

Remove experimental modules from core (or treat them like first class modules).
[meta] No definition of "Experimental" & not nearly enough warning, with proposed solutions detailed in these related issues:

Experimental modules should have their own version numbers.
Use a confirmation form when enabling experimental modules.
Provide a link to the experimental module policy in the status report warning.
Warn about experimental modules on their help pages.

This is by far not as black and white as you make it in regards to experimental modules.

First, on a mission critical production site, you don't want to do anything directly on production. Completely irrelevant then if it's an experimental module or not. Any configuration change or module should be tested first. There are modules to enforce a read only configuration system for example, that's one way to approach that. One example is Configuration Read-only mode, note that I have no personal experience with it.

Second, there are experimental modules and there are experimental modules. The first experimental module apart from migrate, wich is a special case anyway, was big_pipe. Which is now officially stable in 8.3. It is a module that has zero data, zero API, zero configuration, zero UI. You just enabled it and it does its thing. As such, it was perfectly fine to use it on production already and people have been doing that, myself included. After testing it first, like any other module/functionality. If you found a bug, you could disable it from one minute to the other, without loosing any data or critical functionality.

On the other side of that spectrum is content_moderation and anything around that. Once you start using it, it is a critical and central part of your content creation workflow, and getting rid of it again is much harder. We specifically made it so you could uninstall it, and your content that was published was still published and same for unpublished. But your workflows and metadata around that would be gone. Also upgrading is likely going to be tough from 8.2 to 8.3. That's also why we're working hard to get media_entity into core as a non-experimental module, so people have a stable API and data storage that they can rely on.

Third, the concept of experimental modules is pretty new and there's a bunch of modules in core that we would have made experimental if we could have back when they were added. rest.module and the related modules is one example there.

And last, lots of contrib modules are at least as experimental as experimental core modules, they just don't warn you about that in such an obvious way. Especially development/pre-beta versions. They just don't warn you about themself in such an obvious way.

To summarize, as with many other things, you need to do your research about an experimental module before using it, and for example check if it's big_pipe-like or content_moderation-like. And then decide what that means for your site.


Calling Jquery function from link onClick attribute I'm trying to call a jQuery function from a link's onClick attribute but I get the following error: Uncaught TypeError: Drupal.behaviors.main.test is not a function.

I created a simple module that will create a block displaying a list of events. The block template will output the following HTML code:

Event1

Event2

Each link has a onClick attribute calling Drupal.behaviors.main.test($id).

On my theme's info file, I include a test.js file with the following code:

(function ($) {
    Drupal.behaviors.main = {

        attach: function(context, settings) {

            $(function test() {
                console.log('yo')
            });

            $('#home').slick({
             //init slick
            });

       }
    }
})(jQuery);

When the document is ready, slick plugin is well initialized and test() is called so I get 'yo' on the console. It's when I click the links that I get the error, so I'm thinking about a scope problem since the function is called from a module but is defined on my theme.
Does anyone have any idea?

Thanks in advance!

--EDIT--
Thank to rémy, I managed to resolve my issue, here's what I did:
My block outputs the following HTML:

        Event1

        Event2

And on my test.js file:

(function ($) {
    Drupal.behaviors.main = {

        attach: function(context, settings) {

            $('.whatever').click(function() {
              console.log(this.id);
            });

            $('#home').slick({
             //init slick
            });

       }
    }
})(jQuery);

use an id on your anchors, no onclick:

Event2

then use the click event on it in the behavoir:

(function ($) {
    Drupal.behaviors.someClicks = {
        attach: function(context, settings) {
            $('#whatever').click(function() {
               console.log('vamoooh');
            });
       }
    }
})(jQuery);


Views math expression or Computed field to find date difference in views I have two content type, Bill (Type1) and Cash Receipts (Type2), Type2 referencing Type1 when cash is received.

In Type1 I have date field called (Bill Issue date), and Type2 I have date field cash receipt date.

So I want to calculate, different between those two dates. I was trying by creating views with two date (by entity reference relationship), then subtract two filed with math expression field, but it return zero.

Actually, I have no idea whether I was wrong or Its not possible to calculate different between dates with views math expression field?

I think, it can be done with Computed Field, I did one within same content type, but I don’t know how to access a field from different content type, please help.

Code that I was used to calculate date for same content type, but how I can access a field from other content type?

If the Machine name of your date-field is 'field_example_date', then the Computed Code (PHP) would be

$startdate = $entity->field_example_date['und'][0]['value']; // Value of start-date
$enddate = $entity->field_example_date['und'][0]['value2']; // Value of end-date

$datediff = strtotime($enddate) - strtotime($startdate);
/* The PHP Function STRTOTIME parses the english textual datetime description
 * into a Unix timestamp
 */

$num_leaves = $datediff/(60*60*24);
/* Since we need the number of days IN-BETWEEN,
 * we divide the resultant difference by 60*60*24 .
 *
 * Incase of counting no.of days "FROM" to "TO" days, add 1 to the above result.
 * $num_leaves = $datediff/(60*60*24) + 1;
 */

 $entity_field[0]['value'] = $num_leaves;

The Display Code (PHP) will have

$display_output = $entity_field_item['value'];

You can achieve this use a template file, since you can use PHP inside templates in Drupal 7

In your view

Now, add both of your date fields and do this to each of them

In your web directory, go to /sites/all/themes/[yourtheme]/templates folder

Create a file named views-view-fields--[view-name]--[machine-name].tpl.php

EX: views-view-fields--hello-world--block-1.tpl.php

Inside the template file put:

<?php

$date1 = new DateTime('$fields["field_invoice_issue_date"]->content');
$date2 = new DateTime('$fields["field_payment_receipt_date"]->content');
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

?>

Remember to flush/clear the cache to see changes.


Should I replace Magento with Drupal for my e-commerce solution? I am working on an e-commerce project. Essentially, it's a 'expansive product catalog -> shop cart; users database' type of thing. Everything is still in development environment. I am trying out Magento, I have mixed feelings about it. It is plug-n-play powerful, it seems to suit a lot of situations out of the box. However, now that I am getting to know it better, I see that I will have to get my hands dirty and code, customize, add features of my own, concerning website visual and non-visual design.

Is Drupal easier to work with for a developer/designer? How can product catalog importing/exporting be handled in Drupal? With Magento, I use Magmi and csv, which I love. I will definitely be implementing some kind of automated catalog updating, which I was planning to do with Magmi; that is very important to me.

In general, could you advise on your experiences on Drupal v. Magento for e-commerce?

Edit:

Conclusion:

I will be switching to Drupal, because I have found that even though Magento has many mature built in features, I only need a select few of them, and I have too little control over them, it feels like it is cluttered and rigid in my situation. I need something that is more friendly to 'going under the hood', and I think Drupal is it. I think if I was a better programmer, I could get Magento to suit my needs, but I'm afraid I'm not. Goodbye, Magento.

Having never used Magento, I'd say go with Drupal + Drupal Commerce ;-)

Check out the following articles though:

Magento vs Drupal Commerce
E-Commerce: Which CMS is better for e-commerce? Magento vs. Drupal? Others? (Quora)
Drupal Vs. Magento (eHow)
Magento vs Drupal Commerce (drupal.org)
Google ;-)

Drupal will allow you to import products with a combination of Feeds and Commerce Feeds or Commerce Migrate (the latter requiring a bit more work).

I think at the end of the day it comes down to your personal needs.  If you don't need a fully functional CMS (or CMF...make your own mind up), then better the devil you know; might as well go with Magento.

If you want a whole integrated solution, then Drupal is clearly the winner.  I'm pretty sure there are a couple of dev houses around where I am who are migrating sites from Magento to Drupal Commerce, but I've not heard of anyone doing it the other way around.

Lastly, depending on the complexity of your project you may have to get your hands dirty with Drupal too, but it's not that hard :).


7 - Sorting a Views exposed filter options alphabetically I have a custom module which uses hook_form_views_exposed_form_alter() to sort the options of a select list into alphabetical order.

This appears to work because dmp($form) shows $form['field_keywords_tid']['#options'] to be in alphabetical order, but when checking the select list the order is different.

You can see the view and the dpm() output on the dev site.

My code so far is:

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

    foreach ($form_state['view']->filter as $field => $filter) {
        if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
            $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
            asort($form[$field_id]['#options']);
        }
    }
    dpm($form);
  }
}

I thought I needed to replace $form['filter-field_keywords_tid']['#options'] with the sorted array so I tried the following code after the foreach above, but this didn't work either.

$options = array('All' => '- Any -');
  foreach ($form[$field_id]['#options'] as $key => $val) {
      $options[$key] = $val;
  }
  $form['field_keywords_tid']['#options'] = $options;

I also tried the code below found in this Drupal Answers post with the same result. dpm() output sorted but select list not.

foreach($form_state['view']->filter as $filter) {
    if($fid = $filter->options['expose']['identifier']) asort($form[$fid]['#options']);
}

I'd appreciate any suggestions.

J. Reynolds suggestion was the answer.

Creating a new function for the sort code and using $form['#after_build'] to call it resulted in the select box being sorted alphabetically.

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {
    $form['#after_build'][] = '_sort_alphabetically';
  }
}
function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}


How can I programmatically extend the registration form? I'm trying to extend registration form programatically to add an additional field. I was following an example from Extend _form in Drupal 8

I created a new service that will redirect to the new form.
I created a route subscriber to that will return the new form.
I created a form class that will extend the form.

It works for the user login form but wont work on user registration form because it is an _entity_form and I guess it should be treated differently. I changed the router subscriber to match registration form but i get this error.

Call to a member function getEntityTypeId() on null.
if ($route = $collection->get('user.register')) {$route->setDefault('_entity_form',
'\Drupal\form_overwrite\Form\NewUserLoginForm');

Can anyone suggest please what's the right way to extend this form?
I tried with the all known hook_form_alter but even like that I'm not sure how to save the new field content in the configuration files.

I had this same question and it doesn't seem to be answered anywhere so I'll give the answer that I figure out, hopefully this helps someone.
First you need to add the form to the entity do this in the module file in hook_entity_type_build something like the following sample:
/**
 * Implements hook_entity_build
 */
function MYMODULE_entity_type_build(array &$entity_types) {

  $entity_types['user']->setFormClass(
    'MYMODULE_register',
    'Drupal\MYMODULE\Form\myModuleRegisterForm'
  );
}

Create a new class src/Form/myModuleRegisterForm.php to extend RegisterForm:
namespace Drupal\MYMODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RegisterForm;

class myModuleRegisterForm extends RegisterForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    $form = parent::form($form, $form_state);

    // Change the form here

    return $form;
  }

}

Then load it in your controller
public function myModuleRegister {

  $build = [];

  $entity = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->create([]);

  $formObject = \Drupal::entityTypeManager()
    ->getFormObject('user', 'MYMODULE_register')
    ->setEntity($entity);

   $build['form'] = \Drupal::formBuilder()->getForm($formObject);

   return $build;
}

That pretty much covers it, obviously you need the route to point to the appropriate function in your controller but otherwise this should do it.  Hope it helps.


How to conditionally show a views field? I'm using the video and video embed field modules to display uploaded video and embedded youtube videos. I've added a video field and video_embed field to the video content type.

The user either uploads a video or embeds a video with the node.
A custom form validation makes sure that either a video is uploaded or embedded.
I have a template override for the video content tpl.php to hide an empty field on the node display page.

I'm using views to show various video previews. Both fields are added to the view and it shows up fine to the user. However, I'm getting a lot of "Unable to find the video thumbnail for ..." in the log. Those are errors when I have a youtube video embedded and nothing uploaded.

To come to the point:
How can I suppress the video thumbnail from showing in the view when no video is provided. The "Hide if empty" no results setting isn't doing the trick here.

You could do this by creating a views row template for your view and then adding in logic to test whether or not a thumbnail exists. This also lets you style the row output differently so you don't have a gap where the image would have been.

Here's the handbook section on views theming:

http://drupal.org/node/352970

but your logic in the views template would be something like:

  if ($fields['field_<video thumbnail field name here>']->content) {
      <output image>
  }


How can I use a token to display the node body summary? I'm trying to use a token to show the body summary of a node on Drupal 7.

The Replacement Patterns area gives the following information:

Body
[node:body:?]
The main body text of the node. The following properties may be appended to the token: value (Text), summary (Summary), format (Text format)

However, I don't understand what "append" means in this context.  I tried [node:body:summary] and [node:body:?summary], but neither works.  What am I supposed to do to get the summary?

Correct tokens are [node:body] and [node:summary].
Yoy should probably check http://drupal.org/node/1295524 if you experience problems with summary tag


Users are getting spontaneously logged out Every so often, my users get logged out, and are unable to log back in without doing the "forgot your password" thing (which works fine). I've put some watchdog statements into core to try to see what's going on, and, while I'm hardly expert in the ins and outs of the Drupal login process, I can tell that, in _password_crypt(), down in password.inc, things make it all the way through to the comparison of the hashed entered and stored passwords, where it fails. This is perhaps because, in checking the database, the users' values for PASS have changed relative to what I saw there when the users were able to log in successfully.

Some other details:

Yes, I'm up to date on patches (Drupal 7.15, and up-to-date versions of contrib)
System and browser caches have been cleared multiple times.
The site is under apache-level password control, and I've confirmed from the log files that nobody from the outside world is sneaking in. So there's no funny business there.
There don't seem to be any exact time aspects to this, but I can typically run, stay logged-in for a day or so before getting logged out.
I'm running the Twitter Bootstrap theme, and I am also using the Less module for CSS generation. Both seem to work fine.
I've experimented with setting $base_url and $cookie_domain in the settings file; neither seem to have much effect on the problem, either set or unset.
Because of the watchdog statements I added (see above), I've been able to see that _password_crypt() is running at times when I wouldn't have expected it to be running (like, not in response to a user's logging in).  Checking user->pass in the database, I found that at least one of the users' entries was no longer what it was after the user set the password after getting logged in through the login link. When this happened, that user was still logged into a browser, and he was still able to function as that logged-in user. However, once he logged out, he couldn't log back in without requesting a new password. More system tracing is underway.

This is seriously killing me; I've worked with Drupal a lot, and have never seen anything like this. Can anybody offer some thoughts on this?

OK, I think I've got this figured out:

As part of the siteI need to be able to programmatically set user field values -- what used to be called "profile values" in Drupal 6. I looked around for some ways of doing that, and found a possible solution at http://drupal.org/node/1047600#comment-4094988, which recommends something like this:

$existing = user_load($uid);
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($existing, $edit);

The instrumentation I did showed user_save was the guy calling _password_crypt(). My belief is that, somewhere along the way (either the method itself or the way I was using it), my call to user_save() was trashing/regenerating user->pass, leaving me in my unfortunate state.

So: I'm now doing the field-saving stuff in a way that doesn't involve user_save (some day I'll figure out this new entities stuff, but, in the meantime, I'm just bashing values into the database) and, so far, I'm staying logged in.  Hopefully this will solve the problem; thanks to all for your attention.


Discard views filter on field from referenced taxonomy term when relationship isn't present I want to show two content types (A and B) in one view. 'A' has a relationship with a taxonomy term 'foo', 'B' doesn't have this relationship. So the relationship isn't required. However when I use a field from 'foo' as a filter in the filter criteria no nodes of content type B are shown, the nodes of content type A are shown correctly.

Is it possible to configure the view such that it doesn't look at the filter with the referenced field for nodes of content type B?

If something isn't clear, ask me!

Thanks!

Yes, you want to use Grouped Filters in Views. In the View UI, there's an Add/Or, Rearrange option next to the Filter Criteria section.

This allows you to create a complex grouping of filters. To use an example that matches your conditions, here's a setup using Drupal's Standard installation with Basic Page/Article nodes and Tags taxonomy that's exclusive to Article:


Views boolean column if user has a specific role I have a standard Drupal installation with Views and Administration Views modules installed.

By default, the Users view has a column Roles with ALL the users roles.

How to include a custom column (to replace the default Roles column) to show if the user has or hasn't a specific role (like a yes/no column)?

I don't see an out of the box method. Maybe someone else will have a better answer. But what I did for a quick solutions is to add the Views PHP module, then add a PHP field with the following output code:

<?php

  $account = user_load($data->uid);

  $roles = array('YOURROLE', 'ANOTHER ROLE');

  if (count(array_intersect($roles, $account->roles))) {
    print 'Yes';
  }
  else {
    print  'No';
  }

?>

It will print yes if any user has either of the two roles.


How to automatically assign child taxonomy terms? I'm building a virtual network like Instagram but its contents (images) are about a certain event.  The strategy of selecting taxonomy terms is to display all of the tags (about 20 ones) and a checkbox and users can check any one of them. I use ttr_configurable_widget to do so.

The problem is there are many synonyms for a word and I don't want to display the synonyms, as an example in tagging the words female, women, girl, sister, daughter, lady are almost the same so when some one search for female the lady tag should be searched as well, furthermore this tag should be displayed as a hidden element in the web page(for search engines)

So there is a main tag like women and a set of synonyms. What I need to do is to format the tags as follow

Then only display the woman, when a user selects woman its synonyms also be attached to the content.

It is also preferred to load the synonyms but hide them in the node display page.

How can I do this?

The Taxonomy Term Reference Tree Widget and Taxonomy Group Fields are almost doing this but in these widgets users can check or uncheck the children even if the parent is selected.

The best way to achieve this job is using JQUERY,load all terms in the page  ,hide all of  children  terms and when the parent term checked show the children terms of it( also when unchecked hide all children of it).


How do I send an email containing the user password? I'm implementing a function that send the password to users who forgot it.

This is the code I developed so far.

function my_module_lost_password($email) {
  global $language;

  $response = array();
  $account = user_load_by_mail($email);
  $params = array(
    'subject' => "hi",
    'body' => "hello",
  );
  $from = "The_admin@gmail.com";
  $to = $email;
 drupal_mail("???", "???", $to, $language, $params, $from);

}

This function is called by a POST query (web service).

How do I use drupal_mail() to send a mail to users containing the password from the users table?

First thing, you cannot send the password. You can only send a reset/one-time-login link. Passwords in Drupal are a one-way street, they can never be retrieved. To send the link is pretty easy. Use _user_mail_notify()

_user_mail_notify('password_reset', $account);


Printing Administrative title to page Is there a function I can use or object I have access to in page.tpl.php in order to get the Administrative title of the current page or it's machine name?

The page title in Drupal doesn't have a machine name. If you want to add one, you can use Safeword module. How to do that: after installing the module, add a new field to that content type where you want to add the machine name; select field type as "Machine name from node title" and widget as "Machine name". After doing this, save the content type and you'll have the machine name for node title.


Can I use a contextual filter to remove content? So I have this view that searches for content (articles, blogs, etc.) associated with a particular author name. Is there a way with this that I can pass a contextual filter of taxonomy terms that would filter out content?
So let's say we have a couple articles tagged with "love", and "questions" but I have one article also tagged with "talk". Is there a way I can pass that term "talk" as a contextual filter (or filter criteria) to block it from showing up in the list? Essentially I'm hoping there is something like "Content: Does not have taxonomy term ID" or something like that.

Regular Filter
You can add the regular Filter for the Taxonomy term Entity Reference field, select the Is none of under Operator, and then click to select "talk" from the terms list.
Contextual filter
You can also use the Exclude option in the Contextual filter for the ER field. I would use this option only if I needed the filter to be Contextual for some reason, if I needed options that come with it, otherwise just use the regular filter.

Add the Contextual filter for your Taxonomy term Entity Reference field, and configure it with these options:
When the filter value is NOT available
Provide default value
Fixed
[Taxonomy term ID for "talk"]
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[Your Vocabulary]
More
Exclude

Check your results to see if the content tagged with "talk" is removed.
Enter all into Views Preview field to bypass the Contextual and check if the "talk" nodes come back (be careful if you have more than one Contextual filter, you may need to provide more than one argument for Views to show results).


Set node action for specific content type I want to set a trigger to redirect when a node (or comment) on a certain content-type is created.

I have 2 hurdles here:

The Trigger module doesn't seem to offer any distinction between content types. Will I have to write some sort of hook?
I can create an action to redirect to the specific URL, but it always shows up under the 'system' category and is then not in the dropdown list when I go to set it for creation of every content type.

The Rules module will be able to handle this, it's a next-generation version of the actions/triggers that are included with core:

  The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

You can use the "After saving a new comment" event for the comments part, and the "After saving new content" event for the content part.

In both cases you'll be able to use conditions on your rules to make sure the actions are only fired for your required content types.


Pathauto not working I had installed pathauto module and it was generating desired url alias. But now its not working. All the newly created node shows node/node->nid. This issue stops working of my drupal_get_path_alias function i added in views template. Can anyone help me out.

There might be some problem with redirects. To overcome this problem, follow below steps:

Go to URL: admin/config/search/path/delete_bulk

Select option to delete all aliases.

Go to URL : admin/config/search/path

See if there are no aliases left, if any left delete them too.

If you have redirect module installed, go to URL: admin/config/search/redirect and delete all redirects if any.

Recreated all URL aliases, go to URL: admin/config/search/path/update_bulk and select desired URL aliases to be created.
See if problem is fixed. If you still have issues comment below.


How to add classes to every X number of node in a array How do I write a preprocess_node function to add a class to every second/third node it generated?

Scenario: add .last to every 2nd node, so that i can apply margin-right: 0; for the last column in the row.

For node listings for which the node.tpl.php (or a different node template) is being used you have variables like $zebra and $id at your disposal that you can use for this kind of tasks. You can see all the available variables with descriptions in the node modules node.tpl.php file or here.

For example if you want to add the necessary class to this line:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

you could use code snippets like these:

<?php $classes .= ' '.$zebra; ?> - add 'odd' to every first and 'even' to every second node in the list
<?php if (!($id % 2)) $classes .= ' last'; ?> - add 'last' class to every second node.
<?php if (!($id % 3)) $classes .= ' last'; ?> - add 'last' class to every third node.


EntityFieldQuery and how to use aggregate functions SUM, ARG and MAX I have entity type payment and need count all payments (calculate based on field_total), if its hard to undersand, I show it on example:

Payment A - $10
Payment B - $20
Payment C - $30

And I need query that SUM all values. In my example it will be $60.

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node', '=')
                    ->entityCondition('bundle', 'payment')
                    ->execute();

What is best method to solve this problem? I could select all nids and load it. But this is not very good if I have thousands nodes, or Iam wrong?

Thank you for advice.

EntityFieldQuery does not support Aggregations/Expressions.

You have three options, basically:

Load all nodes, make the summary in PHP. As you already said, not a good idea if you expected thousands or even just hundreds of payments.
Write an SQL query, which should be rather simple since your field is probably only attached to the relevant bundle so you only need to query a single table and get the SUM() of the field value of all values. To be sure, you could also join the node table and add a condition on the node type. Although not nice, doing this is IMHO fine for custom code, where you know that the field will always be in the database. If you want to support different field storage implementations like MongoDB, not so much...
Lastly, a bit more work, you could maintain a global summary that you update every time a payment is created/updated by implementing a corresponding node/field hook (like hook_field_insert(), as you can see this is what taxonomy.module does...). This would probably be a good idea if you expected that you need the summary frequently. Also, while it might be tempting to use variable_get()/set to maintain a single value, that's not a good idea as it results in cache clears every time a variable is written.


How to undo the achievement of a goal? I have 2 goals on my website: 'Published 1 article' and 'Published 2 articles'. I have according rules that record the tasks for these goals when new content is published by a user.

Now, assume that a user published exactly 2 articles. That means he/she completed 'Published 2 articles'. How can I undo this goal (programmatically) when one of his/her articles are removed?

PS: I've already found this post, but as there aren't any answers, it wasn't that helpful... :)

Unfortunately, this isn't possible yet. A request has been made here. Hopefully, the maintainers will provide this feature in the future.

If someone gives a working solution later on, I'll mark it as answer instead.


How to get the installed version of a module? We have a "MyModule" module, which has a mymodule.install.
Inside the file, there is mymodule_update_8001, 8002 ... etc.

How can I tell programmatically that on which version the module has at the moment?
I know where to find them in database (key_value table), but I would like to use a service instead, if that's possible.

The closest I found:

$update_hook_count = \Drupal::keyValue('system.schema')->get('mymodule');

This returns the update hook number.

You can use the global function drupal_get_installed_schema_version():

$update_hook_count = drupal_get_installed_schema_version('mymodule');


How do I list all blocks with PHP enabled inside? I added a custom block that uses PHP, and now I get the following notice message:

  Trying to get property of non-object in eval() (line 5 of /public_html/modules/php/php.module(80) : eval()'d code).

I am trying to find which one is causing that notice, and since I have many blocks, I would rather do it without using the user interface.

Is there a way to get a list of blocks using PHP? I would be happy also with a solution using the Views module, as long as I don't need to look at the settings of each block, one by one.

If you want to find all custom blocks that have PHP code as their input format, you can query the block_custom table. The format column will contain the key php_code.

$blocks = db_select('block_custom')
  ->fields('block_custom')
  ->condition('format', 'php_code')
  ->execute();
foreach($blocks as $block) {
  // @TODO: Add your own actionable code
}


Using a Third-Party API to dynamically create pages I have a Drupal website that I'm working on where for section of it, I want to pull data in from an external API and dynamically create pages with this data. Do I need to create a custom module for this? I'm not too sure where to start with this, so any advice would be appreciated!

You have a few options here, though without knowing the API your using, it's hard to nail down exactly what one you would need.

If it's a commonly used service, there might already be a module that exists for it. As a general rule, if there is a module already created to handle it, that should be the way to go.

You might be able to go slightly out of the box if your API spits out some form of feed and use a module to import that feed (it's a bit older, but as an example, feeds does this.) There's a few other ingestion modules out there that might work for you.

Creating your own custom module is, of course, always an option. I know I've written a few import modules, but I normally only do that when the other options are not viable.


Get taxonomy terms by taxonomy term id When I'm on a taxonomy term page, I want to list all my taxonomy in that vocabulary.

So I have a taxonomy term ID in the URL. I need to lookup which vocabulary has this value, than list all the values of that vocabulary.

You'll need a Taxonomy Term view with a Taxonomy vocabulary: Vocabulary ID contextual filter.

The problem here is there isn't a core-provided argument plugin for a default value. The closest thing is the Taxonomy term ID from URL provider, but it supplies the Term ID, not the Vocab ID. So you can:

Use the PHP Code plugin provided by Views to retrieve the term ID and return the vocab ID. (Not recommended, as it could cause various problems & won't be compatible with D8).
Implement a custom module with views integration via hook_views_plugins() and a handler that extends the views_plugin_argument_default class. (You can use the Views module's
views_plugin_argument_default_taxonomy_tid provider as an example).


How to pass a parameter/argument to webform using clean urls? I've found a post which explains how to pass a parameter/argument/referer to webform.

It works fine, but I get an ugly URL.
Is there any way to do this using a clean URL? I mean without using GET parameters.

You could solve this using mod_rewrite in your .htaccess file. Try something like

RewriteCond %{REQUEST_URI} ^/path/to/your/webform/(value)$
RewriteRule ^.*$ /path/to/your/webform?param=%1 [L]

This way you can do many things but you can't configure that with the drupal UI. Here's an example with more paramters:

RewriteCond %{REQUEST_URI} ^/path/to/your/webform/(value1)/(value2)/(.*)$
RewriteRule ^.*$ /path/to/your/webform?param1=%1&param2=%2&param3=%3 [L]

Check out the manual.

EDIT: your comment example should look something like that:

RewriteCond %{REQUEST_URI} ^/myform/(\d+)$
RewriteRule ^.*$ /myform?i=%1 [L]

The exact regex at the end depends on your parameters. If you expect only numbers like 1 or 0125 \d+ should be fine. Check out this cheatsheet for more/other char-classes and regex stuff.


Base path and user picture uploading So I recently migrated my site between servers. I think this is causing some issue with the base path of Drupal, which in turn affects the image upload path when a user tries to upload an image to his/her profile.

So, before migrating, some data was already uploaded to some of the users and their images and paths work just fine. The path is as follows for example:

www.example.com/sites/default/files/styles/thumbnail/public/pictures/picture-125-1377507580.jpg

But now, when I'm trying to add new users and when I upload new pictures, the image doesn't get uploaded and the path to the image is as follows:

www.example.com/new/?q=sites/default/files/styles/thumbnail/public/pictures/picture-125-1377507580.jpg

Why is this happening? How do I change the Drupal base path? Thanks

Firstly, it seems that the new server does not allow clean urls or it needs some configuration. Check the documentation on Drupal.org: Step 6: Configure clean URLs

Then, clean all caches and run cron. You will then see all image paths as /new/sites/sites/default/files/...

That's because the new site is set on folder ROOT/new or am I wrong? So there is no error, you have to set the domain to look at this subfolder.

If you don't have permissions to do this in your hosting or there are no options like Add-On domains you can follow the discussion at Drupal installed in subdirectory but made to appear in root according to your hosting enviiroment.


How do I get my accidentally disabled side menu back? I accidentally deactivated the left side menu for every page. I think it's still there, just deactivated.

How do I get it back?

Go to: admin/structure/block

Then move to the bottom of the page and search Navigation and in the select you must select Sidebar First, then go to the bottom and click the Save blocks button

See this picture:


How do I display social media buttons on new content pages on my Drupal Commerce site? I have installed Kickstart Commerce 2. With the demo store, the social media buttons (facebook like, g+, and tweet buttons) are shown at the bottom right of the product page directly below the add to cart button, as shown in this kickstart demo store link, http://demo.commerceguys.com/ck/drinks/drupal-commerce-wake-you).

When I create a new product of a content type that was pre-created by the demo store, these social media icons show up the same way. But now that I have created my own content type for other products I choose to add to my store, this does not display. I thought it was a block, but no blocks seen to have this information.

How do I display social media buttons on new content pages on my Drupal Commerce site?

Thank you to anyone they can offer some direction in this please.

Kickstart 2.0 Distro uses the service links function.  That's what you're seeing below the "add to cart" button.  Pretty easy fix.  Make sure the service links module is enabled and hit configure, or visit: .../admin/config/services/service-links.

At the top, you can just check the boxes on whichever content type you want these links displayed, as well as a bunch of other fun features below.

Enjoy!


Drupal module development - How to build admin items list? I'm creating a Drupal module and I would like to know how to build the admin panel table with the list of each items that I've been created with the module.

What is the hook to use ? and/or the API function... ? I did not found it.

All the tutorials that I read on the web explain how to create a form for submitting content but no one explain how to create the list of the content that have been submitted with the form.

You can see in the joined picture two examples of that I want to do.

I think you have at least two possibilities to proceed.

First, you can use "Views" module to display a list of whatever you want (you can easily configure it to display all contents of a certain content-type that the user currently seeing the page created, etc, etc). You can inspire yourselft with this article about creating an administration page with Views 2 (http://zugec.com/2010/08/create-administration-pages-views-2). It is not very different.

If you want to do it programmatically,  you can always create a "page" that displays whatever you want using hook_menu(). Just set the path under "admin/" and permissions the way you want. Use the page callback function to make the appropriate query (select the nodes you want, created by the current user, order them, sort them, etc...) and to display the results.

If you want more explanations about one of the two solutions provided up there, just ask and I'll develop deeper :-)


Google Analytics Events Tracking Module not working out of the box I was super excited to learn about the google_analytics_et module. I downloaded it and then uploaded to my staging site and enabled the modules like that mentioned. I then clicked around and notice that nothing happens like the documentation states. So I went to the internet to search for some answers. Nothing that helps me.

I am hoping that someone has some information. I wanted to add event tracking and the module seems to have promise. Is there a trick to getting it to work. Do I need to add javascript to the site, example module to make it work?

Is there a better way? Not being a developer is making it harder to figure out.

Thank you in advance.

No JS additions are needed; that's taken care of for you. The GA Events Tracking module doesn't work by itself however, it requires 2 things:

The GA module.
A module implementing hook_google_analytics_et_api().

The module includes an example module which you can either alter directly (not recommended) or just create a renamed copy of it (renaming files & functions from google_analytics_et_example to mymodule). More information can be found on the project page on what you need to do. It does require you to know a little something about:

jQuery: To set the appropriate event (e.g. mousedown) & selector (e.g. #main-menu li a).
Google Analytics Event Tracking: (to set the right data for the event).


Link field with Browse Server button Is it possible to add the Browse Server button on Link Field? So user can link to and see internal file or image? I have tried the Linkit module, but that is not really what I want.

You can use the IMCE module.

  IMCE is an image/file uploader and browser that supports personal
  directories and quota.

  Features

  Basic file operations: upload, delete
  Image(jpg, png, gif) operations: resize, create thumbnails, preview
  Support for private file system
  Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
  Personal or shared folders for users
  Permissions per directory
  Ftp-like directory navigation
  File sorting by name, size, dimensions, date
  Tabbed interface for file operations
  Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
  Built-in support for inline image/file insertion into textareas
  Multiple file selection(using ctrl or shift)
  Ajax file operations
  Themable layout using tpl files


(Nearly) single page website - any clever ways to manage menu anchor links? So,

I am creating a (nearly) single page website. It has a one-page homepage, plus a contact page and a ToS page which are standalone pages. The menu links on the homepage are like '#intro', '#whatwedo', etc, but on the standalone pages I need the links to be 'site.com/#intro' so that it links them to the anchor on the homepage.

How is the best way to achieve this without having two menu blocks?

Cheers

Use the single page site module, this has all the functionality you need to get this working.
https://www.drupal.org/project/single_page_site


Which Apache module is required by Drupal system Could anyone advise which Apache module is required by Drupal system?

The most common enabled module (or installed if not available) is mod_rewrite which helps your site have nice and clean urls. But even this isn't really required ... you can live without it but your site won't have nice links instead they will look like : www.example.com?q=node/12345. If PHP is working than that means that you have the necessary config to run Drupal.


How do I use a custom theme in a module? As I know Drupal 8 removed theme(), which is still present in Drupal 7. There  is function hook_theme() to call and render the theme in a module.

Can anyone help with some of the examples? How do I use a custom theme in my custom module?

It is very easy. You just need use '#theme' element in your render array.

For example:

Drupal 7 has both way:

// Render array.
$build['cars_list'] = array(
  '#title' => t('Cars List'),
  '#theme' => 'item_list',
  '#items' => array('Mercedes', 'BMB'),
);
// Ready HTML.
$build['cars_list'] = theme('item_list', array('items' => array('Mercedes', 'BMB')));

Drupal 8 has only one way:

// Use render array.
$build['cars_list'] = [
  '#title' => t('Cars List'),
  '#theme' => 'item_list',
  '#items' => ['Mercedes', 'BMB'],
];

Actuality you may create a custom theme via hook_theme() and use it.


How can I upload an image for a specific image style? I'm trying to support retina on my site, so I set up a 2x image style and a 2x responsive image style. Now the generated HTML for images looks something like:

<img
    srcset="/sites/default/files/styles/2x/public/2019-01/foobar.jpg?itok=H_4_Z44r 1926w"
    sizes="2x"
    src="/sites/default/files/2019-01/foobar.jpg"
    typeof="foaf:Image" />

This image was already uploaded to my site when I made the change to support 2x images, and I noticed that it actually copied the original image over from /sites/default/files/2019-01/ to /sites/default/files/styles/2x/public/2019-01/.

My problem now is that I'd like to update the 2x version from the authoring interface, but I can't find anywhere where I can upload my 2x version. Is this possible?

Image styles are “derivatives” - they’re automatically derived from the original image you uploaded. A UI to manipulate those derivatives wouldn’t really make sense, the whole point is that they’re generated automatically.

If you can’t change the way you’re working, as in upload the 2x version as the original, and use a 0.5x image style for desktop, and the original upload for Retina, you could always replace the generated styled image files manually via sFTP or similar. But it would become a pain quite quickly.


Filter Content Cronologically Based on Current Month I'm working on a project where the user wants to display upcoming shows. They want to display these shows in three blocks. Each block would list shows for the nearest month, in order.

For example, if the the current month is January, and the upcoming shows were in February, April and June each block would list the shows in the month. (Block 1 = February, Block 2 = April, Block 3 = June)

I was originally thinking of creating three block views. I would filter the first view's date field so that it is equal to the month, the second view's date field so that it is one more than the month, and the third view's date field so that it is two more than the month.

However, since the client's shows are not every month, the shows would only appear until they fit that specific filter. The example above would not show any upcoming shows until it was February, and would leave the second and third columns blank.

All I could think of was to create a block view for each month, but the client would have to arrange them every month.

I can't think of a 'clean' way of doing it within the Drupal interface, but it should be doable by using a template. An override of views-view-table.tpl.php (or the list version of that) and then test the dates as they come through.
It would be a little tricky to know which block has been previously put up (and therefore where to start the next block) but I think it is possible.

In more detail.

Create a view with the listing that you want (for all months).
Create three blocks within that view (they can be the same).
Using the Theme Information tab, find the name of the template that
handles the rendering of the rows.
Put code in that template to only take a months worth of dates at a
time.
Set a flag that 'Feb' is done, so next iteration will be 'Apr'.


How do I apply different css files to different viewports with Omega subthemes? I´m working with an Omega 3.x Subtheme in Drupal 7.
I´ve been reading the handbook of Omega, specially about the layered css files.

Even if I do understand that the layer structure of the default responsive css files is (from bottom to top): global → default → narrow → normal → wide, I can´t mach that to the Grid Settings UI, and I just can´t understand how "default" css file works, and for what layout.

These are the css files that I´ve got:

  global.css = global

  yoursubthemename-alpha-default.css = default

  yoursubthemename-alpha-default-narrow.css = narrow

  yoursubthemename-alpha-default-normal.css = normal

  yoursubthemename-alpha-default-wide.css = wide

And these are the different default layout settings at the UI (/admin/appearance/settings/mytheme):

Narrow Layout (weight 1) --> media query: all and (min-width: 740px)
and (min-device-width: 740px), (max-device-width: 800px) and
(min-width: 740px) and (orientation:landscape).
Normal Layout (weight 2) --> all and (min-width: 980px) and
(min-device-width: 980px), all and (max-device-width: 1024px) and
(min-width: 1024px) and (orientation:landscape).
Wide Layout (weight 3) --> all and (min-width: 1220px).

How about default css file?
I´ve also noted that all mediaqueries are set: orientation:landscape, so how do I manage to apply different css files for portrait viewports?

Example:

I´ve got a phone (480 x 320), a Nexus 7" Tablet (1280x800), a 10" netbook (1024x600) and a 19" pc monitor (1366 x 768).

I´ve customized global, normal and wide css files, applying global.css to my phone (portrait and landscape), normal.css to my laptop and wide.css to my pc monitor.

  cellphone orientation: portrait and landscape ---> css global file.

Works ok. It just takes the global file.

  tablet orientation portrait ---> css ?? file.

It takes the global file, and it looks as the pgone, but bigger. I would like another template. I´ve tried the "default" css file, but it´s not "taken".

  tablet orientation landscape ---> css ?? file.

I´ve copied all contents of "normal" to "narrow" css files, but that won´t work, because it´s a weird narrower result, even if its a copy of the normal css file.

  netbook orientation landscape ---> css normal file

It works fine, it just takes the normal css file.

  desktop monitor orientation landscape ---> css wide file

It works fine, it just takes the wide css file.

So, in other words, how do you apply the css templates to tiny viewports (cellphone), smaller ones (7" tablet), small ones (10" netbook), and bigger ones (big desktop monitor and maybe tv)?

Thanks for your help!

The way I see it you've got 2 options:

Option 1: Don't use multiple style sheets. You can have conditional elements in a single CSS file using CSS media queries like this:

// Default styles
.content {max-width:960px}

// Tablet styles
@media only screen and (min-device-width: 600px) and (max-device-width: 960px), screen and (min-width: 600px) and (max-width: 960px){
  .content {max-width:600px;}
}

// Phone styles
@media only screen and (max-device-width: 600px), screen and (max-width: 600px) {
  .content {max-width:100%;}
}

That will even work on a desktop PC with a small window. For more info go here.

Option 2: There is a way to include those conditions in a link tag. That way you can divide up your CSS files for easy viewing. Like this:

< link rel="stylesheet" type="text/css" media="screen and (max-device-width: 600px)" href="mobile-view.css" />

You'll have to include it manually. I don't know if drupal_add_css will work with media property. You might have to use drupal_add_html_head.


How can I edit a mini-panels output? I have a minipanel that out puts a price, based on the node, but without a currency symbol. I wanted to add a dollar sign so created a new .tpl file and added it as such:

<div class="<?php print $classes; ?>" <?php print $id; ?> <?php print $attributes; ?>>
  $<?php print render($content); ?>

However, the content renders a div as well, so on the front end I get:

$

49.99

Would anyone know where I can access this 'entity-property' div so I can drop in my '$' sign?

Turns out there was yet another .tpl file, just for this element, I could copy from the moduel and place in my themes directory - component.tpl.php


if I change site with local devdesktop it will not change anything with my live site? I am new so bare with me! I am using a local acquia dev desktop 2 beta and want to make sure if I play around with it in drupal it will not change anything with my live site.

We do not host with acquia so I am sure it wont but I want to make sure anything I do does not translate to the mysql?

Again, I am apologize if this is a newbie question.
Thanks.

Normally there is nothing to worry about. Some advices:

make sure that you are working on a local database and not producction.
Sanitize your database (users + passwords) or use reroute email to ensure that your site does not send emails from your local environment.

drush sanitize

  Reroute email: This module intercepts all outgoing emails from a Drupal site and
  reroutes them to a predefined configurable email address.

  This is useful in case where you do not want email sent from a Drupal
  site to reach the users. For example, if you copy a live site to a
  test site for the purpose of development, and you do not want any
  email sent to real users of the original site. Or you want to check
  the emails sent for uniform formatting, footers, ...etc.


How do I display submenus separately from their menu tree? I'm trying to display all 3rd level submenus for a menu item on one page, with each in its own display block. I've tried the Menu Block module but it only seems to work for the active trail, which means I can only display all 2nd Level and 3rd Level menus as one unit rather than just 3rd level menus as separate units.

In addition to the Menu Block module, I also tried access the menu tree directly with this code.

      $main = menu_navigation_links('main-menu', '2');
      echo theme('links__system_main_menu', array(
      'links' => $main,
      'attributes' => array(
      'id' => 'main-menu',
      'class' => array('links')
    ),
  ));
?>

Here's the menu structure:

- Parent Menu 1
- Parent Menu 2
  - Child Menu A
    - SubChild Menu 1A
    - SubChild Menu 2A
    - SubChild Menu 3A
- Child Menu B
  - SubChild Menu 1B
  - SubChild Menu 2B
  - SubChild Menu 3B

What I'd like to display when Parent Menu 2 is selected:

Block 1:    SubChild Menu 1A  | Subchild Menu 2A  | SubChild Menu 3A

Block 2:    SubChild Menu 1B  | Subchild Menu 2B  | SubChild Menu 3B

Any help on the right way to display submenus separate from their tree would be greatly appreciated.

I think the best way to go about it is to just use the Menu block module. Here is a quote about it (from the module's project page):

... have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).


Replaced form AJAX not working I'm facing a problem with Ajax enabled forms, so this is the scenario.
I have 2 blocks, the first one has some buttons and the other one has a form ,constructed using the Form API.

When I click any of the buttons in the first block and AJAX Request is sent to the server, then in my callback function it replaces the second's block form data with new values,
for doing this I call the drupal_get_form function, so the code for the callback is more or less like this:

$form = drupal_get_form('panorama_info_form');
print render($form);

And the elements of the form have the following style:

//Text field for title
$form['panorama_titulo'] = array(
        '#type' => 'textfield',
        '#title' => t('Nombre del panorama'),
        '#default_value' => $panorama['titulo'],
        '#description' => t('Nombre del panorama'),
        '#size' => 40,
        '#maxlenght' => 120,
        '#required' => TRUE,
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array(
          'callback' => 'panorama_info_form_callback',
          'wrapper' => 'panorama_titulo_div',
          'method'  => 'replace',
          'effect' => 'fade',),);

Now, in my jQuery Http 200 success function I replace the old form  with the response data like this:

function reload_element(data){
    $("#panorama-info-form").replaceWith(data);

}

where data is the rendered form.

This works, and I can see my form with the new default values that I declared, however after the form is replaced, ajax is no longer triggered by events. What I mean is that before I replaced the form with jQuery, it used to work, the value was sent to the server and the callback function declared for the textfield was in fact getting called. However after the replacement, no more ajax request...
Why is this happening??? I guess that's because there's some kind of script that uses the form's element's classes to attach functions dynamically to it... Maybe that could be one reason.
How could I fix this???
Thanks a lot.

You don't post the code performing the actual AJAX request, so I have to assume it's directly calling an URL returning just the rendered version of the textfield wrapper with id "panorama_titulo_div".

Since this is sort of side-stepping Drupal's own AJAX functionality (which operates on a per-form basis, initiated by the "#ajax" key being present on certain elements), you'll need to perform some steps manually.

First you need to tell elements in the form that they are about to be removed using Drupal.detachBehaviors($('#panorama_titulo_div').get(0), Drupal.settings, 'unload');

Then you replace the form like you already do.

Finally, you need to re-attach all the JavaScript behaviors since any script operating on the elements in the replaced form won't have any references to the new elements.

Drupal.attachBehaviors($('#panorama_titulo_div').get(0));
This is where Drupal would normally pass the settings received together with other commands returned from an AJAX operation. We don't have that here, and it's not that important since we're not adding/removing elements or otherwise alter the DOM structure and won't introduce any new scrips.
Just to be sure every behaviors works, Drupal calls Drupal.attachBehaviors() again with the entire form as the context argument. You may want to do that too if you notice some things aren't working. It's a safe operation since all behaviors are required to keep track of whether they're already attached or not (often done using jQuery's .once() method.


How to move the "Main navigation" in the Bartik theme? In Drupal 8, with the Bartik theme, I want to put the "Main navigation" tabs of the "Primary menu" region, on the top right, beside the "Site branding" block.

If I just move the "Main navigation" to the Header region, the tabs are lost.
I want to preserve the tabs.

How do I do it?

First the main navigation is a block. Under Structure->Blocks you'll see Navigation. Move it to where it makes sense to you. Secondly Structure->menu is where you determine what items appear in your menu.


Theme function cannot be found Drupal For some reason my theme function is not being found by Drupal.  I swear I have followed everything and spent hours of time trying to make this work to no avail.  Plus with not a single answer in the past 48 hours, Drupal's online support forum is about as much help as a bike with no wheels.  Maybe some of you can figure out what is going wrong with this code.

    function opti_format_results($response) {

    $results = array(

    '#theme' => 'opti_design'

    );

    if ($response) {

    foreach ($response as $key => $value) {

    $results['result '.$key] = array(

    '#markup' => $response[$key]['title'],

    // '#link' => $response[$key]['link'],

    );

    }

    } else {

    $results[] = opti_nothing_found();

    }

    return $results;

    }

    function Opti_Search_theme() {

      return array(

    'opti_design' => array(

    'render element' => 'optisearch'

    )

      );

    }

    function theme_opti_design($variables) {

    $content = $variables['optisearch'];

    var_dump($variables);

    $content = "What is going on??";

    echo "IT HAS THEMED! :D";

    return $content;

    }

The error is quite simple.  "Theme hook opti_design not found."  Can someone please tell me what is wrong.  Everything looks fine.  The hook_theme() function was set properly, and worked in an entirely other module just fine but for whatever reason will not do it's job here.  I feel like it is something simple but I am not seeing it.  Thanks for any and all help.

Your logic is fine, so check these:

Your module is named 'Opti_Search". If not, Opti_Search_theme() needs to be changed to MODULENAME_theme(), and the caches cleared. This one seems most likely given the error message you received.
You've cleared the caches since implementing hook_theme().
The module is installed and enabled.


How is the class loader set to load the files containing classes? I was trying to understand how Drupal 8 initializes the class loader to look for files containing classes in core/lib and modules/*/src.

I found out that the class loader is set to an instance of ApcClassLoader in DrupalKernel::initializeSettings().

  // If the class loader is still the same, possibly upgrade to the APC class
  // loader.
  // ApcClassLoader does not support APCu without backwards compatibility
  // enabled.
  if ($class_loader_class == get_class($this->classLoader)
   && Settings::get('class_loader_auto_detect', TRUE)
     && extension_loaded('apc')) {
    $prefix = Settings::getApcuPrefix('class_loader', $this->root);
    $apc_loader = new \Symfony\Component\ClassLoader\ApcClassLoader($prefix, $this->classLoader);
    $this->classLoader->unregister();
    $apc_loader->register();
    $this->classLoader = $apc_loader;
  }

Following the methods that are called after that, I cannot find the exact method setting the class loader to correctly find the files containing Drupal classes. I expect it to be done from Drupal code, since the directory layout is very specific for Drupal.

Which method set the class loader to look in the right directories Drupal uses?

For modules with composer dependencies in 7.x, try https://www.drupal.org/project/composer_manager. If you want to support modules with PSR-4 autoloading, see https://www.drupal.org/project/registry_autoload (integrates with the standard 7.x class loading registry) or https://www.drupal.org/project/xautoload.

That said, the code you pasted is just the APCu wrapper for the class loader. The actually relevant line is this, in \Drupal\Core\DrupalKernel::discoverServiceProviders():

$this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));

What it does is register a PSR-4 namespace for each module with composer. Below that, everything follows the standard rules.

But composer dependencies is something else, that's handled automatically by composer's autoload.php and all the files that that then loads. Which is basically what composer_manager does, load the generated autoload.php file.


How to get update status of multiple Drupal sites I have several servers each with numerous Drupal sites on.
Not all of them are developed by me.

How would you keep on top of the sites to make sure they are all up to date security wise.
In an ideal world I would like them to report to a central location. From that one place I can be alerted.

Worse case I will write my own module to call a Web Service and send the status across. How ever if this has all ready been done will save some time.

A search on drupal.org found Drupal Remote Dashboard

If that module doesn't work for you, I would suggest a thorough search of drupal.org before jumping into creating your own module.


Drupal 8 Custom front page issue I have created a custom front page in my theme (page--front.html.twig) and put some custom content which is coming up as expected as long as I am not logged in. But when I log in as admin, I cannot browse the homepage anymore. Rather Drupal always takes me to eventcloud.dd:8083/user/1. Even if I manually modify the URL to eventcloud.dd:8083/ it gets redirected to the above URL, i.e. with user/1.

To double check I created an Authenticated User (without administrative rights) and logged in with this account. Same thing happens. Why the system navigates to another page and not staying on the homepage? How to fix this so that homepage only loads up homepage?

I initially created a page upcoming-events and set it up as my default homepage from admin/config/system/site-information. I removed that and presently there is no homepage defined separately.

Please advice.

Try going to admin/config/system/site-information and set the default front page to /node. I think what you describe is related to the Views module which provides the default frontpage in Drupal 8.


use features to export products i would like to use features module to export products. The commerce_features module gives a way to do the products types and other things but not product itself. It does not show up under content section or anywhere I can see. How to use features module to export products? How do you export products from one environment into another? Thank You for any help

Features will handle export and import of content types (a.k.a. products types, I think) but not nodes (which is what I think you mean by exporting "products".)  I have not used it myself, but I think that the Node export module is designed to do what you want.


Drupal 7 disable submit when pressing enter on an autocomplete field In Drupal 7, when you are within an autocomplete field on a node edit form (in my case, it is specifically an entity reference autocomplete field), pressing the Enter key submits the entire form.

How do I disable this behavior?

Here's a nice solution that will allow the user to press Enter in order to select an autocomplete option.

<script>
(function($) {

Drupal.behaviors.ACChangeEnterBehavior = {
  attach: function(context, settings) {
    $('input.form-autocomplete', context).once('ac-change-enter-behavior', function() {
      $(this).keypress(function(e) {
        var ac = $('#autocomplete');
        if (e.keyCode == 13 && typeof ac[0] != 'undefined') {
          e.preventDefault();
          var fauxEvent = $.Event('mousedown'); // Create an event to trigger
          $('li.selected', ac).trigger(fauxEvent);
        }
      });
    });
  }
}

})(jQuery);
</script>

Note: This will only override the behavior of Enter while the autocomplete dropdown is visible. Otherwise, pressing Enter does the normal behavior (submits the form).

But if you want to halt form submission via Enter in any input field, try the following:

<script>
(function($) {

Drupal.behaviors.DisableInputEnter = {
  attach: function(context, settings) {
    $('input', context).once('disable-input-enter', function() {
      $(this).keypress(function(e) {
        if (e.keyCode == 13) {
          e.preventDefault();
        }
      });
    });
  }
}

})(jQuery);
</script>


scrollable views in drupal 6 is needed I want to create a views with scrollable content. I've searched using google and found this : http://drupal.org/project/scrollable  but it is abandoned.

Is there anything similar to it ? I use Drupal 6.

You can download it from the "View all releases" link (near the bottom of the module's project page). That page contains a link to scrollable 6.x-1.x-dev.


drupal_add_js within AJAX callback How can i add some data to drupal setting object using drupal_add_js withing some ajax callback?

For example I have ajaxified flag link on my page, and have implemented hook_flag in my module, how can I add JS within this hook?

function hook_flag($action, $flag, $content_id, $account) {
...
  drupal_add_js(array(
      'my_module' => array('color' => 'green')
    ),
    'setting'
  );
...
}

drupal_add_js doesn't work properly in an AJAX callback. If you need to execute a JavaScript function within an AJAX callback, here's a way :

First, in your form, you have to create (you can just import it) the JavaScript function :

function my_module_form($form, &$form_state) {
// [...]
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
      // Whatever you want to do.
    }',
    'inline'
  );
// [...]
  return $form;
}

Then, in your AJAX callback, you need to call this function you created :

function my_module_my_ajax_callback($form, &$form_state) {
// [...]
  $commands[] = array("command" => 'myFunction',);
// [...]
  return array('#type' => 'ajax', '#commands' => $commands);
}

Hope it helps !


view's query "was not run" while getting results I'm working with drupal 7 and views module (7.x-3.11 version) and I'm getting a strange problem.

In the Views admin, when I run the query, I get a message no query was run while I actually get expected results. Moreover, if I add a filter criteria and run the query, the results are affected by this new criteria while I still get no query run message.

Secondly, I have created a custom module to use views_query_alter to modify view's queries. It never comes into the function on this particular view while it does for other views.

So, to summary, I have a no query was run message and nothing is passing by the hook_views_query_alter but query is run somewhere because I get some results and it is sensitive to filter criteria changes.

I really need to find this query and to override but I just can't find it.

Do you have any idea of what's going on here?

If your views having contextual filter using relationship, then you should check if correct relationship set in contextual filter.


How can I associate an advanced forum with an organic group? I am trying to set up a site which has forums and organic groups.

I want to set it up so the specific forum for a group appears only on that groups page.

By keeping tight control on group creation I can ensure that when a group is created I also create a forum for that group with the exact same name - this allows me to show the forum for that group on the group page by parsing the URL and then filtering by the group name to check it matches a forum name - then displaying that forum in the view on that groups page.. so far so good..

I have also added a group reference field to the forum topic content type, so topics show in the recent group content etc..

When adding a new forum topic, I'd like to automatically populate this field so the topic is assigned to the correct group, rather than give the user a choice, which they could then change. Hopefully this shouldn't be too hard as if a topic is added in the 'football' forum it will be the 'football' organic group that it should be associated with.

How do I go about doing this?

(if there is an easier way of doing the whole thing I'm open to suggestion there too! ie if the group name and forum name will always be the same anyway, it should make things easier all round, no?..)

I have struggled with this problem myself for some time and finally decided to just create a separate content type for my group forum topics and "create" a forum in each group with those topics.

I created a new content type called "Group Forum Topic." In Advanced Forum settings, I added this content type to the "node types to style" so that it would make it look like the forum.

On the og_content view, I added an additional block and named it "Group Forum topics" and I changed it to use the forum topic list format. Using the view from Advanced Forum (Topic list) as a template, I set up the view to display the "group forum topic" content like a forum.

This allowed me better control over the permissions -- I am using entityreference-prepopulate to prepopulate the group when they add the content and I have the group content set to private, so I know that the content will be kept private to the group.

I tried using other modules, but ran into issues with auto-selecting both the forum name and the group and didn't want to chance the user accidentally not selecting one of those things on their own. After a lot of testing and trying, this seemed to be the easiest solution to having a private group forum on the group page.

Keep in mind this does NOT create a listing for the forum on the forum index page. What I have done instead is add my group listings to my forum index page view, so that beneath my "regular" forums, I have a listing of "groups," which contain their private forums inside.

This is my first answer here and I know this question is old... but I ran across it when I was researching this issue myself and thought perhaps the next person looking for a resolution might find it and it might help them!


Make an Inbox block for privatemsg Question

I would like to make a block for printing messages from the user.

I already have a snippet of code which print me the last 5 messages, but I want to add more information like the author and the date.

Snippet of code

global $user;

$query = _privatemsg_assemble_query('list', $user, 'inbox');

$list = array();
$count=0;
foreach ($query->execute() as $thread) {
  if ($count <=5) {
    $list[] = l($thread->subject, 'messages/view/'. $thread->thread_id);
    $count++;
  } else {
    break;
  }
}
 if ($list) {
  print theme('item_list', array('items'=>$list));
}
   else {
echo '
You still have no message yet
';
}

Using print_r($thread); in your code gives this.

stdClass Object
(
    [thread_id] => 2
    [subject] => Testing
    [last_updated] => 1443004733
    [has_tokens] => 0
    [is_new] => 0
    [last_reply_to_mid] => 2
    [participants] => user_187,user_298
)

The below gives an array of the participants names.

    $participants = $thread->participants;
    $msg_users = explode(",",$participants);
    $prefix = 'user_';

    $authors = array();
    foreach ($msg_users as $msg_user) {
        if (substr($msg_user, 0, strlen($prefix)) == $prefix) {
        $msg_user = substr($msg_user, strlen($prefix));
        $msg_user_names = user_load($msg_user)->name;
        $authors[] = $msg_user_names;
    }
}

And something like the below gives  the date.

print date("Y-m-d\TH:i:s\Z", $thread->last_updated);

I'm sure you can work out what to based on that.

ps. I've wanted this exact thing so thanks for the snippet :)


Aplying image styles to images return 404 for images When image styles are aplied to images the modified images are not created and the image url returns a 404 error.
I've been checking for solutions and none worked for me. I commented the Options +FollowSymLinks in the .htaccess
(https://www.drupal.org/node/1170440), I changed the files folder permissions to 777, I changed the theme and back... (image style (imagecache) images are not being created), and still nothing.

The worst part is that it was working fine until yesterday (at least i found it yesterday) and many of the pictures have their modified versions working, but not the new ones for which the url returns de 404.

Is there any thing I can do that I've not tried yet?

Thank you

I don't know what caused the issue but at the end I solved It following this steps:

http://www.aldibier.com/blog/articulo/drupal-7-cuando-no-aparecen-las-imagenes-generadas-por-image-style

1- Adding to the Nginx():

location @rewrite {
  # Some modules enforce no slash (/) at the end of the URL
  # Else this rewrite block wouldn't be needed (GlobalRedirect)
  rewrite ^ /index.php;
}

location ~ ^/sites/.*/files/styles/ {
  try_files $uri @rewrite;
}

2- Adding to the settings.php:

$conf['image_allow_insecure_derivatives'] = TRUE;

3- Rebooting the server.

This solution may bypass the error since, for what I know, nothing in the server configuration was changed when the problem started so this shouldn't be the root of the problem.


Cannot get translated value for an entity inside twig Inside a custom module I get the translated nodes like this:

$ids = Drupal::entityQuery('node')
    ->condition('type', 'event')
    ->condition('status', 1)
    ->execute();

$nodes = Drupal::entityTypeManager()->getStorage('node')->loadMultiple($ids);

$events = array_map(function ($node) {
    return Drupal::entityManager()->getTranslationFromContext($node);
}, $nodes);

and inside the template:

  {% for event in events %}

{{ event.title.value }}

        {{ event.field_event_type.entity.name.value }}

  {% endfor %}

The event_type entity which is a taxonomy is displayed in the original language always. How can I get the translated value for the entity too?

You would need to prepare the taxonomy entities the same way like the nodes. But normally it's not your job to do either of this.

Use viewMultiple() instead of array_map() in the first php example:

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($ids);
$build = \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, $view_mode);
$variables['events'] = $build;

In Twig:

{{ events }}

Customize the twig of the view mode specific event content type and other templates like the taxonomy field template if needed.


Sorry, 10.0.11.38 has been banned For my website when using Firefox or Chrome you get the following message:
Sorry, 10.0.11.38 has been banned.
For Internet Explorer you 403 forbidden error.

Note: 10.0.11.38 is the internal IP of the load balancer which has the domains certificate and associated public IP address.
I went to admin/user/rules and noticed that this ip of 10.0.11.38 has been listed as a host to deny access so I deleted this rule and the drupal website displays again.
We did not enter this ip as a rule originally so I suspect that drupal somehow decided to add this ip as a denied host.

How would I prevent this from happening again?

admin/user/rules is not a path in a regular Drupal install, so you must have some module that does this for you. Since you tagged your post with domain-access I can only guess that the one. You should start looking into the settings of whatever module holds that path.


Rearranging subfields with the Address Field module Is there a way to rearrange the fields within the widget with a specific hook? Should I use hook_form_alter()?

To be more specific, I want to put the country field below the zip-code field when using the Address Field module.

I have two solutions for it:

hook_field_widget_form_alter()
Ctools plugin

Solution 1. hook_field_widget_form_alter().

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, $form_state, $context) {
  if(!empty($element['#addressfield'])) {
    $element['country']['#weight'] = 100;
  }
}

Use $element and $context arrays and implement own IF statement. You can find all the information about the field and user here.

Solution 2. Ctools plugin

It's possible with ctools plugins. Review addressfield/plugins/format/ or https://drupal.org/project/addressfield_vn as an example.

Just add your custom plugin with addressfield alter in 5 steps:

Step 1: Create MYMODULE/plugins/format/ folders structure.

Step 2: Add next code to your MYMODULE.module file:

/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/' . $plugin;
  }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function MYMODULE_ctools_plugin_type() {
  $plugins['format'] = array(
    'load themes' => TRUE,
  );
  return $plugins;
}

Step 3: Add file with alter code. E.g.: MYMODULE/plugins/format/address-alter.inc:

/**
 * @file
 * Move country field to the very end.
 */

$plugin = array(
  'title' => t('Alter addressfield'),
  'format callback' => 'MYMODULE_format_address_alter_country',
  'type' => 'address',
  'weight' => -80,
);

/**
 * Format callback.
 *
 * @see CALLBACK_addressfield_format_callback()
 */
function MYMODULE_format_address_alter_country(&$format, $address, $context = array()) {
  // Move country field to the very end.
  $format['country']['#weight'] = 100;
}

Step 4: drush cc all

Step 5: Enable your plugin for addressfield in customer profile fields settings. E.g. at /admin/commerce/customer-profiles/types/billing/fields/commerce_customer_address

In the current example all the alter code will be inside the MYMODULE_format_address_alter_country() function. Just play with weights of your fields and you'll get the form rearranged.


How to Remove "Edit Summary" Off Editor I would like to be able to remove the option to show the "Edit Summary" option. All I need is that users fill up the field and save. I believe this is called "Teaser" but I might be wrong.

You can actually disable user's ability to provide summary. I found this while pursuing the first solution:

Administration » Structure » Content types » Basic page

you should see "Manage Fields" tab. Click on it, and you should see a table. The row for Body should show Widget Type as "Text area with a summary" which is a link that allows you to edit it.

Rather than changing the Widget Type which is not possible if you already have one or more entries, go to the "Edit" tab.

About half-way down the tab is a checkbox: "Summary input"
("This allows authors to input an explicit summary..."). Uncheck it, and save. Your content edit page for Basic Page should be free of "Edit summary" options.


How do I setup a proper 404 page? At present, my Drupal 7 website’s "Page not found" is 301 redirected to a custom 404 page.

However, I just checked the HTTP response code for a random URL and I noticed it 301 redirects to a custom "Page not found" page, but that page returns a 200 HTTP response code.

Shouldn't the page response header be 404?

If that's the case how do I fix the response code to 404 in Drupal 7?

Instead of using a 301 redirect to your custom 404 page, just go to

Admin > Config > System > Site Information

/admin/config/system/site-information

Enter your new path into the 404 error page box, and click "Save configuration".

You might also want to try the CustomError module:
https://www.drupal.org/project/customerror


Views exposed filter by season from date field (date range group as month only?) How would I create an exposed filter by season (spring, summer, fall, winter) based on date fields? I figured the approach would be to create date range filter groups by MONTH only (no year), but I don't see a straightforward way of doing this.
Any tips or advice for getting a workable solution? Thanks!

You can create the season date ranges and name them by using the Grouping Exposed filter option.
You can find it in the regular Date filter, select Grouped filters instead of Single filter for the Filter type to expose option.
Set the operators to Is between and enter the dates for your seasons (you can see spring and summer in this screnshot):

Drupal will assume midnight if you ommit the time and only include the date. You can look up the exact astronomical times for the seasons if you like :)
Be careful not to exclude some results if you use the same date in separate grouped options but not the same time.


my page.tpl.php overrides path of page display of views I created a view and a page display of it. I set a path for it. this is its path

http://localhost/myProject/library

but when I copy and paste this url in address bar, it just displays my page.tpl.php what I have created for front page. why?

Your issue seems to be in the file name - page.tpl.php will be used automatically for display of all pages.

If you want to have separate template, use hook_preprocess_page():

function MYTHEME_preprocess_page(&$variables) {
  if (arg(0) == 'library') {
    // This will look for template named page--library.tpl.php in your theme.
    $variables['theme_hook_suggestions'][] = 'page__library';
  }
}


The $string argument to t() should not begin or end with a space I am using coder to review code of my module, and I am seeing this in .module file. I am not sure how to fix this up.

Line 49: The $string argument to t() should not begin or end with a space. (Drupal Docs) [i18n_11]

  '#title' => check_plain(t('Role Limit (' . $value . ')')),

The correct way of using variables in t() function is using placeholders.

Example of a correct usage:

$string = t('Role Limit @value', array('@value' => $value));

There are three types of placeholders for t() function.

@variable : The variable will be checked through check_plain() function before it is inserted, so you don't need to check it in your script.
!variable : The variable will be inserted as it is.
%variable : The variable will be checked through check_plain() and highlighted with drupal_placeholder()


DBTNG Migrate: SQLite -> PostgreSQL fails because of custom fields I am trying to migrate a website from a development setup that uses SQLite as a database backend to a production environment, where PostgreSQL is used as a DBMS.

My research so far has led me to the DBTNG Migrator Module, that promises to migrate a Drupal site to/from any database system the abstraction layer supports.

This is the database configuration in my settings.php:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal',
      'username' => 'db_user',
      'password' => 'db_pass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'pgsql',
      'prefix' => '',
    ),
  ),
);

$databases['sqlite']['default'] = array (
  'database' => 'sites/default/files/site.ht.sqlite',
  'driver' => 'sqlite',
  'prefix' => '',
);

Both databases are correctly being displayed in the DTNG Migration UI. However, when I run a Migration check for SQLite -> PostgreSQL, I get the following error message:

field_data_field_custom does not existing in default

field_custom is a custom field I defined in the development site.

Is there way to migrate my complete drupal setup, including custom fields and content types to PostgreSQL, using DBTNG Migrator?

To answer my own question:

The migration should be run on an empty database. This way, everything gets replicated successfully.


HTML tags being removed after theme_preprocess_node I am using theme_preprocess_node to modify an HTML tag, but the tag is being stripped somewhere in the theme layer.

mytemplate.twig

{% if node.field_embedded_media.value %}
  {{ content }}

mytheme.theme

    function mytheme_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'ebook_export') {
        $contentBody = $variables['node']->get('body')->value;

        $pattern = '/<drupal-media/';
        $replace = '<drupal-media data-view-mode="markdown_link"';
        $contentBody = preg_replace($pattern, $replace, $contentBody);

        $variables['content']['body'] = array(
            '#markup' => $contentBody
          );
        }
     }

Original input (node body value):

<drupal-media data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media>

This is some text.

<drupal-media data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media><pre>

This is some more text.

dpm($contentBody) in mytheme_preprocess_node (this is what I want to output, and it's correct here)

<drupal-media data-view-mode="markdown_link" data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media>

This is some text.

<drupal-media data-view-mode="markdown_link" data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media>

This is some more text.

Actual HTML output on page render (this is what I get, and the <drupal-media> tags are gone)

This is some text.

This is some more text.

The <drupal-media> tags got stripped.  How do I prevent them from being stripped?  I don't understand enough about the theme layer to determine where this is happening.

As described in Render API overview, the value passed in #markup is sanitized via \Drupal\Component\Utility\Xss::filterAdmin(). You can eventually pass the tags not to filter via the #allowed_tags properties, but the tag attributes could still be sanited.

To have full control on what it is sanitized, you should use #theme or #type instead of #markup. (The first is my choice when the markup is rendered only in a single place/page. Alternatively, you could also use #inline_template as in the following example code taken from the documentation page.

$build['hello'] = [
  '#type' => 'inline_template',
  '#template' => "{% trans %} Hello {% endtrans %} <strong>{{name}}</strong>",
  '#context' => [
    'name' => $name,
  ],
];

It allows to use any Twig filter Drupal core can use and to have full control over the rendered tags.
It's the easier alternative to #theme which doesn't require to implement hook_theme() nor putting the template content in a separated file. (If you need to reuse the same inline template in different pages, or the template content is rather complex, using #theme is still preferable.)


Which permission is associated with variable_set()? It seems that only site administrators can use variable_set(). If this is truly the case, is there a special permission that grants variable_set() function to site administrators?

There is no permission associated to using variable_set(). Permissions are associated to pages, and not having a specific permission doesn't allow to see those pages; associated to part of the page, and not having a specific permission doesn't allow to see that specific part of the page; or associated to an action, and not having a specific permission doesn't allow to do/start that action.

There could be a module that checks the currently logged-in user has a permission before saving some data with variable_set(), but that doesn't mean every call to variable_set() needs the user to have a specific permission. variable_set() doesn't even check for any user permission.

As for what done from Drupal core and its modules, none of the functions calling variable_set() that aren't part of tests use code similar to the following PHP pseudo-code.

if (user_access($permission)) {
  variable_set($key, $value);
}

This means that, for example, in a form submission handler for a setting page used by Drupal core, the settings will be saved independently from the user permissions the logged-in user has. That user has the permission to see that setting page, though.
If you are noticing that setting values for a form are saved just when the user is administrator, and that happens also for setting pages handled by Drupal core modules, then there is something wrong happening.


Prevent caching of variable in twig template In my custom page.html.twig I have a variable that adds an alert bar to the page if the user is expired. This is based on a custom user field.

It's  generated here in my custom_theme.theme file like so.

function custom_theme_preprocess_page(&$variables){
    $uid = \Drupal::currentUser()->id();
    $current_user = \Drupal\user\Entity\User::load($uid);
    $now =strtotime('now');
    $paidThrough = strtotime($current_user->field_expiration_date->value);
    if($paidThrough < $now){
         $variables['alert'] = 'Your account has expired';
    }
    $variables['#cache'] = [
        'max-age'  => 0,
        'contexts' => ['url.path']
    ];

}

and then inside my page.html.twig file I have

{{ alert }}

{{ page.content }}

Even though some users have been updated to no longer see the alert, they still see it on the home page. If they click around to different pages they no longer see the report, but on the home page they always see it. I'm guessing they no longer see it on other pages because those pages were not cached for them. Also I'm using the page manager and panels plugins for many of these pages including the home page.

Why would twig variables be cached for authenticated users? Is there a way to prevent twig variables from being cached?

I did see a similar post here
Twig/Drupal caching and dynamic variables
But I'm not sure how that would work or how to implement that.

UPDATE: It was mentioned that using $variables['#cache']['contexts'][] = 'url'; would be problematic but if this is a dynamic alert box that appears on every page wouldn't that be necessary?

UPDATE 2: Actually it occurred to me that I'm already using

$variables['#cache']['contexts'][] = 'url';

in my own way here

$variables['#cache'] = [
    'max-age'  => 0,
    'contexts' => ['url.path']
];

But that didn't seem to resolve the issue. Unless 'url' and 'url.path' makes a difference.

This seems a bit chaotic. You don't need an url context on a page, because this is set already. You don't need other cache data, if you have max-age = 0. If your message depend on the current user, you need a user context. And always add cache data, never replace it.

I would use a block for the message which, if it depends on the current user, can be auto-placeholdered. Then you don't need to disable page caching, which is better for performance, see https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


PHP - MENU_LOCAL_TASK in Drupal How do I add #markup or #suffix to MENU_LOCAL_TASK in Drupal?

$items['user/%/checkins_history'] = array( //add to to user's profile
            'type' => MENU_LOCAL_TASK,
            'title' => t('Checkins History'),
            'suffix' => '
Num'.$num_of_results .'
', // NOT WORKING
            'access arguments' => array('Administer Checkins'),
            'page arguments' => array(1),
            'file' => 'manager.inc',
            'page callback' => 'manager_checkins_history_page'
        );

What you're asking doesn't really make sense.

MENU_LOCAL_TASK is used as metadata for a route defined in hook_menu().

#prefix and #suffix are properties for render arrays.

The two concepts are not compatible.


How to get a link to entity_reference in ListBuilder? I have a custom entity (Person) with these fields: ID, nom, prenom, telephoneportable, estactive, adherentid, userID, created, changed.
I created it with baseFieldDefinitions.

adherentid is a 'entity_reference' link to another custom content entity 'Adherent'.
userID are is a 'entity_reference' link to standard Drupal 'User' entity.

In the PersonListBuilder, I try to have these ids showed as links to the corresponding entities.

Here is the code for userID (and it's working fine):

$row['userid']['data'] = array(
'#theme' => 'username',
'#account' => $entity->getUser(),
);

What should be the code for adherentid (can't make it work so far):

$row['adherentid']['data'] = array(
'#theme' => '???',
'#account' => $entity->getAdherent(),
);

Thanks in advance

One possibility is to use the Link render element, and by using the canonical link for the Adherent entity. This assumes that the Adherent entity type definition has a canonical link, and that the route is defined in your module's routing YAML.

$row['adherentid']['data'] = array(
 '#type' => 'link',
 '#url' => Uri::fromRoute('entity.adherent.canonical', ['association_adherent' => $id]),
 '#title' => 'My link',
);

Another possibility is to render the field, and use the display mode that provides a link to the entity using the entity label. However this is less accessible in the documentation to look up within a reasonable time.