I am trying to enable the jQuery UI module, but I am hitting with error

Looks like the module is expecting this structure:

modules/jquery_ui/jquery.ui/(actual jquery ui files)

However, it looks like jQuery UI library removed the version.txt file that this module checks for. If it does not find that text file, it considers the plugin 'not installed' which is kind of a bad check.

People are talking about it here, with a fix for Drupal 6 (and some talk for 7): https://www.drupal.org/node/1954136

However the project page advises you to use jQuery Update instead:

  Drupal 7+ Since Drupal 7 ships with jQuery UI, the jQuery UI module
  has been deprecated and moved to the jQuery Update module.

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

You should dump this module and use jQuery Update and go from there.


hierarchical select to display taxonomy tree

ASSIGN $child to an select list just set taxonomy id :
$taxonomy_vid = 3;
   /*** A HEADACHE CODE :p arrange the parent child taxonomies****/
 /*      $tree_type =  taxonomy_get_tree($taxonomy_vid);   // taxonomy id here
    $childs["selected"]="Select a Value";
    //$childs[45]="New Launches/Projects";
    foreach($tree_type as $key =>$value) {
$temp_ = taxonomy_term_load($value->parents[0]);       //IF parent is set already
                if($value->parents[0]==0) {                   //if no any parent taxonomy
                        if(is_object($temp_)==TRUE) {
                        if(isset($childs[$temp_->name])) {  //if array key is already set
                                if(is_array($key)!=FALSE) { //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                        }else {
                                if(is_array($key)!=FALSE) {    //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                            }
                        }else
                        {
                            $childs[$value->name]=array();
                            $childs[$value->name][$key]=$value->name;
                            //drupal_set_message("-------<pre>".$value->name."</pre>-------");
                            }
                    }else {
                        //$temp_ = taxonomy_term_load($value->parents[0]); //IF parent is set already
                        $childs[$temp_->name][$key]=$value->name;       //$childs[$temp_->tid]=$temp_->name;
                    }
        }


How do I remove all default styles (such as div.widthMarker) from CKEditor?

In CKEditor profile settings /admin/config/content/ckeditor
click the edit link on the profile you want to change.

Under "Editor Appearance" uncheck "Stylesheet Parser plugin" and save.
This will remove the default classes.


Can I render the same block twice on a page?

If what @Chapabu said doesnt work for you, if you have any hand-coded module on your site you can use hook_page_alter to copy the render array information for the block in question and set it into another region of the page.

This is more of a 1-off solution. But, I try to stay away from extra modules todo 1 thing on a site. Especially if you're somewhat comfortable coding a solution.

Here is a small example using hook_page_build (which runs at the beginning of page builds, hook page_alter runs at the end):

/**
 * implementation of hook_page_build().
 *
 * Depending on the path or NID or whatever, we want to
 * embed additional blocks and stuff into the page.
 *
 * I could use Context or the BlocksUI for this but I
 * give clients "Basic Page" for all of these urls and I'm
 * merely appending additional data on those pages.
 */
function ccs_core_page_build(&$page) {
  _page_build_section_header_image($page);
  _page_build_embed_course_views($page);
  _page_build_embed_faculty_views($page);
  _page_build_embed_distinguished_alumni_view($page);
}

function _page_build_embed_distinguished_alumni_view(&$page) {
  if (drupal_get_path_alias() == 'people-contacts/distinguished-alumni') {
    $view = views_get_view('distinguished_alumni_listing');
    $display = 'blocks';
    $view->set_display($display);
    $output = $view->preview($display);
  }
  if (isset($output)) {
    $page['content']['system_main']['distinguished_alumni_listing_view'] = array(
        '#weight' => 99,
        '#markup' => $output,
    );
  }
}


Ctools Multi step form throws error when form_validate is from another file

Figured it out, we need to include using the below function

form_load_include($form_state, 'inc', 'module_name', 'module_name.file');


How to fetch/load a node form using jquery/ajax?

I don't think you've got the right parameters on the jQuery "load" method. The jQuery API page has this for the signature:

.load( url [, data ] [, complete ] )

This might be a working revision (not tested):

$('.custom-form').load('?q=node/add/custom', {}, function() {
     Drupal.attachBehaviors($('.custom-form'));
});

However, your strategy will load the entire Drupal page, not just the form. The AJAX-loaded page and form will not be in the expected request context - I'm not sure that the form can be successfully submitted in this circumstance.

You might try looking into implementing CTools Modal API instead, which is designed to allow the loading forms into modal windows via AJAX.


How can I set up Protected Pages so users only have to log in once?

Protected pages is really intended for one off password protection of webpages on a site. In order to have users login once to access a section of content, you should setup a user role assigned to a specific content type.

In the case where your existing content requiring authentication is the same content type as the non authenticated content, you can use the TAC Lite (taxonomy access control lite) module. To restructure the existing site to use this:

Create a new taxonomy to distinguish the password protected nodes from the others
Assign your custom term to the nodes to distinguish that they need authentication to view.
Install TAC Lite module.
Setup a new user role to associate with viewing permissions for the nodes with the assigned term.
Configure TAC Lite for the node type with term and user role.
Remove protected pages passwords for the given pages.
Clear caches
Test accessing (without login, you should see permission denied messaging)
Optionally, install r4032login module to automatically direct nonauthenticated users trying to access this section to the login page, and subsequently redirect back to requested url.

For future site builds or enhancements, I would recommend just setting up a distinct authenticated only content type and installing r4032login.


Views: Table rows containing multiple nodes by taxonomy tag

I ended up using Views Field View, which allows you to implement a separate view's output per row based on a particular field. Definitely resource intensive. Definitely less than ideal, but it works.


Find slowest loading / longest time to generate pages

The Performance Logging and Monitoring module was split out from the Devel module last summer, but is mostly the same.

The summary logging page is sortable by all of the table columns.  For example, if you want to show the slowest pages first, you just need to click on the "MS (MAX)" column heading until it sorts descending.  The direct URL would be at /admin/reports/performance-logging/summary?sort=desc&order=ms+%28Max%29

You can also do a manual query on the database if that is where you are storing results:

SELECT *
FROM {performance_summary} performance_summary
ORDER BY ms_max DESC


Error while creating a node with file attachment through custom PHP code

replace

$node->field_file[$node->language][0]['value'] = (array)$file;

with

$node->field_file[$node->language][] = (array)$file;

Also, add $node->validated = TRUE; before node_save($node);


How to load node with AJAX on a Calendar click?

You can take help of Drupal hook_menu with Json object output and a Drupal JS beahvior to handle click event.

Idea : In the click event call an ajax function to your menu callback that gets you a JSON object of required content. Load the content in your desired DOM element.

code for hook_menu; considering your module name 'mymodule'

function mymodule_menu() {
  $items['mymodule/%node/load-content'] = array(
      'page callback' => 'mymodule_ajax_node_load_content',
      'page arguments' => array(1),
      'access arguments' => array('access content'),
  );
  return $items;
}

code for Page callback :

function mymodule_ajax_node_load_content($node) {
  // The variable holds complete node object for you.

  $data = array();

  $data['body'] = $node->body['0']['value'];
  // Consider providing any other node details if required.

  $output = array('status' => 'ok', 'data' => $data);

  return drupal_json_output($output);
}

JS code for attaching a behavior to Drupal,

Drupal.behaviors.nodeLinkClick = {
  attach: function(context, settings) {
    // sort by click.
    $("a.node-link").click(function(e){
      e.preventDefault();
      $.ajax({
        url: Drupal.settings.basePath + 'mymodule/' + nid + '/load-content',
        type: 'GET',
        data: data,
        dataType: 'json',
        success: function(response) {
          $(".dom_to_load_content").html(response.data.body);
        },
        error: function() {
          // show error in any DOM.
        },
      });
    });
  }
}

NOTE : The above code not tested; a small snippet cut-out from my project.
Hope this helps you. Let me know if you still facing any problem.


How change "user menu" to current username

You could do that with hook_preprocess_block

e.g, in template.php

function MYTHEME_preprocess_block(&$vars){

  global $user;
  $block =& $vars['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $block->subject = check_plain($user->name);
    }
  }

}

Clear theme registry cache after adding new preprocess function.


How to add custom operation to commerce/orders list?

The proper way to add new operations is to define them as menu items. Here is a snippet from the payment module, responsible for the payment operation listed in the screenshot:

  // Payment tab on orders.
  $items['admin/commerce/orders/%commerce_order/payment'] = array(
    'title' => 'Payment',
    'page callback' => 'commerce_payment_ui_order_tab',
    'page arguments' => array(3),
    'access callback' => 'commerce_payment_transaction_order_access',
    'access arguments' => array('view', 3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'includes/commerce_payment_ui.admin.inc',
  );

The key part being this line right here:

'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,

In fact, in most (maybe all?) places where you see this list of operations or tasks in Drupal Commerce 1.x, they will be defined this way. Another example of this being the transaction listing screen. Payment modules can add new contextual menu items for things like credits, captures, etc:


You need to remove '#required' => TRUE from the render array.

States only control "soft" changes through javascript. They don't (and can't) have any effect on the backend validation; if they could, it would be trivial for anybody to bypass the server-side validation for a field just by setting some CSS styles on it. That would not be a good situation to get into.


How to fix error 'This site can’t be reached' for a site installed on Amazon?

It's because by default port 22 (SSH) comes open in your EC2 security group, but port 80 (HTTP) is not open.

