Programmatically import users and create each for them organic groups

Your explanation seems a little bit confused. Creation of an OG is as simply as creating a node.

So from what I understood you wish :

Get a user data from external source (how you perform this ? by cron ?)
Create a group for each user
Assign that user as group admin ?

Is it what you want to perform ?

Also take a look here :

http://drupalcontrib.org/api/drupal/contributions%21og%21og.module/7


I suspect the problem is that this hook can't be implemented in a template

Correct :)

Only hook_theme(), preprocess hooks, and alter hooks can be implemented in template.php. For any others, including this one, you'll need to write a custom module.


The problem was that the mongodb block module disabled the normal block module. When I re enabled the block module, and disabled the mongodb block module, it worked fine.


Deleting a cloned node erases all paragraphs

Paragraph in 8.x integrates with the replicate project only at the moment: https://www.drupal.org/project/replicate

If you use that, cloning a node will also create clones of the used paragraphs.


Using References module, is it possible to only show nodes created by the logged in user in select list?

You can try making a views which return the list of all node title created by the user & then use View reference module to have field calling that.


$is_front is not available in all templates

You almost answered the question yourself, you can add the variable to all templates with this code:

function theme_preprocess(&$variables, $hook) {
  try {
    $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  }
  catch (Exception $e) {
    $variables['is_front'] = FALSE;
  }
  // Ensure the cache varies correctly (new in Drupal 8.3).
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

For performance reason you can make a condition on $hook to only add the variable to the templates you need, and to avoid that the code is run twice for page.

Edit:

New in Drupal 8.3: Cache context for determining the Front Page


Using Backup and Migrate Module to download windows compatible backup

There's a couple steps you still need to do:

To "untar" the tar ball on Windows, you just need the right software for it. An easy to use and free software that supports TONS of compression types is 7-Zip -- http://www.filehippo.com/download_7-zip_64.
Once you have all the files available to you, you'll need to import the database into MySQL. Luckily WampServer comes with phpMyAdmin. You can find a link to it in the tray icon for WampServer. First create your database, then use the Import tab to load in the SQL file.
Modify the settings.php file to match the database database connection information for your local MySQL installation. The default installation of Drupal creates this file is at /sites/default/settings.php.
Then visit http:// my-local-host/ (or http:// my-local-host/[my-drupal-subdirectory]/) to see if it's working. (Replace "my-local-host" with "localhost" since StackExchange doesn't like "localhost" in a link).


Entity reference to user doesn't work without 'administer users' permission

You could try creating an entityreference display in views which, with the 'access' options defined in views, handle user access however you please.

Here is an example view display to get you started:
https://gist.github.com/acao/7297342

Just configure the field settings to use this view instead of the default handler, and see if that gets you around your problem!


How should I structure a multiple-value Field Collection where each value is uniquely named?

You could simply add an additional field called "Location or Type" to the field collection with the various options. Then you can use that field in a view block to filter by, or even more simply in your node.tpl.php file.


Where are the Page Manager "Caching options"?

Although the language is german in this screenshot, location of the menu/options should be the same.


How to iterate multi dimensional array and pipe each sub array to another plugin as input in Migration yml

There's no such process plugin in core or migrate_plus. If you can't find what you need in those lists, you'll probably have to write a custom solution. You may want to check out SubProcess process plugin which may be able to work with your decoded array with minimal changes.


D7: Empty image upload field when adding a translation

Figured it out after spending about a whole day of trying in the wrong hook.

Turns out you need the hook_field_widget_form_alter for this.

/**
 * Implements hook_field_widget_form_alter();
 */
function my_module_field_widget_form_alter(&$element, &$form_state, &$context) {
  $field_name = isset($element[0]['#field_name']) ? $element[0]['#field_name'] : NULL;
  if ($field_name === 'field_series_image') {
    if (strpos($form_state['complete form']['#action'], '/edit/add/') > 0) {
      // Works for single image fields (product display).
      $element[0]['#default_value']['fid'] = 0;

      // In case we have more images uploaded, unset all.
      for ($index = $element['#file_upload_delta']; $index > 0; $index--) {
        unset($element[$index]);
      }

      // Also reset the upload delta to 0.
      $element['#file_upload_delta'] = 0;
    }
  }
}

Code above suits our needs.


You can use this patch http://drupal.org/node/1529708#comment-6633022
If you need something more specific you can use hook_site_map() to add things to your sitemap and take a look at the _site_map_menus() function.


Form submission in modal is throwing an error

Ok, after a a few hours tinkering and extensive googling, i sadly found the answer i was looking for (but not hoping for).

How to open a popup form from a view link?

Turns out, in D8 this is impossible.


Drupal 7, displaying an image to search results

This is a core issue. See http://drupal.org/node/1166114.

Workaround is to add this to your theme's template.php. Also copy search-result.tpl.php from the core search module into your theme folder and clear cache.

function YOURTHEME_preprocess_search_result(&$variables) {
  $result = $variables['result'];
  if (isset($result['node'])) {
    $variables['snippet'] = $result['node']->rendered;
  }
}

The rendered node will pick up the Manage Display settings.


Required field not being shown on password reset page

Fields setup in the Account profiles only appear on the creation/edit forms for users and not the password reset form.

If you have existing users and just recently added the field, you could set the field for your existing user base with Views Bulk Operations; otherwise they won't be able to edit their accounts/reset passwords until the field has been assigned a value on their user account profiles.

This is also true of content types/nodes, when you add a new field with a default value- the default value will only appear for new nodes and not existing ones; likewise any required fields will prevent edits to the existing content until they are populated.


unset the path for the library used by FullCalendar

When you update a module what ever changes you have done would automatically be over written. if you have just made changes to js then it would be better to add that JS to your theme rather than the module itself.

You could you the hook_js_alter (On Drupal 7) or jsalter (On Drupal 6) in yout theme to remove the module specific js.


"Manage display" tab missing in Manage fields window

The tab might just be somewhere else. When you edit a content type, you see at least two tabs (provided that the core "Field UI" module is enabled):

Manage Fields
Manage Display

If you go to "Manage Fields" and then click on "Edit" for a given field, you will see the "Field Settings", "Widget type" and "Delete" tabs, as you say, but not the "Manage Display" tab. To see it, you need to go to the content type edit screen, it will display the list of fields and their display properties.

Hope that helps,


How to add JavaScript to a specific View if I don't know the node?

Check out hook_views_pre_render https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7.x-3.x
That provides a view object where you could retrieve the machine name of your view and add your drupal_add_js when its the relevant view being loaded


How can I have multiple caches of the same page with different query arguments?

You have to add a cache context for the query parameter version to the page:

function THEME_preprocess_page(&$variables) {

  $variables['#cache']['contexts'][] = 'url.query_args:version';

}

The context will then be used to vary the cached pages by this query argument.


How do I redirect users after they submit a form?

You're getting that error because fromRoute() takes the route name as the argument, not a literal path.

Assuming you know the node id you want to redirect to:

$url = Url::fromRoute('entity.node.canonical', array('node' => $node_id));

You don't ever want to redirect to internal paths like that (in your question) because they are subject to change.


It turns out that all of this information was already available, and I just had to work within mytheme_preprocess_item_list__search_results. I had the Node objects for all the nodes that matched, and so I was able to reconstruct the render array exactly the way I wanted.


commerce feeds product import not showing up

Yesterday on #drupal-commerce in IRC, someone had a similar question. It appears that the "title" module may be interfering with commerce_feeds. Try disabling the "title" module and see if that helps your import woes.


Use the following code:

/**
 * Implements hook_preprocess_region().
 */
function YOURTHEME_preprocess_region(&$vars) {
  // Make sure we are on a single node page
  // This code will allow you to add the following templates for regions:
  // region--node-NID.tpl.php
  // You can update the conditions to anything you want and rename the template
  // suggestions.
  if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
    $vars['theme_hook_suggestions'][] = 'region__node_' . arg(1);
  }
}


Get webform submissions filtered by data value

The $filters parameter on webform_get_submissions() can be used for field filtering. The function's code loops over the filters and adds them as conditions.

foreach ($filters as $column => $value) {
  $pager_query->condition($column, $value);
}

So something like:

$old_form_submission = webform_get_submissions(array('email_field_name'=> $provided_email));


Programmatically set property based on other properties in a custom entity

For a custom entity type, you can override EntityStorage::doPreSave() in your entity class:

function doPreSave(EntityInterface $entity) {
  parent::doPreSave();

  // Perform field manipulation here.

  return $entity->id();
}


Facing this error while Acquia Drupal set up

Not much info so this is a bit of a guess...

Acquia support PHP versions:

  5.3.29, 5.4.45, 5.5.30 (default), 5.6.14, 7.0.0 RC2

The error message you're seeing suggests short array syntax isn't understood by the version of PHP that's running, which in turn suggests you're running the 5.3.29 option.

Short array syntax was added in PHP5.4, so in theory to fix you just need to install the software with that version instead of 5.3.


How to display the survey results created with the Webform module?

If you want to create charts from the survey results of the Webform module, there are 2 alternatives to pick from:

Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).


Updating Drush to newer version on Drupalpro VM Virtual Machine Instance

Using a fresh setup of Drupal Pro VM image, all you have to do is just goto the drush directory and do a git pull from there to pull in the latest code from drush's repo. This is what i did:

