How can i select taxonomy terms applying filters on its fields?

The EntityFieldQuery class is the normal tool fot this sort of task. Have a look at the docs for more information, but this is a basic example based around what you've mentioned in your question:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vocab_id_of_terms_you_want_to_select)
  ->fieldCondition('field_author', 'tid', $the_author_tid);

$results = $query->execute();

$found_terms = taxonomy_term_load_multiple(array_keys($results['taxonomy_term']));


How do I apply check_markup() as Twig filter?

First of all, what is the motivation here? Are you getting double escaping or something? Providing more background information may help to get you a better answer.

Before we get too much further, relying on a certain configuration of the full_html text format seems like it's not a good solution. For example, to get the below to work for automatically creating links for this scenario, I had to enable Convert URLs into links in the full_html text format.

If you take a look at the documentation for check_markup() you'll see this note:

  Note: this function should only be used when filtering text for use elsewhere than on a rendered HTML page. If this is part of a HTML page, then a renderable array with a #type 'processed_text' element should be used instead of this, because that will allow cache tags to be set and bubbled up, assets to be loaded and #post_render_cache callbacks to be associated. In other words: if you are presenting the filtered text in a HTML page, the only way this will be presented correctly, is by using the 'processed_text' element.

So based on that I think what you may want to do is in your block build method create a 'processed_text' element (render array):

foreach ($tweets as $tweet) {
  $cleanTweets[] = array(
    '#type' => 'processed_text',
    '#text' => $tweet->text,
    // Relying on the full_html text format to do certain things is probably
    // not a good idea.
    '#format' => 'full_html',
    // Potentially add keys for #filter_types_to_skip and #langcode.
  );
}
$params = array('tweets' => $cleanTweets);
return array('#theme' => 'twitter_pull_tweet_listing', '#params' => $params);

Then you can do this in your Twig template (twitter-pull-tweet-listing.html.twig):

{% for tweet in params.tweets %}
  …
  {{ tweet }}
  …
{% endfor %}

To relate this to Drupal 7, that Twig template code would be roughly equivalent to running render() on each array element (individual render array) in the $cleanTweets array.

If you're more interested in creating an actual Twig filter, the Twig documentation has some information on that, and Symfony has some very comprehensive documentation that matches up with how you would create a Twig extension in Drupal 8.


Countdown timer field with a scheduler module

Here is a good place to start:

http://code.zeurois.com/jquery-countdown/configurator/new/-/tpl/t105-900


how can i change new password/confirm password by using services module in drupal

https://drupal.com/servics/user/9

where 9 is User ID

Method : PUT

Pass 'X-CSRF-Token' paramerter with user token value in header.

Example Call :

{"uid":"9","current_pass":"guessusername1","pass":"guessusername1xxx","pass1":"guessusername1xxx"}


Exclude the www- append to only one multisite

Unfortunately putting separate htaccess files in each sites folder doesnt work, otherwise it would be quite straight forward.

Perhaps you can use REWRITECOND to do this?

RewriteCond %{REQUEST_URI} yourclientsdomain.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


How to display block using hook_block on specific pages only

You need to add 'visibility' option that is equal to 1 and  'pages' option that should be a string that contains one or more page paths separated by '\n', '\r', or '\r\n' for your block information

 $blocks[0] = array(
  'info' => t('User Management block'),
  'weight' => 0,
  'status' => 1,
  'region' => 'left',
  'visibility' => 1,
  'pages' => 'node/1'
);


Overriding the User entity list_builder handler

my_module.module :

<?php

use Drupal\my_module\MyModuleListBuilder;

function my_module_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setHandlerClass('list_builder', MyModuleListBuilder::class);
// $entity_types['user']->setListBuilderClass(MyModuleListBuilder::class); // Other solution possible
}

my_module\src\MyModuleUserListBuilder.php :

<?php

namespace Drupal\my_module;

use Drupal\user\UserListBuilder;

class MyModuleListBuilder extends UserListBuilder {
    // Implement the function you want to edit
}


Subdomain drupal sites cannot read domain cookies

You need to provide an appropriate value for $cookie_domain in settings.php.

e.g.

$cookie_domain = 'example.co';

That will allow you to set/retrieve cookies from example.co on foo.example.co, and vice versa.


Update Entity Reference field programmatically

Fields in forms are fun, there's some info about those here

To summarise, the element you're looking to alter will be something like

$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id'];

Rather than replace the whole thing it would be wiser just to replace the existing options array, but that'll need a small change as well.

Select options are key => display, so if you use 0 as the key, it won't match up with anything on the backend (namely a node ID in this case), and the form won't save properly. Similarly the #default_value is expecting the key rather than the node title.

Something similar to the following should do the trick:

...
$options = array($entity_node->nid => $entity_node->title);
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#options'] = $options;
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $entity_node->nid;


Auto Increment on users table is not functioning

This is a duplicate of Create a user programmatically and give they a role

// The first parameter should be blank so a new user is created.
user_save('', $new_user);

If you want to use user_save($new_user); you can set $new_user->is_new to TRUE or omit the $account->uid field.


You could use Features Translations:

  Features Translations adds a new Features component called
  Translations that allows to import/export sets of translated strings.
  String sets can be chosen per language and per text group.


Field is translatable, but field instance is not

Every node field has one storage setting. Here the field is configured how it is stored in the database, field type, single or multi value, or translatable or not. This settings can't be changed after the field is set up and filled with data. It's shared among all content types.

The field can be used in multiple content types. In each content type it can be configured to be translatable. (Option "Users may translate this field"). This setting can be changed any time and without data loss.

If you want the field to be translatable, you need both options set, in the field storage and in the content type where the field is used.

If you use the UI, then you don't have to worry about this, because Drupal sets the storage settings the first time you place a field in a content type.


How to secure access to a Forena data block?

Quote from the documentation that comes with Forena, about Data Block Security:

Data Blocks Security is a technique used to secure a selected data block. It is an additional (but optional) security layer on top of the Drupal permission "access repository name data" right (whereas "repository name" is the name of the data block's repository). Using this technique it is possible to enforce additional Drupal permissions such as:

access content
access administration pages
administer content
administer users
administer permissions
... (the (Drupal permissions) sky is the limit)

Data Blocks Security is actually implemented by means of a comment containing ACCESS=some_permission. It is added near the top of a data block which indicates the Drupal permission required to access the data retrieved by the data block. Its format depends on the format of the Data Block (which can be either in SQL format or in XML format), as further detailed below.

From the scenario in the question here, it appears to me that there is no need for adding such comment with ACCESS=some_permission, instead it should be sufficient to only use the access repository name data for those "couple of roles" that should have access to the data in the report.
Note the data in the report I wrote here: it is well possible that users who do not have the required permission for the data blocks, do have access to such "reports" anyhow. However: those reports, by design, do not show any data of the data blocks they do not have access to.
Nevertheless, I wonder if there is anything (like a bug?) that may be related to the "my_db" part of your issue. Therefor I'd recommend to also experiment with (eg) the "Drupal" reports: only grant access to these reports to "Admin" role, and then run a similar testcase. How do your results look like in that scenario? As a variation, can you (temporarily) rename "my_db" to "mydb", to check what results you then get?


Block View Relationship between two content types

I ended up figuring out what was needed for my issue. A Contextual Filter and a Relationship needed to be set.

For relationship, I needed to select Paragraph referenced from field_courses.
Then the contextual filter needed to be Courses (field_courses) Paragraph (category) Appears in: semester_courses (Description).

Now when I go to each course, it displays what program that course is taught in.


In views there is an option called Rewrite out put. You can use the rewrite out but as link and Provide the link as well as the target.

If everything is going through views then you can change the path of your content to reflect the path of your view using the pathauto module and use a breadcrumb module that would allow you to create breadcrumb from the path this way the path to the main view would be displayed in the breadcrumb for better navigation. You can take a look at the breadcrumb module


Programmatically publishing and unpublishing nodes: anonymous access

Most probably caching. Directly changing something in the database is, though the fastest, not really the safest / most reliable way of doing things in Drupal.

I'd suggest to use enity_query (or in this case even direct database access) to retrieve node ids of nodes you want to update and then use 'correct' drupal way of doing things -> load all the nodes, individually change their publish status and save them.

Something along these lines...

$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}


Make Foo and foo to be different free tagging tags in Drupal 6

This goes beyond Drupal - your database is using a case-insensitive collation, so all queries are case-insensitive.

Changing the collation would be the way to sort it ("how" is out of scope here but easy to find on Google), but that might produce unwanted results. I'd advise taking a backup beore making any changes, and having a good read up on the whole collation concept before going any further.

Another approach might be to alter the individual queries that go into the txonomy_term_data table (using hook_query_alter()), and set the collation manually (SQL examples in the COLLATE docs above). Again, your mileage may vary so take a backup before trying anything.


Do Drupal 8 / backbone.js have conflict when using AngularJS on top?

Seems like Backbone.js and AngularJS don't have conflict if used in the same page.

So one can ignore Backbone.js existence and do stuff with AngularJS.

Still there might be better ways doing this in future since D8 is still in development as I post this.

And for curly braces conflict with Twig in AngularJS we can config interpolateProvider service explained here


Is there a way to share content between users?

You will find that the Organic Groups module is very useful for allowing users to protect content in this way.  You may configure og such that only certain users may create groups, or if you prefer, as in the use case you describe above, many users may be allowed to create new groups for diverse purposes. There are many options on inviting users to groups, allowing users to request memberships to groups, or just letting anyone join groups automatically. It looks to me as if the behaviour you want can be achieved with just the og module, but if that is not the case, there are also many additional contrib modules that can extend or modify og's behavior.