You need to edit your security group. To get there, in your EC2 list, scroll all the way to the right and click on the blue security group name. You will be taken to your security group settings page, for inbound, add Custom TCP Rule of port 80

  PS: If you're going to use HTTPS might aswell open port 443 (HTTPS)


How to display an Image based on content author role in view?

Add relationships:

From node to it's author
From author to his role

Then add role field to display, and in tpl.php substitute it for your desired image.

You can read about relationships on http://example.org/help/views/relationship if you have Drupal installed (substitute example.org with your domain or localhost as needed) and advanced help on.


How do I get a form element to display in a lightbox?

If you want to display form element into popup, then I would suggest you to use ctools api. It will provide you functionality to create a custom popup to render content.

  Ctools provide Modal dialog functionality to display element in modal.

You need to follow below step for the same:

Create a custom module and create Menu item which will interact with ctools modal.
Define ajax callback for the menu item and return HTML of the modal
using ajax.

You can check working example  (http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7)


How should I create a main page with a mix of dynamic and static content?

There are a number of options available to customise the front page -

have a look at
http://www.devdaily.com/blog/post/php/how-customize-content-front-page-drupal

I usually go the route of creating a custom page-front.tpl.php (as explained in the link above) and then use a combination of views and blocks to get in the content I need.

hope this points you in the right direction...


Assuming you want to load

sites/all/modules/custom/spower/polygon/polygonBase.php

then

module_load_include('php', 'spower', 'polygon/polygonBase');

should work fine.

Make sure the file polygonBase.php is readable by the webserver user.
Make sure module_load_include is added for processing prior to using functions in that file.


Use Views 'rewrite output' feature for the Field: Title field on your mycontents view.