cd ~/drush

git pull

git checkout 7.x-5.9

You can load up another drush version by just listing out the ones available by doing a git tag


It seems that the path your using is "admin/config/people/accomplishments"
Make sure that the users that need to have access to this menu item have sufficient permissions in administering people or use another path

Last make sure you flushed the drupal caches so the changes are applied. Drupal only calculates the menu items once and then it caches them


Module for Importing and exporting Vcards

You can check the vCard module. It can be useful for you.

Here is a quote about it (from the module's project page):

  ... adds a vCard download link to every users profile. This link makes it easy to add users on your Drupal site to your local address book. Since we love microformats, there is also a theme function (theme_vcard) for displaying user data in the hCard format.


Can I include other template into template?

You can get another drupal theme path with drupal_get_path('theme', 'theme_name'); and finally

<?php
     include(drupal_get_path('theme', 'theme_name').'/example-file-template.tpl.php');
?>


How to force users to choose a forum when creating new thread?

Bit late, but someone else might find this useful.

My method was to use my theme template.php in D7 to modify the form:

Add an entry to the list of forums (I only had a simple, non-hierachical list) e.g.    $form['taxonomy_forums']['und']['#options']['0'] = '-choose a forum-';
Add a validation function to the form. $form['#validate'][] = 'cirqasupport_validate_forum_area';
In the validation function test the 'tid' being returned and if it was zero return an error on the forum field.

For example, add the following to template.php for your theme (or it could be done in a new module instead):

function mytheme_form_forum_node_form_alter(&$form, &$form_state){
   // force user to select a forum by putting a blank one at the top
   // and then checking that it is not what gets returned
   $form['taxonomy_forums']['und']['#options']['0'] = '-choose a forum-';
   $form['#validate'][] = 'mytheme_validate_forum_area';
}

and the validation function:

function mytheme_validate_forum_area($form, &$form_state){
   // A taxonomy_forum tid of 0 means they haven't selected one
   if ($form_state['values']['taxonomy_forums']['und'][0]['tid'] == '0')
   form_set_error('taxonomy_forums', t('You must select a forum.'));
}

The only problem I found is that the blank forum went in at the bottom of the sorted list no matter what number I gave it or how it was named.


How to manipulate a Views grid output order?

There are three module (two that come with ctools) that you probably should be looking at.
Page Manager, Views content panes, and Panels

Also, one of the best screen cast tutorials addressing views can be found here:
http://dev.nodeone.se/en/list-group-content-with-page-manager

The focus is OG, but the way views is being used seems to directly apply to what you described.


How can I avoid clearing caches when CSS changes are made?

Install AdvAgg, go to admin/config/development/performance/advagg and set "AdvAgg Cache Settings" to "Development"

If you don't want to do that, go to admin/config/development/performance and uncheck "Aggregate and compress CSS files" as well as "Aggregate JavaScript files"

Another option is to install the admin menu module. That has an option to just clear the css/js cache.


The normal method for creating a custom page--user--login.tpl.php is not to create an empty file, but to copy the  page.tpl.php supplied with the theme you're using into the templates/-directory of your sub-theme, rename it page--user--login.tpl.php, and edit the copy.

For instance, to remove the footer, just locate the markup in your copied page--user--login.tpl.php that is used to template the footer, and delete it!

  <?php if ($page['footer_firstcolumn'] || $page['footer_secondcolumn'] || $page['footer_thirdcolumn'] || $page['footer_fourthcolumn']): ?>

      <?php print render($page['footer_firstcolumn']); ?>
      <?php print render($page['footer_secondcolumn']); ?>
      <?php print render($page['footer_thirdcolumn']); ?>
      <?php print render($page['footer_fourthcolumn']); ?>

  <?php endif; ?>

  <?php if ($page['footer']): ?>

      <?php print render($page['footer']); ?>

  <?php endif; ?>

The block above is an example of how this may look like (this is from a copy of Bartik), if you copy it from another theme, it may look different.

But to get rid of it, you pull it into your favourite text editor and delete all of it.


Active user account after administration's confirmation

I don't think you need a contrib module for that. You can set " Visitors, but administrator approval is required" under "Who can create accounts" on admin/config/people/accounts.

As for sending e-mail, create an advanced action at admin/config/system/actions and then set it on admin/structure/trigger/user to be triggered by account creation.

The core Action and Trigger modules are all that are required for that.


Remove Filter When Exposed Filter is Selected

You can do this by combining two "Authored on" Filters, one regular and the other one Exposed with the OR Operator working between them/groups of Filters.

Add the regular "Authored on" Filter Is less than or equal to now.

Add another "Authored on" Filter and Expose it with your preferred settings, how you want your visitors to use it, don't enter a default value.

Then under Add dropdown choose And/Or Rearrange, Create a new filter group. move the Exposed "Authored on" to it, and choose the OR between the groups, while keeping AND within groups.

Recreate any Filters you might need in the second group.

That's it!

Be very careful of your entire Filters configuration. If you have Exposed filters in the first group too, they will not be able to be applied at the same time (because OR), which may be confusing to users...


Drupal advanced forum - different styles for different forums

On further investigation I believe this can be done with a combination of assigning a path to a post via pathauto, and the Context module, which can add CSS depending on the path.


How can I add help tips on each page, like a sliding panel?

It sounds as if https://drupal.org/project/popup may be suitable for for your needs.

You could create a block with various contexts (your translations / page) and then use this module to display the block (using sub module 'Popup Block') on each page when the user requests it, by rollover or click or whatever you choose.

The module is mature, widely used, has a recent version and has documentation provided.


Adding contacter's email to reply field in contact form email

You can do that with the Webform module. For a better explanation check out this: https://www.ostraining.com/blog/drupal/how-to-create-a-contact-form/


How can I get the active menu trail for the current page?

MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters() is what you want. To use the example above:

$menu_tree = Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters('main');
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

The resulting menu tree should have inActiveTrail flagged.


How to views-filter attached field value by calculated values?

I solved my current problem in a similar way to the solution here: http://drupal.org/node/1259914

Added a filter to the view with my taxonomy field as "not empty"
Implemented hook_views_query_alter() to call $query->add_where with my field_table_name.field_data_column and the values I wanted to accept with the 'IN' operator.

That said, I'm still interested in the views_handler_filter->query() solution(s).


Status code 403 (Forbidden) does not mean that you are not properly authenticated. Since you received all tokens properly you are authenticated successfully. 401 Unauthorized means that you do not have a proper token, i.e. you are not authenticated).

If you receive 403 then you simply are not allowed to access the requested resource with the token you presented. The account you used does not have access privilege for whatever you are trying to access.

If I would have to guess:

Either you used the wrong account (e.g. Stage account used on Production) => use the correct account
Your account was not set up to access the endpoint. => talk to whoever created the account

Edit:
It comes down to "Authentication != Authorization" ("who am I" vs. "what am I allowed to do").


Routes node.add.CONTENT_TYPE are no longer available starting from Drupal 8.4 in hook_menu_links_discovered_alter()?

There are several things I notice here:

An undefined index error shouldn't result just from this code - you're not referencing the array index; just setting it. Does the actual code have a more complex expression which references $links['node.add.article']?
This is not quite correct for this hook (and the linked issue is for 7.x, so it can't be compared). The hook documentation says that the menu item must be an associative array - it should be altered with $links['node.add.page']['title'] = '...';
The array key is not guaranteed to be fixed:

  Since the machine name may be arbitrary, you should never write code that assumes it is identical to the route name.

Therefore you should probably iterate and identify the menu link by the route name instead.

From what I can tell, core doesn't (and never did) define menu links for the node.add.{type} routes. The links on the /node/add page are dynamically generated, and don't actually show up in any menu.

So it doesn't seem to be possible to alter the links on the /node/add page by altering the menu. As you can see from the function below, these links are actually generated in a template preprocessor:

function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = [];
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = [
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', ['node_type' => $type->id()])),
        'description' => [
          '#markup' => $type->getDescription(),
        ],
      ];
    }
  }
}

The only way to modify the link text would be to replace the links in another preprocess function.

Edit: This other answer actually explains how to do that in detail: How to modify the link titles shown in /node/add page?


hook node access drupal 7, not working when the node is updated

I cant seem anything that stands out as a problem other than maybe moving:

if (in_array('contributor', array_values($user->roles))) {

Into the hook_node_access and change $user for $account.

However when troubleshooting problems like this I would firstly ensure you do not have any other access control modules enabled, they can often override each other depending on the modules weight in the system table.

Turn off all modules but core and try isolate parts of your code to get it working bit by bit. For example start off initially with:

function publish_entities_node_access($node, $op, $account) {

        if ($op == 'view') {
            if ($account->uid == $node->uid) {
                  return NODE_ACCESS_ALLOW;
            }
            else {
                  return NODE_ACCESS_DENY;
            }
        }
 }

This code should work and easy to test, if you are not the author of the node then you will not be able to view it. You can then start adding on your additional if statements above until you run into a problem.

You can also install the devel module to nicely output the array's to ensure the values you are using conditionally in your code are available.


How do you functional test your Commerce Kickstart 2.0 projects?

You can install the Commerce Kickstart 2 on your local environment and it would automatic have some data. If you do not know have a development environment I would recommend you to use Lazy Dubuntu (if you wish to build it on Ubuntu computer) or Acquia Dev Desktop 2 for Mac or Windows.

If you do not want to used your local environment you can use Pantheon to test it out for free.


How to fix “Cannot read property 'icons' of null” error?

To anyone who is running into this issue:

 * Defines the "inline_comment" plugin.
 *
 * @CKEditorPlugin(
 *   id = "machine_name_that_must_match_with_icons",
 *   label = @Translation("CKEditor Inline Comment")
 * )
 */

and

getButtons() must return the same ID.

Annotation is new to me and I am sure it's not new to anyone else who are Drupal 8 developers but it might help someone who is new/still learning about how Drupal 8 works.

https://www.drupal.org/docs/8/api/plugin-api/annotations-based-plugins


if you want to hide elements the appropiate way is to set the #access attribute on each element to FALSE, using a hook_form_alter()

  '#access'

  Used by: All elements and forms

  Description: Whether the element is
  accessible or not; when FALSE, the
  element is not rendered and the user
  submitted value is not taken into
  consideration.

  Values: TRUE or FALSE.

Source: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#access


I totally looked past the display fields part of the field configuration of fields ui. That's exactly where you can set it to output 24hr notation.


restrict to subdirectory not work and media module load all images in public://

Option 1
Media Browser Plus module states that it will allow

Personal and public “folders”

Which might answer to your needs
Option 2
Views Media Browser should allow you to specify a view to use as the media browser - you could then filter the view based on file path or other file attribute to get the result you are after.
Option 3
If you are using v2 of Media module you can apparently define a View with a 'views media browser' display to create your media module listing. Media module 2.x is currently in alpha, so take care if you wanted to go down this route, and obviously do not test on live site.
see https://drupal.org/node/1547884


Ajax button in list to delete row entry - submit function is called instead of callback

Remove the '#submit' => 'delete_auction_person_ajax_callback_submit', it does not seem necessary. Adding ajax-processed class on the button doesn't seem necessary either. The function delete_auction_person_ajax_callback receives $form and $form_state, and will tell you what input was clicked that triggered the callback, from there you can do whatever it is you need to do.

I built a lot of tables this way, but I don't think I had the form items as a submit type. If I recall, I used buttons.


You programmatically alter it via hook_node_view_alter()

  This hook is called after the content has been assembled in a
  structured array and may be used for doing processing which requires
  that the complete node content structure has been built.


If you want to change the default value of fields in node edit form. You should looking on any *.tpl.php files. You have to define your own custom module and use hook_form_alter

You can use this if-statement inside the hook function.

// remember change [nodetype] to the one you want to alter.
if($form_id == 'nodetype_node_form'){
    // your code here
}


Webform many dropdownlist results saved under one unique field

Ok, I found a solution: I've used a presave hook. This hook is saving all values submitted by users in a hidden field called "model". A loop will be needed to read the 56 listboxes and save the only value the user have selected.

To do my test I've created a test webform, with only one listbox and one hidden field (this field created automatically my needed field "model" in my database). That speed up a little my tests:

First at all I've created a custom module with a "presave" hook
In a new directory named "duplicated_data", I have create two files:
data_duplicate.info
data_duplicate.module

In the info file I've declared my module

name = Data Duplicate
description = Duplication Data for Webform
core = 7.x
package = Webform
dependencies[] = webform

In the module file I've written my php code

<?php
function data_duplicate_webform_submission_presave($node, &$submission) {
  $component_id = 1; // dropdownlist cid = 1
  $mem = $submission->data[$component_id][0]; // retrieve the submitted value
  drupal_set_message('datos :'.$mem); // print the result
  $component_id = 2; // cid = 2
  $submission->data[$component_id][0] = $mem; // save the data in the hidden field
}
?>

Now I need to activate my custom module.
Each time I make a choice in my dropdownlist/listbox and click on submit, the results will be saved in the database in both fields.

For my production webform , I need to create the loop in order to read all the 56 listbox values and save in my field "model" only the value from the selected listbox. It will be easy to catch it, because it will be the only one, different from NULL.

Hope it will be help somebody else!


What happens after module upgrade if you modify the default views

It should not necessarily change your view, views shipped with modules are usually kept in code, if you change that view, you override it and have it in the database, as long as this overridden view is in your database and a module update does not drop these changes on purpose you should be good to go.

But, always do a backup and test on a local/ different environment than live.

If it does indeed change stuff, you will have to clone the current view and maybe even mimic custom views hooks that are added by that module for that view.

btw. it's worth reading the commit messages since the latest release and or changelogs, if you can read code it's worth looking into the module.install file, and looking at the module_update_n hooks, there you can see if anything major might get dropped as well.


Select the group level in Views here:

and then here


The direct answer to your question (can you use "OR" in an .info file?) has already been provided, but the actual functional outcome you're looking for can be achieved with hook_requirements.  For instance, you might use this code in my_module.install:

function my_module_requirements($phase) {

  $requirements = array();

  if ($phase == 'install') {
      if (module_exists('submodule1') && module_exists('submodule2')) {
        $requirements['too_many_modules'] = array(
          'title' => $t('Too many modules'),
          'description' => t('You may not enable submodule1 and submodule2 simultaneously'),
          'value' => 'Too many modules',
          'severity' => REQUIREMENT_ERROR,
        );
      }
      if (!module_exists('submodule1') && !module_exists('submodule2')) {
        $requirements['not_enough_modules'] = array(
          'title' => $t('Not enough modules'),
          'description' => t('You must enable submodule1 or submodule2 (but not both)'),
          'value' => 'Not enough modules',
          'severity' => REQUIREMENT_ERROR,
        );
      }
    }

  return $requirements;
}

Further reading


Non-Members of Organic Group can still view Node links

Please allow me to offer helpful insights even 6 months after your posted question.  Hopefully, this will help others who are struggling with the Drupal module OG as well.

Note that in your content type, you should already have bundled Group content visibility as another field.  Go to /admin/config/group/fields to accomplish this:

In this picture as my live example, note that my Content Group is the Group content type and that the Content Group Submission is the content type FOR hosting articles that should only be visible to any particular group.  What you need to do is bundle Group content visibility as a new field for this content type as shown below.

This means that you will have Group content visibility field as an additional field to your own content type.

The Groups audience field is meant to make content authors specify the intended audience of the content they are authoring.  The Group content visibility field is meant to make content authors specify the exposition criteria of that particular content.  This is best shown in the following two pictures.  Let us now look at the field set of my content type Content Group Submission.  In my example, I went to /admin/structure/types/manage/content_group_submission/fields.

If you edit this field, you will see its values to be constrained to the following options by default:

- None -,
Use group defaults,
Public,
accessible to all site users

and Private -
accessible only to group members.

The last one appears to be what you are interested in.  You should make that as your default value for this field.

Save all of that.  And your content authors will be offered with these options.  In my case, go to /node/add/content-group-submission.

And this is how your content authors would be able to constrain your article's exposition to only his/her intended groups.  By this method, non-group members would not be able to see nor access the nodes (even titles only) that are intended for private groups where they do not belong.


How do I add multiple images in JSON to meet Google's schema.org requirements?

This takes a little while to set up but is pretty straightforward.

Download and install the Image Widget Crop and Schema.org Metatag modules.
Go to admin/config/media/crop and create three crop types: 1x1, 4x3, and 16x9.  Set the aspect ratios to 1:1, 4:3, and 16:9, and set a hard limit of height 696 and width 696 for all three as stated in Google's documentation.
Go to admin/config/media/image-styles and create three image styles, 1x1, 4x3, and 16x9, and each should use the effect Manual crop pointing to the crop type you created in step #2.
Go to /admin/structure/media and find your image type. Go to Manage form display and use the crop widget.  Require all three crops.
Go to /admin/config/search/metatag/ and choose the content that includes the images.
For Schema.org Article, scroll down to Image and choose ImageObject. Enter the URLs as tokens.

For example, if your image styles are:

hero_16x9
hero_4x3
hero_1x1

And your node contains an entity reference to the image you want to use in field_ref_media_hero, then you can enter the URLs separated by commas like this:

[node:field_ref_media_hero:entity:field_media_image:hero_16x9:url], [node:field_ref_media_hero:entity:field_media_image:hero_4x3:url], [node:field_ref_media_hero:entity:field_media_image:hero_1x1:url]


Can you add a 'select all' option to a webform_select_options_list?

The Checkall module enables this functionality for any checkboxes form element.

  This module provides an extension to the builtin checkboxes element
  that allows developers add "check all" / "toggle" / "uncheck all"
  actions to them. This is specially useful for checkboxes that have a
  lot of elements.

A hook_form_alter() on your webform with this module should get you there.


Put a wrapper div around every second row in drupal view

This should accomplish it:

<?php
  $last=count($rows) - 1;
?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!($id & 1)): // if this an even row id, open the <div> ?>
    <div class="row">
  <?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
  <?php if ($id==$last || ($id & 1)): // if this the last or an odd row id, close the <div> ?>
    </div>
  <?php endif; ?>
<?php endforeach; ?>

It'll wrap each group of two rows with a div with a class of row and make sure if it's an odd number that the final div is closed.