Enroll user on course module error due to permissions

I haven't used the course module in quite a while but aren't there other permissions specific to the module itself?


Can access arguments only be specified once for all sub-routes?

Basing on the documentation for hook_menu() access arguments are inherited from the parent route only if the access callback is inherited, and that only happens for MENU_DEFAULT_LOCAL_TASK routes.

For the code shown in the question, this would happen only if it would be written as follows.

function mymodule_menu() {
  $items['admin'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_users_page'),
    'access arguments' => array('administer users'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/users'] = array(
    'title' => 'Users Listing',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

I take the route names are used just as example. Since admin is already defined from system_menu(), it is better not to use route names containing admin or admin/.

As side note, the page callback is inherited from the parent route, in any case.


Problem updating from Drupal Core 8.3.7 to 8.4.0 with composer

I had the same issue and here is what worked for me

Requirement : PHP 7.1
Explanation :1. Doctrire, a dependancy of Drupal core, requires PHP 7.1. Doctrine uses the latest PHP 7.1 syntax to declare the methods' return type eg. function my_function() : void {...}. There is a core bug concerning this issue with status "Needs work". Even if this bug is patched, 8.4 requires PHP 7.
2. webflo breaks the chain of dependencies
3. Drupal 8.4 requires Drush 9.0

If you have PHP 7.1 on your server you can do the following:

edit the composer.json file: "drupal/core": "~8.4" and "drush/drush": "~9.0"
delete composer.lock
delete vendor
update webflo: composer require "webflo/drupal-finder ~1.0.0"
update the database: ../vendor/bin/drush updb -y
update the entities schemas: ../vendor/bin/drush entup -y

Applied on three different production servers (Linux + Apache) and on local environments (macOS + Apach, Ubuntu + Apache). Not tested with Vagrant.

The two entity updates are concerning "paragraph entity type" : (1) The Published field needs to be updated. (2) The Behavior settings field needs to be updated.


It looks like someone has fixed this in style!
https://drupal.org/project/node_vertical_tab_elements

Haven't tried it myself, but it looks made exactly to fix this issue.


Best way to create outbound link with node field content

There are many ways to do it, depending on the field type you are using. The easiest is with the Link or Url field type (link is better as url field is lightweight). You can just set the display formatter correctly, and style it in CSS as a button. If it is in a text field, then you have to output the field in anchor tags setting it as the href attribute value. You can do it in a preprocess node template function in your theme's template file where you rewrite or replace the field value to be an anchor or if you are more of a site builder than a coder then you should look at Display Suite module and use the code field option.

Another easy option is to override the node.tpl.php file for your node type (use the proper override in the naming) and in the template file output the link using the url() function. Depending on the order of your fields you might have to then also hide the field if the content variable is rendered before you need the anchor.

My personal preference is to use Display Suite as it is such a versatile module.


Rule to send mail to the users about the percentage of their profile completed(single & multiple profiles)

How about using Content Complete or Profile Complete Percent to track profile completion. Content Complete integrates with Rules.


There are several possible reasons for that behavior. The most likely one is that your database encoding does not support these characters.

You should use a UTF8 encoding as standard character set (collation).


Try to do it with View field template. Edit your view and check for 'Theme information'. View will suggest some suitable field template according to your field and view's name. The most common template of fields is views-view-field.tpl.php

Other specific can be:

views-view-field--<my-field>.tpl.php,
views-view-field--<my-view>.tpl.php,
views-view-field--<my-view>--<my-field>.tpl.php,
views-view-field--<my-display>.tpl.php,
views-view-field--<my-display>--<my-field>.tpl.php,
views-view-field--<my-view>--<my-display>.tpl.php,
views-view-field--<my-view>--<my-display>--<my-field>.tpl.php

Here <my-field>, <my-view>, <my-display> are placeholders to replace actual field, view and display name.

Create any one of template in your active theme directory and
Try print_r(get_defined_vars()); in your template to know available variables/values.


How to make mymodule_preprocess_node run only once?

I found the issue. As @Kevin mentioned, it was being called for every node being rendered. I added a condition to check the view more as well and it is being called just one time now.

function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link')) && $variables['elements']['#view_mode'] == 'my_view_mode') {
    // perform some logic.

   ksm('in here'); // printed once as expected
  }
}


How could I create an iframe page like this in Drupal?

Add a field for URL, and then in your theme spit out the URL field value as an IFRAME tag.


Remove blog-like recent content from  page

Another way is to add the following code in your HOOK_preprocess_page() function in template.php:

if (drupal_is_front_page()) {
  if (isset($variables['page']['content']['system_main'])) {
    unset($variables['page']['content']['system_main']);
  }
}

This causes the default Drupal frontpage node-list in your theme to disappear. This method won't modify your front page title.

You'll probably want configure (admin/config/system/site-information) the Number of posts on front page option to lowest possible value (i.e. 1)  to save some performance too.


Interface Translation: Separate Drupal interface strings from theme strings?

Looks like you are looking for contexts. In t documentation:

  Parameters

  $string: A string containing the English string to translate.
  $args: An associative array of replacements to make after translation. Based on the first character of the key, the value is escaped and/or themed. See format_string() for details.
  $options: An associative array of additional options, with the following elements:

  'langcode' (defaults to the current language): The language code to translate to a language other than what is used to display the page.
  'context' (defaults to the empty context): The context the source string belongs to.

You can have separate translations for separate contexts if you need.


How to iterate through Drupal.settings in a js file when there are lots of variables?

You can add your module name to settings like this

$locations = array();
for($i=0; $i < $length; $i++) {
  $locations[] = array('a'.$i =>array(
    'lat'=> $form_state['storage']['results'][$i]['geometry']['location']['lat'],
    'long'=> $form_state['storage']['results'][$i]['geometry']['location']['long'],
  );
}

drupal_add_js(array('mymodule' => $locations), 'setting');

and loop is js like

for (var x in Drupal.settings.mymodule) {
  // ...
}


You could use the References module. This module enables you to use the results from a view as the values for a field.


Array $field_instance is occassionally empty

Apparently this was an issue with the manual lat/lon override. I didn't have it checked to allow it, but when I did check it and edited the problem nodes, the override box was already checked. Unchecking it then allowed my address field to be geocoded.


You are missing the display name, which is the machine name of the block/page.

You can find the machine name under Advanced settings in the right side of the view.

try:

   <?php
    $view = views_get_view(view_name);
    $view->set_display(machine_name);
    $view->preview();
    return $view->result
    ?>


entity_autocomplete field thats added by ajax is not working

Ok, So thanks to 4k4 I now understand what i was doing wrong, and for the favour of everyone that will meet this issue again:

The form_alter is invoked as well when ajax callback is invoked.
by the time the execution got to my ajax callback (getAjaxArgumentsFields) the form_alter has already altered my form, so all i had to do was return the fields without changing them.
Here is the code that worked for me:

use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
    $element['display_id']['#ajax'] = [
      'callback' => 'getAjaxArgumentsFields',
      'wrapper' => $id . 'arguments',
      'method' => 'replace',
      'event' => 'change',
    ];
    $display_id = $element['display_id']['#default_value'];
    $element['options']['arguments'] = get_argument_fields($display_id); //here I change my field, both on load of the page and also before ajax
}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
    $array_parents =  clac the path to the wanted field
    return  NestedArray::getValue($form, $array_parents);
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
          '#type' => 'entity_autocomplete',
          '#title' => $argument_definition['title'],//Taxonomy term
          '#target_type' => $argument_definition['type'],//taxonomy_term
          '#default_value' => '',
          '#selection_settings' = [
                 'target_bundles' =>
           $argument_definition['bundles'],//voc_name
           ],
           ];
      $args_field['#prefix'] = '
';
      $args_field['#suffix'] = '
';
      return $args_field;
}


How can I add an unescaped script tag and contents to a page?

Here's a simple way to do this with no additional modules required. For the sake of this example, I'm going to add this field to the Basic page content type that comes with the Standard installation profile.

First, let's create a new Text format. Go to admin/config/content/formats and click Add text format. I name the Text format JSON-LD and make it only available for Administrators. Be sure to leave all options blank and set Text editor to None, like so:

Then, let's add a new field to the Basic page content type. Go to admin/structure/types/manage/page/fields/add-field and select Text (formatted, long). I name the field JSON-LD with an automatic machine name of field_json_ld.

Then let's make sure we hide the field's label. Go to admin/structure/types/manage/page/display and make sure to set the Label to our new JSON-LD field to - Hidden -, like so:

Now it's time to add the script to a new page. Go to node/add/page and fill in the Title and Body as you like. Here's the important bit: for the JSON-LD textarea, be sure to set the Text format to JSON-LD, like so:

Now click Save and publish. Your node will look like this:

Nothing special, right? Now let's take a look at our source code:

Bingo!


How can I add markup above the table in a custom module?

You have multiple solutions to achieve what you want

