Multistep module not works for User Edit form (Edit Profile)

Never used this module, but it seems that it could do what you need

https://drupal.org/project/step

It can be used both with deafult drupal registration system or with Profile2 module, however mind that it is still in dev version.

Cheers


Update programmatically value of field collection item

If you want to Update value of field collection item use Set Something like:

$book_wrapper->field_title->set($title);

For more info See Entity metadata wrappers Docs Example using field collections Section.


Drupal Services is a bit strange in that it doesn't seem to fall back to calling the user_access() function. Instead, I always provide a custom access callback function, and in it usually just make a call to user_access(). Try this:

'doli' => [
        'create' => [
            'callback' => 'custom_api_create_user',
            'access callback' => 'example_access_callback',
            'access arguments' => array('administer access control'),
            'access arguments append' => TRUE,
            'access callback file' => array(
              'type' => 'inc',
              'module' => 'example',
              'name' => 'example.resource',
            ),
                'args' => [
                [
                    'name' => 'data',
                    'type' => 'struct',
                    'description' => 'data',
                    'optional' => FALSE,
                    'source' => 'data'
                ]
            ],
        ]
    ]

Then make a file called example.resource.inc in your module's folder, and place this code into it:

function example_access_callback($permission) {
  return user_access($permission);
}


How to use language-specific menu items in URL aliases

Your configuration is too complex to be able to say with certainty, but your menu tokens seem to support "languages", so it may be the Path that needs some extra support.

Have you enabled Path translation or tried Pathauto i18n?


Is there something like a private FAQ/ask-the-expert?

The question_answer module is probably what you want. I used to make a private Q/A for registered users on a site. All the "workflow" you talk about can be done via either the workflow module, drupal actions or the Maestro module ... I'd give Maestro a shot only because I haven't used it.


Modify the store for hundreds of products

There are two methods that are the "Drupal" way.

One is to write a PHP script that changes the products as needed.  You would write a loop, load the products, update, and then save them.  You then can the execute this script with drush as drush scr whatever.foo.  This will bootstrap Drupal, and then execute the script in the context of a running Drupal install.  Just keep in mind that loading a lot of entities in the same process can cause problems with the static cache getting too big.  There are other questions here about how to handle this.

The second is to write a hook_update_N() function, and put it in a custom module.  This is essentially the same as the standalone script.  If you go with this approach, you can batch the changes (say update 50 at a time).  You can then run the update from the UI or with drush updb.  This approach works a little better with database backups / restores, and also works nicely if you have a dev -> staging -> production environment, especially if it also pulls the database backwards at each step and automatically runs updates.


How do I display different "No results behavior" based on exposed filter results and total results?

You could easily adapt the views-view.tpl.php to your specific view, eg, views-view--VIEWNAME.tpl.php and change up the portion dealing with no results...

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

...with something along the lines of...

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php if (count($_GET)>1): ?>
      Sorry, there are no results matching your search criteria.  Perhaps with other filters you may find some.
    <?php else: ?>
      There are no postings at this time. Please check back later.
    <?php endif; ?>

<?php endif; ?>

...with just some really simple logic based upon parameters Views uses for the exposed filters (eg, if more than ?q=PATH is sent it will have more than just 1 in $_GET).

Now if you want to get fancier than this you may want to investigate one of the Views preprocess hooks and actually change up the $empty variable and not put a lot of logic in the template.

If that's the case you could go further and re-run the View via views_get_view_result() without any filters and if it had any results, actually return your desired Sorry, there are no results matching your search criteria.  (You could do this in this template file but I really try to keep lots of deep logic outside of them)

(Is there any way to dynamically add a CSS class selector to a view with submitted exposed filters? has some more code you might be able to re-use here as well)


No install link for sub theme of sub theme

Copied the base theme's info file and changed 'name' to 'base theme'. But the base theme entry needs to be the machine name of the theme, whereas the name is a descriptive name.


the easiest way is field_collection:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

You can make a compound field in code as this Phase2 Blog Post describes .... maybe there's a module for a compound field, but its usually not worth the effort.


Node status is baked into the node access system fairly deeply in implementations.  What I mean is, it is not directly used by used hook_node_access() and hook_node_grants(), but implementations of these hooks do.  The node access system defines who can see and do what to nodes.  So, if you are using nodes outside of page content (eg, using Rabbit Hole w/ Nodequeue), you can still hide your unpublished content from people who don't need to see it.


Adding tool tips to menu items and views

Take a look at the qTip module or the Tipsy module as alternatives to get "good looking" tooltips or simply add a description to the menu items for basic browser created tooltips


Set views contextual filter as request_path()

If you want to filter nodes in a Views list that have the same expression in their "Alias" field as the path where the Views Block is shown then you can do it by adding the "Alias" field as a contextual filter and configured like this:

When the filter value is NOT available
Provide default value
Raw value from URL
Path component 1

Adjust the path component to the place where your service appears in the path.

You can also adjust the validation and other options that are relevant to you, but that first bit is what is the most important to match the path to your field.

The field value content/services might  match only on pages where the path starts with content/services. I haven't tested this, I expect the field expression will be treated as a one string, but the path will only take the first part before the / so in the end it won't match.

If you find that it doesn't work, then you might make it work with the help of Views Argument Substitutions and Views Contextual Filters OR.

You could also do it with the Context module and Context entity field but it's a fairly complex to configure.


The directory sites/default/files exists but is not writable and could not be made writable

RHEL and Fedora (among others) may have SELinux security enable.  This will mask whatever the regular Unix permissions are showing.  If this is enabled and there is not a "rw" in the context for the files/ directory it will not be writable no matter which group, user or unix permissions are granted.  To see these "hidden" settings:

ls -laZ sites/default

drwxr-sr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0 .
drwxr-xr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0 ..
-rwxr-sr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0         default.settings.php
drwxrwsr-x. apache www unconfined_u:object_r:httpd_sys_content_t:s0 files
-rwxr-sr-x. apache www unconfined_u:object_r:httpd_sys_rw_content_t:s0 settings.php

To change the settings on files/ so it is writable:

sudo chcon -R -t httpd_sys_rw_content_t files

When the install is done reset the context using the same command with the original "http_sys_content_t" context.

fyi - This command will also be necessary to enable writes when installing themes under the "all" directory.


Inclusion of SEO-related content in the header using structured Microdata

You can use Drupal hooks and functions like

hook_preprocess_html - Get and set metadata here
drupal_add_html_head - add element to HTML head

You could also call drupal_add_html_head from other API hooks such as hook_node_view, hook_ctools_render_alter, hook_init etc..

e.g:

/**
 * Implements hook_preprocess_html
 */
function mytheme_preprocess_html(&$vars) {

  $content = drupal_get_title() ? drupal_get_title() : variable_get('site_name', 'Drupal');
  // Add open graph title to head
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => strip_tags($content)
    )
  );

  drupal_add_html_head($element, 'fb_social_open_graph_title');

}


How to prevent behavior-attached functions from being attached twice?

The once() function will help with that,e.g.

(function($) {
   Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

      $('.skip-line', context).once('mymodule').on('change', function(){
        // some code
        if ( confirm(Drupal.t('Apply to all languages?')) ) {
          // applying...
        }
      });
    }
  };
})(jQuery);

One of the many references


Rules - Check if coupon has been added to an order

Add A Condition Also In Rules That Will Help You In These You Can Also Create Manual Option


How to set image style for media browser in node edit form?

Once you have chosen the image and clicked save and the overlay is closed, images are display in the "Media thumbnail" image style. Did you perhaps change the settings for that image style under admin/config/media/image-styles?


force webform to reload or start from page1 with rules

While adding rule action you can select System > page redirect

This is how you can choose:

Thanks!


This sounds like a folder permissions problem.
Check to see that the user account that your web server is using to server web pages has write permissions in the 'sites/all/modules' folder.   Your webhost can help you with this.


The problem is that the <div> with id #views_slideshow_cycle_teaser_section_partners-block for the browser has an height of 0. Therefor, the most simple solution for you would be to set a static height for this element using CSS (i.e., the largest slide is currently 656px).

If you want the 'view all' link to be right below the slide that is shown to the user, in your situation I think the most easiest solution would be to alter the height of #views_slideshow_cycle_teaser_section_partners-block using JavaScript (i.e., jQuery).

For more information on this, see this post: Make absolute positioned div expand parent div height


WYSIWYG module is not finding my custom plugin

Turns out the tutorials and answers were wrong (at least for my set up/needs) The extra hooks and $settings['extraPlugins'] = 'button_styles'; were probably causing conflicts. I removed all but this;

function MY_MODULE_wysiwyg_plugin($editor, $version) {
switch ($editor) {
  case 'ckeditor':
    $module_path = drupal_get_path('module', 'MY_MODULE');
    return array('my_plugin' => array(
      'path' => $module_path . '/plugins/MY_PLUGIN/',
      'buttons' => array(
        'style_1' => t('Style 1'),
      ),
      'load' => TRUE,
    ),);
  break;
 }
}