Now, if you want to remove all the classes from those inner rows that Views inserts, then you just need to clean them up or out of that obvious if in the middle.

CAVEAT:  If you have done anything with Views pre_render()ing or other similar hooks that have deleted any of the rows out of the results and not reset the ids to be consecutive, this logic will most probably fail.


It will avialable in Format -> Settings -> Check 'Stortable' Check box


The following code worked perfectly fine for me,

(function($) {
    $(document).ready(function() {
      $("#edit-body-und-0-value").val('this is a test content.');
    });
})(jQuery);

I have placed this code is test.js file. 'edit-body-und-0-value' is the ID of the textarea.

I have installed WYSIWYG module and placed CKEditor under sites/all/libraries/ckeditor folder. Although it doesn't matter if you are using CKEditor or any other editor because we are mainly referring to ID of our textarea.


I'm not sure this is possible. You would create the custom block in a module, add content to it there as well. Then you can theme it or call it in various places inside your theme as well as theme the actual block. That is the usual use scenario for blocks. I will try to add some links in just a bit with more explanation.


Translation of a element['#object'] rendered field

Use getTranslation(), see How to load translated entity values in Twig for SEO purpose?.

In your case you can try something like this:

{% if element['#object'].field_country.entity.hastranslation(element['#object'].langcode.value) %}
  {{ element['#object'].field_country.entity.translation(element['#object'].langcode.value).name.value }}
{% else %}
  {{ element['#object'].field_country.entity.name.value }}
{% endif %}


cache_form has been truncated. Permanent error MYSQL Incorrect key file when a form is accessed

This sounds like someone tried to do some optimization to {cache_form} through a MySQL interface and did something that makes it incompatible with Drupal, or the table is damaged due to a dull disk (see this happen before).

First make sure you have free disk space, and then do a CHECK TABLE cache_form; and see if there are any errors.  If you see some, you can try the standard repair techniques, but it is often best to just re-create the table.

These steps are dangerous and can destroy your site.  Make sure you have backups.

To re-create {cache_form} I would

Start a MySQL interface , and delete {cache_form}, eg DROP TABLE cache_form;

Recreate the table from a known good Drupal 7 install.  I think this is the default:

CREATE TABLE `cache_form` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the form system to store recently built...';


Administrator verification for user role type

For the record, the option you refer to ("Visitors, but administrator approval is required") is not for all users.  It only applies to the Anonymous user role, and means that the Anonymous user is allowed to register at the site (gaining the Authenticated user role), but only after the administrator has approved the registration.

The "standard" way of doing this in Drupal is to set up the site so that the "Anonymous" user role does not get access to the content you want to reserve for verified users.

Then, to gain access the anonymous user must 1) register; and 2) the administrator must approve the registration (using the option you refer to).

How would this model work for your site?


How to create mutliple order statuses in Ubercart?

First off, just a friendly reminder to get yourself on the latest release of Drupal 7 core ASAP, as there was a major vulnerability discovered in all versions of Drupal 7 prior to 7.32.

As for your direct question, I don't believe you can set multiple order statuses for the same order at the same time. What you can do, however, is setup a couple of other fields on orders to handle your additional statuses and then automatically set those statuses using Ubercart's Checkout Rules. For the example you stated, though, I'm not sure if it makes sense that an order would be "In checkout", which means that the user hasn't completed the checkout process, and "Paid", which usually happens as part of completing the checkout process.

Regardless, you can add a custom field for an Order at "/admin/store/settings/orders/fields". Then, you can add a new Checkout Rule at "/admin/store/settings/checkout/rules" and set the value of the new field automatically triggered by one of the Rules events Ubercart lists when creating the rule.

If you provide more detail on what the fields are and how you're planning on using/reporting on them, I may be able to help further.


Is there any way to show a "computed field" value in edit mode?

So the solution found is :
I catched the node id from $form_state and then catched the field value from the node like this :
 /**
 * Implements hook_form_alter
 *
 */
function gedproject_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_structure_edit_form') {
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof EntityForm) {
      $entity = $form_object->getEntity();
      $value = $entity->get('field_reference')->value;
      $form['field_reference']['widget'][0]['value']['#value'] = $value;
      $form['field_reference']['widget'][0]['value']['#type']='textfield';
      $form['field_reference']['widget'][0]['value']['#title']='Référence';
      $form['field_reference']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
    }
  }
}


Adding a "my messages (x)" link in the block template file

The module already contains a block that does something similar: "New message indication". You can use that block and alter the output if needed by overriding the theme_privatemsg_new_block() function.


How to quickly create Drupal 7 Installation profiles / Distributions

This really helped me.

How to Write a Drupal 7 Installation Profile http://drupal.org/node/1022020


try the views_data_export ....  it can export to CSV or basic text format. and you could select a users Nodes: title and body at least ... and any other fields you want...

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV

  Microsoft XLS

  Microsoft DOC

  Basic TXT

  XML


How to get Views field value in View twig template if the Views field is set to 'Exclude from display'?

You shall do it like this:

{{ row._entity.field_myfield.value }}


I think it's not a text of Drupal Interface.

Add .price_prefix { display: none } to your theme's css file and it will disappear.


assign role after registration (male female)

You can add a field to the user entity at admin/config/people/accounts/fields. Let's use the List (text) type and call it "field_gender" with the possible values of female|Female and male|Male. Display it on the user registration form.

Then you can use Rules module to react e.g. when someone creates an account and perform various actions. The idea is that you create two different rules for assigning either the male or the female role.

Install Rules if you haven't already done so, and create a new
rule at admin/config/workflow/rules/reaction/add.  Choose a name
for it and tag it if you want. The rule should react on the following
event: After saving a new user account.
Add a condition in the next step and choose Data
comparison. Then type or select account:field-gender in the data
selector.
Choose the data value in the next step to be Female.
Now your condition is ready, add an action, select Add user role,
then choose the female role.
Repeat these steps and create a rule
for assigning the male role.


A custom access denied page can be defined under /admin/config/system/site-information. For example, one common 404 error page is provided by the Search404 module.

All you have to do is define your own page, perhaps with a teaser from the requested page and informing the user that access to the full content requires that they be logged in.

This will probably require tha you put some php code into the page body, or you might use the Search404 module as the basis for developing your own module to handle this.

Edit: The more I think about this the more interesting the question becomes. I think a case might be made for a 'View Teaser' permission in addition to 'View published content'. In other words, the page could be available for all users, but the teaser would display instead of the full content, and a message could be displayed indicating that the user had to be logged in to view the full content, much like is done for comments now. Perhaps an idea for a contributed model (could not find one on D.O.).


I18n translation of site_name not working

To translate a Drupal 7 Site name you have to activate Variable translation module (which is in the same package as i18n) and the required ones (like Variable store).

After you install these modules, go to Configuration -> Multilingual settings -> Variables tab and choose Site name (?q=admin/config/regional/i18n/variable),Then go to Configuration -> System -> Site information (q=admin/config/system/site-information) and select the language you want. Change the Site name field and save.

You'll find the translated site name in variable_store table.


You can use Domain access module.

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

    example.com
    one.example.com
    two.example.com
    my.example.com


How do I implement a notification/subscription solution?

Have a look at the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture).
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.


Submitting a form with ajax, when multiple instances of the same form are on a page

You can do this by setting a custom form ID for each form. So you define your form like this:

class MyForm {
  protected $formId;

  public function __construct($formId) {
    $this->formId = $formId;
  }

  public function getFormId() {
    return 'my_form-' . $formId;
  }
}

Then, when you call your form, you pass a unique Form ID for each form:

$my_form = new MyForm('some-unique-id');
$form = \Drupal::formBuilder()->getForm($my_form);

Pass a different ID for each form on the page.


How to make different slogan for each content type?

You can use a preprocess function:

function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node'])){
    switch ($variables['node']->type) {
      case 'my_content_type2':
        $slogan = "my super slogan 1";
        break;
      case 'my_content_type2':
        $slogan = "my super slogan 2";
        break;
      default:
        $slogan = "my super slogan 3";
    }
    $variables['site_slogan'] = $slogan;
  }
}

In this case, you preprocess the page before it is sended to the template engine.
More exactly, you change the 'site_slogan' variable according to the node type.

You can add this function in a module: in this case replace "mymodule" in the function's name by the name of your module

or you can add this function in the "template.php" file of your theme folder: in this case replace "mymodule" in the function's name by the name of your theme.


Solution was to use View PHP module and Global: PHP field in filters.


Syntax was wrong. It needed quotes and capitalization definitely matters.

drush user-add-role "administrator" USERNAME


Is there a module that provides a drop-down select box on anode/add form to select a page template to be applied to a node?

This can be done using Display Suite Extras - View Mode Switcher (and very nicely it works too) but only works for nodes at present. Basically you enable view mode switcher in the extras settings page, add the view mode switcher field to each of the displays you wish it to be available on (all of which are customisable template files through display suites layout template system). Now when you visit the node you will get a list of the display modes (which can be labelled as you like) to switch between inline using ajax.


The errors are pretty self-explanatory:

The requested PHP extension posix is missing from your system
The requested PHP extension dom is missing from your system

You need to install those extensions because packages that drush depends on in turn depend on them.


Without knowing the specifics or your installation, nobody can give you the exact reason you got hacked.