Using #prefix

 $table = array(
  '#prefix'=> '
my link
',
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

A better way to do this is

 $table = array(
  'links' => [
     '#type'=> 'container'
     'link_one'=> [
        '#type' => 'link',
        '#title' => $this->t('Add slide'),
        '#url' => Url::fromRoute('my_route'),
      ],
   ],
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

Add module definied actions: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-actions


Bulk registration or disallow registering of certain usernames

You can do this by code, alter the registration form (hook_form_user_register_form_alter), in a custom module like:

function MY_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['validate'][] = 'reserved_usernames';
}

And then implement the validation (in the same MY_MODULE.module file) method like:

function reserved_usernames ($form, &$form_state) {
  $reserved = array();
  $reserved[] = 'reserved_name';
  $reserved[] = 'reserved_name_1';
  $reserved[] = 'reserved_name_2';
  $reserved[] = 'reserved_name_3';
  $reserved[] = 'reserved_name_4';
  $reserved[] = 'reserved_name_5';

  if (in_array($form_state['values']['name'], $reserved)) {
    form_set_error('name', t('The name %name cannot be taken.', array('%name' => $form_state['values']['name'])));
  }
}


Use the Hierarchical Select module:

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!

Another way is selecting Autocomplete term widget (tagging) as field widget, when creating your term reference field

As another option, there is the Simple hierarchical select module.


User Revisioning and Workbench moderation modules only on certain content type

You can most definitely configure only one content type to use revisoning and content moderation.

For example, once the Workbench Moderation module is enabled, the Basic Page content type can be configured here: admin/structure/types/manage/page

Click the "Publishing Options" vertical tab, and you will see you have the option to check the "create new revision" checkbox, which will enable content revisioning.

Below that you can click the "Enable moderation of revisions" checkbox to engage the workbench moderation module features.

You must enable revisioning to enable workbench moderation.  See image below:

For each content type which you desire content revisioning and workbench moderation, follow this procedure.


Content Moderation: how to make a button to move between states?

I think you should be able to do something like this. (But I did not test).

The first code block adds an additional submit button and gives it a custom submit handler. (Button specific submit callbacks should run before form submit callbacks.)

function mymodule_form_TYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Add second submit button (Also check if user can see this).
  $form['actions']['submit_publish'] = [
    '#type' => 'submit',
    '#value' => t('Submit for approval'),
    '#submit' => ['mymodule_submit_callback'],
  ];
}

And the submit callback, which simply sets the new value for the moderation state.

/**
 * Submit callback to submit for approval
 */
function mymodule_submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'MODERATION STATE ID');
}


Yes, to override twig file you just need to have the twig file with filename suggestion you get with debugger.

In case you are not able to see it, make sure of following:-

Your custom theme is enabled.
Folder where you kept your twig file has right permission.
Clear your Drupal caches.


How do I add a node ID as class to the  tag?

In mytheme.theme file: add the below code.
function MYTHEME_preprocess_html(&$variables) {
  // Add node ID to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if (is_object($node)) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }
}

This will add "node-{{nid}}" class in body tag.
Another Option
You can try Node Class module as well.

Node Class is a simple module that allows users to add custom CSS
classes to any node through the node/add interface.


How to get list of blocks for region on current page?

There's a block.repository service with a getVisibleBlocksPerRegion() method. You can either use that or look at what it's doing.

This will cover access checks as well but not empty blocks.

This is however quite a bit of an overhead as all blocks are loaded and access checked twice. There is an issue to add caching there.

Alternatively, you can use preprocess of the region templates I guess.


It is better to use drush_invoke_process() rather than exec().

$values = drush_invoke_process("@site", "cc", array("all"), array("verbose"));


Is there any way of adding the exact same login options of StackExchange websites in a Drupal 7 site?

StackExchange uses the JavaScript OpenID Selector. Drupal can use the JavaScript OpenID Selector by means of the OpenID Selector module.


Display Nodes from Taxonomy Category Term and Parent Terms

There is a function called taxonomy_get_tree() that you can use to fetch all the term IDs under a given parent ID. You can then call taxonomy_select_nodes() with an array of term IDs, which will return all nids that match that collection of tids.


Using Modal Forms - Relative paths don't work

This was due to how I implemented the modal forms. I'd put the following path:
"modal_forms/%ctools_js/login" in my menu links.

Changing this to an absolute rather than relative path solved the problem.


How to have a proper alphabetic pager with number support?

I recently started putting together a blog post showing how I did exactly this a few months ago using a custom module to create a new filter handler for views. I finished it up and posted here: http://garandwebtech.com/blog/2011/creating-alphabetical-filter-numeric-category-drupal-views-using-custom-filter-handler

Once you set up the new filter you just need to link # to pass the right parameter.


WHen I delete products andvariations via VBO some are still left

In Drupal Commerce there are products and product displays. Did you delete the products and perhaps these are the remaining displays, which aren't displaying properly because you deleted the products?


There are brackets missing:

$nids = $query->execute();

In my block this works:

 public function build() {
   $query = \Drupal::entityQuery('node');
   $nids = $query->execute();

  $build = [
   '#theme' => 'item_list',
   '#items' => $nids,
  ];

 return $build;
}


I had a similar (not quite so flexible) issue.

Basically a node lives at node/NID or a url-alias path. I didnt want to write a custom hook_menu to make something so flexible as somecategory/sometype/% -- but i really think you should be able to.

I used the module view_mode_page

  On the manage display page for a given content type, you can assign
  patterns for view modes so that they will become a page at the given
  path. For instance, if you want to show the teaser at a specific URL,
  you could do node/%/teaser. If you also use Display Suite or other
  modules that allow you to create new view modes, you can use these
  modes to display one or more fields from a node at a separate URL.

  Restrictions: currently, the node path must be contained in the URL.
  This means view mode pages must follow the form [node path/node
  alias]/[view mode url]. These pages are added via hook_menu. Multiple
  wildcard characters can be used.

I used it to set many urls for a node of the form:
'url_pattern' => 'instructors/%/'.$val

where instructors/% IS a node alias and $val is a value from a Taxonomy Term field attached to the node. Eg, I get N-subpage urls for however many terms are in this vocabulary for each node of this content type.

I then use Display Suite to create a dynamic field for a custom view mode I associated for this node and url path; I also used Display Suite to create the custom view_mode (or maybe it was the FieldUI I forget). The dyanmic field a View that takes an argument that is the wildcard in the url.

Here's a snippet of code using the view_mode_page API:

  /*
   * Implementation of hook_view_mode_page_get_patterns() from module
   * view_mode_page.
   *
   * This lets me define additional node urls (per NID) with a custom
   * view mode.
   *
   * I then use this view_mode along with Display Suite and custom Fields
   * to completely alter how the node is viewed on that page, and only
   * show a View of related downloadable course files.
   */
  function MYMODULE_view_mode_page_get_patterns($results, $content_type,  $view_mode) {
    $results2 = array();
    $defaults = array('content_type' => 'course', 'view_mode' => 'course_materials_list_view', 'show_title' => 0, 'title' => '');

    // TODO: change this to like a Taxonomy Tree lookup.
    $terms = array('activities-and-handouts', 'administrative', 'assignments', 'data-recordings-and-transcripts','lectures','quizzes-exams','readings-and-reading-handouts');
    foreach ($terms as $pos => $val) {
      $results2[$pos] = (Object) array_merge($defaults, array('url_pattern' => 'instructors/%/'.$val));
    }
    return $results = $results2;
  }

This basically works for me. Breadcrumbs aren't totally happy. It's NOT exactly what you're asking but might help as it's very related. Good luck.


Display error message when validating form in a specified region or div

If you use the form_set_error function instead of drupal_set_message, then the error message will be displayed within the form, which would mean that it would display inside your block.

If you would like to retain the drupal_set_message behaviour for your main form page then you would either need to differentiate which method is called in the validation based on url (or Context), or provide two separate forms so that you can simply validate each separately. In this instance you could build form and validate using a shared function to avoid duplication.


It looks you need to fix the breadcrumbs for a particular contentHere is my idea.

  In your theme, in template.php implement theme_breadcrumns(), as below
  Inside the theme_breadcrumbs() implementation check type of node using

menu_get_object()

function YOURTHEMENAME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

// Lets assume your content type name is chapter
  $node = menu_get_object();
  $node_type = $node->type;
  if($store == "chapter") {
     $links[0] =  l(t('Home'), '<front>');
     $links[1] =  t('Chapter');
     $links[2] =  t('Topic');
     $links[3] =  t($node->title); // Considering Sub topic as node title
     drupal_set_breadcrumb($links);
  }


hook_field_extra_fields: hidden by default

In _field_info_prepare_extra_fields() the extra fields are set to visible by default, but the extra field settings are stored in the field_bundle_settings variable which you can change in your module's hook_install() like:

$entity_type = 'node';
$bundle = 'article';
$field_name = 'my_extra_field';
$view_mode = 'teaser';

$field_bundle_setting = variable_get('field_bundle_settings', array());
$field_bundle_setting[$entity_type][$bundle]['extra_fields']['display'][$field_name][$view_mode]['visible'] = FALSE;
variable_set('field_bundle_settings', $field_bundle_setting);


User approval needed to reference (entity reference) their profile (profile2)

In order to achieve this, at a large scale, is to create a field on the user profile (example "Allow your profile to be displayed on Locations?" Yes or No).

Using views, filter profiles by field with value equal to yes.


"This page was last modified on" code not displaying

Perhaps that content type has "submitted by" information hidden.

Try just:

print 'This page was last modified on ' . date('F j, Y', $node->changed);

And clear cache at Admin > Config > Performance


How do I assign a new role to all the existing accounts on the site?