and now it recognizes my plugin.js.


Update values of multiple value field programmatically? (Rules action)

DOH! - Seconds after adding my previous edit i realised what was wrong. Below the final code :)

function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom group'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();
    $new_ref = commerce_order_load($orderID);

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $new_ref;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}


How to allow user registration based on roles?

I would recommend that you have all users register on the same page, and have "business" users register for the right to add businesses using either the Apply for Role module or Organic Groups.  Note that Organic Groups will allow you to put a checkbox on the registration page, so business users could check the appropriate request checkbox as they sign up.  An admin would have to approve their request to join the "business" group.


Front page works; the rest returns "URL not found"

Note: This answer tells you how I fixed it in Ubuntu. I don't know about other operating systems, but you might wanna look up if
  mod_rewrite exits there too. If yes, you probably need to enable it
  there too.

I had that happen to me. I fixed it by enabling mod_rewrite.

In your terminal, type:

sudo a2enmod rewrite

sudo service apache2 restart


Expose two filter blocks from the same view using drupal 7 ?

An alternative to this is to

Clone your page display - but do not change the cloned pages path...
Override and modifty the filters for that cloned display

You will have an exposed block with different filters that submits to the original view.


How to export recent logs report in csv file drupal 7

Assuming that you're looking for a module-driven solution to export the content of the 'watchdog' table, you could combine Views, Views Watchdog and Views data export.


Add external database name in settings.php(../sites/all/default/settings.php) file of your project. You can set databse in settings.php as follows:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '8080',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '8080',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

And you can directly add your query in files.


hook_commerce_order_presave firing on page load

This is unusual. The hook should not be executed on every page load. You might want to check if some code in a custom module, custom theme, rule is causing an update of commerce_order which could trigger the hook.

To ensure that the order is updated on every page load, you can implement hook_entity_update(), in your custom module

function MODULE_entity_update($entity, $type) {
  if ($type == 'commerce_order') {
    // Execute your code here.
  }
}

If the code inside if loop is still executed, you can be sure that the something is triggering update of commerce order on each page load. And you can proceed to find out what is the actual cause of the problem.


Get array length of a multiple fields of a node content type

Confirmed that as suggested in the comments, the following works quite well:

count($node->field_categoria_del_libro_presen);

Here the count would be 2 (based on the example in the question).

This works because even though the field_categoria_del_libro_presen property on the node object is a EntityReferenceFieldItemList, it implements (by way of implementing ListInterface) the native PHP \Countable interface.


Unfortunately I have to surrender. There is a bug somewhere in the og module but I can not track it down. What happens is that the default group membership role can not be changed. Changing the definition of OG_AUTHENTICATED_ROLE in the og.module does nothing. Because of that all the access rights given to the "member" role are being inherited by all the other roles and so they can not be weaker.

My solution will have to be creation of new members role - "full_member" where I will be able to define roles of that member. I will also remove all permissions from the "member" role. The problem is that I will have to redo all the rules, contexts, pages, blocks, custom code and so on. Few days of boring work and debugging.


For creating a new date format to be used in views:-

Go to yoursite.com/admin/config/regional/date-time
And create the new format.

Now, Go to the view you're working on, add date field, change its format. Yes, it's as simple as that.

Plus: You can use Date module, it has got amazing features.


How to delete children when main entity is deleted?

You could use rules  to react to an entity being deleted, then add a loop over the reference field and use entity delete for the current list item.

Currently on my phone so apoligies for the compact answer.


Customizing search results page to use template.php and search-results.tpl.php

To change the snippet (that jumbled mess you mention), use theme_preprocess_search_result() (you want to override each search result, not the page of search results). Explicitly set $variables['snippet'] to the value you want to display.

A common tactic is to use the node's teaser view.

function mytheme_preprocess_search_result($variables) {
  $teaser = node_view($variables['result']['node'],'teaser');
  $variables['snippet'] = drupal_render($teaser);
}

You can manage the node's teaser in Admin -> Structure -> Content Types -> Your content type -> Manage Display -> Teaser as always.

There's a no-code approach also. While you're managing displays, check out the expandable fieldset for 'Custom display settings' and check the one for 'Search results highlighting input'. Here you can control the fields you want to display, but Drupal will still show only a snippet, and it will highlight where in the node your search terms show up. Ditch the preprocess function in this case.

Here is one more example with the theme_preprocess_search_result() function that shows the first 160 characters of the body field: https://alastaira.wordpress.com/2011/01/07/customising-the-search-results-snippet-in-drupal-7/ (note that this one does not check for language).


node_save() not working with LANGUAGE_NONE

I presume by your code example you use D7. And I presume by the error you get you don't use Entity Translation.

In D7 the built-in approach to offer multilingual content is called 'content translation'. Meaning you translate node by node. You hit the language switch and get redirected to another node.

Whereas in D8 the Entity Translation module now became part of core and so it replaced the 'content translation' approach by the 'entity translation' approach. Meaning you translate field by field. By providing a language key for every field. You hit the language switch and the same node reloads, but this time rendering the field values in a different language.

To come back to your question, as you don't use Entity Translation, you only have to set a language for the node (and possibly map it to their matching nodes in other languages). You MUST NOT specify a language for each field.

Alternatively, start using Entity Translation and configure the fields you want to be multilingual. Then, if I remember it right, your code will work.

Comparing both approaches, each has its pros and cons. And I already built D8 sites where we had to somehow rebuild a custom 'content translation' workflow (node by node translation), to get back the flexibility this has (especially in connection with Paragraphs – but that's a different story to be told).


Use this:

function fieldmidity_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'midi_formatter') {
    foreach ($items as $delta => $item) {
        if ($item['uri']){
            $element[$delta] = array('#markup' => file_create_url($item['uri']));
        }else{
            $element[$delta] = array('#markup' => $item['uri']);
        }
      // Options for $item; filename, uri, description, filesize, timestamp, fid, uid
    }
  }

  return $element;
}


Well, I guess that you are asking about creating hierarchical menu structure, so that menu item pointing to your "another basic page" is a child of menu item for first "basic page"?

Then yes, there is a way, and pretty easy to it, when creating a second "basic page" and providing a menu link for it (in Menu settings section), make sure that you select your first "basic page" in Parent item dropdown.


Can MySQL 5.6 be used with Drupal 6 and php 5.2.17

MySQL 5.6 works fine; using the mysqli driver. PHP 5.4 works after fixing a couple of notices, and php 5.2 works without any modifications.

In your settings.php file change $db_url = 'mysql://...' to $db_url = 'mysqli://...' to use the mysqli driver; it's that simple.


Commerce Card on File module was built exactly to solve this purpose!

  Commerce Card on File provides an API and user interface for storing and reusing credit card data on subsequent orders within Drupal Commerce. The module does not retain full card numbers locally but instead stores the remote ID of the full card data from the payment gateway used to validate and process your credit card transactions. This means card on file data will only be good for a single payment gateway; if you change payment gateways or accounts, your stored card data may no longer be usable.


You could use the Computed Field module, which allows you to write custom PHP functions to determine field values.  You will of course need to be familiar with PHP.


How to automatically modify a field after saving content?

You can use the Rules module to get this logic implemented. Have a look at my answer to "How to set the values of some fields depending on the value of a list box?".

The rule shown there uses these fields:

a selection list field with machine name field_optionlist (corresponds to your field 1).
a text field with machine name field_free_format_text (corresponds to your field 2).

If you adapt the machine names in that rule (in Rules export format) to the names from your 2 fields, should be straight forward to further tune (customize) it to also match the values as in your case.

However, to make this to work with only 1 rule (instead of writing 3 rules, ie one for each possible value of field 1, so one for "A", one for "B" and one for "C"), you also need the "Conditional Rules module. That way you could expand the prototype to say dozens of different possible values. For an example using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Best practice advise: the more you start using the Rules module, the more you should try to group rules together using the Rules Conditional module. Just to keep the entire set of rules manage-able (eg to have related business logic shown on a single Rule UI screen). A good sample of how easy it is to end up with a lot of rules, is what you can see in the Answers module (current 7.x-4.x-rc2 version):

It comes with 12 separated rules (not using the Rules Conditional module).
By using Rules Conditional, those 12 could be reduced to only 4 (possibly even less).


Do you mean you have 2 URL (www.ex.com and sub.ex.com) with the dir/ and files:

/sites

   all/

      themes/

      modules/

   www.ex.com/

      themes/

        your_theme/

   sub.ex.com/

and no "/sites/sites.php" in here? (read for ex "example.sites.php")

And selected in www.ex.com/admin/appearance for ex bartik as default
and for sub.ex.com/admin/appearance "the your_theme" as default (and clear cache)?

