All the properties can be searched and found from the code in Drupal core. And they seems to be the properties of drupalSettings object in JS.

This object is initialised in core/misc/drupalSettingsLoader.js.

(function () {

  'use strict';

  // Use direct child elements to harden against XSS exploits when CSP is on.
  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  ....

This code explained that the drupalSettings is contained in

<script type="application/json" data-drupal-selector="drupal-settings-json">

And it must be under <head> or <body>.

I suspect that your <script> tag is wrapped in other element. Please check your template files and remove the wrappers or check if there is a content with missing closing tag.


Drupal views show all taxonomy of specified vocabulary

All you gotta do is create a view of Taxonomy Terms and use fields

Then use a template file for your view.

In your template file all you gotta do is load your node's taxonomy term field value and compare it the view's taxonomy term name. If it's equal we print the underline <u>.

<?php

    $node = node_load(arg(1));
    $node_term = check_plain($node->field_name[0]['value']);

    if ($fields["name"]->content == $node_term) {
        print '<u>' . $fields["name"]->raw == $node_term . '</u>';
      } else {
        print $fields["name"]->content;
      }

?>


db_query(); -- list of files attached to a node?

replace uppercase by your data:

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$sql = 'SELECT f.* FROM {field_data_field_YOURFIELDFILENAME} ff INNER JOIN {file_managed} f ON ff.field_file_fid=f.fid WHERE ff.entity_type = :etype AND entity_id=:nid';
$result = db_query($sql, array(':etype'=>'node', ':nid' => YOURNID));

foreach($result as $row) {
  print_r($row);
}

Create custom function for processing uri: public://FILENAME.EXT and getting right path from this.


Entity token availabe in Rules but non-functional

I'm not familiar with using the Button Field module in combination with the Rules module.

But from your question details, it seems that the entity:nid value is indeed blank. A possible solution is typically to add a Rules Action which is either of these:

"Fetch entity by ID" (if you know the ID you're processing).
"Fetch entity by Property" (if you have some criteria to build a list of things to be processed in a subsequent Rules Loop).

Especially the "Fetch entity by ID" is what I think you should give it a try. Also because of what's written in Comment nr 3 of issue nr 1796952, and which has some pseudo code like so:

event : on User clicks a button field
condition: Entity is of type on entity (make sure everything is in scope of rule)
actions:

Fetch entity by id with ID (data selector) : entity:nid
pump the 'fetched entity' into a component and do things in there

If none of the above helps, then the "Submissions show up on reviewers profile page" part of your question is something that may help to use a completely different approach. If that's something like a Views result" (is it?), then you could maybe use either of these approaches:

Add a Rules Action to load a list the list of results created via a VBO enabled view.
Use the Views Rules module to have each row of that view processed via Rules, whereas you can make each column of such view available as a rules token, so if that "nid" is included in it, you have what you're looking for.

If none of the above help, You may want to use Rules debugging (eg to display values of relevant things using the Devel module, so that you can (temporary) add a Rules Action like "Display a value".
For more suggestions about that, refer to  "How can I display the value of a variable inside a condition?".

PS: those 2 AND Rules Conditions are not needed in your case (that's the default of how Rules combines multiole Rules Conditions).


You need to specify your node name. for example: you want to display your block on www.yoursitename/news page. Then you need to specify only news in that box. Hope this will work.


How can I translate "Read More" on Drupal 7

Assuming you have added and enabled another language in admin/config/regional/language

Just head over to admin/config/regional/translate and search for the string you want translated.

IMPORTANT The strings are both case and whitespace sensitive. Searching for "Read More" returns no results but "read more" has a hit (see screenshot).

Also, since a lot of strings have placeholders that are substituted with variables you might have better luck with other strings if you search for a small subset of it as opposed to the entire thing!

Additionally, I strongly recommend installing the Localization Update module, it will automatically download and update translations for all contributed modules.


In Drupal 8+, you do not need to use a separate theming function as was required in Drupal 6. You can put the form element directly into the table without rendering, and Drupal will handle that on the back-end. It's much simpler:
$row = [];
$row[] = [
  'data' => [
    'something' => $form['something'],
    'something_else' => $form['something_else'],
  ],
];

$rows[] = $row;


How to hide horizontal tabs on page load?

Following @Janpan suggestion, I have hidden the tab content and then added a click function, so I have shown the rendered node inside the div.

here the code:

 $("fieldset").hide();
                $(".tab a").click(function(){
                    $("fieldset").slideDown({
                        direction: "up"
                        }, 300);
                });


Is there a module that provides a field for referencing values of another field

Field reference module may help you !

  Defines a field type for referencing one field from another.

  This module is modelled on Node reference and usage is similar.

  Depending on configuration, authors can pick fields from the same
  node/entity, from other nodes/entities, from specific revisions, from
  specific languages, or even a specific delta value within the field.
  Fields can be displayed using either the 'full' or 'teaser' mode from
  their original node/entity.


Views AJAX error when too many results returned per page?

Found the fix (finally - at least in my case). Generating the View was exceeding the memory limit. I simply increased the allowed memory limit in my settings.php file by adding the following line to it:

ini_set('memory_limit', '512M');


If you have the "Limit allowed HTML tags" checked, it will generate a textarea at the bottom of the configuration of your full_html profile.

You need to authorize the "style" attribute on the span tag by adding this attribute on the list.

<span style>

By default, you have for links :

<a href hreflang>

If you define a new style explained on this documentation it will be added automatically.

EDIT: It seems that for XSS reason, style tag are stripped out everytime, see this thread where they talked about that.
You have to create styles and define what kind of stuff your end user will be able to add. If you absolutely need your user to be able to add some style directly from code source of  your ckeditor, you have to disable the option "Limit allowed HTML tags" but it's not recommended.


Is there a way to show different Amazon affiliate link based on visitor locations?

I wrote that plugin, so should be able to help!

There is a Javascript-only version of the Amazon Link Localiser. I don't know Drupal, but I can't see any reason why you wouldn't be able to use this - you'd just insert the JavaScript link into your template.

Cheers

Pete


Indexing image url in search api drupal 8

It looks like that should be available as a field.

If your field name is "field_image", you would select "field_image:entity:uri".  I think that would give you "public://path-to-file-in-public-directory.jpg"

You could add a custom field to your index in a custom module at src/Plugin/search_api/processor:

In this way, you can add any sort of custom value that's not available by default in the fields provided.


How to create a content-type with "sub-pages" that are default and/or custom per node

Everything you've described is done by OG (Organic Groups).

OG is originally designed for GROUPS to have 'private' sections of a website, or to manage how groups manage different parts of a website, but the side effect of that allows you to build highly contextual "sub sections" of a website just like you're describing.

All of the 'contextual' stuff you mention.   Site side branding, sub section branding,  site wide menus, section based menus.  Are covered by OG.

Good luck!


The code that outputs the links for the table header is contained in tablesort_header().

$cell['data'] = l($cell['data'] . $image, $_GET['q'], array('attributes' => array('title' => $title), 'query' => array_merge($ts['query'], array('sort' => $ts['sort'], 'order' => $cell['data'])), 'html' => TRUE));

The function is called from theme_table(), which is the theme function used to render a table.

What you can do is implementing your theme function that is then used to render the table your module is outputting. There isn't any other method, as theme_table() is not getting any parameter that changes the URL for the table header; as such, implementing hook_preprocess_table() would not achieve anything.

To implement a theme function, you need to declare it using hook_theme().

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_table' => array(
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
    ),
  );
}

Once you declared the theme function, you can use it as you used theme_table(), simply replacing any call to theme('table', /* the rest of the arguments */) with theme('mymodule_table', /* the rest of the arguments */). Notice that in hook_theme() the theme function is referred as mymodule_table, but the PHP function is theme_mymodule_table().

The code you need for your theme function is the same used by theme_table(), except that instead of calling tablesort_header() it will call your own function.

foreach ($header as $cell) {
  $cell = tablesort_header($cell, $header, $ts); // Replace it with the call to your function.
  $output .= _theme_table_cell($cell, TRUE);
}


Views with exposed filters WITHOUT `Use Ajax`?

I believe you need to use the Page Display. That behavior doesn't work when the view is rendered as a block.


How can I export and then import taxonomy terms?

The line between config/content can be blurry since there are many use scenarios. Drupal assumes a default scenario where terms are user-edited content that's not part of the CMS configuration.
Taxonomy terms are content entities, unlike taxonomy vocabularies, which are config entities. Hence, the D8 configuration export/import will not work for taxonomy terms.
There are various modules that will let you import content (and thus taxonomy terms). Some are more general-purpose (e.g. the migration framework, the content sync module), others are specific to taxonomy (e.g. taxonomy import module). Research solutions and figure out what works best for your scenario.


How can I add commerce product automatically when saving a node 'product display'

You could use a triggered rule using Rules on the event "After saving new content", creating the product entity, saving it and editing the product reference field after as well.


The requested URL /node was not found on this server

Have you verified that the .htaccess file from the Drupal 7 core package is in the website root?

You can easily download and extract that file from drupal.org base package:  http://drupal.org/project/drupal


How to make labels of fields selectable?

You'll have to make a custom field formatter with a settings form where you select the label and then output it accordingly.

Like in this tutorial about field formatters


Can I make a content type for a single user's blog entries?

I think what you want is to create a view. Show all blog entries by 'user 1' only in your block.
Create a view: Under your display(on the left) select block from the drop down. Give it
a name, say Test1.
Under Fields add Node:Title and Node:Body.
In the filters add Node-type:Blog, Node:Published:Yes and User:Name=Admin

Then goto Site building->Blocks and you should see Test1:Viewname. Enable that block and configure it to show it on the page where you'd like.

Hope that helps.


How to collect time periods, calculate the total, and present in ISO 8601 format?

You're asking two completely unrelated questions here.  To rephrase:

How can I provide Google with dates in a format that Google's scraper will recognize, as specified in Rich snippets - Reviews?
How can I accumulate time periods and present the result in a format suitable for humans?

Asking two unrelated question in one question is depreciated on SE, and will usually get your question closed, but I am going to answer them anyway.

First question: The ISO 8601 format requested by Google is YYYY-MM-DD with leading zeros if required, so July the 4th 2013 would be 2013-07-04.

To format the ISO date you can use the PHP function date like this:

$isodate = date('Y-m-d', $timestamp);

where $timestamp is an integer with the number of seconds that has elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT).

Further, Google expects the $isodate string to be embedded in the page attached to the dtreviewed property using the syntax one of three metadata schemes (microdata, microformats, or RFDa).  You do this in Drupal by overriding the template of page, node, etc. you want to embed the dtreviewed property in.

Second question: To accumulate time periods, you need to convert periods input by users (such as "1 hour and 5 minutes" or "01:05") to an integer format with seconds resolution.  To convert to seconds you multiply the days with 86400, the hours with 3600 and the minutes with 60, so "1 hour and 5 minutes" becomes:

1 (hour) * 3600 + 5 (minutes) * 60 + 0 (seconds) = 3900 (seconds)

and  "2 hours and 25 minutes" becomes:

2 (hour) * 3600 + 25 (minutes) * 60 + 0 (seconds) = 8700 (seconds)

To accumulate, you just add the seconds:

3900 + 8700 = 12600 (seconds)

To display in a suitable format, you can use format_interval.

$interval = 3900 + 8700;
$intervalstring = format_interval($interval, 2);

and $intervalstring will now be:

3 hours 30 minutes

(You will lose the "and" by using this standard function, if this "and" is important, you'll need to write your own.)

For avoidance of misunderstanding: Goggle is not interested in your time period data. A time period is typically an interval made up of hours and minutes, and not attached to a particular date.  Google wants dates (as in year, month and day of month).  Dates and time periods are different things, and there is no way you can format a time period as a date, or vice versa.


Drupal installation profile: menu_link_save() doesn't work for "import" path

As tvl advised, "import" path is not yet defined in when MYPROFILE_install() is called in MYPROFILE.install. So moved the code over to MYPROFILE.profile and used hook_install_tasks() as explained here: https://www.drupal.org/node/1022020

/**
 * Implements hook_install_tasks().
 */
function MYPROFILE_install_tasks($install_state) {
  $tasks['add_import_link'] = array(
    'display_name' => st('Adds import link to menu-administrator'),
    'display' => TRUE,
    'type' => 'normal',
    'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    'function' => 'callback_add_import_link',
  );

  return $tasks;
}

function callback_add_import_link() {
  // Add the menu link
  $link = array('menu_name' => 'menu-administrator', 'link_path' => 'import', 'link_title' => 'Import', 'weight' => 5);
  menu_link_save($link);
  menu_rebuild();
}


Automate hyperlink to send variables to webform

If you are doing it in Drupal 6 then hook_nodeapi(&$node, $op, $a3, $a4) is to alter node object for additional information.

function custom_module_nodeapi(&$node, $op, $a3, $a4){
  if ($op == 'view' && $node->type == 'project') {
    $node->content['project_link'] = array(
      '#value' => l('Sign Up', 'node/[id]', array('query' => "project=" . $node->title)),
      '#weight' => 100,
    );
  }
}


i will advice you to use "Fluid two column stacked" layout. This layout provides a header region, then two left and right columns and one footer region.
So you can display your data by putting appropriate fields in the right regions. Also if you don't have any fields in any region that region will simply not display and if you don't have data in the left column then the right column will shift to the left side.
Hope this solves your problem.


To get a different content and/or interface for the USA and UK, go to admin/config/regional/language/add :

In predefined language, select English, british. This will add a new "english British" language with en-gb prefix, while default english has en prefix, and will import related .po files.

If you have only en-US and en-GB in your project, when the content is the same for both, simply set it as Language neutral  in the content node submission.

Maybe you already know the great article series Drupal 7's new multilingual systems compilation. It is a valuable source to get a complete overview of Drupal 7 multilingual setup.


Display shipping subtotal including taxes

This is happening because the "Order Total" process combines like price components together and then lists them out. As a result, the base shipping rate component is appearing unaltered and the VAT is being combined into any other product VAT (or shipping VAT) components. It's an unfortunate display side effect of the implementation of price components, but it's on the roadmap to be updated in Commerce 2.x.

In the meantime, your solution will involve implementing hook_commerce_price_formatted_components_alter(), which you can find documented in commerce_price.api.php. This is purely a display alteration, so all the necessary data will still be there unaltered - you can just fiddle with the display amounts of the price components so your VAT component gets added to your shipping component instead.


Using menu tokens (or similar?) to create "invite user link" on OG Group page

I was having similar trouble as you, due to the bug in menu-token.

The way I would go about is, as a work-around, is to create a views-block relative to your groups, adding your node id or gid as a field that is not displayed (you'll have to move this to the top of your fields list in views for it to work).

Then you add a "global text" -field with a value like "Invite", re-writing the output as a link that includes the node id/gid as a token in the URL. This must be located below the node id/gid in the field order(!).

Finally, you will have to set your views filter to restrict the output to the page a user is currently on, this way the Node id/gid field will return only the correct value. Also set your pager to a single result as measure of ensuring only one value is passed through.

Hope this helped!


How to bulk re-index the whole site for core search?

You can use the following drush command.

drush search-reindex --immediate --verbose


This works:
$action = \Drupal::entityTypeManager()
  ->getStorage('action')
  ->load('send_mail');
if ($action) {
  $action->execute($entity);
}


backing out of a module update after uploading it and before the database update (new update is incompatible with my version of PHP)

Should I delete the reCAPTCHA module from /sites/all/modules/, and then put the files for the old version in there?

Yes, that's exactly what you should do.

  If I do that, will the database updates script be confused?

They shouldn't be - when you start an update, the current versions of modules are queried from fresh again. So as long as the current version of the module in the database matches the version in the file system (which it will if you restore to before the file system change), you should be fine.


PDOException when setting field value in node presave

Sounds like you should be setting target_id instead:

foreach ($nameResult as $row) {
  $node->field_co_pi[LANGUAGE_NONE][$i]['target_id'] = intval($row->entity_id);
}

Note that not all fields have the same data column (such as 'value'). Reference fields have target_id which holds the referenced entity id.

Aside from that, just make sure that it has a value before setting, or you will get the same error again.

You redacted other parts of the code, so, I can't see if you set $i or not. Are you incrementing that per loop with $i++? I just assumed it is a multivalued field since you are doing a foreach instead of setting [0] directly.


How to alter storageSettingsForm in a custom Field Type definition, set default cardinality and not allow change

Problem solved in 8.4.0 :)

Full list of changes


A bit late, but just figured this one out in case it helps someone else:

{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': tid}) }}


Dull ax approach would be to cycle through your $form looking for fieldsets and unsetting (now setting #access to FALSE) all but the one you want to keep, eg, something along the lines of...

// drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');
foreach($form as $key => $field) {
  if ($key != 'field_FIELDNAME' && is_array($field)  && $field['#type']=='fieldset' && $field['#collapsible']) {
    // unset($form[$key]);          // ADDITION/EDIT: '#access' below is a better/working approach
    $form[$key]['#access'] = FALSE; // than unset if required fields are in the fieldset :)
  }
}

...with the drupal_set_message() helping to get the field_FIELDNAME for your scheduling fieldset.

Just realize that without further logic, you would never be able to edit any fields inside these fieldsets again.

Another option might be to check out the nodeformcols module that makes lengthy node forms a bit nicer and does contain this functionality out of the box for both fields as well as fieldsets.


How do I declare a Telephone field in a content entity?

Okay, the following configuration seemed to work:

$fields['display_number'] = BaseFieldDefinition::create('telephone')
      ->setLabel(t('Display Number'))
      ->setDescription((t('The phone number to display')))
      ->setDefaultValue('')
      ->setDisplayOptions('form', array(
        'type' => 'telephone_default',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);


How can I programmatically validate that an user has uploaded an image in CCK?

You may have to use hook_form_FORM_ID_alter().Define your own module and in your module try the following code

function yourModuleName_FORM_ID_alter(&$form, &$form_state) {
  $form['#validate'][] = 'yourModuleName_FORM_ID_validate';
}

//your validation function
function yourModuleName_FORM_ID_validate($form, &$form_state) {
  if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name']['machine_name_of_the_cck_field'])) {
    // File uploaded
  }
  else {
    //File not uploaded
  }
}


You will need to have access to the web servers folder structure. You will find the themes inside sites/all/themes, sites/default/themes, sites/YOURSITE/themes or profiles/YOURPROFILE/themes. Once copied to the other Drupal installation it can be enabled under admin/appearance. More on installing a Drupal theme can be found here.

It might be that the theme you are going to copy is a subtheme of another theme. In this case you need both themes. Look inside the THEMENAME.info in your theme and look for the line that starts with base theme =

If a base theme is defined there you need that as well on your target installation.


You could always copy the tab HTML and put it somewhere outside the QuickTabs output, and then position them using CSS where you want them on the page.


How to trim the Node field is rendered in page.html.twig?

We had a similar issue on our site recently. You are trying to print a FieldItemList, which has no __toString function, and therefore cannot be implicitly converted to a string, as you are trying to do.

In your case, node.field_custom appears to be a FieldItemList. I know, you thought it was just a string value from a field -- but it's not. Drupal treats ALL fields as FieldItemLists in the API, even in cases where the field can't possibly contain more than one value. (This presumably makes the implementation cleaner.)

One quick solution to your problem, although this is a bit messy, is to call first(), to get a TypedDataInterface, getValue(), which returns an associative array, and ['value'], in your Twig template, like so:

node.field_custom.first().getValue()['value']

That should return a string. However, for those functions to be accessible in a Twig template, you need to enable them in settings.php and clear the system cache. Here's what worked for us:

$settings['twig_sandbox_whitelisted_methods'] = [
        'first',
        '__toString',
        'bundle',
        'id',
        'label',
];

But in your case, you may have to whitelist more methods to get what you want.

Here is some more information on discovering variables in Twig templates.


Can no longer run "composer require drupal/swiftmailer"

I know you're sorted now, but wanted to suggest that this could be because the repository URL for the coder module is using https.

See here:

https://help.github.com/articles/why-is-git-always-asking-for-my-password/

The link at the bottom of that article suggests that you can cache your credentials to avoid the need to enter them when using https:

https://help.github.com/articles/caching-your-github-password-in-git/

(I would have commented rather than answered, but it seems I don't have enough reputation to comment yet!)


Passing variables from hook_mail to cutom twig template

Rather than using node get to print a value just use this in twig.

  node.field_myfield_name.value

Otherwise preprocess your twig and get only required fields over sending complete node object to twig.

function theme_name_preprocess_mail_body_content(&$variables) {
  $variables['myfield_name'] = $variables['node']->field_myfield_name->value; //$variables['node'] will be render $node from your hook_mail() function.
}

And in Twig myfield_name will work


How do I add more pages to views pagination on mobile?

You must do this in the views configuration.

First you need to set the pager to use full pager instead of mini pager.

Then in the settings you can set the amount of pager links visible (in your case 5).

That should show the pager you want with 5 pager links visible.


How do you go to an overlay view within Drupal using drupal_goto?

You cannot pass a URL fragment into drupal_goto() like that or it will get escaped and won't work properly.

From the drupal_goto() docs it says the second parameter is an array of $options that get sent through to the url() function.

Looking at the url() function docs shows that one of the allowed $options is:

  'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.

So you should be able to do this:

drupal_goto(current_path(), array('fragment' => 'overlay=admin/vendor/auth-stripe'));

Note the use of current_path() as the path so that the page under the overlay will be the on the user was previously on.

If you didn't want that, then this would use the front page instead of the current page (because if you pass an empty path into the url() function it uses the front page as a default):

drupal_goto('', array('fragment' => 'overlay=admin/vendor/auth-stripe'));


Is there a REST endpoint for getting the logout token?

It appears this does not currently exist. I just created a patch for core. Please review it and make suggestions if you have a chance. https://www.drupal.org/project/drupal/issues/3004421

I will edit this answer if any progress is made with the patch.


How do I remove the authoring information?

You can disable it for each content type, going on admin/structure/types/manage/<content type> (e.g. admin/structure/types/manage/article for the Article content type).

What you are looking for is in the "Display settings" tab visible at the bottom of the settings page.


How can we theme menu blocks in drupal 6

You can user the theme developer module to check whether your template is called at all. It will show you what nameing conventions to use.

And just in case: You have to flush your caches to make sure new templates and theming methods are taken into account.


What security should I double-check before opening my site to being multi-user?

Mittenchops, here is a suggestion

Create a role for the new users
Guarantee that this role doesn`t have permission to use PHP Filter
Check all the "administer " permissions to see if the new role is not
having access to certain areas that it should not have
Create a new user for you with this new role and test the site.
During the process of creating the new user check if you are able to choose the role (you shouldn't be)
You should also try to access pages like http://yousite.com/admin which a common user should'n have permission

I think you would be safe with this.


You can give permissions to menu links according to role.give permission to the above links then they will appear as per according to roles.
use the below given module for permissions as per role

Menu per Role

May this will help you.


It is default behaviour to show content tagged with that term. It does not copy content, it just runs a SQL query against it. You can control it easily by activating the view 'Taxonomy term' that is installed but inactive. Through that view you can more easily control how the associated content is displayed.

There are also various hook and theme functions that you can implement to change the output, such as hook_taxonomy_term_view_alter, template_preprocess_taxonomy_term etc.

Look at this post for more detail on that: Custom taxonomy term pages

There might be situations where you do not want your taxonomy terms to be links (to similar content tagged with that term). In that case you can set the field display formatter (which is link by default) to plain text.


You need to wrap your javascript in a Drupal Behaviors handler. You can read the Javascript Documentation for more information (scroll down and look for the heading "Behaviors").

Basically, your code will end up looking something like this:

    (function ($) {

      Drupal.behaviors.exampleBehavior = {
        attach: function (context, settings) {
         // All your code here
       }
     };

   })(jQuery);

If this does not solve your issue, you use check your site for any javascript error messages and update your original post to include them. The way I recommend to do this is to install the Web Developer plugin for Firefox and open up the Error Console (tools -> web developer -> error console) and look for messages highlighted in red.


form_get_errors() is NULL when calling it in an AJAX form callback

I found a way to make this work.

I haven't fully investigated this for issues yet but it works with and without javascript enabled.

My use case was only running  my validation if other validation passed:

/**
 * Custom validation function for some form.
 */
function MODULE_NAME_custom_form_validate(&$form, &$form_state) {
  if (isset($form_state['storage']['errors']) && !empty($form_state['storage']['errors'])) {
    return;
  }
  // Do our extra validation here since other validation passed.
}


Display a menu on all pages except a specific page type

I suggest using the context module for better and more advanced handling of blocks.

Alternatively, you could use pathauto to create a unique url for that content type (like mysite.com/type/content ) and set the block to show up everywhere, excluding 'type/*'. If you do this, make sure to rebuild your urls.


Base fields are defined in code. When code updates change the database schema you can implement the updates via entityDefinitionUpdateManager in an update hook as shown in the question. This is not possible in a form submit.
If you want to store field settings in a form submit load the field config and save it:
// if the entity type has no bundles use the entity type id:
$entity_type_id = 'vehicle';
$bundle = 'vehicle';

$fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions($entity_type_id);
$field_config = $fields['field_example']->getConfig($bundle);
// make changes
$field_config->save();

For form and view display settings you can use EntityDisplayRepositoryInterface::getFormDisplay and EntityDisplayRepositoryInterface::getViewDisplay:
$display_repository = \Drupal::service('entity_display.repository');
$display = $display_repository->getViewDisplay($entity_type_id, $bundle, 'default');
$display->setComponent('field_example', $display_options);
$display->save();

For both code examples if there is no configuration stored yet it will be created.

Your question is about a custom form. Instead you could expose the core field admin UI by adding field_ui_base_route to your entity, even if you don't intend to use bundles or view modes. This works also for base fields marked as configurable. See How do I add a view mode to a simple custom entity?


VBO action on pending node revision (using Revisioning) publishes the revision

So, I found out where the issue is coming from.

Basically, Revisioning works as follows:

A node gets saved by Drupal. Drupal doesn't care much about the status.
If the node is published, it remains published. It is important to realize
that, when using Revisioning, if a node has a published revision, for
Drupal the node has a status of 1, regardless of the pending, unpublished
revision. Upon saving, Drupal simply stores a new revision, and updates
the node database row, pointing the revision ID to this new revision.
Revisioning kicks in, with revisioning_node_update(). It checks the
revision_operation property. Based on its value, it "reverts" what Drupal
just did, setting the revision ID in the node table back to the previous
revision. This is what keeps the published revision one step behind the
pending revision.

Now, this revision_operation property is only set when in context of a node form. When using VBO (or any way to trigger actions, for that matter), Revisioning doesn't see the revision_operation property, and revisioning_node_update() doesn't revert the revision ID.

We could patch this in Revisioning, but the project hasn't received much attention lately (for the D7 version). So this is how I solved it (I have several actions, but I'll give the example of the node_assign_owner_action action):

/**
 * Implements hook_action_info().
 */
function mymodule_action_info() {
  return array(
    'mymodule_assign_to_user_action' => array(
      'type' => 'node',
      'label' => t("Assign to user (Revisioning compatible)"),
      'configurable' => TRUE,
      'behavior' => array('changes_property'),
      'triggers' => array('node_presave'),
    ),
  );
}

/**
 * Assign a node to a user.
 *
 * We need a custom action for this, as actions are not entirely compatible with
 * Revisioning. We need to tweak the node a bit to force a pending revision to
 * stay that way. node_assign_owner_action() does not allow this. See
 * _mymodule_actions_reset_revision_operation() for an explanation on why we
 * need this.
 *
 * @see node_assign_owner_action()
 * @see node_action_info()
 */
function mymodule_assign_to_user_action($node, $context = array()) {
  // Simply proxy to node_assign_owner_action().
  node_assign_owner_action($node, $context);

  // Make sure the revision_operation property is correctly set.
  _mymodule_actions_reset_revision_operation($node);
}

/**
 * Configuration form for mymodule_assign_to_user_action().
 *
 * @see mymodule_assign_to_user_action()
 * @see node_assign_owner_action_form()
 */
function mymodule_assign_to_user_action_form($context = array()) {
  return node_assign_owner_action_form($context);
}

/**
 * Validation callback for mymodule_assign_to_user_action_form().
 *
 * @see mymodule_assign_to_user_action()
 * @see node_assign_owner_action_validate()
 */
function mymodule_assign_to_user_action_validate($form, $form_state) {
  node_assign_owner_action_validate($form, $form_state);
}

/**
 * Submission callback for mymodule_assign_to_user_action_form().
 *
 * @see mymodule_assign_to_user_action()
 * @see node_assign_owner_action_submit()
 */
function mymodule_assign_to_user_action_submit($form, $form_state) {
  return node_assign_owner_action_submit($form, $form_state);
}

/**
 * Set the correct node revision_operation property.
 *
 * @param object $node
 *    The node on which the action is performed.
 */
function _mymodule_actions_reset_revision_operation($node) {
  module_load_include('inc', 'revisioning', 'revisioning_api');

  $is_moderated_content = isset($node->revision_moderation) ?
    $node->revision_moderation :
    revisioning_content_is_moderated($node->type, $node);

  $node->revision_operation = (int) $node->is_pending + (int) $is_moderated_content;
}

Thanks to this, we can still use actions provided by core or other modules, but we need to wrap them in another, Revisioning compatible action. When calling _mymodule_actions_reset_revision_operation(), we use the same logic as Revisioning is using when altering the node form.

It now works.


How to show organic groups users that their subscription is pending?

A possible solution for this is to use a combination of the Flag and Rules modules, which integrate very well with the Organic groups module.

Here are the highlights of how you could make it work:

Create a 'global' flag (using Flag) that will be used to identify (flag) users with their membership is pending
Create a 1st rule (using Rules) like so:

Rules Event = User has become a group member
Rules Condition = og-membership:state EQUAL TO pending
Rules Action = set the flag (defined as in "1.") the user (using Flag)

Create a 2nd rule (using Rules) like so:

Rules Event = User has become a group member
Rules Condition = og-membership:state EQUAL TO active
Rules Action = unset the flag (defined as in "1.") the user (using Flag)

Create a 3rd rule (using Rules) like so:

Rules Event = Content is viewed
Rules Condition = "Path matches some path on which you want to show such message"
Rules Action = Show a message on the site

In case you have multiple organic groups for which you want to implement something similar, you have these options:

Create a similar flag and a similar set of 3 rules for each of these groups.
Use the Rules Conditional module so that you can combine the above logic for all groups in an enhanced version of rule2, -3 and -4.
It would probably also be a good idea to move part of the logic in the above rules in a 'rules component'.

Using the Rules Conditional module you could also combine rule 2 and rule 3 above in a single rule.

In case the above may seem like overkill (2 extra modules, and 3 rules to be created ...), keep in mind that with these very same 2 modules you can implement lots (dozens?) of other functions/features. Probably also to address "... quite a number of questions related to Organic Groups..." you mentioned in your question.

Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module. For Organic Groups there is another set of amazing videos to Learn Organic Groups.

Possible alternative

For anybody who considers the Organic Groups module as rather complex (like me ...), have a look at the Group module as a possible alternative. For (way) more details about this module, refer to my answer to "How to create basic Organic Groups functionality with flags and references?".


dev site reverts to production site url when clearing cache

@Clive's suggestion jarred my memory and I figured it out. I have a multisite setup that I was migrating and had the base url setting in settings.php set to www.example.com and I had forgotten to change it to the localhost url. When I commented out the base url setting, everything was fine.


If I understand the question correctly, you need to set the Use panel path to Yes in order for things like pagers, exposed filters/exposed sorting, and ajax to work properly.


How do I include a twig file in a custom block type module?

Create a theme hook with the template name by replacing dashes with underscores:

mymodule.module:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__bundle__jumbotron' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}


I've missed configuration at admin/config/regional/content-language :|


You need to copy over The Zen theme as well, A sub-theme requires both the sub theme and its parent theme in order for it to work


Creating a List View and Thumbnail view in Drupal 7 view

You could create one view with 2 pages or blocks depending on how you are setting up your view. Then have one show list view and the other show thumbnail view. You could then use tabs to switch between the 2 views.


Purging session data on devel user switch

Problem is - $_SESSION was never really meant as temporary data storage. Proper and safe way is to use cache_set() to store data.

First argument, $cid is customary used as a string with sections separated with :, so in your case it should look about like that:

global $user;
// ...
cache_set('mymodule:' . $user->uid . ':' . $user->sid . ':kind_of_data',
          $data, 'cache', CACHE_TEMPORARY);
// ...
$data = cache_get('mymodule:' . $user->uid . ':' . $user->sid . ':kind_of_data',
                  'cache');

That way you will allow Drupal to benefit from database permanency, memcached speed, whatever you please. And by including uid of current user, you are sure data is well separated and no collisions will occur. Including session ID allows proper anonymous user handling. For logged in part $user->sid might be safe to ignore, depends if you want data to be shared between logged in seats or not.

If you use session id as a part of cache key, like above, entries will be only valid for one session. If your site has few users, obsolete cache entries are not a problem. And if you have many, you should store both sessions and cache in memcached, apc or similar technology anyway. Database is simply to slow for this. Memory based cache engines are very good at automatically destroying unused entries when needed, destroying them from code is a waste of time and effort.


Custom entity api admin UI overview table how to add extra columns and operations? Drupal 7

I figured out how do do this, and it, of course, isn't terribly straightforward...

You're on the right track, you just need to override the EntityDefaultUIController::overviewTable function in your own custom class. I don't think there's an easier way (since you're looking for one).

So, copy the the implementation of overviewTable from EntityDefaultUIController (in entity/includes/entity.ui.inc in the Entity API module) into your custom ui controller class and look for the calls to:

$this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);

...and add the $additional_cols parameter which should be an array populated with the extra data (which you can pull from the $entity object already populated in the foreach loop. So, do something like:

foreach ($entities as $entity) {
  $additional_cols = array($entity->someField, $entity->someOtherField);
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity, $additional_cols);
}

In addition to that you'd have to add the associated headers into the render array at the end of the overviewTable function like so...

$additional_headers = array('some field', 'some other field');

$render = array(
  '#theme' => 'table',
  '#header' => $this->overviewTableHeaders($conditions, $rows, $additional_headers),
  '#rows' => $rows,
  '#empty' => t('None.'),
);

...my guess is that you already figured out this much, but to answer your question, no, I don't think that there's an easier way. I hope this helps you, or someone else. ...or if someone knows this easier way, let me know too... =)


Since the second argument of theme() is an array, you are writing code for Drupal 7. In that case, theme('table') doesn't use any array item whose index is an integer. The only array indexes you should pass as second argument to theme('table') are the following:

header
rows
attributes
caption
colgroups
stricky
empty

Since you are using array('variables' =>$my_vars) it could be you are trying to set attributes, but in that case the array should be an array of HTML attributes, or colgroups, and in that case the array should be similar to the following one.

$colgroup = array(
  // COLGROUP with one COL element.
  array(
    array(
      'class' => array('funky'), // Attribute for the COL element.
    ),
  ),
  // COLGROUP with attributes and inner COL elements.
  array(
    'data' => array(
      array(
        'class' => array('funky'), // Attribute for the COL element.
      ),
    ),
    'class' => array('jazzy'), // Attribute for the COLGROUP element.
  ),
);

If you are trying to set attributes, your code should set the $build variable as following.

$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => $my_vars,
);

Replace '#attributes' with '#colgroups' to set colgroups.

In the case theme('table') accepted variables (which could be the case if a module overrodr the default implementation of the theme function), then the code should be similar to the following one.

$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#variables' => $my_vars,
);


I found a solution to this problem here: https://www.drupal.org/node/1578656

The idea is to add the following keys to the 'file_managed' field at the time you want to clear it:

$form[FORMKEY]['#file'] = FALSE;
$form[FORMKEY]['filename'] = array();
$form[FORMKEY]['#value']['fid'] = 0;

In your case it should be something like this in the form builder function:

if ( isset($form_state['storage']['reset-file-field'])
  && $form_state['storage']['reset-file-field'] === true
) {
  $form['Input type']['file']['#file'] = FALSE;
  $form['Input type']['file']['filename'] = array();
  $form['Input type']['file']['#value']['fid'] = 0;

  $form_state['storage']['reset-file-field'] = false;
}

And then in your submit handler:

$form_state['storage']['reset-file-field'] = true;

The if-block is necessary to prevent the upload field being reset when you press 'upload', thus making it useless.


How do I automatically approve a user account in Drupal 7 based on a rule

I'm pretty sure you can do that with rules in D7:

Event: "After saving a new user account".

Condition: "data comparison" on "account:mail" contains "@email.com".

Actions: "Unblock a user" and "add user role"

I personally like this tutorial by node.se.


Link image to another view mode with Media 2 and File Entity

I'm not sure what you're asking. Normally you say "show title" and check "link this to content". Same thing here, Make your File view_mode whatever you want and link it to your content url. You may be asking for a Lightbox approach to showing a set of images.

If there's no option to "link to content" for this field, simply create a rewrite url in the Views Field settings to generate a link using tokens.

Now you may ask -- this isnt addressing the teaser -> full view_mode switch for the Entity (or Field?). Creating links in Views, or with the l() function has nothing todo with View Modes ... they're just links you're making.

I find it helpful to add additional view modes to entities, I have used Entity View Modes for that.

You either setup a custom URL to your content that forces the view mode, using for instance View Mode Page or you could try to set a context or something and hand code something that forces the view mode on your destination url yourself using a custom module, for a small example:

/**
 * Implementation of hook_entity_view_mode_alter().
 * Change the view mode of an entity that is being displayed.
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node' && $context['entity']->type == 'slang_word') {
    $view_mode = 'slang_dict_word';
  }
}

You could use a custom view mode to only show the Field in question -- with the custom view_mode set.

... maybe this rambling will help you or someone else :)


If anyone will be looking for similar problem:

I wrote myselft a function. It fetches all the items from menu (which we use as a hierarchy for Workbench Access) and compare them with current Workbench Access items, those that aren't there yet, get inserted. It refreshes caches and it is possible to use all the items as sections, because it's synchronized now.

For now it seems to work. I couldn't find better solution so far.

function update_possible_workbench_sections($menu_name="menu-global-packages") {

$wanted = array();
$records = db_query("SELECT mlid FROM {menu_links} WHERE menu_name=:menu_name", array( "menu_name"=>$menu_name))->fetchAll();
foreach($records as $r) {
    array_push($wanted, $r->mlid);
}

$access_scheme = db_query("SELECT * FROM {workbench_access}")->fetchAll();
$existing = array();
foreach($access_scheme as $r) {
    if( intval($wpis->access_id)>0 && $r->access_type_id==$menu_name ) {
        array_push($existing, $r->access_id);
    }
}

$missing = array_diff($wanted, $existing);
$values_to_insert = array();

foreach($missing as $item) {
    array_push($values_to_insert, array( "access_id" => $item, "access_type" => "menu", "access_scheme" => "menu",
                "access_type_id" => $menu_name ));
}

$query = db_insert("workbench_access")->fields( array('access_id', 'access_type', 'access_scheme', 'access_type_id'));

foreach($values_to_insert as $value) {
    $query->values($value);
}

$query->execute();
workbench_access_reset_tree();
module_invoke_all('workbench_access_save');
return count($values_to_insert);

}


How do you message/email the purchaser an order update?

Since Drupal Commerce is based on the Rules module, you can simple create a custom rule which watches order status and react when one is changed.

Assuming you have Rules UI enabled you can go to: admin/config/workflow/rules/reaction/import

Here is a simple Rule which you can import:

{"rules_admin_order_update" : {
    "LABEL" : "Admin order update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "commerce-order:status" ],
          "value" : [ "commerce-order-unchanged:status" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "admin@domain.dk",
          "subject" : "Update",
          "message" : "The order changed to [commerce-order:status-title]."
        }
      }
    ]
  }
}

You can then change the add more info, change parameters etc.

Hope this can get you going. :)


Views Refresh Results are Scrambled Syntax

Yes, I saw this problem recently on a Drupal 7 setup. The modules involved in my case were jQuery update + Calendar but the behaviour in views was the same. Setting jQuery update back to the default (I want to say it's 1.5, not sure) solved the issue with Views and Calendar for me.

Of course I needed jQuery 1.7 for a different purpose, so I had to change it back once the views were done and ready to be used. Not exactly ideal but it worked well enough. Everything functioned fine besides actually making changes to the views.

If you are using jQuery update give changing the jQuery version back a try.


I'm new to object oriented php. Trying to query database but not getting any results

I won't address your question specifically...because you're doing it wrong, and that should stop here :)

This is very, very bad:

db_query("SELECT * FROM tls_connect_stage_timer WHERE '".$agent."' IN ('start_processing_agent' || 'end_processing_agent')");

You should never concatenate data into an SQL string, you'll leave yourself ripe for injection attacks.  This one is even worse:

db_query("SELECT * FROM tls_active_applicants WHERE `".$searchParams."`='".$input."'");

As you're liable to injection attacks from both the field name and the argument.

If you want to use dynamic field names you should use the SelectQuery class, accessible via db_select(). E.g.

$values = array('start_processing_agent', 'end_processing_agent');
$query = db_select('tls_connect_stage_timer', 't')
  ->fields('t')
  ->condition($field_name, $values);

$rows = $query->execute()->fetchAll();

You'll need to make some changes to the above for your specific query, but that's the general idea.


The list of unapproved comments is on admin/content/comment.

Unapproved comments are the comments left from users without the permission of skipping the comment approval, which is given in admin/people/permissions.

In the site where I took this screenshot, authenticated users are allowed to skip the comment approval, which means that any user with an account is able to write a comment without it gets approved before to be visible to every user.


I suppose your list is implemented with views (if not you can easily do this), to load a view via Ajax use the following code; I supposed your view's name is VIEW_NAME and it's display machine name is block_0 and there is a contextual filter to get filter

$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'POST',
    dataType: 'json',
    data: 'view_name=VIEW_NAME&view_display_id=block_0&view_args='+filter,
    success: function(response) {
        var output = response[1].data;
        $("#filter").html(output);
    },
   error: function(data) {
        alert('An error occured!');
    }
});

The Ajax call in Drupal framework is different to the one you usually see on non-Drupal websites.


How do I add tags to Advanced Forum posts

1. If you want to create the Tag in the new topic content, you can follow as suggested by the @lixu (This method will add the tag below the body content, but you can also shift its position up-down by going at manage-field). But this method will not show the tags on the advanced forum topic list.

2. If you want to create the tag at the list of topics page, like stake-exchange but not completely like that, You need to go to views. Advanced forum provides 5 views, Go to Structures->Views->Advanced Forum topic list->Edit, to the field add new field Content: tags.
You can rearrange the position of it by rearranging option(Check second image). I have added to the last as shown in the image. What this will do, it will add one more column of Tags in the topic list page, besides the last-post column(check third image). You can shift the column of tag wherever you want, by shifting the tag filed in views.


This one is ugly on google's part. My site is https, and feedburner doesn't support SSL... I figured that out the hard way.  I didn't want to muck around with my SSL settings given that it's a wildcard cert, so I figured out a painless workaround.
1. Subscribe to your blog feed through Google reader.
2. Create a bundle folder with your blog feed.
3. Grab the bundle URL (not https, which is the workaround)
4. Paste it into feedburner.

Done, google accepts that, and gives you a branded feedburner url.

I'm sure there's a better approach, but this was an easy workaround for those with https sites.


drupal7 : db_select node with multiple values field

I've often struggled with the join methods in the D7 database layer. When I've needed to use a join, I've just used db_query() and passed it my SQL string. I know that when calling the join() method, you must already have the object initialised. So:

$query = db_select('node', 'n');
$query->join(field_data_field_date_programme_culturel', 'fdfdpc', 'fdfdpc.entity_id = n.nid');

and you already have it like this so I don't think that's the issue. I'd suggest using db_query($sql).


Trying to add an html head tag in Drupal 8, beta 2

You don't have $build in preprocess, so can't work like that. $build needs to be a render array that is rendered somewhere. I also don't see how this could have worked before, as this is already converted in template_preprocess_html() before your function runs.

Add hook_page_attachments(_alter)() and deprecate hook_page_build/alter() was just committed, and as a theme, you can implement hook_page_attachments_alter(), look for examples in the committed patch, like common_test_page_attachments_alter().

So, something like $page['#attached']['html_head'][] = [$viewport, 'viewport']; should work in there.


How do you provide conditional checkout options depending on whats in the cart?

I believe you have already set different product types to handle different kind of product.

So what you have to do is, by default disable payment methods and set them one by one in rules to make a payment option available if certain product type in in cart.

Add Event "Select available payment methods for an order"
Add Condition "Order contains products of particular product type"
Add Action "Enable payment method: (Your Payment Method)"

I have done something like this for COD(Cash on Delivery) for certain product type in certain postal codes.


Provided you have a rule that triggers when a user joins a group, and a condition that checks that the group is the group you want, then add a execute PHP action to that rule that runs this code :

// Build a new node object
$node = new StdClass();
// set the type
$node->type = 'your_content_type';
// set the language
$node->language = LANGUAGE_NONE; // or whatever language you use.
// this fills the node with the default data
node_object_prepare($node);
// set a custom title
$node->title = 'Nice title';
// set whatever you want, for example body
$node->body[LANGUAGE_NONE][0]['value'] = 'This is some text for the body';
// Set the formatting for the text
$node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
// Save the node to the DB
node_save($node);
// If you need the node ID
$nid = $node->nid;
// Just for debugging
watchdog('your_module','Just inserted the node with nid = '.$nid);

The key here is that node_object_prepare sets some default values for your content type.


The work-around that I'm currently using (because I really need to move on and accomplish other things) is to add a

drush -y vset site_name "My Site"

call to the bash script that I'm using to create the mysql database and run the installation. Not an elegant solution, (and it bypasses localization, but that's not an issue yet, since the site is currently in only one language), but it gets the job done for now so that I can get other things working.

Leaving this here in case it helps someone, but not "accepting" it, since it's a work-around, not an answer.


Drupal module versioning and compatiblity. How to know what to use?

Unfortunately, there are no rules.
"Recommended" is just a flag set by the maintainer meaning "I think this is my most stable branch".
Alpha and beta are also just labels, in the Drupal world beta often means "Works for me, but I don't want to create a full release yet."

You'd usually want to use a recommended release, if it's not too old (if it's a year old, yesterday's -dev will probably be better).
Sometimes the -dev release is the most stable version of the code, if the maintainer doesn't create releases regularly.

When I have a dilemma such as yours (which version of dependency X should I use for module Y), I open an issue in the Y issue queue and ask. The maintainer knows best which code he optimized for.


how to make radio buttons be one under the other on drupal contact form

add this to each of the select button wrapper display: block; also it's not a drupal issue, you should ask these kind of question on stackoverflow


Does module_invoke() work for non core modules?

You are probably looking for module_invoke_all. The module_invoke function only invokes a module in a specific module (casrel.module in your example).

By the way, you usually do not need to invoke hook_nodeapi yourself. The node module invokes hook_nodeapi when necessary, if you just use the api functions (like node_view) correctly. If you need to alter a node before it's viewed, you need to implement hook_nodeapi instead of invoking it.


The correct way for a reference field is to set the property target_id:

$term->parent = ['target_id' => '2'];

All this shorter versions work too:

$term->parent = ['2'];
$term->parent = '2';
$term->parent = 2;

Also works like this:

$term->set('parent', ['target_id' => 2]);
$term->set('parent', 2);


How to export translated variables settings in code?

Update: With recent version of the Variable translation module (ie. 7.x-1.7), the list of translated variables is stored by the language variable realm controller in its list variable. The following code demonstrate how to use the realm controller to set translated variables from a module hook_enable() implementation.

function MODULE_enable() {
  // Get the language variable controller.
  $controller = variable_realm_controller('language');
  // The list of translatable variables.
  $translatable_variables = $controller->getEnabledVariables();
  // The list of variables that could be translated.
  $available_variables = $controller->getAvailableVariables();
  // Add our variables to $translatable_variables.
  foreach ($available_variables as $name) {
    // Translate user mail messages.
    if (preg_match('/^user_mail_[a-zA-Z_\[\]]*\[mail_part\]$/', $name)) {
      $translatable_variables[] = $name;
    }
  }
  $translatable_variables = array_merge($translatable_variables, array(
    'user_registration_help',
    'user_picture_guidelines',
    'maintenance_mode_message',
    'menu_main_links_source',
    'menu_secondary_links_source',
  ));
  // Save the updated list of translatable variables.
  $controller->setRealmVariable('list', array_unique($translatable_variables));
}

Update: This is not the way to do it, unless you are using an old version of Variable translation module (< 7.x-1.7)

The names of the translated variables are stored in the i18n_variable_conf variable. This variable itself cannot be exported using Strongarm (or similar solution). I ended using an old trick: checking the variable in a hook_init implementation and setting it if needed. The array in the foreach controller contains the names of the variables to be translated.

/**
 * Implements hook_init();
 */
function MODULE_init() {
  $i18n_variable_conf = variable_get('i18n_variable_conf', array());
  $i18n_variable_conf_updated = FALSE;
  foreach(array(...) as $name) {
    if (!in_array($name, $i18n_variable_conf)) {
      $i18n_variable_conf[] = $name;
      $i18n_variable_conf_updated = TRUE;
    }
  }
  if ($i18n_variable_conf_updated) {
    variable_set('i18n_variable_conf', $i18n_variable_conf);
    variable_set('i18n_variable_list', variable_children($i18n_variable_conf));
    cache_clear_all('*', I18N_VARIABLE_CACHE, TRUE);
  }
}

Compared to a feature based solution, this enforce the settings for the configured variables and will cancel any manual edit. This may wanted or not wanted. In my case it was.

My only issue with this solution, is that it had some overhead to each request.


Serving Drupal from within a sub-directory of my web root

You have to edit the nginx virtual host file of your website.
You'll usually find it at /etc/nginx/sites-available/yoursitename.vhost.

Open it with write permissions, and edit root directive at the top of server block as following:

server {
    listen x.x.x.x:yyyy; #IP:port
    server_name www.example.com;
    root /var/www/html/web/drupal;

Save the file and reload nginx conf : sudo systemctl reload nginx.service


Alter submitted by text and retain RDF tags

The function that returns the content of that tag is date_iso8601().
To understand how those tags are output, you should look at rdf_preprocess_node() and rdf_process().


The Group module provides Views 'relationships' to any node's parent group.

Try these steps to create your view:

Add a relationship to the parent group.
Add a contextual filter on the group's id (gid).
Create a page, a block, a content pane, etc (whatever fits your needs).


Taxonomy term not displayed in the current language

The language of the parent entity is passed to entity formatters and they respect that when displaying referenced entities.

If you want to override that, you can for example provide your own entity formatter plugin that overriddes \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView() and ignores the passed in $langcode. There is no configuration for that.

Since you probably want the entity label to be displayed, you should subclass \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter.

Alternatively, you can also do something in preprocess/twig.


How to add separator option in Form API 'select' element?

If it's really a separator you're looking to add then it might make more semantic sense to use <optgroup>s to group your select options.

You can do this with the form API simply by wrapping each group you want in the <select> in an array, keyed by the title you want for the label:

$form['test'] = array(
  '#type' => 'select',
  '#title' => 'test',
  '#weight' => -10000,
  '#options' => array(
    'Group 1' => array(
      1 => 'Group 1 Item 1'
    ),
    'Group 2' => array(
      2 => 'Group 2 Item 1',
      3 => 'Group 2 Item 2'
    )
  )
);

That will produce a select list like this:


CKeditor to search images on PC instead of server

This is one way to do this:

Install IMCE
Go to Configuration > Content authoring > CKEditor. Click edit for the Full profile
Expand the File browser fieldset. Select IMCE in the dropdown menu under File browser type. Save.

Then, when you click the Browser Server button, you will see the following window. Notice the Upload button. Clicking it will allow the user to select a file from their computer.


Can we create a core PHP file inside the files folder?

Files under that folder are writable by the web server. You could argue that makes it a security risk, but your server would already have to have been compromised in one way or another for it to become so. If your server is configured properly it will only execute PHP files, not serve them for plain-text download.

From the point of view of convention, though, you shouldn't do this. Putting code files all over the file structure makes maintainability infinitely harder.


Block body translation for Full HTML content

Found it,
http://drupal.org/node/1298440#comment-5127390

  In case anyone else has trouble finding this setting, it's at
  Configuration > Regional & Language > Multilingual Settings > Strings

  (admin/config/regional/i18n/strings)


create bilingual language site with drupal 6

You must use the t function on all text if you want translate it directly throw the admin panel.


How to unsubscribe from issues on drupal.org to not see the updates in my dashboard?

You can unfollow the post by clicking on following.


I believe the default variable for the author is $name. So you could perform a simple if statement in the template:

if (isset ($name)) {
print $name;
}

That will check if the $name variable is set - and if it is, print it out. If it's not set, nothing will happen.


How can i use main-menu items as a fields in selectbox in drupal 7

First, create a view that references the nodes you want - e.g. that have a parent item with node id x (or whatever the criteria is for those nodes). Get that view right, and the rest is easy.

Upload and enable either the references, or the entity reference module http://drupal.org/project/entityreference or http://drupal.org/project/references

In your content type, choose a node reference item and select widget. You can base the option list on your view.


If your settings.php file is at /usr/share/nginx/www/drupal-7.16/sites/default/settings.php, then you should change your 'root' line as follows:

'root' => '/usr/share/nginx/www/drupal-7.16',

The way you have it, Drush is expecting that your Drupal root is at /usr/share/nginx/www/drupal-7.16/sites, which is to say that it is also expecting to find your settings.php file at /usr/share/nginx/www/drupal-7.16/sites/sites/default/settings.php. Take out the extra 'sites' as shown above, and it should work fine.


In Drupal 7, how can I include a CSS file only when the front page is being viewed?

Try this:

function mytheme_preprocess_page (&$variables)
{
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
  }
}

See template_preprocess_page and drupal_is_front_page for more info.


drupal webservice error Access denied for user anonymous

This most likely has to do with permissions for anonymous user. Try updating permissions and it should solve your issue.


What is significance of confirmation page before deleting a node?

This is no t exactly Drupal specific, but I'll answer them anyway because one could miss a few reasons. Correct me if I'm missing any.

It prevents accidentally clicking the delete button and actually deleting it.
It provides security against CSRF attacks. If the node is deleted as soon as the node/xyz/delete page is loaded, an attacker can make an administrator open that URL, and the node will be deleted without his intention.

Because the specifications say so. http://www.rfc-base.org/txt/rfc-2616.txt     GET requests should not make any change in data, so the request must be either a POST or a DELETE. Since Drupal forms only support GET and POST, we use the latter.


ubercart zip/postal code reformatting in views using php

for anybody interested - this is the working code

 return chunk_split($data->uc_orders_delivery_postal_code, 3, ' ');


You can create as many alternate date formats as you like. See this page for help: https://www.drupal.org/node/1600786


Twig Translation String without Enabling Interface Translation

Our solution in the end was to create a new Twig extension called tr.

The class of the extension plugin checks to see if a 'translations' directory exists in the current theme. If it does, it reads the containing YAML translation files into an associative array (en.yml, es.yml, fr.yml etc.)

When {{ tr('source string') }} is called in the twig template, it will check the loaded associative arrays to see if there is a translation available for the current language and requested string. If there is it will return the translated value.

This works for us since in our case we're only translating a fairly short list of values - short strings and labels like 'Read More', 'Learn More', 'Subscribe' etc. The rest of our translated content comes from the content translation of the entities.

Hope this helps...


Site Access control through a particular user field

Let's say there is a specific path you want this rule to apply to, e.g. /special

<?php

function my_module_menu()
{

    $items['special'] = array(
        'title' => 'Special Page',
        'page callback' => 'special_page',
        // Permission in next line will be overridden by the check inside the page callback function.
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
        );
}

function special_page()
{
    global $user;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user');
    $query->propertyCondition('uid', $user->uid, '=');
    $query->fieldCondition('field_special_field', 'value', 'required_value', '=');
    $query->range(0, 1);
    $result = $query->execute();

    if (isset($result['user'])) {
        // User meets the condition
        // Do whatsoever, show special content ..

    } else {
        // Deny access
        drupal_access_denied();

    }
}

?>

Make sure to download and enable the Entity API module to use the above code.


Parsing the 'q' in drupal to get the current URL

I'm not sure why your code happens to fail in some cases, and in some cases not. But what I would try is replacing that code with the provided by Drupal arg function.

On "team/surf", arg(0) will return "team", and arg(1) "surf". This is what I use myself, and hopefully that will solve the problem for you.


Disable user registration in /user/register, but allow registration during commerce checkout?

You can do that with hook_menu_alter() by changing the access for that path:

function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = FALSE;
}


you create a filter for "Content: Has taxonomy term" and then select "Is empty (NULL)" as the operator.


There is an default view called statuses_all/facebook_status_all(D6) in statuses/facebook_status(D6) module itself, You can use that one.

When you're enabling FBSMP module it will automatically add FBSMP themed attachment field to all the default views of Statuses/facebook_status(D6). So that view will list down all the statuses with media(If its available.)


Problem with i18n_string + features + sites with different default language

My solution:

Do not enable i18nviews.
Create all views with English strings.
Use the core translation system to translate all those strings.
Optionally, use features_translations to export translations.

I do not claim that this solution works for all cases where i18n_string assumed source language causes trouble. But in this case it seems to be sufficient.


Using arguments in addConstraint() for validation

Options needs to be an array I think. You can access it on the constraint object in your validator, see ListStringItem::propertyDefinitions() and LengthValidator, which then uses it as $constraint->max.
Base fields are exactly that. Base fields. There is no bundle, they are the same for all bundles of an entity type (they can be overriden per-bundle, but then they become accessible in the bundle hook).
You shouldn't ask two different questions together :)


Where are the "local files" for the Localization Update module stored?

On the bottom of the module's configuration page you have to set a path for the local files.

  Store downloaded files A path relative to the Drupal installation directory where translation files will be stored, e.g.
  sites/all/translations. Saved translation files can be reused by other
  installations. If left empty the downloaded translation will not be
  saved.


How to get a certain header on FunctionalJavascript tests

I was getting all wrong. This is the key, copied from https://www.drupal.org/node/2857562

  All assertions within these tests must be done by checking the UI. Assertions that don't relate to UI should be added to other types of tests, a BrowserTestBase for example.

I should break this test in two one Functional to check proper header setting and the other pure FunctionalJavascript to check the element (whereas the token is set or not) is present on the page. Also does not make sense in this specific case to have two Webprofiler bars present on the page so a simple document.querySelector('[id^="sfToolbarMainContent-"]') should do the trick.


It is incredibly easy. Use BOOK content type. Just need to enable Books in core modules. If you already have lots of existing content (to much to copy/paste into book pages), you could add a field for Node Reference and link the pages that way.  Book has all that "pagination" functionality -- as well as local menu/index -- built in. Great solution if you aren't too far along.  At the very least, enable Book module and do a sample to demo for client -- to help you conceive the exact behavior that you want.

By the way, that approach is independent of your WYSIWYG (CKEditor).


Different page--user.html.twig for different user roles

It's not much different from how it got solved in the other question you asked. You just have to target page this time. So hook_theme_suggestions_HOOK_alter() becomes hook_theme_suggestions_page_alter().

And you need to check if you are currently on a user page before you add the suggestion.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_match = \Drupal::routeMatch();

  // Check if on user page.
  if ($route_match->getRouteName() == 'entity.user.canonical') {

    // Get current user
    $current_user = $route_match->getParameter('user');
    if ($current_user instanceof \Drupal\user\entity\User) {

      // Get user roles.
      $roles = $current_user->getRoles();
      foreach ($roles as $role) {

        // Add template suggestion per role.
        $suggestions[] = 'page__user__' . $role;
      }
    }
  }
}

Alternatively, if you want the suggestion to be added only for a certain role, try that:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_match = \Drupal::routeMatch();

  // Check if on user page.
  if ($route_match->getRouteName() == 'entity.user.canonical') {

    // Get current user
    $current_user = $route_match->getParameter('user');
    if ($current_user instanceof \Drupal\user\entity\User) {

      // Add template suggestion for certain role.
      $role = 'somerole';
      if ($current_user->hasRole($role)) {
        $suggestions[] = 'page__user__' . $role;
      }
    }
  }
}


security kit module settings are blocking own site jQuery calls

If this code inline, then try with this:

'unsafe-inline'

Allows the use of inline resources, such as inline  elements, javascript: URLs, inline event handlers, and inline  elements. You must include the single quotes.

'unsafe-eval'

Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes.

Howewer, the proper way to set up this module you can find  this.


Views filter: how to compare two fields?

Not sure you are going to use it, but for those who may get here looking for the same:

Under the Filter Criteria, Search for "Globals: Fields Comparison".
For the record, the fields you want to compare should be among the fields you are loading in the current View.

So, if you want to compare to something you are not willing to show, you should add the fields to the View and check the Exclude from display.

Hope it helps!


How to store Ajax Return value into variable after clicking the Submit button

You need to move the $form['city'] form input creation into your form_test_form function otherwise it's considered tampering with the form, so the values will get taken out.

function form_test_form($form,&$form_submit) {
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If there's a "State" value set, then we create the City dropdown
  if (isset($form_state['values']['state1']) && !empty($form_state['values']['state1'])) {
    $form['city_element_wrapper']['city'] = array(
      '#type' => 'select',
      '#title' => t('District'),
      '#options' => $options_city,
      '#required' => TRUE,
    );
  }

  return $form;
}

Now the callback becomes a simple return of the relevant element:

function _ajaxfunction($form, $form_state) {
  return $form['city_element_wrapper'];
}

Finally check the values of $form_state['values'] in your submit handler:

function form_test_custom_form_submit($form, $form_state){
  var_dump($form_state['values']);
  die();
}


That function is just a wrapper for this function:
https://api.drupal.org/api/views/views.module/function/views_set_current_view/7.x-3.x
which will just return a reference to a static code cache.

Conclusion: no view gets run, it's just grabbing a copy of what's already been created.

In general, views is very efficient in such cases.

But I'd tend to agree with @berramou that you might have a better way of accomplishing what you really, really want.


How to process more than one item from queue in each run?

The queue system is designed to process items until the time is up. Maybe it's a bug in Ultime Cron? Try running the default core cron.php to verify that.

Are you sure that you're actually adding multiple items to be processed? Check
your queue table.


Open Atrium 2: comment forms not appearing on pages

I believe you need to add the comment box via panels. Admin > Configuration > Content Authoring > Panelizer > Content [link to the right of Your Content Type]


Well, normally the webform provides you the facility to edit the submit button form text at

Go to webform->form settings->Submit button text

Or either way you can use the string override module

Hope it may help you!


Giving custom argument value in 'q' variable

Your question seem a little bit unclear to me. But my understanding is that you are having problems with theme template.

You should try it out using the node in your url. There is an example...

If you had the following path:

/node/99/edit

PHPtemplate looks for the following templates, in descending order:

page-node-edit.tpl.php
page-node-99.tpl.php
page-node.tpl.php
page.tpl.php


Correct way to disable /node in Drupal 7?

You can probably use this code with your custom module:

function hook_menu_alter(&$items) {
 $items['node']['access callback'] = FALSE;
}

Note: If you want specific people to access this page, you can set "access arguments" declared with hook_permission


In your node--contenttype.tpl.php you can add a div (optionally with a textbox) which is hidden by default and fill it dynamically with the title and content of your node. Create a button that uses the colorbox module to show that div when pressed and your done.

  <textarea>

<?php echo $node->title;?>

      etc..

  </textarea>

Alternatively you could just use javascript to copy the content of your page to a div when the button is pressed.


Progress bar advances, operations does nothing

Try below code

$operations = array();
foreach ($result as $row) {
  $operations[] = array('batch_create_user', array($row));
}

$batch = array(
  'title' => t('Importing users ...'),
  'operations' => $operations,
  'init_message' => t('Commencing'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('An error occurred during processing'),
  'finished' => 'batch_import_users_finished',
  'file' => drupal_get_path('module', 'user') . '/' . 'user.inc',
);

Also add path to redirect after batch process

batch_process();


How do I add column to existing table on module installation?

For the sake of giving a (hopefully) complete answer:

You will need to alter the schema of an existing module, signalling the change to the system. So implement hook_schema_alter().
You will need to implement hook_install() to actually add the field to the database.
You will need to implement hook_uninstall() as well, to remove the extra field when the module is uninstalled. You might need to do extra cleanup at this stage.

An example which alters the Webform module's webform_submitted_data table:

function MYMODULE_schema_alter(&$schema) {
  $schema['webform_submitted_data']['fields']['extra'] = array(
    'description' => 'Some random extra info.',
    'type' => 'text',
    'size' => 'big',
  );
}

function MYMODULE_install() {
  db_add_field('webform_submitted_data', 'extra', array(
    'description' => 'Some random extra info.',
    'type' => 'text',
    'size' => 'big',
  ));
}

function MYMODULE_uninstall() {
  db_drop_field('webform_submitted_data', 'extra');
}


db_update without table prefix on custom table

In your settings.php file where you have prefix set in the $databases array. Change this

'prefix' => 'drupal_',

to this

'prefix' => array(
  'default' => 'drupal_',
  'my_table' => '',
),

If you want a more wildcard like way to do this you can set the target. So lets say this is what your $databases array looks like inside settings.php

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
  ),
);

Change it to this, where everything is the same except the prefix is empty.

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
    'noprefix' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Then in your function call do this

$key_cached_update = db_update('my_table', array('target' => 'noprefix'))
  ->fields(array('key_cached' => $apikeyinfo->result->key['expires'],))
  ->condition('keyid', $row->keyid, '>=')
  ->execute();


How to set percent discount by old and new price

There isn't really enough information here to diagnose your issue, but the likely problem is a mismatch between the data type required by your custom field and the data type of your calculated value. Since you didn't specify the type of field you used to create your custom field, I can't say for certain, but Rules will only allow you to set it to a valid value for the field type.

At the very least, it doesn't appear to be anything to do with Commerce or Rules themselves.


How can I display a WebForm in a Modal Window

Use modal form module to load into modal window. Create link using modules custom method after check user is loggedin.

$links[] = ctools_modal_text_button(t('webform'), 'modal_forms/nojs/webform-path', t('Webform via modal'),  'ctools-modal-modal-popup-small');


How to render HTML output in hook_ENTITY_TYPE_presave()

In hooks which are not executed in a render context use renderPlain(), see Cron error: LogicException : Render context is empty

$html = \Drupal::service('renderer')->renderPlain($processedResult);

Caveat: Text filters can bubble up metadata which you ignore by storing only the HTML. For a custom text filter this might be OK when you know it doesn't depend on cache metadata and attachments, but don't use this as a general approach. This can have security implications, like revealing data to non-authorized users.


How to skip first row in a dynamic query?

You could do something like this:

// Begin query build
$query = db_select('node');
$query->fields('node', array('nid', 'title'));
$query->condition('type', 'article');
$query->condition('uid', 1);

// Get total count for query
$count = $query->countQuery()->execute()->fetchField();

// Execute range query
$start = 1;
$query->range($start, ($count - $start));
$result = $query->execute();


I personally use preprocess functions to do this, something like the following:

function HOOK_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'VIEW_NAME' && $vars['view']->row_index == 1) {
    // Do stuff here.
  }
}


Phone international error in submit form

The error suggests that you haven't followed the installation instructions on the module page:

Since the module requires an external library, Composer must be used.
composer require "drupal/phone_international"


Should have used user, instead of @user.current_user_context:current_user.


How to remove default 'search' text form search form

The Search text in input is created by jQuery from any where. When I search through the JavaScript files, I find the following file:

file : /sites/default/modules/hg/sw_tweaks/js/sw_tweaks.js

The code

//Search Bar @ Top of Home Page
    $(function () {
      $('#edit-search-block-form--2').val("search");
    });
    jQuery('#edit-search-block-form--2').click(function () {
      jQuery('#edit-search-block-form--2').val('');
    });

Try to remove this code.
I hope this helps you or help you finding the problem.


Why is form api ignoring the weight that i'm giving to the action buttons? (node edit page)

I added a cancel button to some Drupal 6 node forms in this fashion:

  $form['buttons']['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#weight' => 7,
    '#submit' => array('MYMODULE_node_form_cancel_submit'),
  );

so I'd suggest changing 'actions' to 'buttons' and see if it works equally well for you.


If you have Tokens module enabled and also if you have a lot of fields, then it'll take a lot of time for the token ui to load up. This was the problem in my site. It took me a long time to figure this out. If there is a performance hit, only when you try to edit or create a content type then it might be caused by the tokens module. It's worth checking it out.


What does the array_filter key in $form do?

Nice catch! It does nothing. You can safely remove it. Looks like some kind of forgotten relict.
Ah, yeah. The same pattern can be found in core's book module: BookSettingsForm.php.
And there is a 12(!) years old open issue to have it removed. [#315176] Clean-up remains of $form['array_filter'] hack with array_filter in book module


This is expected behavior.

The "Text Format" Select List affects the way drupal parses and displays the data after it has been saved and is being displayed to the end user; not the way it is saved nor the way it is displayed on the Node Edit form.

By default:

Given Input:

Title

  <?php echo 'bar'; ?>

"PHP Code" filter output

Title

  bar

"Full HTML" filter output

Title

"Filtered HTML" filter output

Title


3-rd decimal digit has disappeared in the output

If you type of "Coefficient" is float, you can change scale in display options for your Content Type. (admin/structure/types/YOUR_CT/manage/display). By default it's 2.


output same form buttone on same page - drupal_render($form

From the top of my head, I would just duplicate the button in hook_form_alter() and render it as two separate buttons.

Some code examples here:
https://www.drupal.org/node/1415334

And here:
How to add extra save buttons


How to get a separate form_id for each of the taxonomy/term/%term exposed form?

Without patching the module you can't...but the View object is always available in the form state, so you can use that to check where you are. e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'foo' && $view->current_display == 'bar') {
      // ...
    }
  }
}


create a new template file and add any classes you want. Here's a good introduction to D7 templates.

your template should be named like this: node--node_type.tpl.php. In your case, I think it should be node--pdf.tpl.php. You can use node.tpl.php as a starting point


Hook for the "Welcome (awaiting approval)" email

I have used the Maillog / Mail Developer module to debug things such as your question.

To find the message ID, simply use code similar to the following one:

function YOURMODULE_mail_alter(&$message) {
  dpm($message['id']); // Assuming Devel module is installed.
  // Or just ...
  print $message['id']; exit;
}

Hooks are run for every module they are declared in; if you don't know the message id, simply create the hook and output the message id it finds. (Exiting might actually be a bad idea if your sending many types of messages—you didn't state that—because then the code might stop short of the exact message ID you're searching for.) Since the hook is declared, it will run for each outgoing message.

To access the user's 2 profile fields, they are just fields as long as you have a user object you can access them:

function MYMODULE_mail_alter(&$message) {
  global $user; // Get's a reference to the logged in user.
  if ($message['id'] == 'welcome_message_approval') {
    $message['body'][] = t("Your Firm's ID is: @firm", array('@firm' => $user->firm);
  }
}

To easily access fields I recommend the Field data extraction module.

I believe the Profile2 module should "eagerly" load the profile fields. If they are not in the global user object because of lazy loading, then you should be able to get at them by calling field_attach_load().


D8: Cannot redirect user at onKernelRequest event

Instead of sending the response yourself you can try to use the method setResponse() of $event:

$event->setResponse($response);


Drupal 8 - Variables - Template Twig - Cache

In your question, it wasn't clear how you are defining the render array (a block, a form, etc.) Assuming you are rendering this twig file through a render array, you could add the following to the render array for this particular element to turn off caching of this element:

 '#cache' => [
    'max-age' => 0,
  ],

You could get more specific by implementing conditional logic to clear the cache on a certain condition. From the examples module, in the cache_example, we have the CacheExampleForm function createExpiringItem():

/**
* Submit handler to create a new cache item with specified expiration.
*/
public function createExpiringItem($form, &$form_state) {

$tags = array(
  'cache_example:1',
);

$interval = $form_state->getValue('expiration');
if ($interval == 'never_remove') {
  $expiration = CacheBackendInterface::CACHE_PERMANENT;
  $expiration_friendly = $this->t('Never expires');
}
else {
  $expiration = time() + $interval;
  $expiration_friendly = format_date($expiration);
}
// Set the expiration to the actual Unix timestamp of the end of the
// required interval. Also add a tag to it to be able to clear caches more
// precise.
$this->cacheBackend->set('cache_example_expiring_item', $expiration_friendly, $expiration, $tags);
drupal_set_message($this->t('cache_example_expiring_item was set to expire at %time', array('%time' => $expiration_friendly)));
}

And, also shown in the examples is invalidating:

$tags = array(
  'cache_example:1',
);
Cache::invalidateTags($tags);

So in your preprocess, you could use this type of logic to invalidate the cache. Hope this helps.


Cache contexts cannot be invalidated.

Cache tags describe data dependencies. Data can change. When data changes, the associated cache tag(s) are invalidated, causing the cached results to get invalidated and then recomputed.

Cache contexts describe context dependencies, which means they describe variations. It's very much like HTTP's Vary header. Cache contexts usually describe input from the request (such as the URL or parts thereof, the requestor's IP address, the associated user, the associated session, or even the matched route), but could also describe some global state such as which day of the week.

You could create a custom cache context for your use case, but it'd be the combination of the url.query_args:whitelabel (assuming ?whitelabel=foo is what you meant) and session cache contexts. But it'd be much simpler to instead just associate those two existing cache contexts!

(Note that using the session cache context makes things extremely uncacheable, because it causes a unique variation per session!)