One option would be to do it via the GUI (admin/people) where you can select all the shown users with the uppermost checkbox and then under 'update options' add the role you want. If it's a one time thing for ~300 users then this is probably the quickest way to handle it.

For a programmatic approach the user_multiple_role_edit() function can be used. You need to pass the user id-s as an array, the operation and role id to the function and it'll do the rest for you. You can get the role id by checking the edit link of the wanted role via the GUI (admin/people/permissions/roles).

To get all the user id-s and assign them the role you could use the following example (modify where needed):

$result = db_query('SELECT uid FROM {users}');
$uids = array();
foreach ($result as $record) {
  if ($record->uid == 0) continue;
  $uids[] = $record->uid;
}
user_multiple_role_edit($uids, 'add_role', 4);


Loading content alone for each page from drupal to other site?

You could create a custom HTML template that would remove the HTML tags but that would render on a certain URL. However, that would make that URL every time it rendered. Web services are your best bet rendering the information an XML format. Below is the services module for Drupal 7

https://www.drupal.org/project/services


Why do my custom elements not get rendered?

For radios or checkboxes to work you need to call
\Drupal\Core\Render\Element\Checkboxes::processCheckboxes

or
\Drupal\Core\Render\Element\Radios::processRadios

Your example code, is extending Radios but trying to render checkboxes. I recommend extending Checkboxes and gradually override the default methods including \Drupal\Core\Render\Element\Checkboxes::processCheckboxes.
Below is an example
<?php

namespace Drupal\my_custom_element\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Checkboxes;

/**
 * Provides a form element for a set of My custom element.
 *
 * @FormElement("my_custom_element")
 */
class MyCustomElement extends Checkboxes {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $properties = parent::getInfo();
    // My custom properties.
    $class = get_class($this);
    $properties['#process'][] = [$class, 'processMyCustomElement'];
    $properties['#element_validate'] = [[$class, 'validateMyCustomRadio']];
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function processCheckboxes(&$element, FormStateInterface $form_state, &$complete_form) {
    // You can override and extend this method.
    $element = parent::processCheckboxes($element, $form_state, $complete_form)
    return $element;
  }

  public static function processMyCustomRadio(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add and manipulate your element's properties and callbacks.
    return $element;
  }

  public static function validateMyCustomRadio(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add custom validation logic.
  }
}


Get the custom fields created for User entity in Drupal8

You can filter the fields by checking which interface the field implements:

$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

The second parameter of getFieldDefinitions() is the bundle. The user entity doesn't have bundles, but you can configure bundle fields. In this case the bundle name defaults to the entity id.


How to change the image style for image preview in node-add/edit form?

If you are using the Media module, I couldn't find a way to change it so it doesn't use the "Media thumbnail" image style. But what you could do is edit the "Media thumbnail" image style by going to /admin/config/media/image-styles/edit/media_thumbnail and clicking on the override button which will let you edit it to your liking. (Tested on Drupal 7)

If you're not using the Media module, you can by going to your content type's Manage Fields and clicking on edit for your image field. Scroll down a bit until you see Preview image style


Running Drupal in a Windows environment (IIS, SQL Server)?

Easiest way is to use the Microsoft Web Platform Installer to install Drupal 7 - http://www.microsoft.com/web/downloads/platform.aspx

The only option it currently provides is using SQL Server as the back-end database, so you should be golden. (The Drupal 6 WebPI installs do not target SQL Server)

I've been running Drupal 7 on a Hyper-V-based VM under Win2k8 R2 with SQL Server Express as the backend DB for a few weeks without incident.


Can not override template for specific view

You either haven't rebuilt cache, or the page you're viewing isn't being generated by your Categories Views. It seems to be generated by the default Taxonomy term Views. Or you're viewing the wrong page :)

Views templates debug info is shown further down the source HTML, you won't find it at the top of the source page. Try looking below the main page heading in the source HTML, that's there the page views will start with their own templates.

This issue is also relevant:
Views file name suggestions often missing from Twig debugging

Especially the fifth comment there:
#5

Also:
[PP-3] Twig debug output does not display all suggestions when an array of theme hooks is passed to #theme

I haven't tried this module but it may be relevant:
Views Templates


How do I add a prevent duplicate item RULE to my commerce site

You're looking for the action 'commerce-order: commerce-line-items' in Rules as a way of inspecting and testing against what the user already has in their carts. The recipe outlined here goes through how to add this rule in and do some preliminary testing, I've tried to modify it for your use case:

Create rule, name it; Event: before adding a product to the cart
Add your conditions, ex. check if content is a patch
In Actions add Loop through commerce-order:commerce-line-items
Create component, single rule, name it
Create following variables of the component and name them as you wish:

Commerce line item (line item of the order from the loop of the main rule)
Commerce product (product added to the cart)

Add condition to the component: Entity has field, Entity: [line-item-in-order], Field: commerce_product. this will bring us the product from actual line item in current order (shopping cart).
Add condition to the component: Data comparison. Data to compare: line-item-in-order:commerce-product with product-added-to-cart -- This would be where you would determine if it is also a patch
Add action to the component: Remove an item from a list. List: [order:commerce-line-items], Item to remove: [line-item-in-order].
This will completely remove duplicated product from the shopping cart and from the order as well.
Eventually add another actions. At least Display some message to the user to inform him/her that the item has been removed sounds sensible.

Come back to your main rule created in step 1. Add action to the loop and select the component you have just created in steps 4. - 9. and set the variables.


Using Views Conditional Module you can set conditions for fields . The other module which may become useful is Views Field View.

Here are some description about Views Conditional Module :

  Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
  with fields in views. Conditions include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the condition.


To know what theme functions are available

The default theme implementations for Drupal core can be found listed here:

http://api.drupal.org/api/drupal/modules%21system%21theme.api.php/group/themeable/7

If you want the theme functions for contrib as well, you could use hook_theme_registry_alter on your install and dump out the theme registry with devel to list all the theme implementations.

e.g

/**
 * Implements hook_theme_registry_alter
 */
function mymodule_theme_registry_alter(&$registry){
  dpm($registry); // requires devel module
}


Setting #element_validate in a form (not form alter) removes original #element validation

You can create validate callback for the entire form and validate the element in that callback.$form['#validate'][] = 'new_validate';

Also separate validate callbacks can be attached to 'submit' ('preview', 'cancel' etc) buttons within the form. And the element can be validated there as well.

$form['submit_button']['#validate'][] = 'new_validate';


You can only use type of fields which are defined in hook_element_info.

List all the type of elements using drush by:

drush ev "print_r(array_keys(module_invoke_all('element_info')));"

If you don't need to use Webform email, check the Email field module how it's implementing such element type. See: Usage of email field with the form API.


Try the Webform Field Repeat  module

  The Webform Field Repeat module enables the webform to remember selected field entries from current submission for up to an hour. It uses the $_SESSION to do so. If the session is active, the form will be populated with selected entries from remembered submission when opened again.


How to replace I18nVariableLanguageRealm controller?

In the Drupal world 'replace' in your context is usually synonymous with 'alter'.

Try this:

function mymodule_i18n_variable_variable_realm_info_alter(&$realm) {
  $realm['language']['controller class'] = 'MyModuleI18nVariableLanguageRealm';
}


How to modify default login page using theme?

Go to

  web/sites/default/services.yml

and change the debug value from false to true

debug: true

You will get file name suggestions like shown in the image, u should use the same names.

Also, was your sub-theme succesfully installed?
Is the sub-theme under this path ? `

  themes/custom/myproject_bootstrap_subtheme

`


How change user form mode programmatically?

something like this:

/**
 * Implements hook_entity_type_alter().
 */
function YOUR_MODULE_entity_type_alter(array &$entity_types) {
  // We get all form modes, for all entities, and loop through them.
  $form_modes = \Drupal::service('entity_display.repository')->getAllFormModes();
  foreach ($form_modes as $entity_type => $display_modes) {
    if ($entity_type !== 'user') {
      // We are only interested in adding a handler to the Node entity.
      continue;
    }

    $user_entity = $entity_types[$entity_type];
    foreach ($display_modes as $machine_name => $form_display) {
      if ($machine_name !== 'sinscrire') {
        // We are only interested in adding this form mode to the definition.
        continue;
      }
      // We get the default handler class. It will be enough for us.
      $default_handler_class = $user_entity->getHandlerClasses()['form']['default'];
      // We set the form class, keyed by the machine name of our custom form mode.
      $user_entity->setFormClass($machine_name, $default_handler_class);
    }
  }
}

Credit goes here: https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8


Main page colorbox and facebook like box

You can use the hook_boot() to set/unset the visitor's cookie.
You can then use hook_init() to check the value of the cookie and execute some javascript to construct your div. Your javascript can be inserted in the page during hook_init() through drupal_add_js().


How to bulk resize images imported with feeds importer module?

If you have access to a command line and ImageMagick, you can run convert from find.
In Unix et al
From Drupal root:
find sites/default/files/products -name '*.jpg' -execdir convert {} -resize 700x400 {}\;
(Note: this assumes all product images are in the "products" directory in sites/default/files. You DO want to make a copy of this directory with cp -r sites/default/files/products sites/default/files/products_backup before running the above in case it does something you don't want it to!)
In Windows:

Download and install findutils.
Download and install ImageMagick
Make sure both are working on the commandline. Type "find" and hit enter. Same with "convert". If neither gives you a "command not found" error, they're installed and working.
Backup your product images directory.
Instead of the above command, try:

find sites\default\files\products -name '*.jpg' -execdir convert '{}' -resize 700x400 '{}' ';'
If find chokes on that path, try using backslashes. Also, make sure it's using the GNU version of find and not some other version (The lender Windows machine I'm working on right now has a find command, don't know if that's standard or something somebody else installed).