and each time, you need to go in sub.ex.com/admin/appearance in order to set "the your_theme" as default, with no error in logs?


Detecting one account being accessed from multiple computers at the same time

If you just want to log the user out to prevent multiple logins at the same time, then you could use the Session Limit module.

  Session Limit allows administrators to limit the number of
  simultaneous sessions per user.

Also taken from the project page:

  Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.


How to restrict JS applied to a block only to block visible pages?

Using hook_block you can show the js wherever the block renders.

function hook_block($op = 'list', $delta = 0) {
   $block['content'] =
   switch($op){
     case 'view':
      switch ($delta) {
        case 'header_block'://block name
        //here you add that js
          drupal_add_js(drupal_get_path('module', 'mymodule').'/sample.js');
          $block['content'] = theme('header_theme');
          break;
      }
      break;
   }
}


Make custom textfield autocomplete compatible with slashes?

Take a cue from the Drupal core's taxonomy autocomplete implementation and just recombine the arguments passed into callback function back into one string:

function taxonomy_autocomplete($field_name = '', $tags_typed = '') {

  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments, recover the intended $tags_typed.
  $args = func_get_args();
  // Shift off the $field_name argument.
  array_shift($args);
  $tags_typed = implode('/', $args);


I have seen this too. Looking thru the code, it appears that the pager templates do have translations set up properly. So in theory, UI translations should work. But they don't.

I haven't tried it but you probably could do this thru the hook_preprocess_pager__page(&$variables) function (for full views pages).  There seems to be a $variables['pager']['#tags'] array with the values for pagers. You might be able to do the UI string translation here.


Overriding an entity add/edit form through alterroute

Alternatively, you can use hook_entity_type_alter() to override the default form handler classes. It would be something like:

/**
 * Implements hook_entity_type_alter().
 */
function mymod_entity_type_alter(array &$entity_types){
  $entity_types['commerce_product']->setHandlerClass('form', array(
    'edit' => 'Drupal\mymod\Form\EventForm'
  ));
}


How to auto unpublish a node after edit and later published by admin?

Here's how you can do this:

Create a rule on node update event.
Add Condition where user role is not "Administrator/Moderator". (This will make sure that the content doesn't get unpublish when admin is updating it.)
If required, Add condition where content is of type "Article".
Add Action "Unpublish content" under node section and save.
Add another action "Send Mail" under System. Add required details to send email and save.

Above steps will unpublish content and notify site admin using email. After which site admin can navigate to "Admin => Content", review the content and approve. If you need to provide a custom/different UI, you can create a list using views and VBO module and allow site admin to Approve Content.


Not easily because you are going direct to the path.

You could do it in a similar manner to sites such as sourceforge which show you the confirmation page first and use JavaScript to open the download. This method should also have a direct link option incase JavaScript is disabled.

The best way of doing this would be to add a menu hook which shows the message and then links to the path. You would need to add a .htaccess to capture the page downloads and perhaps pointing it to /download-confirm?link=(Base64 encoded link).


Rendering a form element without drupal_get_form?

You can embed a for in a template file for instance with drupal_render_form() in D6 or drupal_render_children() in D7. See this community issue.

You will still have to get the FAPI array somehow, you usually still use drupal_get_form() for getting the $form array.


How do I modify a custom entity delete form?

The relationship is the key of the url relationships, aka edit-form, not edit_form. Try that in urlRouteParameters() and what you are doing should work.


Custom search results usign Search API + views

1) Although I can't give you the exact answer, what you're looking for is probably View Attachments (https://www.youtube.com/watch?v=s9GC-trMH0o). That allows you to display part of the view in a different way.

2) No idea.


Allow users to choose which layout to be applied

Responsive designs usually rely on media queries to apply the styles, but you could make a copy of those styles and prefix its selectors with body.desktop. Then, when you want iPad users to see different styles, just add the class to the body element (using jQuery). CSS preprocessors like SASS will help you mantain those styles without duplicating the code — Zen 7.x-5.x has awesome out-of-the-box support to SASS/Compass and responsive designs. See the Sassy module as well.

There is also the adaptive design approach: it relies on browser sniffing to return device-specific markup and styles. The mobile tools module will surely help should you choose this approach.


Cron tasks don't work: Could the Domain Access module be the cause?

The error is coming obviously from these lines of code in the cron settings form, when it tries to build the cron link:

$cron_url = $this->url('system.cron', ['key' => $this->state->get('system.cron_key')], ['absolute' => TRUE]);
$form['cron_url'] = [
  '#markup' => '
' . t('To run cron from outside the site, go to @cron', [':cron' => $cron_url, '@cron' => $cron_url]) . '
',
];

So you somehow lost the State variable system.cron_key, which is on your site "" and causes the error. You find this in the database in the table key_value and collection state.

To set a new key you can rerun this code from system_install():

  // Populate the cron key state variable.
  $cron_key = \Drupal\Component\Utility\Crypt::randomBytesBase64(55);
  \Drupal::state()->set('system.cron_key', $cron_key);


Migrating data from a CSV source: Where should the source go?

Please add the file as :

source:
  plugin: csv
  path: 'public://csv/test.csv'

And under sites/default make a folder named as csv and place the file inside that. It will work.


Right now, I think D8 is too initial state to have a contrib solution for something "custom" like this. Personally, I would leave Views, and going instead:

Set up a route to a controller
In controller inject your own custom services and return the results in twig.
In your own service, inject any other service you need and to the business logic here.


Standards/recommendations for Drush make files included in contrib modules

@jhedstrom recomendation is valid. Modules should not include a module_name.make file, to prevent drush make running them on recursion. Adding module_name.make.example is desired, and is helpful to build makefiles, specially when the module has several dependencies, including libraries.

OTOH profiles do include makefiles. It is a common practice for a different use case, where discovery and recursion is desired.


How to exclude contributed modules from being upgraded when we run composer install or composer update?

In composer.json, you remove the ^ and specify the version
Ex: Normally most modules are like this:
"require": {
    "drupal/commerce: "^2.21",
},

and to lock it, you change to
"require": {
    "drupal/commerce: "2.20", // will always install version 2.20 and never update.
},

But because Ubercart is in Alpha, you'll see its currently
"require": {
    "drupal/ubercart: "^4.0@alpha",
},

And to lock needs to be
"require": {
    "drupal/ubercart": "4.0-alpha3", // will always install alpha 3 and never update.
},


How could I check that the field's value has indeed been modified?

Using hook_entity_presave():

  You can get the original entity object from $entity->original when it is an update of the entity.

So something like this ought to work:

function foo_node_presave(\Drupal\node\NodeInterface $node) {
  if (!$node->isNew() && $node->get('field_bar')->getValue() != $node->original->get('field_bar')->getValue()) {
    // ...
  }
}


Is there any way to count the number of items in cache?

Given the interface provided for cache backends (CacheBackendInterface), you cannot.

It doesn't expose a method that returns the number of items in the case, which would have made things easier for your use case. There could be a cache backend with a method to count the number of items in the cache, but since it is not part of CacheBackendInterface, that would not be a method you find in every cache backend.
Since CacheBackendInterface doesn't expose any method to know the database table used for cache bins, you should assume some implementation details, and that those details are never changed. If you make assumptions about those implementation details, you can use a SQL query to count the number of items contained in a cache bin. Keep in mind that a cache backend could not use a database table at all, such as in the case of the ApcuBackend class.


You forgot about unique keys in your form elements. Here is a working example:

function test_form($form, &$form_state) {

  // your size options
  $options = array('small', 'medium', 'big');

  $form['checkboxes'] = array(
    '#type' => 'fieldset',
  );

  foreach ($options as $size) {

    $form['checkboxes'][$size . '_checkbox'] = array(
      '#type' => 'checkbox',
      '#title' => t($size . ' size'),
    );

    $form[$size . '_field'] = array(
      '#type' => 'fieldset',
      '#title' => t($size . ' size'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#states' => array(
        'expanded' => array(
          ':input[name="' . $size. '_checkbox"]' => array('checked' => TRUE),
        ),
      ),
    );

    $form[$size . '_field']['some_info'] = array(
      '#type' => 'textarea',
      '#title' => t($size . ' size textarea'),
    );
  }
  return $form;
}

Result:


You can use the EVA module, it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity, in your case the teaser.

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.


Get shipping and billing information from rule

The shipping information isn't directly stored on the order. The only way you have of figuring the shipping details is to look at the line items at $order->commerce_line_items one or more of them will be shipping line items, which can tell you about the shipping details.


How to theme Logintoboggan Access Denied Login Page

Assuming Drupal 7, if you are trying to override LT's toboggan/denied page, eg, what overall structure you see when you land on www.example.com/toboggan/denied, you could copy your theme's page.tpl.php to page--toboggan--denied.tpl.php and modify whatever you wanted in there. (If Drupal 6, the new name would be page-toboggan-denied.tpl.php.)

If you are instead (or also) trying to override the output of LT's theme function that produces the You are not authorized to access this page message on that page, you could create a function in your theme's template.php file:

function YOUR_THEME_lt_access_denied($variables) {
  return t("Whoa, Dude!  You aren't allowed in here!");
}

that would override LT's theme_lt_access_denied() function, which is just a quick:

function theme_lt_access_denied($variables) {
  return t('You are not authorized to access this page.');
}

Or, you could instead create a template file called lt-access-denied.tpl.php in your theme that would accomplish the same thing with some potentially more fanciness:

<?php
  // contents of lt-access-denied.tpl.php
?>
<div class="tsk-tsk">
  Whoa, Dude!  You aren't allowed in here!
</div>

In any case, if you are trying to override any of the other theme functions in LT, or any other module for that matter, you would first look in the module and search for the hook_theme() to see what's available, and in LT, that would be the logintoboggan_theme() function found in the logintoboggan.module file.  Another great resource is Drupal 7 Template (Theme Hook) Suggestions which details the template names and variants used in Drupal core modules.


Get cron to process QueueWorker items at a specific time

Copied from \Drupal\Core\Annotation\QueueWorker, the annotation and placd where the @QueueWorker annotation is documented.

 * Worker plugins are used by some queues for processing the individual items
 * in the queue. In that case, the ID of the worker plugin needs to match the
 * machine name of a queue, so that you can retrieve the queue back end by
 * calling \Drupal\Core\Queue\QueueFactory::get($plugin_id).
 *
 * \Drupal\Core\Cron::processQueues() processes queues that use workers; they
 * can also be processed outside of the cron process.
 *
 * Some queues do not use worker plugins: you can create queues, add items to
 * them, claim them, etc. without using a QueueWorker plugin. However, you will
 * need to take care of processing the items in the queue in that case. You can
 * look at \Drupal\Core\Cron::processQueues() for an example of how to process
 * a queue that uses workers, and adapt it to your queue.

See the last paragraph, the solution is simply to just fill an arbitrary queue and then implement similar logic as Cron::processQueues() for your queue to process the items when you want. Nothing will happen automatically with items of a queue that doesn't have a worker plugin.

Instead of a plugin, you can implement your login in a service instead and call that from your own cron implementation.


How to create a custom resource with Services-3.x

All the documentation for the hook is in the services.services.api.php file included with the module. The args array is:

  an array describing the arguments which should be passed to this resource when it is called. Each element in the array is an associative array containing the following keys:

  name: The name of this argument.
  type: The data type of this argument (int, string, array)
  description: Text describing this argument's usage.
  optional: A boolean indicating whether or not this argument is optional.
  source: Where this argument should be retrieved from. This can be 'data' (indicating the POST data), 'param' (indicating the query string) or 'path' (indicating the url path). In the case of path, an additional parameter must be passed indicating the index to be used.
  default value: this is a value that will be passed to the method for this particular argument if no argument value is passed

There are a fair few examples in that file it might be worth giving them a read through, although the API documentation does actually specifically refer to the link you posted above as a detailed example of creating a new resource.


How can I enable HTML output for checkbox options?

For starters, if you're using an admin theme like Seven for your administration pages, nothing on those pages will ever be affected by another theme's code. If you need to write code that applies across any theme, then you should be putting that in a module.

Inline styles are an attack vector for XSS, which is why they're generally not allowed in any kind of markup that is the result of user input. That includes the label text for a form element, such as a checkbox: the label is constructed by theme_form_element_label(), which sanitizes the text with filter_xss_admin(). That's absolutely the correct thing to do.

The proper way to do this is to put your styles in an external spreadsheet, as you've mentioned. Consider whether you could implement your code as a module instead.


You add some filter criteria, and expose them to the users who see the view. The filter criteria can be any of the filter criteria implemented by the Views module, but there is one that you are probably interested to add it for a search view: Search: Search Terms.

You could also add a filter for selecting the user who posted the node, and the date when the node was posted.

At the end, the view page would appear similar to the following one.


You can use views to search all of your content.

Rather than me write out every step for you, Please try the tutorial at http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7


I've resolved this, I think, but would be interested to hear if there are alternative solutions. I think the Taxonomy Menu Block was a red herring - it was just using the URL alias for the associated term references, which exist whether or not a TMB is used. My view had the same URL alias, hence the conflict; setting either alias to something else was all that needed to be done.


Reducing Number of Fields in Content Type

This is really interesting and, whereas the suggestions in the other question are really good as pointed out by the comment above, I don't really think it's practical to give up on the Field UI for this (like mentioned in the other question).

Let me explain:

Creating a custom field is really easy, there's a good example in Panopoly Widgets for the dashboard widget, which has a custom field for the Spotlight widget.
Creating a custom entity isn't so bad either but creating every single field using Form API should be out of the question

The only plausible solution that I can think of would be to implement hook_field_storage_info() and create a new Field API storage backend that uses a better table configuration.

If you look at field_sql_storage.module in core, it's a pretty concise module that provides the one field per table storage backend, I'm sure with some hacking around you could create a new backend that uses one table per entity and stores each field in a new column there (kinda like D6 CCK with cardinality 1 fields).

You would have to be constantly altering the table schema whenever new fields are added (which should be fine). This might be the place to do it: hook_field_storage_create_field().

It's pretty theoretical but I think it'll work... the beauty of this approach is that you can still use Field UI for everything as usual.

Caveat: You're gonna have to figure out how to handle complex fields or multiple cardinality (hint: more columns?)

PS - Knowing of the frequent schema changes, you wanna make sure you have backups/concurrency for peace of mind.

Good luck and if you get this working I'd like to see it! :)


How to achieve MuchoMenu Multilingual functionality?

Looking their module code, it appears as though they did not encapsulate many of their strings in the t() function. Therefore it's not exposed to Drupal's string translation functions. Unless you want to undertake the task of fixing it then, unfortunately, it's not available.

You could also lodge a bug in their issue queue and maybe that will motivate some discussion on their end.

Regardless, as long as mucho menu uses Drupal's native menu handler, it SHOULD still use the same functions for translation for links. Assuming you set up the menu to be translatable the links should be exposed as any other menu in Drupal.


Allowing users to 'follow' taxonomy terms. Then creating a view which displays a list of nodes which are assigned the 'followed terms'

My idea:

You could create a new content type Taxonomy Subscriptions, using taxonomy and user reference (you will need References module).

Then with Rules module you could manage (create) the subscriptions for terms and then you view will be joined with the created content type.


how to write views for our own custom module?

In order to be able to use a custom module's table with Views, you need to use hook_views_data().

Even better, I would recommend that you invest some time to learn about entities. Entities are much better for most and thay can be almost immediately used in views.

To define a custom view into your module, put it in file module.views_default.inc (replacing with your module name), in a function module_views_default_views().


How do I programmatically create a route?

I think that in your case the problem is in this line:

    '/example/',

that should be:

    '/example',

so without the final /.

You can try with the other method extending from RouteSubscriberBase and your routes method needs to receive as a parameter a RouteCollection.

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExampleRoutes extends RouteSubscriberBase {

  public function routes(RouteCollection $collection) {

  }

}

And you need to define the Route Subscriber as a service

  example.route_subscriber:
    class: Drupal\example\Routing\ExampleRoutes
    tags:     - { name: event_subscriber }

Take a look at this example:

Dynamic Routes in Drupal 8 with a RouteSubscriber


How to set an expiration date on an active rule so that it is disabled on a certain date?

Programmatically disable a rule contains an example of how you can disable a rule programatically, as in this example:

/**
* Implements hook_update_N().
* Disables name_of_rule rule.
*/
function hook_update_N() {
  $rules_config = rules_config_load('name_of_rule');
  $rules_config->active = FALSE;
  $rules_config->save();
}

Tune this example to fit the machine name of your rule to be disabled, and then use that as the "PHP code " in a Rules Component (Action) which only performs an "Execute custom PHP code".

With that, the only challenge left to make this work, is to enhance your rule to be disabled, to conditionally trigger this (new) Rules Component "after the moment has arrived" for your rule to be disabled. For this you might want to add "Conditional Rules" (so that you can add a condition within the Rules Action of your rule to be disabled).


You can pass all http client config to the "client factory". You can also include your own custom settings.

$settings = \Drupal::service('settings');
$clientConfig = $settings->get('http_client_config') ?? [];
$client = \Drupal::service('http_client_factory')
                   ->fromOptions($clientConfig);


How can I fallback to one field in absence of another

I would checkout Field formatter conditions where you can set a whole variety of conditions of one field based on if another field is empty or not. You would set these conditions in whatever display mode you are in so in the case of a node, most likely the view mode will be full or default. (e.g. admin/structure/types/manage/[MY_content_type]/display

Alternatively, you could do some custom node template theming and set conditions there such as if one field is not empty do this, else, show the other field.

<?php if (!empty($content['field_foo'])): ?>
  <?php print render($content['field_foo']); ?>
<?php else: ?>
  <?php print render($content['field_bar']); ?>
<?php endif; ?>

This assumes there is a value with field_bar so you may need to add conditions for that field too if it's empty. With per field theming, you may need to not render the general content variable as well, it just depends on the order and where things fall in the template.


hook_menu() and hook_menu_alter() are not always invoked; they are invoked only when Drupal rebuilds the menus, such as when a module is enabled, disabled, and updated, or when the Drupal cache is cleared.

Anatomy of hook_menu reports the following sentence:

  hook_menu() is called rarely, such as when modules are enabled. If you edit a module’s hook_menu(), you must visit admin/build/modules for the changes to take effect.

The function that invokes the implementations of hook_menu() and hook_menu_alter() is menu_router_build(), which contains this code (the code is for Drupal 7):

function menu_router_build() {
  // We need to manually call each module so that we can know which module
  // a given item came from.
  $callbacks = array();
  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);
  list($menu, $masks) = _menu_router_build($callbacks);
  _menu_router_cache($menu);

  return array($menu, $masks);
}

The function is called by menu_rebuild(), which is then called by:

drupal_flush_all_caches()
menu_enable(), the implementation of hook_enable()
menu_uninstall(), the implementation of hook_uninstall()
12 other functions, and 1 method

drupal_flush_all_caches() is invoked by system_modules_submit(), which is the submission handler for the module page where modules are enabled, and disabled; every time a module is enable, or disabled, the menu is rebuilt, and both the menu hooks are invoked.


The obvious approach would be to have your main-menu built with sub-links.

If that doesn't work, you could:

edit your template to call the new menu right underneath the first.

or

add the new menu to the same block as your first menu (you may want to define new block areas for this)


I'd use an Event Subscriber here. See My First Event Subscriber for an example if you're unfamiliar.
In this case, you'd want to subscribe to the Symfony\Component\HttpKernel\KernelEvents::REQUEST event. For example, you might have a getSubstribedEvents() method that looks like:
public static function getSubscribedEvents() {
  // Include Symfony\Component\HttpKernel\KernelEvents with a use statement.
  return [
    KernelEvents::REQUEST => 'myCustomMethod',
  ];
}

Then define myCustomMethod() to check for your session variables and redirect if needed. For example:
public function MyCustomMethod(GetResponseEvent $event) {
  $route_name = $event->getRequest()->attributes->get('_route');
  // I'm not sure what the route name is here. (You also don't need
  // to check against a route name, thought it's probably a good idea.)
  if ($route_name == 'GROUP_ADD_ROUTE') {
    // Check whatever to see if you must redirect.
    if (myRedirectCondition()) {
      // Set these response headers so browsers don't cache the redirect.
      $response_headers = [
        'Cache-Control' => 'no-cache, no-store, must-revalidate',
      ];

      // Build your response.
      $response = new TrustedRedirectResponse(MY_REDIRECT_URL, '302', $response_headers);
      // You'll have to determine how your redirect should be cached and add
      // appropriate cache dependencies, tags, contexts, etc. There is a
      // session cache context, but I'm not familiar with that particulars of
      // exactly how it works. Alternatively, you could use \Drupal::service('page_cache_kill_switch')->trigger();
      // inside your route_name if statement.
      $response->addCacheableDependency();
      $event->setResponse($response);
    }
  }
}

Related: Disabling Page Cache for Redirect Response


How to get all users with a specific permission

I had to get the roles that had a given permission to get users with a permission, example:
$roles = user_role_names(FALSE, 'example_permission');
$rids = array_keys($roles);

$uids = Drupal::service('entity_type.manager')->getStorage('user')->getQuery()
  ->condition('roles', $rids, 'IN')
  ->execute();

Apparently thats what Drupal core does in the permission filter for views, see:
\Drupal\user\Plugin\views\filter\Permissions
Hope that helps some!


Different groups of radio buttons with the same name

Every group is a fieldset

  $form['pickup_group']['term_'.$tid] = array (
    '#type' => 'fieldset',
    '#title' => $pickupWrapper->field_taxonomy->name->value(),
    '#container' => TRUE,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

Every radio

  $form['pickup_group']['term_'.$tid]['shipping_pickup_point'][] = array (
    '#title' =>  drupal_render($renderable_node),
    '#type'=>'radio',
    '#return_value' => $pickupWrapper->getIdentifier(),
    '#parents' => array('commerce_shipping','service_details','shipping_pickup_point'),
  );

I solved adding the array of parents and itself in #parents on every radio, I don't like so much because I don't have control about this parents. My code doesn't generate this parents it comes from the commerce_shipping API. But works...


Try
{{ grid_item.entity.field_accordion_list_item_text.processed }} instead of {{ grid_item.entity.field_accordion_list_item_text.value }}
i.e. replace value with processed


How can I insert search box in page.tpl?

According to your tag, you're looking for a D7 solution. The Drupal 7 page.tpl.php doesn't have the $search_box variable anymore. However you can add it in a preprocess function in your template.php:

<?php
/*
 *  Preprocess page.tpl.php to inject the $search_box variable back into D7.
 */
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

Then you just need to print the variable in your page.tpl.php:

<?php print $search_box; ?>

You could also use module_invoke, but you shouldn't have php logic in template files:

<?php
  $block = module_invoke('search', 'block_view', 'search');
  print render($block);
?>


How do I create multiple nodes on the same page?

You could create multiple nodes by creating node objects and using node_save() function to save the node.

      $node = new stdClass();
      $node->nid = NULL;
      $node->nid = NULL;
      $node->is_new=TRUE;
      $node->type = "CONTENT_TYPE_NAME";

      node_object_prepare($node);

      $node->created = strtotime("now");
      $node->changed = strtotime("now");

      $node->uid = 1;
      $node->promote = 1;
      $node->format = 1;
      $node->language = 'en';
      $node->title = '"TITLE" ';

      $node->field_DATA['und'][0]['value']= "VALUE";
      $node->field_DATA['und'][0]['value']= "VALUE";

     // Prepare node for saving
      node_save($node);

you can create multiple objects like this on submit handler and save it. Each node will be assigned with new node id.

I hope this helps you.


Getting a subset of items: Is it better to user PagerDefault and limit, or get'em'all and array_splice?

Use range() instead:

db_select(...)->range(0, 10);


You can use Business Rules module to check if the page has the is on the specific workflow state and if the user has the correct rule to view or edit it.


Drupal theme IMG folder rewrite rule from vhosts conf file?

I would add a RewriteRule to the .htaccess file rather than a vhosts config; it's portable in the event of a server change and it doesn't require an Apache reload if you need to update redirect rules.

For your scenario this line is all you need in your .htaccess file:

RewriteRule ^sites/all/themes/theme/img/(.*)$ /sites/all/themes/theme/img_other/$1 [NC,L,R=301]

If you're using a vhosts conf because it's a multi-domain site (e.g. en.example.com, de.example.com, etc.) then you can add a RewriteCond in front of it to match the domain you need to apply it to:

RewriteCond %{HTTP_HOST} ^de.example.com$ [NC]
RewriteRule ^sites/all/themes/theme/img/(.*)$ /sites/all/themes/theme/img_other/$1 [NC,L,R=301]


Views' taxonomy term page by content type

in the view you can filter by your desired content type.

just add the filter criteria named Content: type


Behavior for #datepicker onselect not working

jQuery(document).ready(function() {
    jQuery(".datepicker").datepicker({
        showOn: "button",
        buttonImage: "/images/calander.png",
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        maxDate:'0',
        onSelect: function (selectedDateTime){
                //alert("here");
            }
    });
 });

you can also write above code in js file


How to alias pages generated by panels (node edit or view pages)

Sub-pathauto (Sub-path URL Aliases) works for me. It takes care of situation like yours. Here is a quote about it (from the module's project page):

The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


Send Email After User has confirmed email address using Rules

I did something like this on a site not long ago, and at the time I couldn't find a solution that would work without some extra code because of the way registration was set up, but for your case you should be able to use a rule to check when the user's access timestamp is first set, reacting to the "after updating an existing user account" event.

So you need to check the account-unchanged:last-access is 0 and the account:last-access is not 0, then fire your rule. I haven't tested that this will work, and you might need to add some extra conditions for your particular circumstances.


It's important to understand that the Services module is closely tied to the Drupal Forms API, meaning that the JSON delivered via POST/PUT is sometimes dependent on the Widget that is selected for the field(s) in question, so it won't always match what is delivered via GET.

That being said, I can see some problems with your JSON. Try these instead:

integer, text field

"field_scrap_weight": {
  "und": [ { "value": "1" } ]
},

node reference

"field_surplus_location": {
  "und": [ { "target_id":"... (256)" } ]
},

long text w/summary, text area widget

"body": {
  "und": [ {
    "value": "dd"
  } ]
}

Often times it appears you are missing the wrapping [], this indicates the delta value for the field's item, i.e. it's an array so you can pile up extra values if your field is configured for more than 1 value.

The entity reference field can be any text, but the target id must be wrapped in the parenthesis.

The Date field is the trickiest and I would advise looking at the following answers:

https://drupal.stackexchange.com/a/78925/10645
https://drupal.stackexchange.com/a/180101/10645
https://www.drupal.org/node/1898072

If you're looking to POST/PUT exactly what is delivered via GET, then check out the Services Entity module and this extra configuration that can be added to jDrupal.


Fixed with i18n_menu_translated_tree

$tree = i18n_menu_translated_tree($pid);

as an alert for the next guy, there is some development to move towards i18n_menu_translated_menu_link_alter()
http://drupal.org/node/1693074


Datatables Module not Sorting all Columns

I used a hook_views_data_alter() to add 'click sortable' to the field that didn't have that option.

/**
 * Implements hook_views_data_alter().
 */
function utagta_helper_views_data_alter(&$data) {
  // Allow the views fields to be sortable.
  $data['views']['view']['field']['click sortable'] = TRUE;
}


Absolutely, one might argue that's one of the reasons to use Omega in the first place; as per the first two features listed on the project page:

Fully Responsive Grid layouts based on 960.gs standards.
12, 16, 24 Column Layouts built in.

Have a look in the CSS files with names like alpha-default-normal-12.css under omega/alpha/css/grid/alpha_default/* to discover what classes are available for you to use.

Those files should make it fairly obvious what conventions Alpha/Omega use for naming those classes too, so you should be able to predict what you need to use easily.


A) improve the response time on the REST endpoint to be as good as the
  custom controller

For the REST endpoint, you can use $response->addCacheableDependency() check this block for example:
https://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/
https://spinningcode.org/2017/05/cached-json-responses-in-drupal-8/

Make sure to add cache context and cache tags, carefully.

  B) use OAuth2 with the custom controller. I've been looking for
  instructions on this but every OAuth2 resource I've come across so far
  assumes I'm using a REST endpoint.

Check the example from "simple_oauth_extras" sub module of "simple_oauth"
https://git.drupalcode.org/project/simple_oauth/blob/8.x-3.x/simple_oauth_extras/simple_oauth_extras.routing.yml#L22

Controller is:
https://git.drupalcode.org/project/simple_oauth/blob/8.x-3.x/simple_oauth_extras/src/Controller/DebugController.php#L39


How do I enable Clean urls within a migrated site?

Did you read this:

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

Actually, you should use the original D8 .htaccess cause there are some special rewrites for core and autoloader (and more).


How to hide empty fields on user accounts display?

One way to look at this use node.tpl for this node type and add a php check like the following:

 <?php if(!empty($content['your_field_name'])): ?>

<?php echo t('Your Label'); ?>

    <?php print render($content['Your field Name']); ?>
 <?php endif; ?>


I'm not sure, based on your code, how you are adding buttons to your form(s)/pages, however, I would venture to guess the AJAX controlled buttons are not working because they are calling the built-in loading/submit callbacks within the Drupal 7 AJAX API (example.)

You may find the following example useful:

/**
* Implementation of hook_menu().
*/
function myModule_ajax_menu() {
  $items['get/ajax/Simple Drupal AJAX load with jQuery and delivery callback'] = array(
  'page callback' => 'myModule_ajax_get_ajax', // Render HTML
  'type' => MENU_CALLBACK,
  'page arguments' => array(2),
  'access arguments' => array('access content'),
  'delivery callback' => 'myModule_ajax_callback',  // Magic goes here
 );
 return $items;
}


How do I display a message to users, with the selections they has made from the contextual filter?

You can add a Header to the view, some of the tokens you can add include the Contextual filter values


Why can't I find my uploaded file on disk?

You're just missing the third parameter for file_save_upload():

  $destination: A string containing the URI $source should be copied to. This must be a stream wrapper URI. If this value is omitted, Drupal's temporary files scheme will be used ("temporary://").

The uri in your table is temporary://download.jpg which seems to support that.

To save your file in the public file system you just need to pass that parameter in:

$destination = 'public://some/folder/';
$file = file_save_upload('myFile', $validators, $destination);


How to set and inherit variables within different twig templates?

EDIT

You could write a theme hook in your "mytheme.theme", modifiy the "variables" array and add title to the specific field AND then move the template file (in the original post) to your own theme template directory, make the changes using your new variable (called maybe title) which was provided from theme hook.

OLD:

First of all, "node.html.twig" is TOO general to claim that it's content in the future will consist only one field (file-link).

At least rename it to "node--my-content-type.html.twig".
In the file-link.html.twig you won't able to reach the "title" variable (label) of the node.

You have the following work around:
{{ content|without('field_file_link') }}
{% include directory ~ '/templates/my-custom-twig.html.twig' with {'title': title}  %}

Which means:
 1. exclude your field from content.
 2. create your own twig template
 3. Pass any variable from the caller template you would like to pass.

Twig syntax / semantics is still changing, maybe my twig codes of lines can lead to error, but at least it will give you a hint / clue how to achieve this.


highlight the menu items related to the particular content type

You can use theme_menu_link function.
Add this code to template.php of your theme

function themename_menu_link(array $variables) {
  $path_parts = array();
  $element  = $variables['element'];
  $sub_menu = '';
  $menuName = $variables['element']["#original_link"]["menu_name"];
  //Check menu name
  if($menuName == 'main-menu')
  {
    $path_parts = explode('/',$element['#href']);
    if($path_parts[0]=='node' && is_numeric($path_parts[1]))
    {
      $menu_load_node = node_load($path_parts[1]);
      //Check node type (In our case 'article')
      if($menu_load_node->type == 'article')
      {
        $element['#attributes']['class'][] = 'highlight';
      }
    }
  }
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

All links to nodes with type 'article' will have class highlight


User Import: Possible to use other variables in the user notification email?

Probably not easily an existing request in the issue queues shows people want to add fields from the Content Profile module on the 6.x branch of this module:
https://www.drupal.org/node/1060394

There is a small patch in that issue that adds custom profile fields into the allowed list. The tokens would be in the same format as the given !username examples, eg !field_schools_owned_zone_1 for 1 of your fields.

Until that patch is added to the version of the module you're using you'd have to apply or adapt that patch to your site.


How to change new theme for a content type

ThemeKey module can do this:

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
...


{{ content }} is a render array, where you find the label of the key/label pair probably here:

{{ content.field_app_os[0]['#markup'] }}

But this is not ideal for logic:

The position in the render array can change, for example if you
install a layout module.
The content of #markup depends on how the
field formatter is configured in the view mode.
The label is translatable, so the
logic breaks on a multilingual site.

So it's better to use the database value in:

{{ node.field_app_os.value }}

This is the first part of the key/label pair, which is untranslatable and you can access the value independent on how the field is configured in the view mode.


how to add multiple tables in hook_schema() in .install file while creating custom module?

You definitely can!
In your hook_schema implementation, your first array key is the table name. You can add as many as tables in this array:

Ex:

function quotes_schema(){
  $schema = array();
  $schema['quotes'] = array(
    'description' => 'Base table for Quotes. Contains all submitted data from initial page.',
    'primary key' => array('qid'),
    'fields' => array(
      ...
     ),
  $schema['quotes_access'] = array(
    'description' => 'Access tokens to quotes.',
    'primary key' => array('qid'),
    'fields' => array(
      ...
     ),

    ...
  return $schema;
}

This will create both quotes and quotes_keys tables.


The answer is only a google search away..

https://drupal.org/node/1108180


Is there a way to submit a form on an element's #ajax?

You've not mentioned what your ajax callback is doing internal to it, but if all you want is to submit the form upon a change, you can do something like this in jQuery with no drupal involvement:

$('#edit-submit').hide();
$("#edit-field-FIELDNAME-0-value").live('change', function() {
  $('#edit-submit').click();
});

where #edit-submit is the id= in the form html of the submit input button and #edit-field-FIELDNAME-0-value is the id= of your select that you want the form submited upon change.  Throw this and the appropriate drupal behavior wrapper into a js file and you can drupal_add_js() it from your form hook.

ADDITION:

I suppose $('#form-id').submit(); is better than $('#edit-submit').click(); above where #form-id is the id= of your form.

Also, if you are running D6, you'll need the jQuery Update module installed.


From the custom breadbcrumbs README.txt:

  Enable the module
  Assign 'administer custom breadcrumbs' permission to those roles that should   be allowed to add/edit/delete custom breadcrumbs.
  Assign 'use php in custom breadcrumbs' to roles that should be allowed to use   php to determine breadcrumb visibility.
  Go to Administer > Site building > Custom breadcrumbs to add new breadcrumbs
  Click "Add a new custom breadcrumb"
  Choose the node type to create a breadcrumb trail for
  For the titles, put each "crumb" one line after another (There is no need to   put in "home"):

  Item 1   SubItem A   SuperSubItem X
  For the paths, put the path to each crumb starting after the domain name.   Don't include a leading or trailing slash.

  item1   item-1/subitem-a   item-1/subitem-a/supersubitem-x
  Click save to save the breadcrumb
  Visit the page and your breadcrumb should appear!


How do I export a content type, views as a single module

You could use some Drupal Console export commands for this:

config:export:content:type
config:export:view

You could use the --module option to specificy which module to export.

It's easier to use the Features module though. From the project page:

  A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.

  Examples of features might be:

  A blog
  A pressroom
  An image gallery


Drupal 7 disable submit when pressing enter on an autocomplete field

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

<script>
(function($) {

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

})(jQuery);
</script>

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

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

<script>
(function($) {

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

})(jQuery);
</script>


Fatal error: Cannot redeclare uc_order_views_data()

"When I remove either version ..."
"I can't see a double-up of modules in /admin/modules"
"The two ubercart directories both contain the same subfolders."
It sounds like you have two copies of Ubercart on your server. THAT IS NOT ALLOWED for ANY Drupal module. You must have one, and only one, copy of each module.
The correct way to update a Drupal module is to completely remove the old version of the module code first, then replace it with the new version of the code. Then you can run update.php.


Thanks for your answers, I could do it, no with Rules module. I did it using hook_user_login(), and $_GET['destination'].

    function webform_sub_user_login(&$edit, $account) {
    $currentuser = $edit['uid'];
    $_GET['destination']= "/user/".$currentuser."/edit";
    }

If it can cause problems, let me know. But for now it seems to work well.


Drupal Commerce - Line Item 'display path' from views

Edit the view, click the "Quantity input field", are you sure the "Link products added to the cart from this View to this View's path if displayed as a page." checkbox is checked? That's what makes it populate the display path.


How to print node's timestamp in computed field


I thought the following was a bit like Yoast . SEO Compliance Checker - https://www.drupal.org/project/seo_checker

Once downloaded install and enable.

SEO Checklist

Basic SEO Modules

Keyword Rules

Then go to configuration .

Once those modules have been enabled you’ll then have a nice set of Sliders to use in the ‘Thresholds for the SEO Rules’ box.
Set up your sliders depending on what the recommended levels are at the time.
From here you’ll then need to visit the Article that you want to optimise .

  Click on PREVIEW

The Keywords are taken from 'tags' .


What determines what "view" gets displayed first on a page?

If you refer this Question on stackoverflow: How does Drupal Views decide between multiple displays with the same path, I think he has described both situations of views in his answer as separate paragraph and second paragraph is your answer.

I am pasting the entire answer here of @Andrew Aledge,

  If you're referring to the display within the views: each view display
  has a position and the displays are loaded according to that position
  in an ascending sort. So if you create a page display (which may get a
  position of 2 since the Default display typically has a position of 1)
  and then create another page display after that, the next page display
  may get a position of 3. The customer will be exposed to the position
  it reaches first (2, provided that they have met the criteria).

  If you're referring to the views themselves: views are loaded in order
  of their view id (vid). The customer will be exposed to the first one
  loaded.

If you see the LAST TWO Lines, he has mentioned on which basic the views decide which view will be displayed and which one not. He means that Provided all conditions same, the view will be shown as per the view id(vid)

Other situation: Apart from above two situation, Which view user will see if they have different Roles. So in that can I think It will be decided based on which user has access to which view(I mean based on thier role access), and if same user has access to multiple views then in this case it will decided again based on vid.

I think, above three discussion have cover all the various situation of visibility of view.


Composer update : Package "drupal/module_name" listed for update is not installed. Ignoring

I found what was the issue in my case. I post my solution. Even if it is specific to my issue, maybe it could help other users.

I didn’t install these  Drupal 8 modules. The developer who installed them used Drush (he should have used Composer). So I had the same modules installed twice, in /module and in modules/contrib I’ve deleted modules previously installed with drush  in /module and run composer update. That fixed the problem.


In Drupal 6 we had the Multigroup module, which was bundled as part of the CCK 3.x branch. As of comment #353 on the State of the multigroup module thread, you should be able to just swap your CCK 2.x code for the 3.x branch and run the updates without no problem. I used this module a few years ago and it worked fine.

Be advised however that apparently the CCK Multigroup module migration path to D7 is undefined. i.e., if you develop your site in D6 with CCK 3.x there's no guarantee that you will be able to automatically convert your CCK data to D7.

There are other Drupal 6.x field-grouping modules metioned here that you might find worth researching. This post also talks about different grouping modules and it might interest you.


You're a 'victim' of MySQL's ANSI_QUOTES SQL mode:

  Treat “"” as an identifier quote character (like the “`” quote character) and not as a string quote character. You can still use “`” to quote identifiers with this mode enabled. With ANSI_QUOTES enabled, you cannot use double quotation marks to quote literal strings, because it is interpreted as an identifier.

Emphasis mine.

That explains why MySQL is trying to find a column called '%y-%m' rather than interpreting it as a string.

So you need to switch your SQL mode to something else, or (more reasonably), just use single quotes for literals:

$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(created), '%Y-%m')", 'createdMonth');

Many other DBMSs don't accept double quotes for string literals, so using single quotes is a good habit to get into anyway.


Send email to all users with specific role (updated privacy policy)

Mass contact is probably the way to go for you, if it has to be a solution integrated into the site. Categories are really easy to configure.

Automated and integrated solutions are always recommended over hacks, but if you're really doing this only once, the fastest way would be to export email addresses and use an email campaigning service or design and send manually in batches (sending bulk emails are limited per hour for spam reasons) from your site email address but that is difficult to test.

Setting up the HTML styling for your email is what you'll spend most of your time (through Mime mail module). If you plan on testing it on various email clients that is. Many services (Gmail for example) strip styling from emails, so you have to be careful what you style and how. Usually you use a tool that takes your email CSS and applies it all inline, because that is the most reliable way most of the styles will "survive" various email client filtering.

Simplenews is a very comprehensive solution, much much more to configure and understand there than Mass contact.

I can't see configuring Rules to be triggered would be easier than using Mass contact.

In the future you may consider using a module like Legal.


Is there any 'advanced' debugging available for Views?

The admin/reports/views-plugins show a table with every plugin used by Views, noting which views use them. And if you want to figure it out programmatically, you can check the code for that page.


Technically, you can use a function to return an array of menu router items but practically it will not work because of caching.

However you can register wildcats paths like companies/so your page callback will be fired on every companies/ pages.

To do so, set the key of the $items like this:

$items['companies/%'] = array(...menu router info here ...);


Override core permissions used for visualizing a page

You can make it by writing a custom module that implements hook_menu_alter().

function mymodule_menu_alter(&$items) {
  $items['path/to/change']['access arguments'] = array('permission name');
}


What is the purpose of the tabs div when logged out?

The tabs div will contain links even when logged out on some pages, such as the user page, where logged-out users can choose to either "Create new account" "Login" or "Request new password" by using the tabs.

Instead of removing it you can prevent it from taking up space when empty using CSS to remove the padding and margins on the div.


Responsive Menus module is suitable for bootstrap theme.
https://www.drupal.org/project/responsive_menus


You should use below code in your code and clear the cache.

'page callback' => 'drupal_get_form',


If it is a form, you can use hook_form_alter along with the PHP function str_replace to replace JPY with 円. Let me know if you need further help.

EDIT:

<?php
  function YOURMODULE_form_alter(&$form, &$form_state,$form_id) {
    if ($form_id == 'your_form_id') {
      print str_replace("JPY", "円", render($content));
    }
  ?>


How to access form elements in table via getValue()?

You can access $form_state values like below

$values = $form_state->getValues();

If you are printing $values then you will get

Array
(
    [mytable] => Array
        (
            [1] => Array
                (
                    [a] => Value of a
                    [b] => Value of b
                )

        )
)

setErrorByName() function can be used while validating the elements.


Seamlessly, probably not. However, what may work is to merge your own Drupal site's install profile with the code found in idea.install. Additionally, you'll want to enable all of the modules found here.


How to disable the Submit button on a the delete page form?

Yes, you are understanding the behavior of the '#disabled' key correctly. I tried the code you describe and it "just worked."

function custom_form_node_delete_confirm_alter(&$form, $form_state) {

  dsm($form['actions']['submit']);
  $form['actions']['submit']['#disabled'] = TRUE;
  dsm($form['actions']['submit']);
}

My guess as to why the alteration is not creating the desired end result is that your function signature is not using the "&" with the $form variable. That character is needed for the $form variable to be "passed by reference" which allows for the changes to the variable to stick outside the function.


Possible to extract multiple key/value pairs (links) from string in CSV and migrate into multiple link field

Here is my solution to solve a similar problem:

temp_data:
  -
    source: data
    plugin: explode
    delimiter: ','
  -
    plugin: explode
    delimiter: '|'
destination_field:
  plugin: sub_process
  source: '@temp_data'
  process:
    field_attr_1: '0'
    field_attr_2: '1'
    field_attr_3: '2'

Hope it helps.

Regards,
 M.


Add JavaScript and css to page with nodes only if there is no tag in any of the nodes

you shouldn't have use hook_preprocess_node as it gets fired on each node separately, so if only one of the node doesn't have that specific tag the css and javascript will be added to the page unless other nodes have, so rather than hook_preprocess_node use hook_preprocess_page and there you can find an array of nodes (use dsm function with devel module enabled to see variable structure) and you can iterate over that array and check for condition


Send multilingual emails notifications with Checkout Rules in Commerce module?

Look at Commerce Email:

  Adds a configuration page for the order email
  Email content can be entered into textarea/wysiwyg (if available) form
  Email content can also be set to be loaded from a template file: commerce-order-email.tpl.php
  Allows the insertion of the order items into the email, token addition: [commerce-email:order-items]
  Supports Commerce Shipping
  Allows different language versions of each email
  Optional administrator email


You can use the following code, even though for those specific values, I would find a different way (e.g. setting the language for the shown page).

{% html_attributes.setAttribute("lang", "ar") %}
{% html_attributes.setAttribute("dir", "rtl") %}
<html{{ html_attributes }}>

Inside hook_preprocess_html(), since $variables['html_attributes'] is an Attribute object, so you can use Attribute::setAttribute().

$variables['html_attributes']->setAttribute("lang", "ar");
$variables['html_attributes']->setAttribute("dir", "rtl");


How to download files through IMCE file browser?

There isn't one built into the module. One work around is to use IMCE user file browser (/user/[uid]/imce) and click on the preview image. It will open up the image URL in a new tab/window where you can download it through your browser.


Drag and drop the fields in the order you want at page at the "manage fields" or "manage display" pages.

You can reach these pages for eacht content-type via the links beside eacht content type at:

admin/structure/types

Manage fields is used at the node/add or edit screens.
Manage display is used for the actual display, like when a visitors sees the page.


After adding a column to a module's schema, should the new column also be placed inside hook_schema?

hook_update_N() is only used when updating a module, while hook_schema() and hook_install() are used only when installing a module. Since there are users who install the module, the database field must be also added in hook_schema().


The arg to decode is:

  The raw data string to decode

So you need (e.g.):

$breakpointEncoded = Yaml::decode(file_get_contents('/PATH/TO/core/modules/toolbar/toolbar.breakpoints.yml'));


How can I link a gallery made with views to another gallery made in views?

If you are looking for using a view into another as a field then you can use Views Field View to achieve this.

Module page describe :

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Views: apply filter only if a condition matches

You will have to add a custom module for this. I usually have one monolithic module that I add to every project that I name the same as my project for project specific tweaks like this.

In that module's module file, add this code:

function MODULE_views_query_alter(&$view, &$query){
  // target the correct view
  if ($view->name == 'chair' && $view->current_display == 'entityreference_1') {
    // target the correct path
    $node = menu_get_object();
    if ($node && arg(0) == 'node' && arg(2) == 'edit' && $node->type == 'lecture') {
      // edit page on lecture type
      $view->query->add_where("entityreference_tweak", "node.uid", $node->uid, '=');
    }
    else if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'lecture')
    // create page on lecture type
    {
      global $user;
      $view->query->add_where("entityreference_tweak", "node.uid", $user->uid, '=');
    }
  }
}

I named the entityreference view 'chair', the entityreference display took the default name 'entityreference_1', the lecture content type has the machine name 'lecture'. You need to substitute these name in the code above with your own machine names.

Then completely remove the contextual uid filter from your entity reference view and also do not pass anything to the view in the field settings of the content type. The code adds the filter dynamically. It checks if you are on a lecture edit/add page, then adds either the node author uid, or the uid of the currently logged in user.


You'd have to create 2 views, one which takes Year argument with path base_path/yyyy and another that takes 2 arguments with path base_path/yyyy/mm

And you have to create a custom module which defines a hook_block_info and hook_block_view. This block will basically read your node table for blog type posts, and build links to the 2 views you created above, structured in Year > Month hierarchy. I'm not sure if there's an easier way to achieve this.


Where can I download the Windows installer for Drush?

You need to install it using composer as specified here:

https://github.com/drush-ops/drush/blob/master/docs/install.md

After installation, make sure to run and use the drush command inside Git's shell only (the shell environment bundled with Git for Windows)


How to add a user rank in their profile?

Use a combination of the Rules, Userpoints and User badges module, as further detailed below ...

Add a new badge

Have a look at this Rules example (in Rules export format):

{ "rules_grant_a_new_badge" : {
    "LABEL" : "Grant a new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "user_badges", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "7" } },
            "DO" : [
              { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
            ]
          }
        ]
      }
    ]
  }
}

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 7, it will grant the user badge.

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?"). However, by using the Conditional Rules module, you can consolidate the logic for various user badges in a single rule, e.g bronze for 7 points, silver for 77 points, gold for 777 points.

The clue to make this rule work is the very first Rules Action "Load user points of a user". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".

Remove a new badge

If you want "a user's old badge to be replaced by a new one", then you should also add a 2nd Rules Action to the rule shown above. The action to be used is remove_badge_by_name (instead of add_badge_by_name).

Only grant a new badge once

To avoid "displaying a message each time when user getting more than 7 user points" (as in your question), just add a Rules Condition like "NOT User has badge". This is one of the Rules Conditions provided by the User badges module.

Display the badge

To actually "display the badge with the username at the top", you could use what's written in the Community Documentation about User Badges, i.e:

  To display user badges in your theme use:

<?php
  if (module_exists('user_badges')) {
    print user_badges_for_uid($uid);
  }
?>

  Note: $uid means 'a user id' here, not the literal use of $uid. Most people will use the uid of the node ($node->uid) or comment ($comment->uid) author.

  In Drupal (and theming), $node is a PHP object that represents the node, and $comment represents the comment. They are not always both available in every template file, so check the comments at the top of the file to see what is available. You may have access to other uids (user ids), and in these cases you can replace $uid with that value.


Mysql query that performs sums between different tables

Well ... Since no one had this problem, or nobody has a solution, I put the solution that I have given on the site https://www.drupal.org/node/2898276

The problem is how I wrote the query to the database. A Cartesian product is produced. After rewriting the query was solved. It was finally written:

$lo_que_che= db_query('SELECT (SELECT SUM(field_monto_15pts_value) AS 15pts FROM {field_data_field_monto_15pts}) 15pts, (SELECT SUM(field_monto_14pts_value) AS 14pts FROM {field_data_field_monto_14pts}) 14pts, SUM(field_monto_13pts_value) AS 13pts FROM field_data_field_monto_13pts}') ->fetchAssoc();  return $lo_que_che;


Drupal Import Commerce Product Display Multiple Images With Feed?

When using Feeds & Commerce Product Processor you might want to to install Feeds Tamper as well. If the field that you are importing has multiple values you will typically have a delimiter (comma). I'd suggest using the explode function from Tamper to break the field into an array of values to import.  It might also help if you do a replace on the values you exploded to use the public file URI syntax (public://products/myproduct.jpg).


What are the ways to handle a fresh new project?

This is maybe not a stackexchange question but a good question to rather discuss somewhere else. The reasons for your confusion are caused by a problem, the Drupal community is already aware of for a long time but it is not easy to find a better solution for that than as it is at the moment.

An overview

Drush was THE terminal command line tool for Drupal and was precursor in type of such tools long time before Composer or other command line tools like this even existed. It was a very helpful tool for Drupal developers on a daily basis, was VERY innovative in this time and still is.

Drupal Console raised over the last years in the time of when Drupal 8 was on development state and the Symfony PHP framework started to become the underlying construction kit for this new Drupal version. A decision which was long discussed and worried about ot map a good future for Drupal and its principles. A lot of stress and discussion raised in this time regarding the community choices afterwards again and even forks have started. Drupal Console has tried to fill gaps of Drush and treis to find its gap now between Drush and Composer.

Composer is like Symfony a widespread tool on many development projects and therefor not to ignore. Drupal has learned from its isolated position with its own tools in history and tries to adapt tools which are common for developers.

It's all in all a very basic and flat explanation here. But I wanted to keep it simple yet. There are many details missing and finally all 3 tools have a good reason to coexist IMHO.

TL;TR

Drush = Command line Devel, Drupal Console = Good module and theme creation helper, Composer = Maybe THE Drupal project installer in the near future (even admin UI implementation discussion occurs atm).

A good source to read about the work on this: An interesting discussion is going on here regarding Drush pointing same points you have asked about: https://www.drupal.org/node/2906637