First, make sure you have added the Content: NID field to your view.  If you don't want this to be visible on your View, you can 'Exclude it from display` as noted in the graphic below.

You will also need to reorder your views fields to ensure Content:NID is listed before your title so you can access it in the next step.

It's very important to to note that the Content: Nid field is above the Content: Title field.

Next, edit Content: Title and scroll down to and open the 'Rewrite Results' section.

Note: You may need to uncheck the 'Link this field to the original piece of content' checkbox for the Content: Title field.

In the 'Rewrite Results' section, check the box titled 'Output this field as a link.'  In this section, if you scroll down, you will see a link titled 'Replacement Patterns.'  This is where we will get the variables we need for our URL.

In the 'Link Path' box, enter your destination URL: mycontent/[nid]

Don't forget to save your view, but your titles should now be linked properly.


How do I write a hook to compile css and js with drush make?

In general, you shouldn't use Drush for that. Instead, use a build process, and one of the steps in the build would be drush make.

There are a number of existing build systems that can be used to achieve what you're looking for, including (but not limited to):

Phing - https://www.phing.info/
Jenkins - https://jenkins-ci.org/
Grunt Drupal Tasks - https://github.com/phase2/grunt-drupal-tasks
Aquifer - https://github.com/aquifer/aquifer

A typical process would have the following steps:

Delete build TARGET directory
drush make drupal.make TARGET --prepare-install
Symbolically link custom profiles, themes, and modules
Execute task to compile CSS, JS


Views : hide thumbnail for all but one content

The module Display suite gives the option to add different views mode for different rows. Here is a video tutorial ,in this lesson you cover how one can use view modes and display suite to allow multiple options of layouts for content display. This allows a user to have a different layout of the same content for different scenarios of the site. Combining this with views and you can start to see the power of display suite in action.


Features/Themes and Drush Make Files: How to manage updates?

You should build an installation profile to go with your make file.  Then, you could store your theme inside the installation profile.  There's a Drush command to make an installation profile; see this issue on drupal.org.  If you use this technique, you can just run drush pm-update to update modules, and then re-build your makefile and installation profile using the Drush generate-profile command.

Another option would be to just store your custom theme in a git repository.  You can load a module or theme from a Git repository.  See this answer for details on how to do that.


After updating the metatag module I am unable to edit the metatag section of a taxonomy term

Please try updating to the latest version, there were a few issues in 1.0 that were fixed in subsequent releases.

Disclaimer: I'm the module's maintainer.


Suddenly my website front page was not found!

Edit your .htaccess and the setup of your subdomain.richtown.ae...
frontpage on a subdomain?

# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]


How to get user photo to appear in node panel

Jumped the gun and posted this question before I really messed around with it. All you have to do is add  "User From Node" as a relationship in contexts, then it will show up as picture in panels


Is there a way to inherit a Drupal installation profile?

Doing some research and testing I found a way to inherit Drupal installation profiles, using drush make (works in Drupal 7).

1) Apply Drupal patch #47 submitted in this topic

projects[drupal][type] = core
projects[drupal][version] = 7.32
projects[drupal][patch][] = https://www.drupal.org/files/issues/drupal-inheritable-profiles-2067229-47.patch

2) Set Drupal "base profile" in your profile.info file. My installation profile will be based in Guardr

name = MyProfile
description = MyProfile
version = 7.x-1.0
core = 7.x
base profile = guardr

3) Execute with Drush the make file of your base profile. Add it to your profile.make:

projects[guardr][type] = profile
projects[guardr][download][type] = git
projects[guardr][download][url] = "git://git.drupal.org/project/guardr.git"
projects[guardr][download][branch] = "7.x-1.14"

drush will download it and then recursively run the make file of the base profile

I found the reference in this blog post


How do I style a node page for a specific content type?

The easiest way is to create a new template file called node--[node-id].tpl.php, for example node--10.tpl.php

Then you just need to copy/paste your code from the node.tpl.php you have on your actual theme and change it like you want. For the CSS, the cleanest way I think is to add a custom class in your template high enough to be able in your CSS to target it.

You can have a look at this answer that explains the difference between node--[node-id].tpl.php and page--node--[node-id].tpl.php


Drupal Views Search: Creating an Exposed Filter with Checkbox Options

Better Exposed Filters module should help you.


How to render a paragraph 'Text (formatted, long)' as full HTML, not escaped

If you want to render a formatted text field you have to use the render element processed_text:

  {% set paragraph =  item['#paragraph'] %}

  {% set body = {
    '#type':   'processed_text',
    '#text':    paragraph.field_rn_acc_1.value,
    '#format':  paragraph.field_rn_acc_1.format,
  } %}

  <div id="{{ paragraph.field_rn_acc_abbr.value }}-1" class="panel-collapse collapse">
  {{ body }}
  </div>


Why do we duplicate field data in the field_revision_* tables when revisions are disabled?

That's a great question - I wonder if it's any different in D8.

The field_data tables, and node table also track the "current vid" which is the current revision id, I guess they felt there had to be at least one.  But it does seem like there should be another way to do this. Maybe they could just store a 0 or something as a flag in the field_data tables current_vid column to indicate there's not a revision.


How to get the value of an item from a list field to add it to a computed field

Definitely I found out what to do.
Maybe this will help somebody else.

I wrote this before :

$entity_field[0]["value"] = field_get_items($entity_type, $entity, "field_nb_of_tickets");

This is what's new :

I did put the foreign field's value in a variable before adding it to the current field :

$nb_of_tickets= field_get_items($entity_type, $entity, "field_nb_of_tickets");

$entity_field[0]["value"] = $entity_field[0]["value"] + $nb_of_tickets;

Now it works.


What is the minimum I need to get a test for a module on D7?

What you got there will suffice. I copied the code to a project I was working on and it showed up fine.

You problem is either:

Cache (You need to clear cache after updating the .info file)
Overlooked, The test could be there, but you didn't see it. It will show up under the group with the name written in name.


Display set of Views rows with different view modes

You can add another view display and put it below the main view output using block or view attachment.


You can override the page callback used on a node page to use your own function that will select the view mode based on the current user role.

/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter(&$items) {
   $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

/**
 * Copy of the original node_page_view to use result from our
 * MODULE_node_show($node) as return value.
 */
function MODULE_node_page_view($node) {
  global $user;
  // If there is a menu link to this node, the link becomes the last part
  // of the active trail, and the link name becomes the page title.
  // Thus, we must explicitly set the page title to be the node title.
  drupal_set_title($node->title);
  $uri = entity_uri('node', $node);
  // Set the node path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  return MODULE_node_show($node);
}

/**
 * Copy of the original node_page_view to use result from our
 * MODULE_node_show($node) as return value.
 */
function MODULE_node_show($node, $message = FALSE) {
  if ($message) {
    drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  }

  $view_mode = MODULE_user_node_view_mode($node, $user);

  // For markup consistency with other pages, use node_view_multiple() rather than node_view().
  $nodes = node_view_multiple(array($node->nid => $node), $view_mode);

  // Update the history table, stating that this user viewed this node.
  node_tag_new($node);

  return $nodes;
}

/**
 * Determines the view mode to use for the node page of the given node
 * when viewed by the given user.
 * @param $node
 *  The viewed node object
 * @param $account
 *  The viewing user object
 */
function MODULE_user_node_view_mode($node, $account) {
  // ... Implement your custom view mode selection logic here
}

Note: There is probably something that need to be done to ensure the page using a given view mode is not cached and re-used for different user.


Add "n" fields when click on "Add another item"

There is an open feature request for this on Drupal.org but it is not currently supported out of the box. See https://www.drupal.org/project/drupal/issues/1394184 for details


field_attach_form with user picture and user mail?

I was working on a similar task; my task was to put the address field into the popup and I used the following code to accomplish it. I looked at modules/user/user.page.inc for it.

    function MYMODULE_init() {
         //To avoid user_profile_form_validate function not found
         module_load_include('inc', 'user', 'user.pages');
         } //end init function

        //Custom form for fields
        function MYMODULE_form($form, &$form_state) {

        $form = array();
        global $user;
        $account = user_load($user->uid);

        if (!isset($form_state['user'])) {
            $form_state['user'] = $account;
          }
          else {
            $account = $form_state['user'];
          }

        $form['#user'] = $account;
        user_account_form($form, $form_state);
        // Attach field widgets.
            $langcode = entity_language('user', $account);
            field_attach_form('user', $account, $form, $form_state, $langcode);
        //All fields get attached so removing unnecessary fields.
            unset($form['account']['pass']);
            unset($form['account']['roles']);
 $key = array_search('user_validate_current_pass', form['#validate']);
    if ($key !== FALSE) {
      unset($form['#validate'][$key]);
    }
    // hide the current password fields
    $form['account']['current_pass_required_value']['#access'] = FALSE;
    $form['account']['current_pass']['#access'] = FALSE;

            $form['actions'] = array('#type' => 'actions');
            $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Save'),
           );

          $form['actions']['cancel'] = array(
            '#type' => 'submit',
            '#value' => t('Cancel'),
            '#submit' => array('MYMODULE_form_cancel'),
            '#limit_validation_errors' => array(),
          );
          $form['#validate'][] = 'user_profile_form_validate';
          // Add the final user profile form submit handler.
          $form['#submit'][] = 'user_profile_form_submit';

          return $form;
        }

        // Add function for CANCEL button.
        function MYMODULE_form_cancel(&$form_state) {
        $url = $_GET['destination'] ? $_GET['destination'] : 'choose/your/path';
          drupal_goto($url);
        }


How can I get the parent node of a referenced node?

I think hostEntity was specific to FieldCollection in D7 and not to entity reference. Field Collection is tied to one specific host Entity. With entity reference there is no specific host entity, you can possibly reference one entity in multiple host entities.

You can use Entity Query to get all (host) nodes that reference a specific entity within a specific field.

In a very basic form this would return all "Project" nodes that reference a specific building by field building:

$query = \Drupal::entityQuery('node')
  ->condition('field_building', $building_nid);
$nids = $query->execute();

$building_nid is the node id of the building. This will return "project" node ids in your case.


How create Menu items by permissions for a view page?

What I did:

I tried using dynamic menus. But it isn't functional for my purpose. Because, each link menu could have different access by roles.

Then I realized that I needed to create a view for each type of content to be able to manage an individual permission.

Therefore I need to create a view each time that I create a CT, so the is no sense to do it dynamically.

How I did:

I create a view for each CT with a filter content by type. And also I set permission for each view for same CT. And a custom route.

Create one item menu for each CT and set as route same as is in the view.

.links.menu.yml

    vdm.tc_sujet:
     title: 'Sujets'
     parent: system.admin_content
     route_name: vdm.tc_sujets
     description: "Content type subject."
     weight: -1

.routing.yml

    vdm.tc_sujets:
     path: '/admin/content/sujet'
     defaults:
       _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
       _title: 'Sujets'

As result if user have access to that view the item menu will be displayed.

Note: I think that dynamic menus it fix great for add link item to nodes.


There is a Drupal Chat module for chat. It uses node.js and hence highly scalable

  Supports smileys (detects them automatically in chat messages)
  Chat history is retained in between page loads
  Provides option to use Normal AJAX, long polling and Node.js (only in 7.x) techniques to update chat messages
  Provides optional integration with User Relationships module.


White screen appears when viewing huge number of nodes as view result

Why not try use this module View Infinite Scroll to try stagger the amount of results returned by Views in one go? This would help the web server from running out of memory returning 4000 results in one go, but is better UX wise than implementing a pager.


Can the multisite manage multiple databases with a single software?

Yes.

  Do I have to foresee it and create it from the beginning or can I create the software and subsequently, if there is a request, transforming it into a multisite?

You can perfectly start with a single site, and late on transform it into a multisite.

As an alternative to using a multisite, you may also want to consider using the Group module. From the specs in your question, it appears to me that only using this module (without a multisite setup), it could well be sufficient ...


Is the #disabled form element property different from the html disabled attribute?

Yes it's different, as well as rendering the attribute the form API also ensures server-side validation is taken care of.

As with all Drupal form manipulation, the right way to remove the disabled attribute is with the Ajax API, not by manipulating the input directly with JavaScript.

Once you use that method, you'll be able to get values for the input(s) in the form state as normal.


How do I query for the next three dates using EntityFieldQuery or Views? (7)

The query you've got in your question would be the equivalent of this EntityFieldQuery:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->fieldConditon('field_start_test_date', 'value', REQUEST_TIME, '>')
  ->fieldOrderBy('field_start_test_date')
  ->range(0, 3);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
}

I've assumed that date_field was supposed to be field_start_test_date and that the date column is a UNIX timestamp type. You'll need to make a couple of slight changes if those assumptions aren't right.


How do you set a one-off access checker on a route?

The handbook is correct. The access is handled by services. The normal way to implement a custom access check is to define a service in mymodule.services.yml. See this example from the core book module:

  access_check.book.removable:
    class: Drupal\book\Access\BookNodeIsRemovableAccessCheck
    arguments: ['@book.manager']
    tags:
      - { name: access_check, applies_to: _access_book_removable }

And then use this in routing:

_access_book_removable: 'TRUE'

Here you can choose your own arbitrary naming schema.

As described in the handbook, if you want to simplify this, you can reuse the service access_check.custom, which is already defined in core.services.yml:

  access_check.custom:
    class: Drupal\Core\Access\CustomAccessCheck
    arguments: ['@controller_resolver', '@access_arguments_resolver_factory']
    tags:
      - { name: access_check, applies_to: _custom_access }

Then you have to use _custom_access: for the route. You can not use something like _my_module_access: as before, the key must match the tag in the service definition.

The first solution puts the complete logic of the access check in a service and makes it reusable and self-explanatory. If you only need the access code in one route and want to place the access code in the controller class the second method provides a shortcut.


Creating a grid of referenced Commerce products

This is possible out of the box without any custom code, just plain Views. The trick is to make the View based on content of whatever your node type is and set a relationship from the node to the products referenced by its product reference field. Once you have product fields available to the View, Commerce 1.x provides a per-variation Add to Cart form field to drop into the View.
I created a sample View that does this, placing it in a block on node pages of my product display node type. It uses a contextual filter to determine the node ID from the URL, joins to the products via the relationship I described above, and then shows the product title, price, and Add to Cart form in a grid:

Note that the line items added via the product Add to Cart forms do not maintain the context of the node; that's why "Product Three" is rendered as a link in my cart but Two and One are not. It would take custom code to ensure those forms have the appropriate context at this point, but that's another question.
In case you're a visual learner, here's the View I constructed to make this work:


Link field sanitizes query string from foo.cgi?123456 to foo.cgi?0=

I have tracked down the problem deep into Drupal Core itself. The problem actually consists of two bugs, not just one!

EDIT: For the first bug I have submitted a new Drupal Core issue (issue 3007243). For the second bug I have contributed my analysis to the discussions of two existing Drupal Core issues (issue 2987114 and issue 1464244).

Let's start at the beginning. The Link module works with the Drupal Core class Url. At the appropriate time, the Link module gets the URI from the Url object by invoking its toString() method. For external links, this method makes use of the Drupal Core class UnroutedUrlAssembler, by invoking its assemble() method, which in turn invokes another method buildExternalUrl.

Bug #1 is in buildExternalUrl: The method contains this line:

$options['query'] = NestedArray::mergeDeep($parsed['query'], $options['query']);

This is wrong because it doesn't preserve integer keys! Remember that the query parameter in my URL is numeric (1580, see the OP)? The above line causes the 1580 to be discarded, instead the result is the 0 (zero) that we have seen in the mangled query string. The correct line would be this. The all-important thing is the TRUE parameter which tells NestedArray::mergeDeepArray() to preserve integer keys.

$options['query'] = NestedArray::mergeDeepArray(array($parsed['query'], $options['query']), TRUE);

Unfortunately this is not the end of the road. Where does the "=" character in the mangled query string come from? The assemble() method of the UnroutedUrlAssembler class first breaks down the URI into its individual parts like this:

$parsed = UrlHelper::parse($uri);

Then it reassembles the URI, piece by piece. The query string gets reassembled with this line:

$uri .= '?' . UrlHelper::buildQuery($options['query']);

The UrlHelper::buildQuery function generates "key=value" pairs from the entries in the supplied array ($options['query']). It omits the "=value" part if - and only if - the value of an array entry is NULL (the check is made with the PHP function isset()). As I have found out, for my example URL the value of the array entry is NOT NULL, it's an empty string - and that's what causes the "=" character to be generated.

But where is the empty string coming from? The function UrlHelper::parse() uses the PHP built-in function parse_str() to break down the query string into its parts, and that PHP function is the culprit! Here's the proof:

php -r '$query="1580"; $arr = array(); parse_str($query, $arr); echo "isset: " . isset($arr[1580]) . "\n"; echo "+" . $arr[1580] . "+\n"; echo "gettype: " . gettype($arr[1580]) . "\n";'
isset: 1
++
gettype: string

So to ultimately fix the problem, either parse_str() would have to change its buggy query string parsing, or the Drupal function UrlHelper::parse() would have to use some other function to parse query strings.


Which hook do I need to use to pull external content in pages?

hook_page_alter() is used to alter the page returned from another module, and hook_page_delivery_callback_alter() is used to change the page delivery callback for a page output from another module. All the hooks with a name ending with _alter are hooks that alter the output of another module, what another module returns, or the data stored by another module.

The hook you should use is hook_menu() to define a page callback, and drupal_http_request() to get the external content.
The minimal code you should use is similar to the following one.

  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_external_content_view',
      'access arguments' => array('access content'),
    );

    return $items;
  }

function mymodule_external_content_view() {
  $response = drupal_http_request($url);
  if (!isset($response->error)) {
    $data = $response->data;

    return array(
      '#markup' => filter_xss($response->data, $allowed_tags)
    );
  }
}

Replace abc/def with the path of the page you want to output, $url with the URL of the external application, and $allowed_tags with an array of strings for the tags that you want to allow as output. By default, filter_xss() uses array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd').


hook_custom_theme() works except if a user submits a user form with mismatched passwords. Then they get served the admin theme

hook_custom_theme()'s documentation says :

  The return value of this hook will be used on all pages except those
  which have a valid per-page or per-section theme set via a theme
  callback function in hook_menu(); the themes on those pages can only
  be overridden using hook_menu_alter().

so i guess that what you need here is having your custom rules ina  helper function that you call both in hook_custom_theme() and the theme callback of the error page from hook_menu_alter()


Why is an integer variable in PHP interpreted as a string literal when passed from Drupal to JavaScript via Drupal.settings?

If you do

{
  ..
  height: settings.designer.jquery_modal_height,
  ..
}

You are doing it right, else you should do

..
var height = settings.designer.jquery_modal_height;
..

Most likely it's not the variable that's the problem but some other part of your code.


How can I get the parent term in a taxonomy with a hierarchy?

taxonomy_get_parents() returns all the parent terms for the taxonomy term with the ID passed as argument.
The value returned from the function is an array having the following structure:

array(
  'term id' => [taxonomy term object]
)

The taxonomy term object contains a property for each of the fields contained in the "term_data" table.

The code used from the function is essentially the following one.

$result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.parent = t.tid WHERE h.tid = %d ORDER BY weight, name', 't', 'tid'), $tid);
$parents = array();
while ($parent = db_fetch_object($result)) {
  $parents[$parent->$key] = $parent;
}

As you see, it doesn't return the parent terms of the parent terms of the one passed as argument. For that you need taxonomy_get_parents_all(), which executes the following code.

  if ($tid) {
    $parents[] = taxonomy_get_term($tid);
    $n = 0;
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

The function returns all the parent terms in the hierarchy.


Change from address of user registration email

There is one e-mail address that is used as From-address for all mails sent automatically by the system.  By default, this is set to the same as the site administrator email.  To change it, do the following:

Navigate to Administration » Configuration » System » Site Information.
Locate the field "E-mail address". Change it to whatever you want it to be.
Press Save configuration.

Note that will also be used as the From-adress for password resets and other generated mail.

If you require fine-tuning beyond this (to distinguish between different types of auto-generated email messages), you need to write a custom module. In that case, you may use hook_mail_alter to alter the From:-address, based upon some criteria (e.g. the subject field.

For avoidance of misunderstanding: The three steps listed above will not change the site administrator email id.  To inspect and change the site administrator email id, click on the  "My account" link while logged in as site admin, and then press the Edit tab to see it. The  site administrator email id is by default the same email id as the From-address used for email sent by the site itself - but they do not need to be the same.


Complex Shipping Rule: €3 Flat Rate for order's first 2kilos + extra €1.2/extra kilo charge

One of the problems with Commerce (and Ubercart for that matter) is that it takes awhile for someone to come around with weight based calculations. I have done something similar but it might not work for you.

1) I made each increment I wanted to allow a single product (i.e. 1lb of Product X is 1 QTY, if they want 2lbs of Product X, it's the same as saying Product X with 2 QTY.)
2) Then I created bundles for what I wanted to allow.
3) In shipping, you can set up a rule that allows extra for each extra QTY ($6 for 1 QTY and $2 for each additional QTY.)

For you, it might be possible to set your rule to multiply but you would have to create a module that would allow you to set percentages on QTY if you wanted someone to be able to add 1.2 QTY to their cart. For me, it was easier to do by whole increments and much cleaner on the rules. You can also set your shipping rule to line items so that the first line item is the base and the remaining are the additional.


You can have same taxonomy being used by multiple content types.

You can achieve this by using 2 options
1. Overriding node.tpl.php for the taxonomy page. Here you can create two separate tpl files specific two different content types.
2. Create PAGE display of VIEWs and pass "type" as an argument. Based on this argument you can always display the teasers belonging only to the desited "Content Type."

Option # 2 is little easier from implementation point of view whereing Option # 1 though could little time consuming but will be better from performance perspective.


How to add form on ubercart checkout complete page?

Create a custom module and use hook_form to create your form.

Then I would do as suggested in this post to add your custom form to the ubercart page you wish to edit, only instead of rendering items, call your new function.  Does that make sense?


How to override aggregator_block_view() in the aggregator module?

IF you want to alter the block view you can try hook_block_view_alter

Refer to menu block alter example for an example

http://api.drupal.org/api/drupal/modules%21menu%21menu.module/function/menu_block_view_alter/7

---UPDATE---

  function hook_aggregator_process($feed) {
      foreach ($feed->items as $item) {
        mymodule_save($item);
      }
    }

Check out the docs at http://api.drupal.org/api/drupal/modules%21aggregator%21aggregator.api.php/function/hook_aggregator_process/7

Also enable the aggregator settings at admin/config/services/aggregator/settings

----UPDATE-----

Also if you just want to override the item list then you should use themename_preprocess_aggregator_summary_items(&$variables) and check for 'summary_list' this holds the items list. For more details refer to template_preprocess_aggregator_summary_items in the aggregator.pages.inc file.


Check out the Unique field module.

  This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.


Views Custom Join change the 'on' condition

I ended up using hook_query_alter rather than hook_views_query_alter

/**
 * Implements hook_query_alter().
 */
function custom_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('line_itmes_qty')) {
    $query->join('line_items_tally', 't', 't.n <= commerce_line_item.quantity');
  }
}


Disable email alerts when modules are out of date

Go to http://mysite.com/admin/reports/updates/settings, and remove all the email addresses from the E-mail addresses to notify when updates are available textarea:

Just to highlight the pertinent of the description on that field:

  If blank, no emails will be sent.


is there hierarchical user level structure in drupal

Check out Subuser module to see if it fits your needs.

If you want "just" the roles to be hierarchical, Role delegation might be useful

Related: https://stackoverflow.com/questions/1281964/drupal-for-users-creating-sub-users


node--front.tpl.php is for the front page specifically.

If you don't want a specific template file to apply to the front page only, simply delete node--front.tpl.php and flush the caches. node--landing.tpl.php will then be used instead.


I have implemented this custom filter. All Thanks and credit goes to Amar :). I am just sharing the code.

// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'fee_management_handler_filter_payment_status',
      'numeric' => TRUE,
    ),
    );

Handler

class fee_management_handler_filter_payment_status extends views_handler_filter_many_to_one {
  function get_value_options() {
    $this->value_options = array('1' => 'Paid', '0' => 'Unpaid');
  }

    function query() {
    // as per your database st
        ;

  }

}


It sounds like you're running into a common deployment issue with Drupal: the fact that content and configuration reside in the same database. This generally puts a kink somewhere in most deployment strategies, as you start to run into issues whenever you have to merge existing user content (often a moving target) with upstream configuration changes.

Depending on how else you may have things set up, this may or may not involve drastic changes to your workflow, though this is the generally recommended solution for such issues. I'm not sure how much experience you have on these topics, so I'm going to break it down piece-by-piece for the benefit of anyone running into similar issues.

Dev/Test/Prod Workflow

Generally speaking, we have at least three servers in an optimal workflow. A "Development" server where our main version control repository lives (if you're not using one already, I highly recommend it!), a "Staging" server where we run our last rounds of acceptance testing and start adding default content, and a live "Production" server where everything is served to the end user.

Dev/Test/Prod in Drupal

As mentioned above, the fact that the database contains both content and configuration makes things quite messy. It's difficult to check a database into revision control, it makes configuration much less portable, and most attempts to decouple content and configuration are met with frustration (as with locking out certain privileges while making major updates to the site).

The adage "configuration moves forward, content moves backward" through the dev/stage/prod workflow still holds true as best practice with Drupal. We want to put as much configuration into code as possible, removing it from the database in an effort to decouple the two. This way, we can push features forward through the workflow as normal, and then take content from the live site and pull it back to dev when needed, without getting in the user's way.

Moving Configuration to Code

How do we move configuration to code, though? The Features module allows you to export the configuration of most popular modules to code as "feature modules"--in fact, anything that implements CTools Exportables is fair game. You could even add your own hooks to these exported feature modules and bundle them in an installation profile for one-click deployment (they're still just modules!).

In the rare cases where you can't achieve the desired functionality using Features alone and absolutely must hack at the database, you can do so through a custom module or an existing exported feature, using hook_install() and hook_uninstall(). hook_update_N() can be used for incremental updates, but remember to update hook_install() to reflect the same changes as well!

Moving Content

If required, content from staging can also be pushed to live using a solution like the Deploy module. This way, you can push updates from dev to staging, and then use maintenance mode on staging only when polished functionality is being pushed forward from Dev. You could also use it to push content from your live site back to the Dev server, to ensure that you always have easy access to the latest live content.

That said, now that configuration has been stripped out from the database, it becomes much easier to just move the database around as a content store, rather than a hodge-podge of content and configuration.

In Closing

This is a difficult and long-standing problem in Drupal, and doesn't have a quick fix, though I've used the above workflow on several projects with a high degree of success. I'd be happy to clarify any parts of my answer.


How to replace allowed_values for a select field by external definition?

Instead of allowed_values you can add a callback to set the allowed values:

  ->setSettings(['allowed_values_function' => 'callback_allowed_values_function'])

The callback:

function callback_allowed_values_function(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {
  if (isset($entity) && ($entity->bundle() == 'not_a_programmer')) {
    $values = [
      1 => 'One',
      2 => 'Two',
    ];
  }
  else {
    $values = [
      'Group 1' => [
        0 => 'Zero',
        1 => 'One',
      ],
      'Group 2' => [
        2 => 'Two',
      ],
    ];
  }

  return $values;
}

You can get the allowed values from a text file or put the callback in an include file.

For more information see options.api.php

A different approach might be to store the allowed values in config, for which there is a bundle specific base field override, see How to easily alter an entity's base field definition per bundle. Then you can manage the allowed values list in a yaml file of an exported config.


Request a new password using username only

User module accepts either username or email to reset password.. Code goes below in user module...

/**
 * Form builder; Request a password reset.
 *
 * @ingroup forms
 * @see user_pass_validate()
 * @see user_pass_submit()
 */
function user_pass() {
  global $user;

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username or e-mail address'),
    '#size' => 60,
    '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
    '#required' => TRUE,
    '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
  );
  // Allow logged in users to request this also.
  if ($user->uid > 0) {
    $form['name']['#type'] = 'value';
    $form['name']['#value'] = $user->mail;
    $form['mail'] = array(
      '#prefix' => '<p>',
      '#markup' =>  t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->mail)),
      '#suffix' => '</p>',
    );
  }
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));

  return $form;
}

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}

You need to implement hook_form_alter in your own custom module and alter above form validation to add your own which accepts only username... You can achieve using custom module with out touching Drupal core... In hook form alter check for form id user_pass and override validate handlers like below..

$form['#validate'] = array('custom_module_user_pass_validation');

function custom_module_user_pass_validation(($form, &$form_state) {

}


Export/Import Content Types/Contents to another Drupal site (version 6)

For content types, views and much more you can use features, while for the nodes, node_export will do the job.


Saving values using variable_set through an array

It's the same:

The variable_set function saves the variable to database serializing it. variable_get takes the variable from $conf where the variable is already unserialized.

Example:

$var1 = array(
 'key1' => 'value1',
 'key2' => 'value2'
);
variable_set('var1', $var1);
print_r variable_get('var1');

Output

Array
(
    [key1] => value1
    [key2] => value2
)


I realize this is an old question, but I think this may help others with the same issue.

I recently contributed a module to Drupal community for lazy-loading inline images (and iframes).
Once the module is installed, the filter needs to be enabled in desired text-formats.

It requires no changes to the existing content.

Lazy-load
https://www.drupal.org/project/lazy


How to programmatically create forum topics using entity api?

$wrapper->taxonomy_forums = reset($terms)->tid; works!! taxonomy_get_term_by_name() returns an array of objects keyed with extra dimension (I think its keyed by the tid). The wrapper's save method will call forum_node_presave($node) but will look in the wrong dimension for the tid if you don't get rid of it.


what is the use of the migrate module UI in drupal 7

The UI just acts as a display for the mappings that you create, it also tells you how many nodes have been imported and how man haven't so you can manually do it.

There is lots of documentation on the drupal website here http://drupal.org/migrate and the example migrations are worth a look.

To migrate from drupal 6 to 7 I used created an xml view in drupal 6 and then created my mappings to use that in Drupal 7.

Cheers


With managed file, dynamically set fileName and #upload_location

Thanks @Clive. I just read your comment, but in the mean time I found the answer myself. This is the essentials of my code in my submitForm() method. It still seems a bit hacky to me but it works.
$images = $form_state->getValue('images');
$file = File::load( $images[0] );

$file->setPermanent();
$file->save();

$new_filename = "photos/test/test-02.jpg";
$stream_wrapper = \Drupal::service('file_system')->uriScheme($file->getFileUri());
$new_filename_uri = "{$stream_wrapper}://{$new_filename}";

file_move($file, $new_filename_uri); // <===== The essential line!

$file = File::load( $images[0] );
dpm($file->getFilename()); // returns test-02.jpg
dpm($file->getFileUri());  // returns public://photos/test/test-02.jpg


D7 serving node content to related subdomain

This should be pretty simple to do with some mod_rewrite rules.  Apache's mod_rewrite supports proxying requests.


Pass user_register form field values to Pardot for extra processing

First you'd want to add an additional submit handler to your form...

function pardotpost_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id_goes_here') {
    $form['#submit'][] = 'send_to_pardot';
  }
}

Then in your new submit handler you post the data to their form handler

function send_to_pardot(&$form, &$form_state) {
  $url = 'http://pardot.com/your/form/handler/url/goes/here';
  $data = $form_state['values']['submitted_tree'];
  $options = array(
    'method' => 'POST',
    'data' => http_build_query($data, '', '&'),
    'timeout' => 15,
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
  );
  $result = drupal_http_request($url, $options);
}

Lastly you check $result for any errors.
Cheers


Create dynamic page with dynamic addresses

I don't understand what you mean by "my module creates pages". It sounds as if you meant to say "URLs" instead of "pages".

Anyway, if you want to link a callback to a URL, you need to implement hook_menu() in a custom module. See the menu_example module and its hook_menu implementation menu_example_menu for an example.


In you routing.yml change _title to _title_callback as below:

amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title_callback: '\Drupal\amap\Controller\TitleController::title'
  requirements:
    _permission: 'edit distribution inscription entities'

Create a "TitleController" controller in you amap module unser "src/Controller"

TitleController.php

<?php

namespace Drupal\amap\Controller;

use Drupal\Core\Controller\ControllerBase;

class TitleController extends ControllerBase {

  public function title() {
    return t('Update Planning Click here');
  }

}

Now your title will be callable from the controller and you can give whatever that likes you here.


Programmatically adding line items to Ubercart order

The issue was I was assigning the value in order total manually from the product details, instead of using ubercart's $order->getTotal() , which defines line item initially. Hence, this worked for me to get the order generated after setting product and other payment details in order:

$order->total               = $order->getTotal();
$order->line_items          = $order->getLineItems();
$order->save();


Drupal 8 master site for managing customer Drupal 8 sites? Possible?

It sounds very much like you'll need two solutions. For sharing the code and parts of the configuration a distribution/install_profile makes sense (https://www.drupal.org/docs/8/creating-distributions). When you make changes to the distribution you'll need to write hook_update_N functions to make these changes on the sites that are using it. So updating a customer site becomes the number problem of deploying coding and running update.php (or doing a cli command).

With respect to sharing roles and users this I might look to do something different. Maybe integrate with a third party identity services that allows you to share the identities across your sites. The roles can be deployed as configuration as part of the install profile. Buried somewhere in this presentation https://events.drupal.org/dublin2016/sessions/no-compromises-%E2%80%93-react-relay-and-graphql-drupal-8 is something about integrating Drupal 8 with an identify provider. And there's also things like https://www.drupal.org/project/openid_connect


I would build the different displays as separate blocks and then use the quicktab module.

https://drupal.org/project/quicktabs

That way, it will be very easy to switch between the blocks.

Configuration in quicktabs:

Results:


Use username password on different subdomain

Yes,there is no problem using  drupal user table, you just need implement you site and  connect to data base that Drupal install on it and then just need use user table ,
only one note remain that the password  saved with md5 method in  user table.
I thing is not complex, the summery of answer is connect to db use uid(or name) and password field of users table .

as sample code :

<?php

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="drupaldb"; // Database name
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = md5(mysql_real_escape_string($mypassword));

$sql="SELECT * FROM $tbl_name WHERE name='$myusername' and pass='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// want to want
echo "congratulation ,you login";

}
else {
echo "Wrong Username or Password";
}
?>


Which hook to use to give a user a role after purchasing something in Commerce 2?

In Drupal 8 Commerce is using Event dispatcher instead of hooks.

In this case, you should subscribe into the event named commerce_order.order.assign, the hook invoked then a order is assigned to a user. In this moment you can code to grant the role to the user. You can see an example of how commerce_log submodule from commerce used this event here.

If you need, you have this tutorial which tells you how to subscribe to a event from event dispatcher.


Indeed: Field default token.

  This module enables to use tokens as field default values.

See the related core discussion if you're interested.


How does one 'override' string used in a core file?

For overriding a few text strings the easiest way is probably to use the String Overrides module:

  Provides a quick and easy way to replace any text on the site.

UPDATE

The line that sets this particular string is:

$block['content'] = t('Already a member? !login', array('!login' => l(t('Login'), 'user')));

Once it's built up, the string will actually look something like this:

'Already a member? Login'

That's why you're having difficulty targeting it with the string overrides module at the moment. If you're not developing a multilingual site you might just get away with inspecting the  tag in the block, and using that HTML in string overrides. I'm pretty sure it'll work.


How do I load a third party PHP library?

The 8.x-3.x branch of the Libraries module still provides the libraries_get_path() function. And (as of now) it looks pretty much unchanged. So you should be able to use it in the same way.

As far as where to put your library, the libraries_get_libraries() function has been updated with the following addition to the $searchdir array:

// Always search the root 'libraries' directory.
$searchdir[] = 'libraries';

Which indicates that you can place your libraries in a directory named "libraries" at your site root.


Preprocess SCSS with Zen Theme on MS Server

I don't have experience with MS server but I expect the entire process to be the same as described.

This applies to themes in general, not only Zen:

Using Sass preprocess to compile CSS is independent from Drupal, or Drupal themes. This is just an outside tool that you can use to make your CSS life easier, if you are familir enough with CSS and Sass. The end output that themes use will always be CSS, because that is what browsers understand.

Some themes have opted to integrate Sass preprocessing into their workflows. You don't have to use Sass, you can always just override the base CSS that was generated through Sass with your own CSS. But some themes have Sass so tightly integrated that it would a pitty not to take advantage of it. It's entirely your call.

Most of Sass preprocessing situations define which folder on your system contain Sass files, and which folder stores the compiled CSS, they are usually different folders (it's a cleaner practice not to keep the compiled CSS in the same folder as its source Sass). This is what you will find in most themes that use Sass, you will have a dedicated folder for Sass, and another one for compiled CSS, so you can continue using that structure. This structure is then recorded in the gulp.js file, so the preprocessor software knows which files to use as sources, and where to save the compiled code.

If you're not using Sass, but only pure CSS, you should keep your CSS in the third place! Don't keep it in the folder with the compiled CSS, because if a preprocessor is ever triggered, the contents of that folder might be deleted! Keep your dry CSS in a dedicated folder that doesn't have anything to do with Sass. You will add the CSS files to your Drupal theme configuration, so they are applied after all the theme code. This is how you can bypass dealing with Sass if a theme is using it.

Nodejs isn't the only way to get Sass working on your computer, there are other technologies that have it, but either way you'll have to install some engine that makes the Sass processor available.

Once you install nodejs, and the preprocessor packages as noted in the Zen tutorial, you will be able to start compiling CSS out of Sass files "anywhere" on your computer, given the correctly configured gulp.js.

You will probably just want to work on your Zen subtheme, which already comes with a great gulp.js, so if you have the preprocessor installed correctly you can start compiling the Zen subtheme Sass into CSS.

This can be done manually, you edit the Sass files to edit/add new Sass/CSS code, then (through terminal) use nodejs and Sass commands to execute Sass to CSS compiling. So you manually execute the compile command each time you want to compile your Sass changes and test them in browser.

More commonly it is done automatically by using a command to start watching Sass folder (a process is opened on your computer in your terminal). This way when you save changes to a Sass file the processing starts automatically, old CSS files get overwritten with the new CSS that contains the changes. There is also the Browsersync option that refreshes CSS automatically in the page where you're developing (local environment server) but it's more complicated with caching...

So this is what the development steps are with Sass, once you have the preprocessor installed:

Open terminal, go to your subtheme folder
Start watching (there's a command for that, the process is started and is kept active)
Edit the Sass files to make your changes (in what ever editor you usually use)
Save Sass file(s), this is when the preprocessor will compile the CSS, you will see the output in terminal, if you have any errors you need to fix them etc. The output will tell you when the CSS is compiled so you can check your changes in browser (it can be miliseconds or seconds depending on circumstances)
Repeat
When you're done with development you stop watching the subtheme folder after your latest compile (you stop the process you started in step 2)

What is also usually involved in development is commiting changes to Git once you have a meaningful piece to commit (not after every Sass file save). For this I keep another terminal (shell) open, one for keeping an eye on CSS compiling with the watch command, the other for "regular" commands and git.


Only show content in a View if the content has a checked field

I tried on my test site, and it happened to me too, for the simple fact I didn't enter any value for On value, and Off value. Once I entered Show the node in the view, and Don't show the node in the view, for those fields, the filtered criteria showed those values in Options.

If you don't enter any value for On value, and Off value, the Options fields really shows three entries, but the other two are empty strings. They are there, but you cannot see them, and you don't know which value comes first. Is the first row for On value, or Off value?


#default_value for select form elements does not work

The #default_value for a select element should be an integer value matching an array key in the #options array.

In your case, lets say

$taxs = [5 => 'blue dish', 9 => 'red dish', 15 => 'green dish'];

Then an option for the value for *#default_value will be one of 5,9 or 15.

In your case the function $form_state->hasValue('dish_dropdown') will return one of "blue dish", "red dish" or "green dish" which is not an array key in your $taxs array.

So what do you do?

Either select one of your dish types as the default OR
Add a default value - None -

For example:

$taxs[0] = '-- None --';
$reverseTaxs = array_flip($taxs);
$form['dish_dropdown'] = array(
        '#type' => 'select',
        '#options' => $taxs,
        '#chosen' => true,
        '#multiple' => false,
        '#maxlength' => $maxlength,
        '#default_value' => $form_state->hasValue('dish_dropdown') ? $reverseTaxs[$form_state->getValue('dish_dropdown')] : 0 ,

    $form['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Ir al tipo de plato'),
        '#weight' => 50,
    ];
    return $form;


why i can't update user's picture by user_save()

Try this code

 $file = file_load($fid);
 $file->status = 0;
 $edit = array ('picture' => $file);
 $u = user_save($account,$edit);


Create Content Type with a Default Title

The Automatic Nodetitles module can do what you're looking for. When used in conjunction with the Token module, you have lots of options.


How do I add an AJAX action on a select element in a ContentEntityForm to change the value of another select element

SOLUTION: Got this working with the following. You have to set the #ajax property on the widget

// Set the ajax function to run on the change of filing category.
$form['category']['widget']['#ajax'] = [
  'callback' => '_ajax_form_category_change',
  'event' => 'change',
  'wrapper' => 'ajax_id_data_type',
  'method' => 'replace',
];


Drupal 7 - Passing Arguments from Page Manager/Panel to embedded view/reference field

It sounds like you want to pass contexts from panels to a view. If that's the case, see my answer on Send a context from a panel page to a view integrated in it?

If you want to pass arguments (dynamically added by changing the URL to your panels page) to a view, then in the view panes settings, make sure to check Send arguments. You can then access the arguments in the view using Contextual Filters as if it were a regular views page.


Custom theme function for language switcher block

SOLVED!

adding hook_theme_registry_alter(&$theme_registry) was the answer.

/**
 * Implements hook_theme_registry_alter
 *
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {

  $mod_path = drupal_get_path('module', 'MYMODULE');

  if (isset($theme_registry['links'])){
    $theme_registry['links__locale_block']['theme path'] = $mod_path;
    $theme_registry['links__locale_block']['function'] = 'MYMODULE_links';
  }
}


Disable field validation of custom line items when cart is modified

You need to search for this function (since your not giving full information about that custom module you have)

function nameOfModule_form_validate(&$form_state, &$form_id){

You can search inside that function where it is doing the validation


Get $form_state values from individual entity form fields

You could also try $form_state->getValues()['entity_field_1'] as getValues() will build an array of values with the field name as the key.


How can I add form elements in custom form on click of link?

You should take a look at Examples module or in particular the AJAX example
 https://api.drupal.org/api/examples/ajax_example!ajax_example.module/7 It's really helpful.


Drush fails "unable to copy" to drush-backups?

Think I've solved it.

Looks like someone previously ran Drush in the sudo environment and that had the effect of setting permissions to 6226 all over the place.

Updated manually and fixed permissions as I went.


According to the Batch operations page on api.drupal.org, the processing function needs to have $context passed by reference.

Thus your import create node function should read function mymodule_import_create_node($node, &$context) and that should do it

Edit: sample code


How to use relations in Views to get Content type fileds when I use Taxonomy

Is this similar to what you want to do?
https://www.drupalgardens.com/documentation/taxonomy/views


How do I find out the content type within template.php?

Im new to Drupal. Finding variables and displaying them the way i wanted was very important to me. So i used a code that works in any php script. But i recommend you to always to stick with the Drupal API.

Here is the magic code.

<?php var_dump(get_defined_vars()); ?>

This will output all the available variables for the current page. However the page will be very long so don do this on your live production site. Test it on a local site or put your site in maintenance mode.

Also check the http://www.hoomanb.com/cs/QuickRef/drupal-7-theming-cheat-sheet.pdf


How to override function system_send_email_action_validate


Adding an 'Add more' button to a settings form in the backend

It turns out I had two problems:

I have jquery_update installed, which included a version too recent for the backend. I configured a previous version and I got a whole step further.
I did not have my $form and $form_state as input parameters in my main form function and as such the field count was not updated.


How do I trigger a modal from a template that points to a controller returning an AJAX response

You're trying to trigger your modal in multiple ways. Right now your twig is saying to open the href in a modal, but your controller is not return html, it's returning a json/ajax response to open its content in a modal.

To fix this you should do one of the following:

Update your twig to just point to the link, don't do anything there to trigger a modal. Your current ajax response from the controller is handling opening the content in a modal.
Update your controller to return html and leave your twig as-is. In this scenario your twig is handling making the content open in a modal.

I'm not sure about the _format parameter in your route definition, but I think you can just omit it.


Create a block with contextual filter that show related nodes based on field value, not with taxonomy

You can try using PHP code in the contextual filter. You will be able to load the Node using arg(1) - node ID and provide the field value based on the node. Refer screenshot.


Loading default image from a node field in page.html.twig

Here's one approach, using a helper method. It assumes you have access to the loaded node entity ($entity), and would like to get either the set, or default image for a given image field. I've also left comments and links that explain why Drupal::service('entity.repository') is being used, and how I discovered the way in which the Image module loads the default image settings.

    /**
 * Get the set or default image uri for a file image field (if either
 * exist).
 * @param $entity
 * @param $fieldName
 * @return null|string
 */
function get_image_uri($entity, $fieldName) {
  $image_uri = NULL;
  if( $entity->hasField($fieldName) ) {
    try {
      $field = $entity->{$fieldName}; //Try loading from field values first.
      if ($field && $field->target_id) {
        $file = File::load($field->target_id);
        if ($file) {
          $image_uri = $file->getFileUri();
        }
      }
    } catch (\Exception $e) {
      \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
    }

    // If a set value above wasn't found, try the default image.
    if (is_null($image_uri)) {
      try {
        $field = $entity->get($fieldName); // Loading from field definition
        if ($field) {
          // From the image module /core/modules/image/ImageFormatterBase.php
          // $default_image = $test->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
          $default_image = $field->getSetting('default_image');
          if ($default_image && $default_image['uuid']) {
            // $defaultImageFile = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']));
            // See https://www.drupal.org/node/2549139  entityManager is deprecated.
            // Use entity.repository instead.
            $entityrepository = Drupal::service('entity.repository');
            $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
            if($defaultImageFile) {
              $image_uri = $defaultImageFile->getFileUri();
            }
          }
        }
      } catch (\Exception $e) {
        \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
      }
    }
  }

  return $image_uri;
}


How to open file in new tab instead of download when submitting form?

As @clive points out, this cannot be done on the server side. Check this post for a javascript based solution. You need to attach the javascript to your form during build. See below for an example of form build with a javascript attached to the submit element:

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  // Assuming you are extending core \Drupal\Core\Form\FormBase class
  // and prior the lines below you built your form elements.
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Download file'),
    '#button_type' => 'primary',
    '#attached' => [
      'library' => 'your_module/submitToNewTab'
    ]
  ];

  return $form;
}


How to print name of Payment Method in Commerce 2 order receipt email?

This patch (https://www.drupal.org/files/issues/2019-02-26/order_receipt_payment_gateway_and_instructions.patch) from this thread (https://www.drupal.org/project/commerce/issues/2884497#comment-12988057) fixed my issue. It required patching commerce_order.module and commerce_payment.module, as well as adding the display code to the order email receipt twig.


Batch API and curl or file_get_contents() issue in Drupal 7?

I think it isn't related to batch api.

Drupal has other HTTP client implementation - drupal_http_request()


Classes with the same name and description, but different location

That's a bad example, it is then used as another name to avoid a name conflict use Drupal\Component\Discovery\YamlDiscovery as ComponentYamlDiscovery;.

Usually you can see the purpose of the class when you look at the namespace or the corresponding file location. It's OK to use the same class name in different namespaces. As you can see in this issue there can be different opinions how descriptive class names should be and how much you should rely on the namespace of the class to make the purpose clear:

https://www.drupal.org/node/2408667


Drupal 7 Homebox module and Twitter Bootstrap theme

Hi make this change found on sites/all/modules/homebox/hombox.js on line 16.

Drupal.homebox.$pageSave = $homebox.find('#homebox-save-form button[type=submit]');

Why?
bootstrap changes the input type in the page.tpl so you need to reflect the changed


Access denied for unpublished content in drupal 7

Few things to check for to figure out the problem based on your configuration:

Are you logged in or logged out while accessing the content?
Which user are you logged in with? Is this user the author of this content?
Check the permissions of this user (the ones related to unpublished content)...

Let us know if you need help or more details on any of the above.

Cheers.

UPDATE: if you want to customize the message that is displayed when access is denied, you can create a new page containing the custom message and then go to "Administration -> Configuration -> System -> Site information -> Default 403 (access denied) page" and set the path to your created page.


When user gets saved in DB using user_save() it returns the user object. All you have to pass it to $GLOBAL['user']; and save session

   //Here is your previous code I assume where you have user_save()

   $user = user_save($userData);

   if($user) {
        drupal_save_session(FALSE);
        $GLOBALS['user'] = $user;
        drupal_save_session(TRUE);
   }

Hope this may help you


How can I track statistics on my site's user population?

Other than the option you present, I think you have two choices.

One is to wire up a hook_menu(), and create a path that accepts role, gender, and the other field value.  You would then pass this into a db_select() or EntityFieldQuery(), and return the results in HTML table form.

The other option, and the one I would recommend, would be to make up a View over your users, add in your roles and fields, and then use Views Data Export to export as XLS or CSV.  You can then analyze your data in a third-party tool like Excel.

Why do I recommend the later?  Leverage your tools for their strengths.  Drupal is good an managing and serving up content (raw data counts).  Tools like Excel are great at analyzing data.  These three fields are what you need to look at now, but this could change in the future.  Having a full export of the raw data will make this much easier down the road.


What items in the DB do I need to edit when switching from a multisite to a single site?

Since your content is showing, your DB connection is OK.

Even if you don't have DB access to the multisite, you should have DB access to your local (MAMP) server.  And even if that site's styling is broken, you should still be able to back up its contents using Backup and Migrate.

The fact that the content is unstyled and 404 shows on the home page indicates that your basic site setup is not correct.  IIRC, Drupal 6 did indeed appear unstyled if you migrated content between sites without resetting to the default (Garland) before migrating.

There may be a more direct way to repair this (I think  Mołot's link in his first comment points to such a recipe), but the way I got around this problem was by setting up an empty single Drupal 6 site with the default D6 theme (Garland).  While it was still empty, I configured it and installed and enabled all the modules I was going to need.  Then I used Backup and Migrate to backup my content, and migrated that content (using Backup and Migrate) to the newly created and empty Drupal 6 monosite.

After the content was in place, I installed the the theme I wanted to use, and made it the default.

(I.e. the idea is to use Garland until everything else is OK.)


Make view exposed filter shows results related to previous filter in view

As always there are many ways to solve a problem in Drupal.

The easiest way here is probably the Views Dependent Filters module.

This way the "sub-project" form field will only appear after a user chooses the "project" filter.


Hide specific sections on admin configuration page

You have stated that it would be "nice" to have these paths inaccessible. If a user is not supposed to have access to this paths then you should go above and beyond just "hiding links so nobody can see". Here is the solution to both remove those links from the config page AND having those links inaccessible if one were to type in the url in their address bar.

You will need to make a module with the following code. Note: I'm only doing this for the cron config page.

/**
 * Implements hook_permission().
 */
function my_module_permission() {

  return array(
    'access cron config' => array(
      'title' => t('Access Cron Config'),
      'description' => t('Gives a user access to the cron configuration page.'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {

  $items['admin/config/system/cron']['access callback'] = 'user_access';
  $items['admin/config/system/cron']['access arguments'] = array('access cron config');
}

This will give you the "Access Cron Config" permission on the permissions page and there you can choose which role has the cron page appear for them.

Please research more on hook_permission and hook_menu_alter for clarification on how to do this for the media pages.


How to avoid caching on access callbacks?

I did this using following way :

function my_custom_preprocess_page(&$variables) {
  $url = Drupal\Core\Url::fromRoute('<current>');
  if ($url->getInternalPath() == 'my-view-page') {
    $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
    if (!isset($_SESSION['my_custom_pass']) || (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] != Crypt::hashBase64($password))) {
      throw new AccessDeniedHttpException();
    }
  }
}

Edit:
We can add our dependency to access object in our access hook.

/**
 * Implements hook_node_access().
 */
function my_custom_node_access(NodeInterface $node, $operation, AccountInterface $account) {
  $access = new AccessResultNeutral();
  $password = \Drupal::config('my_custom.settings')->get('my_custom.pass');
  if (!isset($_SESSION['my_custom_pass']) || (isset($_SESSION['my_custom_pass']) && $_SESSION['my_custom_pass'] != Crypt::hashBase64($password))) {
    $access = new AccessResultForbidden();
  }
  $access->addCacheableDependency($_SESSION);
  return $access;
}


When I add the shipping line item that was selected to the orders view in commerce it duplicates orders

I found this module called Views Grouping Row Limit which works


Displaying a Page Before Drupal Bootstrap starts

To precisely answer your question, Yes.  If a file exists, drupal will not get involved.  Therefore, if, for example, you went to www.yourhost.com/splash.php, and splash.php existed in your web root/directory, it would be run without drupal getting involved.  In there, if you had a link to www.yourhost.com, where drupal's index.php exists, then upon clicking that link, drupal would bootstrap up and do it's thing.

If this is not what you are asking, you could investigate the Front module that allows you to have different front pages based upon roles.  Here, you could, for example, have a fancy splash page for anonymous users that goes away after they login.

If that doesn't work for you, then you could fake this out in a custom module using your own custom logic in either the boot() or init() hooks.


Changing filter plugin settings before they are saved

It looks like your only options right now are relying on generic form API features, like #process and #value_callback. FilterFormatFormBase doesn't call into the plugins for validate/submit, like we do for example for block plugins.


1 Better exposed Filters for 2 views blocks

You want to create an attachment view display and add it to your main display. For example, if you currently have the OpenMaps display working, create a listing display as an attachment and attach it to the OpenMaps display. Make sure you set "Inherit exposed filters" to "yes" to ensure both displays are using the same set of filters.
In views 3 you can find this settings in the Attachment display settings:


hook_menu - setting a variable to use in page.tpl.php

Just as an option, you could use a specific page template for your path, and sub-paths.

/**
 * Implements hook_preprocess_page
**/
function HOOK_preprocess_page(&$variables) {
  // Optional logic to check path condition
  // e.g arg(), request_uri(), current_path() etc..
  $some_condition = FALSE;
  if(arg(0) == 'base' || $some_condition) {
    // Set single page--base.tpl.php template, for /base and /base/subpath
    // Note: this overrides theme_hook_suggestions[]
    $variables['theme_hook_suggestion'] = 'page__base';
    // Sample template variable
    $variables['foo'] = 'bar';
  }

}

Then, in your theme, you can copy page.tpl.php to page--base.tpl.php and add whatever page specific markup you need in the template.

You could also add logic and template variables to hook_preprocess_page.  They would be available in your custom template. They can also be added there for the default page.tpl.php template. In any case, you will need some condition check for the specific target path match there.

Some relevant API functions to check the URL path include:

arg
current_path
request_uri

Note: arg() is also used by core template_preprocess_page to set the theme suggestions.

  Uses the arg() function to generate a series of page template suggestions based on the current path.


how to load 2 services (or more) through dependency injection

The key idea here is that if the class you are using implements the ContainerInjectionInterface, you get passed a container object from which you can get any service you like.  Since FormBase implements this, your form will already be able to do this.

Here's some code from D8's file example, from the Example Module, as an example:

  /**
   * Constructs a new FileExampleReadWriteForm page.
   *
   * @param StateInterface $state
   *   Storage interface for state data.
   * @param FileSystemInterface $file_system
   *   Interface for common file system operations.
   * @param StreamWrapperManagerInterface $stream_wrapper_manager
   *   Interface to obtain stream wrappers used to manipulate a given file
   *   scheme.
   * @param ModuleHandlerInterface $module_handler
   *   Interface to get information about the status of modules and other
   *   extensions.
   * @param RequestStack $request_stack
   *   Access to the current request, including to session objects.
   */
  public function __construct(
    StateInterface $state,
    FileSystemInterface $file_system,
    StreamWrapperManagerInterface $stream_wrapper_manager,
    ModuleHandlerInterface $module_handler,
    RequestStack $request_stack
  ) {
    $this->state = $state;
    $this->fileSystem = $file_system;
    $this->moduleHandler = $module_handler;
    $this->requestStack = $request_stack;
    $this->streamWrapperManager = $stream_wrapper_manager;
    $this->sessionSchemeEnabled = $this->moduleHandler->moduleExists('stream_wrapper_example');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $state = $container->get('state');
    $file_system = $container->get('file_system');
    $module_handler = $container->get('module_handler');
    $request_stack = $container->get('request_stack');
    $stream_wrapper_manager = $container->get('stream_wrapper_manager');
    return new static($state, $file_system, $stream_wrapper_manager, $module_handler, $request_stack);
  }

Your create() function calls your constructor, and since you've received a services container, you can ask for whatever and however many services you want.


The Admin menu module has a nice sub-module called 'Administration views" which replaces Drupal core content management page with a view. It also adds extra filters and a search function.


Just use the following, and you will obtain what you want to achieve.

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


How to change the url alias after a username change?

Yes, you should be able to do this with a rule.  Something like the following:

Event: 'After updating an existing user account'
Conditions: 'Data comparison'.  Compare account-unchanged:name to account:name and make sure you negate, so the rule is fired when they don't match (i.e. when this field has been updated)
Actions: 'Create or delete any URL alias'.  THis should be under the 'Path' section.  Select account:url and create a new value for it

Hope this helps!

Rules export:

{ "rules_change_user_url_alias" : {
    "LABEL" : "Change user URL alias",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "account-unchanged:name" ], "value" : [ "account:name" ] } }
    ],
    "DO" : [
      { "path_alias" : { "source" : "user\/[account:uid]", "alias" : "member\/[account:name]" } }
    ]
  }
}


How to use Recurring Dates with Views properly?

Eventually I found how to set this up an easy way:

Go to your View
Go to Displays --> <your display name,  for example Page> --> Edit
Select Format : Table
Add a date field:
Select a Content: <your date field name>
You will see Configure field: Content: <your date field name>
Go to "Multiple field settings"
Uncheck "Display all values in the same row"

  If checked, multiple values for this field will be shown in the same
  row. If not checked, each value in this field will create a new row.
  If using group by, please make sure to group by "Entity ID" for this
  setting to have any effect.


Which drupal function can you use to invoke a function stored in contrib module (e.g. in an .inc file)?

You can use module_load_include

  // Load node.admin.inc from the node module.
  module_load_include('inc', 'node', 'node.admin');
  // Load content_types.inc from the node module.
  module_load_include('inc', 'node', 'content_types');

Then you will be able to call the function that is in those files.


How do I add a Product to the Cart programmatically in Ubercart?

Is the node that users create is a valid product type node? In any case you can try this - http://api.lullabot.com/uc_cart_add_item

uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE)

Here $nid = nid of the product, $cid = cart id (also user id) - look at http://api.lullabot.com/uc_cart_get_id

Hope this helps.


How to avoid script being injected into costum blocks?

So if your admin account had it's password changed, I would be willing to bet the hackers gained access to your admin account somehow.

Might want to think about beefing up your passwords, for both your admin account and the box.

You definitely should make sure your Drupal install is up to date. If "Drupal Core update status" isn't "up to date" at /admin/reports/status you should look to update core. If there is ever a security vulnerability found in core, it's normally fixed very quickly and rolled out in a new version, so you should keep your core up to date.

As for ways to make your blocks more secure, one thing you might want to try is to actually move the block from being controlled by the admin to being controlled by code.

You can write a little custom module that will create blocks. You'll want to be familiar with hook_block_info and hook_block_view. Another upside to moving blocks into code is that it will increase their portability.

Also, as another general security note, you might want to take a look at Security Review, which will help point out any security flaws you might have on your site.


How do I get a list of Drupal 7 active contexts for the current page/form in hook_form_alter?

The context name is the array key, not it's ->name field. See my answer here on how to programmatically check if a context is active.

No need for foreach loop on $contexts on the 2nd and 3rd functions. Instead of loopoing on $contexts and printing for each context it's name field, you should simply print the array keys:

print_r (array_keys($contexts));


How to load nodes that are associated with the child of a taxonomy term

visabhishek answer gave me an idea.

Create a tax term page view:

Add Legacy ID as your contextual filter
In FIELDS add term ID (so you will get the term ID of Area 1. You can hide it using exclude from display.)

Then using the Views Field View module

  This module allows you to embed a view as a field in a view.

Add the view from visabhishek answer as a field. For Contextual filter you can pass the term ID as a token (using replacement patterns)

Problem solved :)


I have also get this kind of issue that change field type from one to another with existing data. So as @Eyal mentioned, we can write an update hook to

export data from a field table to a variable
remove fields of all bundles
add new fields of all bundles
restore data to field table

Here is the code example

use \Drupal\field\Entity\FieldStorageConfig;
use \Drupal\field\Entity\FieldConfig;

/**
 * Change node__field_maps from string_long to string type.
 */
function mymodule_update_8XXX() {
  $database = \Drupal::database();
  $table = 'node__field_maps';
  $entity_type = 'node';
  $field_name = 'field_maps';

  $field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);

  if (is_null($field_storage)) {
    return;
  }

  $rows = NULL;

  if ($database->schema()->tableExists($table)) {
    // The table data to restore after the update is completed.
    $rows = $database->select($table, 'n')
      ->fields('n')
      ->execute()
      ->fetchAll();
  }

  $new_fields = array();

  // Use existing field config for new field.
  foreach ($field_storage->getBundles() as $bundle => $label) {
    $field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
    $new_field = $field->toArray();
    $new_field['field_type'] = 'string';
    $new_field['settings'] = array();

    $new_fields[] = $new_field;
  }

  // Deleting field storage which will also delete bundles(fields).
  $new_field_storage = $field_storage->toArray();
  $new_field_storage['type'] = 'string';
  $new_field_storage['settings'] = array(
    'max_length' => 255,
    'is_ascii' => FALSE,
    'case_sensitive' => FALSE,
  );

  $field_storage->delete();

  // Purge field data now to allow new field and field_storage with same name
  // to be created. You may need to increase batch size.
  field_purge_batch(10);

  // Create new field storage.
  $new_field_storage = FieldStorageConfig::create($new_field_storage);
  $new_field_storage->save();

  // Create new fields.
  foreach ($new_fields as $new_field) {
    $new_field = FieldConfig::create($new_field);
    $new_field->save();
  }

  // Restore existing data in the same table.
  if (!is_null($rows)) {
    foreach ($rows as $row) {
      $database->insert($table)
        ->fields((array) $row)
        ->execute();
    }
  }

}

NOTE: Always backup DB and test code before running this code

Other thoughts
In my case, we also have exported configures which means the field type and settings are also included in field_storage_config, field_config, entity_form_display, and entity_view_display config files. So we have to update config settings in those files as well. One easy way could be:

clone your website
delete the field and add a field with the same name again in field UI
export configures to use them in the repo
make sure the config uuid for the field and storage were not changed (change the uuid back if it was) to avoid the import potentially removing data.
import configure after DB update and clear cache again

This is code is inspired by @drugan in the post https://www.drupal.org/node/2816859