Exposed filter in views to filter users by age

You can use the contextual range filter module. to create a filter range for your age field.

  Views Contextual Range Filter is a simple plugin for Views that adds
  the option to contextually filter, not just by a single value, but
  also by range.

  Numeric, alphabetical (string) and list ranges are all supported. Node
  ids, user ids and even taxonomy term ids are all special cases of
  numbers so will work also. Range-filtering on the "created" (posted)
  and "updated" (last modified) node properties is also supported,
  provided you use the correct format as dictated by Views. So, YYYYMMDD
  for full dates or one of the shorter year+month, year-only,
  month-only, week-only and day-only formats.


Organic Groups admin has can't edit roles and permissions in groups

The problem is probably that the group doesn't have it's own role/permission settings. It's using the global og roles/permissions, and so the settings within the group are all read-only.

One of the fields you can add to group entities via the OG Fields settings is a "Group Roles and Permissions" field. Once that field is added, you can edit the group entity and set the field to "Override default roles and permissions".

Once that's done, the group will have it's own permissions, and users within the group who have permission to edit the groups permissions will be able to.


How can I get the machine name of a taxonomy term knowing its tid?

The table taxonomy_term_data lists the terms, and taxonomy_vocabulary lists the vocabularies.

In the table taxonomy_term_data, the term string is found in the name field. The field vid identifies the vocabulary assocaiated with the term. And the field tid is the numeric taxonomy id.

So you can look up the relationship between the term name, tid and vid directly from the this table.

Then, to determine the vocabulary name string associated with the term, you need to left join the taxonomy_vocabulary.name field, where taxonomy_vocabulary.vid = taxonomy_term_data.vid.


Panels is definitely the easiest way to create different layouts.

What you have to do is go to Panel Content and on the edge of each panel there is a little gear icon or arrow (if i recall correctly) that opens a drop down menu with many options. one of them is "add content", it will open a modal dialog with options to select from blocks the content you want to display, you can also add custom fields if you want!


Drupal Commerce have customer choose how many items to buy

You could just create 3 separate products in Commerce to represent each quantity. This makes sense especially if you only have a few like you describe. Each "bundle" product can have it's own SKU/model number, and it's own price. This also provides historical record, if you change your bundles in the future, you can keep the old SKU but archive it, and make a new one to represent your new pricing/quantities.


View/query to show latest node related to each term in a taxonomy vocabulary

I think that's the purpose of the module Views Grouping Row Limit.


Incomplete Object error when updating site (after Drupal timeout)

I had this error when running update after disabling Metatag and Metatag: Views. It went away when I re-enabled those two modules.

That also seems to have fixed some other issues I was having with the modules form; it would white screen on me after disabling (certain?) modules, although I could return to the Admin interface.


Toolbar broken, permission errors after permission changes

Issue was from the instructions at the top of the page of this top-ranked search result for Drupal permissions.

I did chmod -R 664 files for the files directory, which apparently wasn't sufficient to change all file permissions. Issue persisted until changing permissions it via find files -type f -exec chmod 664 {} \; as described here.


I wrote an article tackling this problem.

In short, you have to use hook_form_alter on the form taxonomy_form_term and use the function taxonomy_select_nodes() to check if a node uses the term in question.