I suspect that your server is running a vulnerable version of PHP and that Apache has write access to your site files.  Typically, there will be a bot that will GET a specifc URL that will download a script onto the server, which will then append to well-known (or all) Javascript files.  These additions will add in the malicious code.

After you fix this problem, you should.

Patch your PHP to bring it up to the latest revision for your version of PHP.
Update Drupal to the latest revision for your version.
Clean out your /tmp folders on the server and reboot it.
Read up on Securing file permissions and ownership.  It is important that you fix permissions each time you update files; a lot of FTP clients botch permissions when they upload.
If you are on shared hosting, consider moving to a VPS or Drupal specific hosting.  Running Apache as your login account makes sense for the server owners, not the website owner.
Create a git repo in your DOCROOT, add all of the files (the standard gitignore shoud be fine), and create a "remote" repo on the local filesystem that you can git push to.  This makes backuping up and restoring site files pretty easy.


This works fine in Drupal 9 for titles only from the node_field_data table:
$ drush php
Psy Shell v0.10.4 (PHP 7.4.13 — cli) by Justin Hileman
>>> $db = \Drupal::database();
=> Drupal\Core\Database\Driver\mysql\Connection {#767
     +"_serviceId": "database",
   }
>>> $query = $db->select('node_field_data', 'n');
=> Drupal\Core\Database\Query\Select {#4281}
>>> $query->fields('n', ['title']);
=> Drupal\Core\Database\Query\Select {#4281}
>>> $result = $query->execute()->fetchall();
=> [
     {#4254
       +"title": "Foo",
     },
     {#4257
       +"title": "Bar",
     },
   ]

Or for only an array of titles use fetchCol():
>>> $result = $query->execute()->fetchCol();
=> [
     "Foo",
     "Bar",
   ]

Node Field Data table:
mysql> describe node_field_data;
+-------------------------------+------------------+------+-----+---------+-------+
| Field                         | Type             | Null | Key | Default | Extra |
+-------------------------------+------------------+------+-----+---------+-------+
| nid                           | int(10) unsigned | NO   | PRI | NULL    |       |
| vid                           | int(10) unsigned | NO   | MUL | NULL    |       |
| type                          | varchar(32)      | NO   | MUL | NULL    |       |
| langcode                      | varchar(12)      | NO   | PRI | NULL    |       |
| status                        | tinyint(4)       | NO   | MUL | NULL    |       |
| uid                           | int(10) unsigned | NO   | MUL | NULL    |       |
| title                         | varchar(255)     | NO   | MUL | NULL    |       |
| created                       | int(11)          | NO   | MUL | NULL    |       |
| changed                       | int(11)          | NO   | MUL | NULL    |       |
| promote                       | tinyint(4)       | NO   | MUL | NULL    |       |
| sticky                        | tinyint(4)       | NO   |     | NULL    |       |
| default_langcode              | tinyint(4)       | NO   |     | NULL    |       |
| revision_translation_affected | tinyint(4)       | YES  |     | NULL    |       |
+-------------------------------+------------------+------+-----+---------+-------+
13 rows in set (0.00 sec)


Any way to add more than one text entry to select fields

In my opinion, the Select Or Other module works with field groups or something. It should allow one "other" value per group. You can do like this:

GROUP GENERAL

[ ] Type 1 Certification

[ ] Type 2 Certification

  GROUP CERTIF 3

  [ ] Type 3 Certification

  [ ] Other Type 3 Certifications [text box entry]

[ ] Type 4 Certification

[ ] Type 5 Certifications

[ ] Other Certifications [text box entry]


Profile2 Registration Path module integration with LoginToboggan Non-authenticated role

LoginToboggan invokes hook_user_update() when it validates an email. It sets the property $account->logintoboggan_email_validated to TRUE so you can test it upon your own hook invocation. Inside your hook_user_update invocation, you can use the profile2 function profile2_load_by_user($user) to load the validated user object profile to determine which additional roles need to be set.


Programmatically assigning new users to groups

The user ID is definitely available, as hook_user_insert() is called after the user data has been committed to the database.

I've just put the following code into a test module called foo:

function foo_user_insert(&$edit, $account, $category) {
  dpm($account);
}

Then I created an account through the admin UI and the output from dpm() looks like this:

So as you can see, the roles are available too.

If you're not familiar with the dpm() function, it's part of the Devel module. It will print any PHP variable to the standard messages area and will display objects/arrays like the screen shot above. It should help you with most of your debugging needs.


How do I display a Media entity reference field in a nested paragraph on a template?

After many attempts I finally figure it out, thanks to the comments above and a little investigation. I think my problem was that I assume that the machine name I need it to use for my nested image field was the one I give when I created the content type but that's not the case, I had to use the field of the media type in my case field_media_image instead of field_image.Below is the working code.
{{ file_url( item['#paragraph'].field_image.entity.field_media_image.entity.uri.value ) }}


Passing an extra element to $edit array when creating an account

If you are actually trying to prevent a user from registering with an email that is in use, Drupal already has that built in. It also has a check that prevents users with an IP in the blocked IP address list to create an account.

Solution

Your flaw in the above code is that drupal_execute calls drupal_process_form which will rebuild the $form_state['values']. A solution could be to add a hidden/value form element to the user_register form with hook_form_alter. Doing that should allow you to send your custom value through drupal_execute.


Does Apache Solr assign a weight to HTML tags?

If you are using the Apachesolr module, then yes. The module has some sensible weighting defaults for the tags, but they can be further customized at admin/settings/apachesolr/query-fields.


How to sort view using already sorted array in hook_views_query_alter

OK I figured it out

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,2,4,6,1,3,5)', 'ASC', 'order_field');


Multiple pieces of data attached to multiple states

The answer to this was the field collection module (alternatively, multifield can be used).

This allows you to create an unlimited amount of field collections, and served my purposes perfectly.


Adding a jQuery interaction with Views Accordion

You have to use $(this) with out working on id/class.

Refer to this link jQuery $(this) Selector with Examples.


How to choose between all the Views hooks

The documentation View Hooks is clear about the purpose of every hook. It says about hook_views_post_execute(&$view):

  This hook is called right after the execute process. The query has
  been executed, but the pre_render() phase has not yet happened for
  handlers.

And gives an example what you can do with this hook:

function hook_views_post_execute(&$view) {
  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  if ($view->total_rows > 100) {
    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

At this point the database query was executed and you can do something with the result of the query, for example place this warning.

When you search in drupalcontrib, you find, that it is only used once:

drupal contrib search

Here it is used following the documentation. But no one in contrib used it for other things. You would be the first, with unpredictable results.

What you want to do is not specific to views, and because of that it is not in your list of view hooks. It is more connected to theming in drupal.

It is not advisable to put extensive code in the templates *.tpl.php, better put it into a preprocess function. Some examples for views:

hook_preprocess_views_view
hook_preprocess_views_view_field
hook_preprocess_views_view_fields
hook_preprocess_views_view_grid
hook_preprocess_views_view_table
hook_preprocess_views_view_unformatted
hook_preprocess_views_view_list

Use the preprocess hook, that correspondents with your views configuration.


Ionic Framework won't authenticate in browser (works in emulator)

Incase someone faces a similar issue, I managed to find a fix by:

Setting up an ionic proxy see: http://blog.ionic.io/handling-cors-issues-in-ionic/
Sending the Cookie with the headers as Authentication to bypass the issue 'Refused to set unsafe header "Cookie.  Then adding this code on hook_init() https://www.drupal.org/node/1133084#comment-8433677.


If you are achieving this html by using views then set the rows even and odd patterns and do the CSS according to the even and odd class.


How do I let users be able to view, update and delete their own content?

You can use Views. Create a view of content on your site and use table format, list the fields as listed in admin/content. Add a relationship to the content:author so as to get access to the user table. In contextual filters (arguments for drupal 6), add user:uid => provide default value => user id from logged in user. Add a page display to your view and optionally provide a normal menu entry (or do that with the menu system) and Save your view. Go to the page you created, you should see only the content you created. To be able to mass delete or perform other bulk operations on the content, use Views Bulk Operations


Sort a view by country - according to the translated countries

Your problem is that views uses SQL to sort, since that is a lot easier and faster and it otherwise would be required to load all the records and sort them with PHP, before selecting which to show, which is a massive resources waste if you have a lot of records and use paging.

A simple solution to this problem, is to create a work around. Since the country names is stored in english, you can create a field that you hide from the user where you store the French country name. You can then in your view use this field when sorting. You would need to write a bit of code - in a custom module you create - to hide the field in the UI and automatically set the correct value based on the country the user selected in the interface. This can all be done with hook_form_alter.


When programmatically adding conditional element to webform, I get errors

It seems as if there's really no clean way to do this.  What I realized is that it was easier to just remove all existing conditions, and then re-add them all with the additional condition included.  So I started by setting:

$node->webform['conditionals'] = array(); //remove all conditions
node_save($node); //save the node, removing all old conditions
$node->webform['conditionals'] = $new_array_of_conditions; //add entire new array of condtions
node_save($node); //save the node with new conditions

This doesn't break anything on old nodes because no data or anything else is reliant upon conditions...so removing them doesn't hurt anything or lose any crucial data.


In D7, the language switcher block is created in locale_block_view():

function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

You can use hook_block_view_alter() to modify the markup of the block.

If you want modify the output of the links, you can override the theme_links() function in your theme using THEME_links__locale_block() in the template.php file.


How to copy current user'id to a custom field when adding a new entity?

You probably want to use the setValue() function, like this:

$user = \Drupal::currentUser();
$node->FIELD_NAME->setValue(['value' => $user->id());


Autocomplete results showing behind the form

I can only speculate as to how you've styled up the second form, but it might be its z-index is higher than that of the autocomplete dropdown.

Trying setting a higher z-index for the autocomplete div in your stylesheet:

#autocomplete {
  z-index: 1000;
}


How do I set the exact post date timestamp as Views contextual filter?

I think you only have to pass the hours and minutes in to your contextual filter.

I have a View with filtering between dates and the URL is like that:
http://mysite.com/myview?changed%5Bmin%5D=23-03-2013+12%3A24&changed%5Bmax%5D=23-03-2013+18%3A24

This is for the access data from 23-03-2013 12:24 to 23-03-2013 18:24.

Also, make sure you have enabled the Date submodule Date views as it provides some improvements using dates in Views.


How to auto generate barcodes for Entity Registration in Drupal 7

Its complicated but I essentially ended up using the available barcode online generators (Google has an online QR Code generator) and then embedding the URL in HTML mail that I was sending out.


How to redirect users to log in page when they try to access the order page, but not when they try to check out

That's one of the main features of the LoginToboggan module.

When the Present login form on access denied (403) is enabled in its setting form, any access denied page will display a login page. Upon login, users are redirected back to the previously requested path.


Dynamic value in Twig or preprocess based on config and getHost()

In case you wondered, I resolved this by adding my methods to a service class, as @Hudri suggested in comments.
I can call those methods in a Form or other OO class by dependency injection of the Drupal\clientname_cta_base\Cta\Base service class:
    // Active URL configuration (read-only).
    $form['clientname_cta_base_computed_base_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed base URL (Preview)'),
      '#default_value' => $this->ctaBase->getBaseUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];
    $form['clientname_cta_base_computed_cta_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Computed CTA URL (Preview)'),
      '#default_value' => $this->ctaBase->getCtaUrl(),
      '#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
      '#attributes' => ['disabled' => 'disabled'],
    ];

The example above does not include all the dependency injection setup in the Form class, or the service class setup, services YAML config, and other steps that are well documented elsewhere.
In theme preprocess, dependency injection is not available, so I get the computed values via \Drupal::service('cta.base') like so:
/**
 * Implements template_preprocess_page().
 */
function clientname_preprocess_page(&$variables) {
  $service = \Drupal::service('cta.base');
  $config = \Drupal::config('clientname_cta_base.settings');
  $variables['computed_base_url'] = $service->getBaseUrl();
  $variables['computed_cta_url'] = $service->getCtaUrl();
  $variables['default_link_text'] = $config->get('default_link_text');
}

Note that for configuration values that are not dynamically generated, I can just access them directly in theme preprocess via \Drupal::config('clientname_cta_base.settings').


How can I display a node create form in a Panel pane?

One simple solution is installing formblock. But that won't allow to save the nodes at the same time.

If you dont mind programming, this should be of help.


Calendar: How to limit the range of hours in Days display?

Change the Settings of the Calendar format in the View and set the time grouping to custom.  In the box, specify the intervals/start times that you want to show up starting at the hour you want to start at.  See illustration below:


How to make links to private directory always use ssl?

Depending on where you've placed the above code (e.g. a hook_init invocation), it might not trigger for an anonymous user if caching is involved on your site.

An alternative to this approach is to do it at the web server level so that any request that matches a URL pattern will always switch over to HTTPS. For example, with Apache RewriteRule you could do the following:

  RewriteCond %{SERVER_PORT} !^443$
  RewriteRule ^system/files/webform/(.*)$ https://www.example.com/system/files/webform/$1 [R=301,L]


Using the Entity reference module you can reference all entities (nodes, users, terms etc).

When you use the Entity Reference module you get a field where you can choose one ore many entities to reference. In this case it will be other users you choose (children).

This is the way it could look when you choose children in your user profile.

I suggest you read up on the Module Monday blog post by Jeff Eaton about Entity Reference. to get up to speed on relationships.


How to take contents of a tab and insert them inside a node

You can create a block using the block module hooks and you can generate the content of the block by using the page callback function in the menu to get the signatures displayed inside the block. You can then configure the block in whichever region you want.

Another option would be to use the page callback function inside the template file (.tpl file) of the petition  node and print the content near to the petition form.


How to view to user only the node that referenced to him?

Entity Reference and Rules Solution.

Install both modules
Add an entity reference field with unlimited values to your content type. Make sure it references users.
For views, create a content view and add a contextual filter for the field you created. My test contextual filter was called Content: User Ref Test. Your contextual filter will have the same name as the field you created.
In the contextual filter's settings, click Provide Default: User ID from logged in User. This will only show content where the user has been referenced.
To make the content safe from typing in the url, create a Content is Viewed rule for that content type.
In the conditions, choose "list contains item". The list is the entity reference field and the item is the logged in user. At the bottom of the condition, you then negate the rule. It should look like NOT Item in List "Parameter: List: [node:field-user-ref-test], Item: [site:current-user]
Add a second data comparison condition that allows the admin (or you could do this by user role) to view the content. Negate this condition as well. NOT Data Comparison > Parameter: Data to compare: [site:current-user:uid], Data value: 1
Add a system redirect to the homepage and a message explaining why the user couldn't view the content.

If it doesn't work, check to make sure the entity reference field is set to unlimited because that's why we use the list in rules.


You could use the Mass Contact module.

  The Mass Contact module allows anyone with permission to send a single message to multiple users of a site, using its roles functionality.


Turns out there was a home page rule set up in metatag configuration that had the url hardcoded. Didn't see that at first.


Combine multivalue field rows with copy of same multvalue field

I've found the solution via media entities and "media pdf thumbnail"


What's the difference between the container and html_tag render elements?

I did "Blame" on the 7.x system.module after I didn't found a clue of 'container' in the 6.x branch. In the "Blame" you can see that Dries himself committed the patch that introduced $types['container'] in 2010 and that it leads back to the following issue on drupal.org:

#557272: FAPI: JavaScript States system

The issue which introduced #states to the Form API! Now let's scan the page for "container". Okay, comment #36 explains quite a bit of the reason why it was introduced:

As discussed with kkaefer and tha_sun, we switched the "wrapper" Form
API element type to "container" to not get too confused with other
"wrapper" stuff, like "wrapper_callback", "theme_wrappers", etc. The
"container" type still uses the CSS class of "*-wrapper" though, to
match with the rest of the Drupal coding standards.

And in the commit itself you then can see how container elements already replace some markup elements (markup being the default if #type omitted) which had '#prefix' => '<div>', '#suffix' => '</div> with hardcoded HTML.
To make it short: Container is a classical wrapper. And more of a form element. Whereas html_tag is more of a render element, traditionally used for void elements, often in the HTML <head>. Like placing meta tags or placing JavaScript and CSS libraries in script tags.


Drupal Form Button + "Are you sure"-Button

Using hook_form_alter you can implement simple popups like this using #attributes.

 $form['submit']['#attributes'] => array(
  'onclick' => 'if(!confirm("Are you sure?")){return false;}',
 );

or

$form['submit']['#attributes']['onclick'] = 'if(!confirm("Are you sure?")){return false;}';


Drush Enable a module and all its submodules

There is nothing out of the box to automatically enable submodules, but it is, in fact, possible to specify similarly-named modules via a wildcard:

drush en 'coder*'

As previously mentioned, this is only useful in certain niche situations.  I have never used it in any practical situation.  If you happened to need it, it would be just the thing, though.


Custom Template for Comment based on node type

According to Drupal 7 Template Suggestions, the custom comment template for a content type should be named comment--[node-type].tpl.php. That is confusing, because the actual template you have to use for an article content type is comment--node-article.tpl.php.

Alternatively you could add your custom template suggestion inside template.php:

function bartik_preprocess_comment(&variables) {
  // Let's say you want to have a custom template like comment--custom-TYPE.tpl.php
  // e.g. for an article content type, the template file will be comment--custom-article.tpl.php
  $variables['theme_hook_suggestion'][] = 'comment__custom_' . $variables['node']->type;
}


to reduce results by the content type, when you set up the view, filter by content-type, and select the appropriate content type. If it already exists, use a FILTER CRITERIA and use content-type (I believe this can also be accomplished through the search settings)
to group: set format to fields, add the taxonomy term to the fields list to group by (you can hide from display if desired), click on Settings under FORMAT. There you can group by any field currently in the view
for Solr, take a look at Apache Solr Views Module and the related documentation for implementing this functionality.

Apache Solr Views:

  This module provides a Views integration to the Apache Solr Search
  Integration project. It provides the views plugins and handlers needed
  to be able to create a view that fetches its results from Apachesolr
  index, without hitting the database.


Is it possible to get the field value of user reference autocomplete from username?

You can do this with user_load_by_name($name).

Once you load the user object you should be able to access the reference field normally.


To add Sort functionality using Drag and Drop into admin/content section, you need to play with administration views using Admin Views module. Note that Weight module is also necessary for this. After installing and enabling these module you can edit administrative views under admin/views section.

But if you simply want to add your new views of specific contents then there is already Weight view available under admin/views section. You can check this view to see the working and functionality using Drag and Drop.

Note: Weight module must be enabled for contents to be sorted.


I think that this module is what you want to use, jquerycdn.
It allows you to change the default jquery to e.g google cdn.


Store age from Date of birth when use registration

Computed Field Module will do the job:

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

You can also google "Drupal Computed Field Age" for more information.


Exclude the current node in a view with related items in case of multiple contextual filters

What are the "other purposes" of the first nid contextual filter? Are you taking in the current nid in order to build a relationship to something like a taxonomy term to then get other nodes in the same term?

If so, then the contextual filters should be using different relationships.


Drupal Apache solr does not return "no results founds"

I met the same issue, and the main reason was the solr 'bias' settings in admin/config/search/apachesolr/settings/solr_search/bias

I changed some of its configuration. the solution is clicking 'reset to default' button.


You need to invoke hook_mail() to specify a 'body' parameter. It is a little confusing since it is two steps but well documented: http://api.drupal.org/api/drupal/includes%21mail.inc/function/drupal_mail/6

See 'example_notify()' and 'example_mail()' from the above link.

In your case yo need to call drupal_mail outside of your invocation of hook_mail. See below for an example. You can pass the body as in the $param when you call drupal_mail or you can edit it when you invoke hook_mail.

Be advised that this is not the best example since it would fire off an email any time somone visited that page, but I'm not sure where you are trying to call drupal_mail from:

$query = "
SELECT uid
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@mail.com'
AND users_roles.rid =6
AND users.status =0
";

 // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    $account = user_load($links->uid);
    $body = t('Message for %name', array('%name' => $links->name));
    $subject = t('New email!');
    $params = array('body' => $body, 'subject' => $subject);
    drupal_mail('customstats', 'html_mail', $account->mail, user_preferred_language($account), $params);
    $page_content .= l($account->name, 'mailto:'.$account->mail) . '<br />';
   }

  if ($page_content == '') {
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}


Making menu items active on desired page

Is there a way you could make the Context module a dependency for your module and hook into the Context module to do this?  Context already allows you to do this exact function.  You specify conditions and reactions when those conditions are met, per context.  In your case you would specify particular paths as conditions, and then your reaction would be to simply activate a particular menu item.  I would seriously consider checking it out rather than reinventing the wheel.


accessing block type in the theme_preprocess_node()

You can't get access to a block object from a node preprocess hook; the context simply isn't passed down the chain.

As you're using a view, though, you can get hold of the View object, and test the name/display id. The basic idea would be:

function theme_preprocess_node(&$variables) {
  if (!empty($variables['view'])) {
    if ($variables['view']->name == 'some_view' && $variables['view']-> current_display == 'block_1') {
      $variables['theme_hook_suggestions'][] = 'node__productstream';
    }
  }
}


You may do a SQL query to update the field.

Table: field_data_field_NAME

Column: field_NAME_value

Table: field_revision_field_NAME

Column: field_NAME_value

UPDATE `db_name`.`field_data_field_NAME` SET field_NAME_value = replace(field_NAME_value, '/sites/files', '/sites/files/images');

You may want to update the revision table of the field as well

UPDATE `db_name`.`field_revision_field_NAME` SET field_cc_NAME_value = replace(field_NAME_value, '/sites/files', '/sites/files/images');


A simple solution could be the content import module that allows you to import among other things paragraph content from CSV I believe and you can specify language for each field.  Give it a try


How to see the call stack of the functions being called in a page

If you want to see the complete callstack of the functions being called, you should set up a debugging environment for doing so.
The quickest way to do is by downloading the Quickstart: Prebuilt Drupal Development Environment, which is a virtual machine copy of preconfigured ubuntu. The netbeans IDE is configured for debugging the Drupal code. It also has an display to look at the callstack at the bottom of the IDE, when in debug mode.

What all is included in it:

Support for Drupal 7 and Drupal 6
Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
Firefox (with developer plugins) and Chrome
Drush, drush make, and custom drush commands
Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
Netbeans and Eclipse, configured with XDebug
XHProf and Webgrind profilers. Emails logged as files
cvs, subversion, git, bazaar

You can have a look at its dedicated youtube channel for helpful screencasts.


What hook can I use to modify Views Datasource JSON output?

I find my 1st answer informative regarding auxillery information regarding views and views_datasource. So here's 1 way I think you get the url you want.

You said:

  My guess is that Views Datasource is processing the data after I've
  seen it in my hook implementations.

It is, look at what views_json_view_pre_render() is doing:

function views_json_views_pre_render(&$view) {
  if(isset($view->plugin_name) && $view->plugin_name == 'views_json') {
    // Support for Video field.
    if(!empty($view->result)) {
      // Process each View result.
      foreach($view->result as $row => $result) {
        // Only process the entity fields defined by the View.
        foreach($view->field as $field_name => $field) {
          if($field instanceof views_handler_field_field) {
            if($field->field_info['type'] == 'video') {

              // Get the Video URL.
              $video = $field->get_value($view->result[$row]);
              // -- See this line !!
              $url = file_create_url($video[0]['uri']);
              $render_array = array(
                '#type' => 'markup',
                '#markup' => filter_xss($url),
              );
              // Substitute embed code with URL. @todo Add support for escaped embed codes.
              // See this line !!
              $view->result[$row]->{'field_'. $field_name}[0]['rendered'] = $render_array;
            }

If its a video field views_json is taking each of the results and replacing the embed code with the URL of the video. This is what  you're seeing.

So how do you fix this. You write your own hook_views_pre_render() that runs before views_json's pre render. In your pre render function you change $video[0]['uri'] to whatever url you want -- ultimately thats the value views_json will use. If you can get the FID or the full url to the image here you should be able to easily set that value.

So in your own module you'd write 2 functions:

// File: mymodule.install
function MYMODULE_install() {
// Set the weight of the mymodule.module to a value lower than views_datasource's views_json module.
  db_update('system')
   ->fields(array('weight' => -1))
   ->condition('name', 'mymodule')
   ->execute();
}

// File: mymodule.module
/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render(&$view) {
  if(isset($view->plugin_name) && $view->plugin_name == 'views_json' && $view->name == 'YOUR_SPECIFIC_VIEW') {
    // Support for Video field.
    if(!empty($view->result)) {
      // Process each View result.
      foreach($view->result as $row => $result) {
        // Only process the entity fields defined by the View.
        foreach($view->field as $field_name => $field) {
          if($field instanceof views_handler_field_field) {
            if($field->field_info['type'] == 'video') {
              // Change the video uri to the image you want ...
              $view->result[$row][0]['uri'] = /* some logic here */;
            }
          }
        }
      }
    }
  }
}

Your pre render hook will run before views_datasource's. It simply alters the url to whatever you want. Then views_datasource's views_json hook runs and just uses it as its supposed to -- you just slipped in the correct value. This should work. Code is untested.


Generate drupalSettings in Ajax Callback

Well, I'm answering my own question. The secret is to use BubbleableMetadata. Here is my code explaining what I did and how it happened. Here is my entire controller response that generates the JSON for the response:

 public function ajax_callback($type)
 {
    // Retrieve the form
    $form = \Drupal::service('form_builder')->getForm('Drupal\path\to\Form');

    // Render the form
    $rendered_form = render($form);

    // Get the data from BubbleMetaData
    $data = BubbleableMetadata::createFromRenderArray($form);
    // Retrieve the attachments from the $data
    $attachments = $data->getAttachments();

    // Generate the settings to be sent back with the ajax response
    if(!empty($attachments['drupalSettings']))
    {
        $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
        $settings .= Json::encode($attachments['drupalSettings']);
        $settings .= ');</script>';
    }

    // Send back the rendered form along with the settings
    $response = [
        'content' => $rendered_form . $settings,
        'status' => TRUE,
        'type' => $type,
    ];

    // Return the data as a JsonResponse
    return new JsonResponse($response);
}


Textfields and values with a value of 0 get blanked out if stepped forward/backwards

You could also simply allow users leave the field empty and convert any empty “numeric” fields to a '0' in your submit handler. That might be a better user experience since it would save users the trouble of having to enter any values in those fields.


Create View with a join on the same content type

Install Equi Join module

  The Equi Join module allows you to create relationships between
  different entities based on an arbitrary field. This allows the use of
  relationships in Views without having to add Node References to a
  content type, which may not be an option when displaying data stored
  on a third-party database or data provided through custom Views
  handlers. That said, it works with nodes as well.

Using only a single content type Route create your view as follows:

Add your from and to fields.
Add a Relationship of Equi Join: Content and give it a name. Set Left field to field_to and Right field to field_from
Add a second set of from and to fields, but set the relationship on
them to the new Relationship you added.
If you wish you can then either remove the first To field or the
second From field.


How do I create a log/statistics of on page events?

Since, you've built everything in js, next thing to do is send the data from the client. You could do that with an endpoint in a custom module and sending everything you want there with ajax.
From there it depends how often you anticipate db writes from these data and you can assess the next step to take. You could:

Create a content type and programmatically save data to it.
Create a custom db table with only the fields you want and implement some db logic to save data.
Use mongoDB and setup a document table to store these data. This is the best option performance wise. You would need to setup the mongoDB module for it.


You can try using Extended Path Aliases module..

Project page says

  Would you like your human-readable, SEO-friendly aliases to be carried
  through on all your tabs, links, Views, and blocks, on all your
  pages, not just on that single aliased base path? If so, then this
  little module is for you.


What is the parent name for the admin menu?

parent:system.admin is the answer , obvious wasn't it.


This was the correct answer:

public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $result = array();

  foreach ($tree as $element) {
    $link = $element->link;
    array_push($result, array(
        'title' => $link->getTitle(),
        'url' => $link->getUrlObject()->getInternalPath(),
        'weight' => $link->getWeight()
      )
    );
  }
  return new ResourceResponse(json_encode($result));
}


In general, you should probably only give Full HTML access to only your most trusted users (which may only be the site administrator).

Now the example you linked to was intended to be used in a block.  Block administration is also something that will likely only be done by your site administrators.  Every site needs an administration plan, so it's fair to ask, can the people entrusted with block creation also be entrusted with the use of Full HTML?  If so, no need to create a custom block.

Alternatively, the example code is fairly benign, so you could add a Text Format that allowed for the use of those tags & attributes (admin -> configuration -> content authoring -> text formats and editors).  I often create a Text Format called Advanced HTML that allows for most tags but I don't include any of the potentially problematic tags like script, object, style, etc.

To produce that carousel, looks like you would minimally need the following:

<div id class role data-*><ol class><li class data-*><img src alt><h3><p>


What is the best way to keep your site code in git and pull in core and contrib in the same repository?

Not exactly the same question as https://drupal.stackexchange.com/questions/260/deploying-drupal-with-git but I have the same answer for you.

http://freso.dk/en/2011/02/26/managing_fresodk_from_cvs_in_svn_to_git

I think it can be useful to have Drupal Core as a real check out, makes it for example easier to track hacks. Because sometimes, there simply is no other way, be it changes to .htaccess or maybe you applied some patches for bugs which affect you directly.


In /sites/default/settings.local.php make sure you have
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

You need to go to /sites/development.services.yml and turn off Twig's cache by adding
Parameters:
    twig.config: { debug: true, auto_reload: true, cache: false }

This is what mine looks like:
# Local development services.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
parameters:
    twig.config: { debug: true, auto_reload: true, cache: false }
    http.response.debug_cacheability_headers: true
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

For more info, see Disable Drupal 8 caching during development


A ton of errors in panels content editor

Known CTools bug - see https://drupal.org/node/1991496 and https://drupal.org/node/1925018

Fixed in http://drupalcode.org/project/ctools.git/commitdiff/280ccd0 and the fix is available without patching if you use 7.x-1.x-dev.


How to use cache set and get to store time cron ran?

I don't think there is something wrong on cache_get() and cache_set(). It seems a logic problem. In your code the cache is never set if a cache is not found.

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  $data = '';

  if ($cache = cache_get('last-run')) {
    $data = $cache->data;
    if($data <= strtotime('-1 day')) {
      //call helper function to perform some logic
      _some_func();
      //set update date in cache
      cache_set('last-run', time(), 'cache'));
    }
  }
  else {
    // set cache if there is no cache.
    cache_set('last-run', time(), 'cache'));
  }
}


Apply text filter (not text format) in Twig

If those HTML are mostly or all static, you could consider implementing your own tokens via hook_token_info() and hook_tokens() in your custom module.

This way, you would avoid any potential risks, and accidentally malformed markup... and would have to full control on the replaced and returned markup.

Your authors would add a token like this in the content: [custom:facebookpost:12345]

... and your token could return an embedded Facebook post markup in return.

In my experience this method works much better than any other alternatives, mostly because:

those embed widgets usually have custom tags and/or tag attributes which may not be compatible with CKEditor settings, text formats, etc.
embedding those widgets directly, would make maintaining content much harder on the long run.
provider(s) may change the embed markup. (Consider updating 100s or thousands of content entries via find & replace vs. updating the embed markup in token definition only)
and it's not a hack.


`Routing` folder not present inside `Drupal\Core\`

That is the namespace. It's actual location in the file system is /core/lib/Drupal/Core/Routing. The autoloader knows where to look via the namespace.


Non-directional/symmetric relation between nodes of the same content type

Corresponding entity references fixes this for you:

  CER keeps reference fields in sync. If you have two entities that refer to each other using Entity Reference (or some other kind of reference field), it saves you the trouble of double-editing your entities in order to have them point at each other. If entity Alice references entity Bob, CER will make Bob reference Alice, and keep the references up-to-date when either entity is updated or deleted.


Validating a Webform with CAPTCHA locally before submitting to an external URL

If you want to validate form, you need to leave action intact. Then, you can send it's content to external server in it's save handler using it's api or drupal_http_request().

The point is - action tells the browser where to send the data. If you make it send data to external server, your Drupal will never get it, so it will have no opportunity to interact with it. Of course you might try to implement validation in browser too, using JavaScript, but that's unreliable and shouldn't be used as an only way of validation.


How to programatically add a pseudo field to views and display the field value based on value of other field?

In addition to the preprocess hook approach noted in the comments, you may want to use:

Computed Field Module https://www.drupal.org/project/computed_field
Views PHP Module https://www.drupal.org/project/views_php


Tags won't show on Advanced Forum Module

Dev error: They weren't showing on any of the posts, because it was a new field, hence once you make the new post and select tags for them, then post, then they show just fine.


Handling external authentication with routing.yml

I can't believe I missed this. I simply had to go to /admin/modules and enable these:


How to extend default user registration page in Drupal 7?

In Drupal 7, you just add the fields to the user entity in "Administration » Configuration » People » Account settings » Manage fields."
Then, for every field there is the "Display on user registration form" checkbox.


create email id for registered users in Drupal 7 and Nginx

Nginx won't help you. It can act as a mail proxy. But you need an MTA: Sendmail, Postfix to create a new mail account on your domain. Take a look here:

https://stackoverflow.com/questions/5273163/how-can-create-email-id-using-shell-exec-or-exec-in-php

You will require root permissions.


Redirect /user/login to HTTPS, all other requests to HTTP

You don't really need /user/login to be served via https; you need the user login form to be submitted via https.

You should take a look at the module securepages_prevent_hijack -- not to use it directly, since it depends on securepages, but to see how the login form is altered.  Like so:

function securepages_prevent_hijack_form_alter(&$form, &$form_state, $form_id) {
  // Secure the login form, so that we always have a secure connection to transmit the
  // initial cookie.  Also, protect the password in transit.
  if ($form['#id'] == 'user-login-form' || $form['#id'] == 'user-login') {
    $url = parse_url($form['#action']);

    $base_path = base_path();
    $path = (!strncmp($url['path'], $base_path, drupal_strlen($base_path)) ? drupal_substr($url['path'], drupal_strlen($base_path)) : $url['path']);
    $options = array('secure' => TRUE);
    if (isset($url['query'])) {
      $options['query'] = $url['query'];
    }
    $form['#action'] = securepages_url($path, $options);
  }
}

You should also figure out whether the cookie that Drupal is setting for you is secure or not.  This will depend on your settings in php.ini.  Check to see if you have set session.cookie_secure to 1.  If you have, then the cookie will not be sent to your http sessions, which could be why you are ending back at the home page (no session cookie == no session == no login info == log out).  Of course, if the session.cookie_secure is 0, then it might be possible for other parties to observe your session cookies in transit, and masquerade as your users.  Perhaps you have already considered this risk, but it does bear some consideration.


Composer updating to 8.9.0beta2 instead of 8.9.0

This and similar dependency conflicts can typically be solved by asking composer to also update symfony packages as described in Drush blocks update from 8.9.0-beta2 to 8.9.2.
composer update drupal/core-recommended symfony/* --with-all-dependencies


How to have exposed filters not displayed on search results

This is pretty simple to do with a little coding:

First create a "Display output" template inside your theme folder that will only target the relevant view (check options using "Theme: Information" bottom right under "Advanced" when you are on your view administration page). Copy the contents of "views-view.tpl.php" inside the file and clear the caches.

After that modify the original filter output:

<?php if ($exposed): ?>

    <?php print $exposed; ?>

<?php endif; ?>

to what you need:

<?php if ($exposed): ?>

    <?php if (!isset($_GET['something'])): ?>
    <?php print $exposed; ?>
    <?php else: ?>
    <?php print l(t('Back to search'), $_GET['q']); ?>
    <?php endif; ?>

<?php endif; ?>

You will just have to replace "something" inside that $_GET to a value that is actually used in your filters (check the URL when you have a search performed - it will look like example.com?something=value1&somethingelse=value2). Since views adds all the filter keys to the URL when a search if performed you can pick any of them.


Should I disable all UI modules once the site is in production?

This is probably considered best practice in terms of performance because on every call each module is loaded into memory and executed.

However you may find it annoying to have to constantly re-enable the modules, particularly with views or rules.


Configuring an Entityform with a term reference field

Add new view that shows content of type: entityform submissions.
Add a field Entityform Submission field 'Document type'
Set the path to /taxonomy/term/%
Add a contextual filter, entityform submission 'Document type' and 'provide default value' - 'taxonomy term ID from url'

Done.