You can just copy the code from the article into your custom module (naming the 'mymodule_form_alter' accordingly to your module's name), flush the caches and that should do it.


Slow query with large dataset in Drupal views — better to process in SQL or PHP?

Are you 100% positive that the view isn't paging in SQL?  When you turn on Query Logging in the Devel module, what do you see for your view?  I just double checked a site and am seeing (formatting is mine):

SELECT node.nid AS nid, RAND() AS random_field
FROM node node
WHERE (( (node.status = :db_condition_placeholder_0)
  AND (node.type IN (:db_condition_placeholder_1)) ))
ORDER BY random_field ASC LIMIT 10 OFFSET 0

when I am on paged view with a random sort.

I have seen the double JOIN thing before.  Often, you can adjust the view parameters and get the query to run the way you want.

Optimizing these queries is really use dependent.  I am pretty sure that both of the columns you are joining on are both indexed already.  You can try to replicate the query manually, and then EXPLAIN it, and manually improve it.  You can then implement this query in a custom block, but then you lose out on other things that Views give you.  Caching the view results, may help, too.

Keeping everything in MySQL is likely best (it is meant for heavy lifting like this), but only profiling will give the true results for your system.  Just make sure you have MySQL, Apache, and PHP tuned so that you aren't chasing the wrong problem.


The comment field doesn't contain the comments, it just contains settings and statistics (e.g. open or closed).

To get the comments, you need to do an entity query and get all comments that have point to your node of your type, load them and then calculate the average from them.

Also, see http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet on how to work with content entities and fields. kint() is highly misleading and confusing.

Update. Instead of having to load all comments and calculate the average yourself, you should be able to do an aggregate entity query and get the average value of your field directly: https://www.drupal.org/node/1918702


Visit the /admin/people/permissions page. Select the Post comments and Skip comment approval permissions for the roles for which you want to disable comment moderation.


Getting field label with entity_metadata_wrapper

How about this?

$wrapper = entity_metadata_wrapper('node', $node);
$fields = $wrapper->getPropertyInfo();

foreach($fields as $field => $info) {
  $label = $info['label'];
}


If you can accept using a module for this, rather than a theme override, you should be able to use CustomError:

  This module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.

Just to make sure I've understood the use case: You write:

  Since I only wan't to change the actual message that is displayed when receiving a 404 page

This message is by default "Page not found  The requested page "..." could not be found. ".  I think CustomError' will reproduce the standard message unless you override this - but it may something about your use case that I have not understood.


Returning all items in Views for Dates with Start dates AFTER Now as well as no date set

You can use OR conditions with the filters, and have one group of filters checking for the date value, and the other one checking for empty date field.

You would end up with something like:

*Some filters group you probably have here*
AND
  Date >= NOW
    OR
  Date IS EMPTY

Here is a post for some info on how to work with these - http://www.webomelette.com/drupal-views-filters-and-or-logic


Hide a field for that particular row based on value from custom table

$view->field['request_access']->options['exclude'] = TRUE;

Exclude will always exclude the field for every single row.

What you need to do is set it to null or empty ''

$result->field_request_access = null; // hide request

A possible downfall is that a user could guess, or have someone tell them the direct link, and still be able to see /node/656.

Thus; in addition, to what you're already doing, should also use hook_node_access

/*
 * Implements hook_node_access()
 */
function access_node_custom_node_access($node, $op, $account) {
  if($node->nid == 656 && $op == 'view'){
    // some db_query here
    if ($something_is_true) {
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }
}

If the person does not have access, the above will automatically hide any "view" link in Views.


Please specify the drupal version you  are using and is there any problem with non admin pages.

Also ensure the following:

Include .htaccess files
Enable clean urls
Clear caches


To suppress this error, add the option --strict=0 Drush

There's enough situations where I need to do that that I have just defined an alias in my startup file.

alias drush='drush --strict=0'

This is in my .zshrc file (or put in your .bashrc file if using bash).


Drush destination command not recognising

Check out the drush documentation here.
There's no mention of ftp, the backup archive is saved locally. If you want to ftp your archive somewhere you will have to handle it separately, archive-dump will not do it for you.


What is the difference between limit(1) and range(0, 1)?

Base difference is that range is a method of SelectQuery class, and limit isn't.

Some APIs can extend SelectQuery and add limit. For example  $query->extendQuery('PagerDefault') will return object of PagerDefault class that has limit method defined.

It may result in a syntax looking like limit() is invoked on SelectQuery, when in fact it isn't:

$query = db_select('node', 'n')
      ->fields('n')
      ->condition('type','problem','=')
      ->extend('PagerDefault')
      ->limit(20);


Is the homepage considered in_active_trail?

As mentioned here, it might be because you are pointing your menu link to "" instead of <front>.

There is also a module called menu by trail path, which might also solve your problem. That module sets the menu item to active if its the page you are currently on.


Easy Way to change all instances of 'Content Types' in admin to a different phrase

To do this with just one or two strings in the user interface ("Content Type" is such a string), you can use the String Overrides module.

If you end up re-writing lots of phrases, you should make a custom language since String Overrides will cause a performance hit if you use it for too many things.


Can we fetch the depth of taxonomy from term load

You can use TermStorage loadTree function. It will load the whole tree and the depths of each term will be avaiable.
A much more cleaner / efficient way can be to use the "taxonomy_term_hierarchy" table, (database service, select..). You query over and over again till the "parent" (or current examined) term parent is 0.

If you really feel you are being lost, take a look on this thread.


So first, the account switcher is for a temporary switch in the same request, to execute a specific thing as another user, it can't be used for what you want.

What Masquerade does is a lot more complicated and I don't understand why you don't just use that. Masquerade automatically adds itself to the user operations, so if you build a view that lists your users with the operations field then you will have exactly what you want to do.

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.


Printing an Entity Reference Field Value in a field collection in views-view-fields.tpl.php

I found my main answer from this question here.. Calling a field in views-view-fields--view-name.tpl.php ---- Error

My problem was excluding the display of the field. I assumed that I would want the field hidden as I wanted to show it elsewhere, but as I am overriding the views.view.fields.tpl.php anyway, I could choose to declare it or not.

As soon as I set the field to display again, I could use...

print $fields['field_link_to_content']->content;

If I had wanted to keep the field hidden, I could have used something like...

$row->field_field_my_custom_field[0]['rendered']['#markup']


How to link to section in same static page?

You need to use Jquery and a tiny bit of css.

Javascript

$('.page-scroll').click(function() {
    $('.cat-pages').toggle('slow');
});

css

.cat-pages { display: none; }

JS FIDDLE DEMO EXAMPLE

edit:

To use jquery in drupal you use

(function ($) {
    // code goes here
})(jQuery);

go to drupal/sites/all/themes/YourTheme/

look for your  theme.info file and add this line in there

scripts[] = js/myscript.js

Then go drupal/sites/all/themes/YourTheme/js and create myscript.js file.

put this inside it

(function ($) {
    $('.cat-pages').hide();
    $('.page-scroll').click(function() {
        $('.cat-pages').toggle('slow');
    });
})(jQuery);

If the above doesn't work, try

(function ($) {
    $(document).ready(function () {
    $('.cat-pages').hide();
            $('.page-scroll').click(function() {
                $('.cat-pages').toggle('slow');
            });
    });
        })(jQuery);

PS:

Don't worry about .cat-pages { display: none; }css anymore, since I added the hide in the jquery $('.cat-pages').hide();


What I would do is add a taxonomy with 6 "product-types" terms, then add a term reference field in contentype, make "6 content pane views" displaying your contentype and filtering on term reference, and with panels module (or display suite) do a 6 column display with all fields that you require, each view will have it's own column, and you are done.


how to display unique records between two table by using db_select query in drupal

I have found that the easiest way to do complex MySQL queries (including JOIN, which is what you're after here) is to use db_query():
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7

And the MySQL docs explain the JOIN syntax quite nicely:
http://dev.mysql.com/doc/refman/5.0/en/join.html


Rendering a content of a page using tpl php

You can use the same template, add your custom content to a variable in template_preprocess_page function.

function template_preprocess_page(&$vars, $hook) {
  $path = current_path();
  if ($path == 'url') {
    $vars['custom_content'] = "your custom content";
    $vars['theme_hook_suggestions'][] = 'page__url';
  }
}

Then print the variable after the content.

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


There isn't any built in way of doing this. I'm sure you could make a custom module that could do this, but it wont exactly be trivial.

What makes this a bit tricky, is that the information is store many different places. Each field has it's weight stored in the field_config_instance table, which holds general information about the field, like widget settings etc. The weights for all the extra fields for the entity/bundle is saved as a key to the field_bundle_settings variable that can be accessed with variable_get.

If you want to explore this you can take a look at the field_ui_display_overview_form_submit function which is responsible for saving the display info.


By default, Drupal use "Full_ group_by" so that why you need to Group all your fields.

If you want disable it and group only on one field, you have to update setting.php

Add this :

$databases['default']['default'] ['init_commands'] = [
'sql_mode' => "SET sql_mode = 'STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
];


If Profile2 fields are empty, problem in accessing data

I would suspect that profiles only get created when needed, hence when it is saved with field values.

You most probably then are trying to look at a profile of a user who does not yet have a profile. You should do a test on $data. If it is null or false, then you should assume that the user has no profile and that the fields are in effect empty. If you want to alter the fields then you must set up a profile object and save it after validation.

The docs for profile2_load_by_user is misleading as it indicates that there will always be a profile returned, but looking through the source code I can see a return value of FALSE.

If there is a profile then return value is either a single profile or an array of profiles, so you must test $data for 3 things: false, object, or array of objects.


Users can choose image style on content type?

Hopefully I've understood you properly; I think you're looking for the Formatter Field module:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.


How to change a field type from Integer to Decimal?

Just to merge all the previous suggestions into one convenient chunk:

// Change this to your field name, obvs.
$field = 'field_myfieldname';

// Update the storage tables
$tables = array('field_data', 'field_revision');
foreach ($tables as $table) {
  $tablename = $table .'_'. $field;
  $fieldname = $field .'_value';
  db_change_field($tablename, $fieldname, $fieldname, array(
    'type' => 'numeric',
    'precision' => 10,
    'scale' => 2,
    'not null' => FALSE,
  ));
}

// Fetch the current field configuration
$field_config = db_query("SELECT data FROM {field_config} WHERE field_name = :field_name", array(
    ':field_name' => $field,
  ))
  ->fetchObject();
$data = unserialize($field_config->data);

// Update the settings entry
$data['settings'] = array(
  'precision' => 10,
  'scale' => 2,
  'decimal_separator' => '.',
);

// Store the new field config, update the field type at the same time
db_update('field_config')
  ->fields(array(
    'data' => serialize($data),
    'type' => 'number_decimal',
  ))
  ->condition('field_name', $field)
  ->execute();

// If you are confident about what bundles have instances of this field you can
// go straight to the db_query with a hardcoded entity_type / bundle.
$instances = field_info_field_map();
foreach ($instances[$field]['bundles'] as $entity_type => $bundles) {
  foreach ($bundles as $bundle) {

    // Fetch the field instance data
    $field_config_instance = db_query("SELECT data FROM {field_config_instance}
                                       WHERE field_name = :field_name
                                       AND entity_type = :entity_type
                                       AND bundle = :bundle", array(
        ':field_name' => $field,
        ':entity_type' => $entity_type,
        ':bundle' => $bundle,
      ))
      ->fetchObject();
    $data = unserialize($field_config_instance->data);

    // Update it with the new display type
    $data['display']['default']['type'] = 'number_decimal';

    // Store it back to the database
    db_update('field_config_instance')
      ->fields(array('data' => serialize($data)))
      ->condition('field_name', $field)
      ->condition('entity_type', $entity_type)
      ->condition('bundle', $bundle)
      ->execute();

  }
}


Send 'compare product' action to Google Analytics

You can use GA Push module

  GA Push offers an API to enqueue informations that are sent GA
  servers, and three submodules to track browser events (using jQuery),
  form validation errors and log exceptions.

So, you can use the API to send an event to Google Analytics when user adds a producto to the comparison.

For example, you can use the page view function and send virtual page views for each compared product:

$push = array(
  'location' => '/comparision/product/' . $nid,
  'page' => 'comparison',
  'title' => 'Product ' . $product_name . ' comparison',
);

ga_push_add_pageview($push);

This code should called when you detect that a product is being compared.

Disclaimer: I'm one of the developers of this module.


Yes, you can use templates for this; there's an explanation of how it works on Drupal.org.

To override the page template for a specific node you would use a template file with a name like:

page--node--1.tpl.php

Where 1 is the nid of your node.

The name of the file is based on the path of the page you want to provide the template for, essentially with / characters changed to --. So for the path '/node/1/edit' the template file would be named:

page--node--1--edit.tpl.php

The easiest way to start the new template file is just to copy the existing page.tpl.php source into your new file, and add/edit what you need.

If it's the node specifically you want to theme (and not the whole page), you can provide template files for it in much the same way. There are more examples in the link above, but basically for node/1 the file would be:

node--1.tpl.php

Remember to flush the caches when you add the new template file so the changes get picked up.


Is custom token module sustainable for masive use?

In general - no, this shouldn't be a performance issue for your use case. The main problem identified with token module and pathauto is in generating the Token UI screen when dealing with a large number of tokens. There are good discussions on this here on stackexchange but I've also found that using the token tweaks module can resolve most of these.

In your use case case, your using just one token to generate the URL path which is then saved to the path alias table, a table optimized and indexed for performance. The only real demand is on token implementation but this is only done once, when saving the article and you're using objects that are already loaded (ex. $user, $node->nid) to generate it so it won't be a performance issue.


How do I reproduce this SQL with Drupal 7's query builder?

You need to do something like this:

$query = db_select('mytable', t)->fields('t');
$condition = db_or();
foreach($mywords as $w {
  $condition->condition(db_and()->condition('myfield1', $w)->condition('myfield2', $w));
}
$result = $query->condition($condition)->execute();

This is not tested but should work.

For reference, see db_or and db_and


How to pass on the user id(block user) after registration

The user registration form is generated by user_register_form(), and like normal Drupal forms, it can be altered via hook_form_alter or hook_form_FORM_ID_alter. When not explicitely set, the submit handler of a form is named form_id_submit(), however, in user_register_form, a submit handler is added to the #submit property of the form - user_register_submit().

In the function user_register_submit, you'll notice the following codes:

...
$form_state['user'] = $account;
$form_state['values']['uid'] = $account->uid;
...

which saves the new user object and ID in $form_state.

To access this after the registration form is submitted, simply add a custom submit handler via hook_form_alter() or hook_form_FORM_ID_alter(). Example:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the user registration form by adding a custom submit handler.
 */
function foo_form_user_register_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] 'foo_user_register_form_submit';
}

/**
 * Custom submit handler for the user registration form.
 */
function foo_user_register_form_submit($form, &$form_state) {
  $account = $form_state['user'];

  $uid = $form_state['values']['uid'];

  // Do something meaningful
}


Can the profile2 fields in registration be made obligatory?

Yes, as you do with any field make it as Required field.


sites/subDomain/libraries doesn't load the library files

I think you would want to keep the imageFlow library itself in the sites/all/libraries folder, then to adjust the images for each site, modify your theme to override the default css and images of the imageFlow library. You could do this by copying the imageflow.css stylesheet into your theme, including it, then modifying it to point to custom images instead of the imageflow default images.

This would be a little bit more standard approach than changing the imageFlow source files.


How to store field data in a file instead of the db?

Your best bet's going to be using the MongoDB module, I think ... Here is a quote about it (from the module's project page):

... is a collection of several modules which allow sites to store different types of Drupal data in MongoDB.
Views integration provided by EntityFieldQuery Views Backend.


"Fields pending deletion" stopping module unistall - how to delete manually?

It turns out that deleted fields in Drupal 8 are stored in the key_value table.

To find them:

select * from key_value where name = "field.field.deleted" or name = "field.storage.deleted"

The values are stored as a blob, but can be viewed (e.g. in phpmyadmin you can click on it to download, and view in vim or similar). The value does not make much sense to a human, but having gone through the code printing and error-logging various things it was clear to me that these entries were what was holding up the uninstall. I backed up the table and deleted the entries, and then was able to uninstall the module.

The same suggestion is made here in answer to a related issue:

https://drupal.stackexchange.com/a/230199/25792


Corresponding Type and Size of Data Types in Drupal in order to create a table field in PostgreSQL

The linked documentation is not missing any field types supported by Drupal. For maximum compatibility to all supported database types, the field types of Drupal's database API is limited to the field types you find within the documentation.

This assures that most modules using the default database API will run the same with PostgreSQL as they do with MySQL and almost SQlite.

However, if you need these field types in order to work on database stored information that will be used by other applications, or have another module specific requirement for using them, you can use the 'pgsql_type' attribute within your schema definition.

This attribute overrides the generic 'type' and 'size' attributes.

Within your module, you may need to query / handle the information of these fields on your own, as the Drupal database driver might not always be able to map / fetch them properly to / from your PHP objects / arrays.


How to append a new form element to a form via AJAX not triggered inside the form?

You can add some custom value to the form_state and use it to determine whether to build a new form element or not. Please try the following example:

/**
 * An example form.
 */
function example_form($form, &$form_state) {

  $form['#tree'] = TRUE;

  // Use this value to determine whether to build a new form element or not.
  if (empty($form_state['add_new_item'])) {
    $form_state['add_new_item'] = FALSE;
  }

  $form['example_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Example form'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['example_fieldset']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => FALSE,
  );

  $form['actions'] = array(
    '#type' => 'actions'
  );

  // add field button.
  $form['actions']['add_field'] = array(
    '#type' => 'submit',
    '#value' => t('Add new form item'),
    '#submit' => array('field_add_one'),
    '#ajax' => array(
      'callback' => 'example_form_callback',
      'wrapper' => 'example-fieldset-wrapper',
    ),
    // hide this form element
    '#attributes' => array(
      'class' => array('element-invisible')
    )
  );

  // submit button.
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );

  $form['#attached']['js'] = array(
    array(
      'type'  => 'file',
      'data' => drupal_get_path('module', 'YOUR_MODULE') . '/js/add_field.js',
    ),
  );

  // append a new form element (after ajax)
  if ($form_state['add_new_item'] == TRUE) {
    $form['example_fieldset']['new_item'] = array(
      '#type' => 'textfield',
      '#title' => 'My new item',
    );
  }

  return $form;
}

/**
 * Submit handler for the "add-field" button.
 *
 * - set the $form_state['add_new_item'] as TRUE.
 * - rebuild the form.
 */
function field_add_one($form, &$form_state) {
  $form_state['add_new_item'] = TRUE;
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback.
 *
 * Returns the fieldset with all values in it.
 */
function example_form_callback($form, &$form_state) {

  return $form['example_fieldset'];
}

/**
 * Final submit handler.
 *
 * Reports what values were finally set.
 */
function example_form_submit($form, &$form_state) {
  $output = $form_state['values']['example_fieldset'];
  drupal_set_message('
' . print_r($output, true) . '
');
}

add_field.js

(function($) {
  Drupal.behaviors.your_module_name = {
    attach:function() {

      var form = $('#example-form');

      // the 'add-field' form element
      // this form element is invisible. It will be triggered by the custom link (not form element).
      var addField = $('#edit-actions-add-field');

      // add an example link
      $('#my-custom-link').remove(); // prevent from adding the custom link more than once
      form.after("ADD FIELD"); // add custom link

      // Attach mousedown() to the custom link in order to activate ajax.
      // Notice: You can attach click() to a normal submit form element (without ajax)
      // but it has to be mousedown() if the form element has an ajax attribute.
      $('#my-custom-link').click(function() {
        addField.mousedown();
      });
    }
  };
}(jQuery));


I am not able to traverse from the last step to the first step in a multistep form

The example module uses a value stored in $form_state['storage'] to indicate which step the form is in, when it is being built. You could add a button with a custom submit handler that unsets this value or set it to the value needed for the step you want to show. Also remember to set $form_state['rebuild'] = TRUE;.

On a side note, if you want to make multi step forms, the ctools multi step form wizard API can help you doing a lot of these things for you.


Better exposed fiters with Views: how to show quantity of nodes tagged with certain term?

I ended up with editing \sites\all\modules\better_exposed_filters\better_exposed_filters.theme

Inside it I made a query to field_data_, got all terms with nodes count:

function theme_select_as_checkboxes:

$res = db_query('SELECT field_dance_styleee_tid, COUNT(*) as count FROM field_data_field_dance_styleee
 GROUP BY field_dance_styleee_tid');
    $allNodes = array();
    while($record = $res->fetchAssoc()){
        $allNodes[$record['field_dance_styleee_tid']] = $record;
    }

Then passed $allNodes to

  $output .= bef_checkbox($element, $key, $value, array_search($key, $selected_options) !== FALSE, $allNodes);

function bef_checkbox($element, $value, $label, $selected, $allNodes=array()) {

$value = check_plain($value);
  $label = check_plain($label);
  $id = drupal_html_id($element['#id'] . '-' . $value);
  // Custom ID for each checkbox based on the 's original ID
  $properties = array(
    '#required' => FALSE,
    '#id' => $id,
    '#type' => 'bef-checkbox',
    '#name' => $id,
  );

// Prevent the select-all-none class from cascading to all checkboxes
  if (!empty($element['#attributes']['class'])
      && FALSE !== ($key = array_search('bef-select-all-none', $element['#attributes']['class']))) {
    unset($element['#attributes']['class'][$key]);
  }

// Unset the name attribute as we are setting it manually.
  unset($element['#attributes']['name']);

$checkbox = '';

$properties['#children'] = "$checkbox $label". ((
      $element['#name'] == 'field_dance_styleee_tid' && isset($allNodes[$value])
  )? "(".$allNodes[$value]['count'].")" : '')."";

$output = theme('form_element', array('element' => $properties));
  return $output;
}


use content type field value as css class in views

The easiest way to achieve this was actually use the views module itself. The value of the type field can be easily used as a row class. Thanks for the other suggestions, but in the end this was all I needed.


Drupal Commerce Line Item temporary delete?

Turned out the issue was simpler than I thought.  If you think about the field between line_items and orders as a reference, it makes sense to just remove that reference, save the order, than re-add it later.  I assume the issue was arising that Drupal didn't like deleting than recreating the exact same line_item, so if it isn't ever deleted, than the reference can just be updated.


View: display first value in a single field in field collection

This can be done by modifying the Multiple field settings of your name field:

Click on the "name" field in your view (to edit the settings of field)
Navigate to "Multiple field settings" (present just above "Style" settings)
Click on the checkbox: "Display all values in the same row"
Choose "Display type": Ordered list
Below display type, there is one field "Display": Replace "ALL" with 1
Save the settings and the view.


How can I show country icons in the select list provided by the countries module on the edit page?

Following MotoTribe's suggestion, I filed a feature request which is already in progress.  Exciting!


How to add/modify new taxonomy terms in node edit form? (taxonomy type is not tag)

May be you are looking for Taxonomy Other module ?


Look at the answer in this question: Flag module views integration

It seems to be possible with relationships, though I would guess that this depends a little on your flag configuration.


one view show nodes and their referenced nodes - both only published

While there might be other approaches, I'd go with Views Field View.

It allows you to use a view as a field in another view. Then just build a view for the answers, taking a nid argument as an entity reference contextual filter. And use that view as field in your question listing view.


What does test status postponed for a patch on d.o mean?

The problem is that the current Rules branch is currently failing an already commited test. While this should obviously not be possible, as tests should be green before they are commited, rare circumstances will cause this to happen from time to time.

Since an already existing test does fail, we know that testing with your new patch will also fail, whether your patch is correct or not. Thus all tests are postponed until the existing and breaking test is fixed.


Using oauth_common in a module to authenticate with a web service?

Have you ever try to use OAuth Connector. It allows us to create the comsumer/application/connection to Twitter, Facebook... or another Drupal website. For my own purpose. I used that for fetch the data from Drupal 6 Services 3 by using this module in Drupal 7 and some extra code and it worked fine.


Why is data-quickedit-entity being printed in plain text when I'm signed in?

This line prints the attributes in plain text:

{{ attributes.removeClass(classes) }}

If you want to remove classes without printing then use set:

{% set attributes = attributes.removeClass(classes) %}


How do I add a class to a row based on the value of a field in that row?

The following will add the class 'hello' to the li tag. I used a view with machine name 'dates' and a display name of 'page'. The time field is the node created time. You can just install Devel and uncomment the dpm($vars) statement to get what you need. I also left the conditional logic up to you.

Put this in your theme's template.php file:

function MYTHEME_preprocess_views_view_list(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    // dpm($vars); //uncomment to see variables
    foreach($vars['view']->result as $key => $value){
      $timestamp = $value->node_created;
      if ($timestamp) { // add whatever conditional logic you need here
        $vars['classes_array'][$key] .= ' hello'; // note the space in front of class
      }
    }
  }
}

An alternative method is as follows:

Put this in your theme's template.php file:

function MYTHEME_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    $timestamp = $vars['row']->node_created;
    if ($timestamp < strtotime('now')) {
      $vars['classes_array'][] = 'bye';
    }
  }
}

and use this views-view-fields--VIEWNAME.tpl.php file:

<div class="<?php print $classes;?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
  <?php print $field->label_html; ?>
  <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</div>


default value for entity reference field

From the sample code given in question, I assume the hook_form_alter() is used. You should first load the referring node, get the Node Title and Node ID from it, and then set the default value using both. This works.

Setting the default value using Node ID alone will not work.

$entity_node = node_load($nid);
if ($entity_node) {
    $form['field_op_product'][LANGUAGE_NONE][0]['target_id']['#default_value'] =
        "$entity_node->title ($entity_node->nid)";
}


How can you change the temporary directory?

In https://www.drupal.org/node/3039026 / https://www.drupal.org/node/3039255, which was introduced in Drupal 8.8.0, the ability to configure the temp directory was removed from the UI and moved to settings.php.

From the change record:

  The following lines are now in default.settings.php

/**
 * Temporary file path:
 *
 * A local file system path where temporary files will be stored. This directory
 * must be absolute, outside of the Drupal installation directory and not
 * accessible over the web.
 *
 * If this is not set, the default for the operating system will be used.
 *
 * @see \Drupal\Component\FileSystem\FileSystem::getOsTemporaryDirectory()
 */
# $settings['file_temp_path'] = '/tmp';

So, you should edit your settings file.

If your temp directory is different in your environments, you need a mechanism to handle this.  I typically use .env files for this, the database connection info, and some other settings.


How to get nid and title from a node array

As mentioned in the comment of @Hudri Node is an object not an array.

In Drupal 8 there are two ways to get the value of a field.

$node->field_name->value
$node->get("field_name")->getValue()

In your case you can get the nid and title like below:

$nid = $node->id();
$title = $node->label();

or

$title = $node->getTitle();

To read about objected-oriented programming conventions In Drupal 8 check this blog article: Drupal 8 API: objected-oriented programming conventions.


How to translate Views header syntax? not Title

Here's how to translate expressions containing HTML code:

Go to admin/config/regional/i18n/strings
Check "full HTML" in "Translatable text formats" section
Then, go to admin/config/regional/translate/i18n_string
Click on "Refresh strings".


how to display an image in theme using img tag?

add image in this way,

<img src="/sites/all/themes/mytheme/images/logo.png" />


Create a new user programmatically and mimic the registration flow?

I'm not clear on what your overall goals are here. However, you might check out the Form Clerk module. You can use it to create users, as well as many other things.

  Form Clerk is an administrative utility that provides a semi-automated way to input data into a Drupal form. Multiple instances of form data can be entered with one command. For example, multiple users with varying permissions can be created, or multiple articles with arbitrary content can be added.


Drupal imposes no limits on how you can use php. If it's possible to do what you need to do in php, it's possible in Drupal.

There are no Drupal-specific API methods to help execute code through the shell, so just approach this as you would if Drupal wasn't involved.

A simple method, depending on what you need to do, might be to install Drush and invoke commands using that. Then the bootstrap/file includes will be handled for you automatically and you'll need to write less boilerplate code.


you can use template_preprocess_user  like

 /**
 * Implements hook_entity_presave().
 */
function mytemplate_preprocess_user(&$variables) {
  // get user object
  $user = $variables['elements']['#user'];
  //- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'offline';
  }
  $variables['status'] = $status;
}

/**
 * @param $uid
 *
 * @return bool
 */
function account_is_logged_in_less_then_thirty_minutes($uid) {
  $connection = Database::getConnection();
  $query = $connection->select('sessions', 'sessions')
    ->fields('sessions', ['sid', 'uid', 'timestamp'])
    ->condition('sessions.uid', $uid, '=')
    //- chef if the user was online in 30 minutes (60 * 30)
    ->condition('sessions.timestamp', \Drupal::time()
        ->getRequestTime() - (60 * 30), '>')
    ->execute();
  //- Get result.
  $results = $query->fetchAll(\PDO::FETCH_OBJ);
  return (count($results) > 0) ? TRUE : FALSE;
}

In you template check on status variable like the following:

{% if status == 'Online' %}
   Online
{% elseif status == 'Absent' %}
   Absent
{% else %}
   Offline
{% endif %}

Add use Drupal\Core\Database\Database; to the top of your file.


How to allow users to create only one group using Organic Groups 7

You could try Node Limit module to limit to one the number of nodes of your group content type to be created by user.


Loading a custom library after all other libraries got loaded

That is neither possible (because JS files have no "weight" anymore in Drupal 8), nor does it make sense: Any module can declare a JS file as async or defered, so even if your file would be in last position in HMTL markup, there is absolutely no guarantee that it will be executed in that order.

PS: Module dependencies seem to quite reliably affect ordering of their JS libs in markup, not really certain about it though.


entitymetadawrapper with field collection multi value

I've found this example in one of the bug reports on d.o, hopefully it will clear things up a bit:

// Load the entity and wrap it.
$entity = entity_load_single('my_entity', $entity_id);
$wrapper = entity_metadata_wrapper('my_entity', $entity);
// Create new field collection items.
$collections = array();
// This is a contrived example so assume $things contains some data that might be set on the collections.
foreach ($things as $thing) {
  $fc = entity_create('field_collection_item', array('field_name' => 'field_example_collections'));
  $fc->setHostEntity('my_entity', $entity, $entity->language, FALSE);
  // Skip saving the host entity since the order in which we are creating the items is not the order we want them saved.
  $fc->save(TRUE);
  $collections[] = $fc;
}
// Set the field collection items via the wrapper.
$wrapper->field_example_collections->set($collections);
// Save the entity.
$wrapper->save();

Just as @Clive commented, you need to first load the host entity that this field collection field is attached to (I'm assuming it's a commerce_line_item?), then loop through your data and create field collection entities. Then after you've done assigning values, collect them all in an array and set the array as the new value for the host entity's field collection field.


Using token_replace in php filter with webform2pdf

When you use token_replace(), you need to provide it with a proper data array. Since you provide it with a node, your token replace can only replace [node:*] tokens (exceptions for global tokens such as [site:*]). If your submission is a node, you should be able to use [node:nid] instead.

If you were to use $sid = token_replace($sid_token, array('submission' => $node));, you can use tokens like [submission:*], but only with node properties (nid instead of sid).

If your submission is of another entity type, you will have to provide that as data as well.


Would hook_access() hide content from Views/Solr if returning FALSE?

hook_access() is only called when viewing/editing a single node. For all listings, both in core and views, you need to use the node access system. You also need to use that for node types which are not owned by your module.


Ubercart - Sale approval required before payment

There's many ways to go about this but I would use Rules & custom Role called Vendor. You can specify on Drupal load if a user doesn't have a Vendor role & is loading the cart/checkout page. That you can redirect them to your application form with a message prompting them to apply before checkout.

Here's an example rule:

{ "rules_check_vendor" : {
    "LABEL" : "Check Vendor",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "test" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "cart\/checkout",
          "operation" : "starts"
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "In order to become a vendor. Please contact us." } },
      { "redirect" : { "url" : "contact" } }
    ]
  }
}


How do I enable and weight fields through .yml?

Adding formatters or widgets to field configuration doesn't work. You have to add them to the existing display modes in hook_install().

See entity_get_display and entity_get_form_display, which are deprecated, but contain examples how to add components to display modes and code replacing the deprecated functions to load the entity displays.


How do I use field_view_field inside a custom views .tpl?

Ok, so I figured it out. First I did a node load:

<?php $node = node_load($row->nid);?>

Then I had to wrap my field_view_field in a drupal_render, finally I added my image style name in the display parameter, like this:

<?php print drupal_render(field_view_field('node', $node, 'field_image', 'image_style'));?>


Adding Contextual Links to Ctools Custom Content Type Plugin

You don't need to do that, what you can do is you can implement a hook_menu_alter and do this.

function YOUR-MODULE_menu_alter(&$items) {
  $items['YOUR-PLUGIN-PATH/%ctools_export_ui/edit']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

and then add your contextual link to your object. If it a block you can add below code in to your hook_block_view.

$block['content']['#contextual_links'] = array(
  'YOUR-CUSTOM-PLUGIN' => array('YOUR-PLUGIN-PATH', array($delta, 'edit'))
);


Save form when user refreshes page from browser or click on any anchor tag inside page

You would need to create your own AJAX implementation to achieve this. Upon some trigger, whenever you want that to be, (I would make it save any time a field looses focus), you would perform an AJAX call saving the information into a database. When the user returns, provided they are traceable in some way either through their UID or a valid session, you would fill the form out again with the information from the temporary table in the database. When the user completes the form, let Drupal write the data accordingly. Otherwise, there is no way to save the users information and present it to them again. This method, if the user is registered, would always work. Make sure you add a "clear form" button though so they can clear it if they want.

Update: You could use .unload