How do I mark a database query with a tag?

In case you're struggling to find the documentation, the class is called SelectQuery, and you're looking for the addTag function.

$query = db_select('table', 't')->fields('t')->addTag('my_tag');

Then in your query alter:

function MYMODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('my_tag')) {
    // Do something...
  }
}


Drupal 8, save new fieldCollection items to user from a foreach loop doesn't work

Make sure you've configured the cardinality of the field collection foo as unlimited (or at least anything more than 1) under "Field settings".

Also double check the name that you are passing to the FieldCollectionItem::create() method. It shouldn't be the label name but the machine name of your foo field collection, which will probably be field_foo:

$field_collection_foo = FieldCollectionItem::create(
  array('field_name' => "field_foo")
);

This also applies to the subfield_data (in your field collection item):

$field_collection_foo->set("field_subfield_data", $data);


I removed the seconds from the daterange widget by setting the step attribute in hook_field_widget_WIDGET_TYPE_form_alter() to 60 (seconds)

function my_module_field_widget_time_range_form_alter(&$element, FormStateInterface $form_state, $context) {
  $element['value']['#attributes']['step'] = 60;
  $element['end_value']['#attributes']['step'] = 60;
}


We use the Link Checker modules on our sites. This would scan all links and give a report back as to which are broken, if any. I don't see any reason why this would not work on any site, including multi lingual.

Whether or not you use the module, you should be able to look at the code to get an idea of what functions and logic it's using to create similar functionality, if you're looking to do it programmatically.


Adding JS to a form within Omega 4 theme

You cannot do what you want to do in the form preprocessor.

Try using hook_form_alter() instead.

Keep reading for more information on why your current code doesn't work.

If you look at drupal_render() you can see that it runs this to theme the element:

if (isset($elements['#theme'])) {
  $elements['#children'] = theme($elements['#theme'], $elements);
}

This call to theme() is pretty much where your preprocess code code is running.

The output of that theme function (theme_form() outputs a string of form markup) is then going into $elements['#children'].

Then further down in drupal_render() it does this:

if (!empty($elements['#attached'])) {
  drupal_process_attached($elements);
}

But the #attached code you added never ended up back in the $elements of the drupal_render() function though so nothing happened.


Overriding page.tpl.php for a menu_hook page

You wouldn't need node- at the beginning of your template file name as your path isn't a node page. Going off the Drupal 7 Theme Hook Suggestions, the file should be called:

page--announce_your_new_products.tpl.php

If that doesn't work, try:

page--announce-your-new-products.tpl.php

Unfortunately the docs aren't very clear on which way will work.


Unable to log in due to session cookies not being passed in

For anyone else who stumbles across this problem I did finally manage to solve it with the following which ensures the credentials are pass for each call consistently. I'm assuming where CORS adds in the additional OPTIONS request, the credentials we're going through.

jQuery.support.cors = true;
    jQuery.ajaxSetup({
        xhrFields: {
            withCredentials: true   // Pass session cookie with requests
        }
    });


How to render the content in which the user is mentioned in?

If you think about writing this as a pure SQL query, what you are trying to do is have multiple WHERE conditions that are separated by OR operators.

Using OR operators with Conextual Filters is not possible out-of-the-box with Views. All Contextual Filters are added as AND filters.

There appears to be a module that adds this option, although I have not tested it. It doesn't have an official release, but appears to be in use by over 2000 sites, so might be worth a try: https://www.drupal.org/project/views_contextual_filters_or

Ultimately, however, this could be solved with a different data architecture. Is there a reason you have multiple different fields for referencing the user? Could these fields be combined into one base field, with instances on various content types? If so, then you can do it with a single Contextual Filter.


Help Needed with a Hook_form_alter Module

I think your not setting the prefix correctly. I think you want to do something more like this:

if ($form_id == ' webform_client_form_289') {
    // Add the directions
    $form['submitted']['#prefix'] = '
Do you know of a high-quality resource that should be in our listings?

Please let us know! We will review it before publishing it, and we will follow up with any questions.
';
}

Looks like what your trying to do on in your code is set resource_name to be an array with just prefix in it.


How to download a module hosted on GitHub via composer.json?

You need Composer Installers for that:

{
    "name": "my-project",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "contrib/term-csv-tree-import",
                "version": "dev-master",
                "type":"drupal-module",
                "source": {
                    "url": "https://github.com/grahl/term_csv_tree_import.git",
                    "type": "git",
                    "reference": "master"
                }
            }
        }
    ],
    "require": {
        "composer/installers": "^1.2"
    },
    "extra": {
        "installer-paths": {
            "docroot/libraries/{$name}": ["type:drupal-library"],
            "docroot/modules/contrib/{$name}": ["type:drupal-module"],
            "docroot/profiles/contrib/{$name}": ["type:drupal-profile"],
            "docroot/themes/contrib/{$name}": ["type:drupal-theme"]
        }
    }
}


"You cannot send more than 5 messages in 1 hour"

Change it using drush config-set.

To get the default settings use:

drush config-get contact.settings

To change the limit to 100 instead of 5, use:

drush config-set contact.settings flood.limit 100


Can I make Drush use a pattern to name sql-sync dump files?

If you use the '%dump-dir' directive, then drush will create a name for your dump file based on the name of the remote host and the name of the database.  It is best to not include the date in the database name for remote sql-syncs, because the rsync operation will be faster if it can update only the incremental changes in the database dump, and this of course would not be possible if the filename changed on every operation.

If you want the date to appear in the database dump's filename so that it can also serve as a backup of your drupal site, you must also be careful to back up the files at the Drupal root as well.  It is common for Drupal to simply fail (with errors or even a WSOD) if you try to use an sql database with a different version of the code (core or contrib) than was used to create the database.

An easy way to backup your database and files together is with the drush archive-dump command, which also has a convenient archive-restore command to go the other way.

Some combination of the above is probably a better solution than what you are trying to do in your question above.  The exact feature you are looking for is not currently supported in drush.  We could certainly consider feature requests to add that capability (ideally posted to the drush issue queue with a proposed patch already attached -- see function drush_sql_dump_file in commands/sql/sql.drush.inc), but there may be some reluctance to accept it, since the alternatives already described are probably better in most instances.


Is there a media-handling module that can handle midi files?

MIDI files can be embedded straight into the page with the <object> tag, so there should be some way to then output that with the link that views gives you at the moment. If you went with a separate field then it's be easy enough to do with Views output rewriting.

After a quick look for a flash solution, it seems that flash itself doesn't have any support for MIDI, so a flash based player is unlikely.


Controlling node's content using field setting

You don't need your own field types for this like comment adds.

You can use checkboxes, radios, lists, whatever you want that makes sense for you.

Moving them into the sidebar requires some form alter code in the node forms that moves them into fieldsets. path_form_node_form_alter() is an example that defines a fieldset and moves a field into it.

Then all that's left is custom preprocessing/twig checks.. check the value of those fields and then display whatever you want.


If there is a mail system installed on your server, Drupal will use it to send mail.

Things to check:

Can you send mail using a CLI mail program (e.g. "mail")?
Can PHP send mail? (Create a small PHP program outside of Drupal that uses this PHP-function to send mail.)

Usually, this is not a Drupal problem.  If you're able to send mail outside of Drupal, then Drupal will also send mail without any special configuration on your part.

Most shared hosting plans I've used (never used Network Solutions) is set up to send mail by default.

Also read this about debugging email problems.


Move menu code to the template.php with the associate hook

You can add your code to custom module as custom block:

/**
 * Implements hook_block_info().
 */
function custom_block_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function custom_block_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = my_block_view();
      break;
  }
  return $block;
}

/**
 * Custom function to assemble renderable array for block content.
 */
function my_block_view() {
  $output = '';
  $menu_array = menu_tree_all_data('main-menu');
  // Prepare your $output variable from $menu_array (like in your code).
  $block = array(
    'menu' => array(
      '#type' => 'markup',
      '#markup' => $output,
    )
  );
  return $block;
}

Then show this block in created region.


The Feeds module - https://www.drupal.org/project/feeds - provided me with the solution to this issue.

Feeds allow you set both the Status of the whole import, and a per user status by adding a Status column to your CSV,

For users who have the same problem, this how you do either:

1. General Status for User Import

Once you have installed the Feeds module go Structure/Feeds Importer/User Import - admin/structure/feeds/user - and go to the Settings option in the Processor section, here you will find an option to set the Status of all imported users:

2. Status column in Import CSV

If you want to add a status column to your CSV file, allowing some users records to be imported as active and others as blocked, then you need to edit the Mapping in the Processor section - again at admin/structure/feeds/user. Add a new field to the mapping selecting 'Account Status' as the target field.

Inside your CSV use the values 0 or 1 for the status - where 0 is 'blocked' and 1 is 'active'.

Note: this will override any default status defined by the steps outline in Option 1 above.

I can also confirm that VBO operation to unblock users will also result in the correct Activation emails being sent out to the users (provided you have an activation email configured in Account settings)


How to display different sets of images per page in sidebar?

Create as many views as content units.

  Is there any other cleaner way of doing this?

Yes, you do not need to create a View for each of your nodes/pages/content. You can create a dynamic view which automatically passes the Content ID to Views.

Create "Four Images" content type set up as a single multiupload image field.
Add these "Four Images" to you node.
Create a View Block

In View, for Fields, add your image
Click on Advanced (far right), for Contextual Filter add ID .Provide default value, Content ID from URL. (Note: The view preview will go blank, which is normal, since the View edit page does not have a Content ID.)

Go to blocks (/admin/structure/block), and add the View block to a region. For Visibility settings select the content type that you want this to appear in.


Change content of email verification email based on gender provided by user

You've got two options:

Create yourself a custom token and use that.
Use the hook_mail_alter function

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_mail_alter/7

The token approach is the more elegant approach, but needs a bit of head-wrapping to understand the concepts. The hook_mail_alter might be an easier quick hack.


How to obtain contents from a drupal 7 query?

execute() returns a resource you can iterate over in a foreach loop, e.g:

foreach ($result as $record) {
  $office_id = $record->office_id;
}

In your case you probably want to use the fetchObject() method to actually retrieve the first record returned from the query:

$result = $query->execute()->fetchObject();
$office = $result->office_id;


There's two ways to solve this...

Easy/tedious way, export only a few fields at a time using content copy and try to find out what's the max number of field you can select before running into php errors. This could be pretty cumbersome as you have a lot of field but this is the recommended/safe way.
Hard/dangerous way is messing up directly with MySQL. You need to be a little SQL savy to do this and rigorous to not forget anything.

So a little explanation for the n°2, the information your looking for is in these tables:

content_type_CONTENT_TYPE_NAME, this table store all non multi-valued fields of your CT (CT = Content Type).
content_field_FIELD_NAME, there's one of these tables for each of your field that is set to be multi-valued.

Internals CCK tables:

content_node_field_instance, stores definitions of each of your fields (label, weight, widget, name of CT...)
content_node_field additionals settings (required, multivalue, db storage...)
content_group_fields and content_group informations regarding the grouping feature.

So now you have the table, now comes the tricky part.

If your CT and fields doesn't exists on the destination, it's quite easy, just export the tables of your CT and fields in SQL, export the content of the internal CCK tables using your CT and fields names.

If your CT or any of your fields (remember that fields can be shared between CT) exists on the destination you have to evaluate the changes and update the table structure to apply these changes, I think this easy pretty difficult to deal with so I wouldn't recommend you to do so.

Good Luck.


How to get remote webpage content with drupal http request?

First, you can read the documentation about drupal_http_request() its pretty well documented and it will help you.

But for simple application, you can just do it like that.

<?php
$result = drupal_http_request('http://google.com/');
if (in_array( $result->code, array(200, 304))) {
  // Use $result->data for the content
}
else {
  // Error $result->code
}

// Also you can see all content from $result with
// if you had installed Devel Module and enable it
// dsm($result)
// or simply like that drupal_set_message('<pre>' . print_r($result, 1) . '</pre>');


What's the proper (seo safe) way to blackout a site (e.g. for SOPA)?

I found this post on the Drupal Google+ page. It says:

  Black out your #Drupal site against #SOPA on Wednesday. Drupal's maintenance mode is 503 status so it won't hurt your SEO.


Poll is a core module and it appears that it doesn't make the "end date" available to views. You could add your own "end date" field to the poll content type but then you have to enter it twice.

Or try the more advanced pollfield module:

Because pollfield allows you to build polls as part of the CCK system, this module provides a more flexible polling option than the Drupal core poll module.

Please let me know how it goes, I'm interested in the pollfield module myself, just don't have time right now to play with it ;-)


You might have a look at Bakery Single Sign-On System.

It mentions "This module started at the 2009 Drupal.org redesign sprint in San Francisco as a way to manage single sign-ons across *.drupal.org infrastructure."

For more details about how it work, you can see this article that has great explanation: Single Sign-on across Sub-Domains in Drupal with No Extra Modules.


I am answering this formally so other people can see one possible solution that will work if they have this same question, but the answer is actually found in the comment by @thumbson above: in order to modify the cookie, I did indeed find success in creating a custom js file that ran when every page loads.


Change input method of "Description field" in "File" type

One way to do it without coding might be to create custom entities with Entity Construction Kit and insert them to your content type using Inline Entity Form. Using ECK, you can add the dropdown/autocomplete field and the file field.

You may then need to use something like Automatic Entity Label to prevent the user from needing to enter description/title themselves (The site won't allow me to insert a third URL here, but an internet search for "automatic entity label drupal module" will bring it up).


Unlimited field collection pagination in node edit page

A great solution to your problem would be to use the EmbeddedViewField module. It fixes your problem, as mentioned in the module's project page:

  EmbeddedViewField is a module that will allow you to render a view as
  any other field.

  It is based on keithm's ViewField module, except that it will always
  render the view, regardless of whether the user is editing or
  displaying the entity that has the EmbeddedViewField. The view used
  for displaying is controlled by the default value set for the view.


How do you re-direct an alias at a scheduled time?

I would use the Rules module for this. But you can't "rely" on the Rules Scheduler in this case, if you want the redirect to start happening as of 00:00:01 01/01/2016 (sharp).

Redirect old path to new path

Here is the rule you'd need for it (in Rules export format, just use copy/past to import it in your own setup):

{ "rules_redirect_an_alias_at_a_scheduled_time" : {
    "LABEL" : "Redirect an alias at a scheduled time",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "AND" : [
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "the_old_path" } },
          { "data_is" : {
              "data" : [ "site:current-date" ],
              "op" : "\u003E",
              "value" : 1451602800
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Please note that the old path (= the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

A few more tweaks to make it fit your exact scenario:

change all occurences of the_old_path to the path to be used until 00:00:00 01/01/2016.
change all occurences of the_new_path to the path to be used starting from 00:00:01 01/01/2016.

Whenever such redirect actually happens, the user will also receive an informational message like so:

  Please note that the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)

If you don't want such message to appear, then just delete the line containing drupal_message in the exported rule above.

Attention: this exported rule uses UTC times ... if your question is about another timezone, make sure to also tweak the value of 1451602800 to fit your needs.

Redirect new path to old path

If you don't want to have the new path be shown yet BEFORE 00:00:01 01/01/2016, then just create a similar rule like the previous one, in which you swap the the_old_path and the_new_path, and reverse the test on the site:current-date.


Try the  Commerce product comparison module

  This module allows you to compare products. This is a familiar feature on commerce website.

There is another module called Dynamic properties

  Provides a dynamic properties field that allows to store product properties or similarly structured information. A property consists of an attribute, the name of the property and a value. It belongs to a category.


You can definitely use the Panels Extra Styles module to wrap multiple panes in as many tags as you need.

On the first pane of your new group click the option cog and, under the Style section (which should read No style), choose 'Change'. Change the selected style to Wrapper:Raw and enter your opening tags in the text area 'Content prefix'. Leave the suffix area blank (as you don't want to close any tags yet)

Save the changes and then do the same with the last pane you want to group. This time close all the tags opened in the first pane by entering them in the 'Content suffix' text area.

Save and update your panel page and et voila! Your panes are grouped with your own HTML!


Build Your Own Content Type

Create a Blog Content Type:

Admin > Structure > Content Types > Add Content Type (yoursite.ca/admin/structure/types/add)
Put "Blog" as the name of the content type
Adjust the opitions, (Submission form settings, Publishing options, Display settings, Menu settings), accordingly
Add the fields you want. If you want Tags, you could add a Taxonomy reference field

To allow users to make blogs, but not anything else:

go to Admin > People > Permissions (yoursite.ca/admin/people/permissions)
scroll down to the Node Section
select permissions, normally Blog: Create new content and Blog: Edit own content at least, for the role you want, (or AUTHENTICATED USER, which is every logged in user)

Use Core Content Type

There is already a core content type called article that has the following fields:

Title
Body
Image
Tags

Instead of making your own content type, you could just use this one.

To allow them to make blogs, but not anything else:

go to Admin > People > Permissions (yoursite.ca/admin/people/permissions)
scroll down to the Node Section
select permissions, normally Article: Create new content* and Article: Edit own content at least, for the role you want, (or AUTHENTICATED USER, which is every logged in user)

Remove front page message

A couple of options. The most elegant is to make a landing page and set that page as the "welcome" page at Admin > Configuration > System > Site information (yoursite.ca/admin/config/system/site-information)

Other options:

a module
CSS (Set display: none on the element)
A view. Follow these instructions.
Or scroll to the top of the mentioned link and read the forum. There are a ton of alternatives.


How can I make a slideshow with tabbed navigation/menu?

In most Views slideshows I've seen, the navigation is just part of the normal slideshow, but themed to not overlap, unlike the images.

Configure the View to select whatever information you need in the navigation, end then make your theme place the navigation to the right.

I would be surprised if VS does not already have functionality for connecting clicks on some elements with sliding to a certain image, but I don't know the ins and outs of the module enough to give more specific recommendations.


Answer for my problems:

function hook_menu_alter(&$aItems) {
    $sNodePath = drupal_get_path('module', 'node');

    $aItems['file/ajax']['file path']    = $sNodePath;
    $aItems['file/ajax']['file']         = 'node.pages.inc';
    $aItems['system/ajax']['file path']  = $sNodePath;
    $aItems['system/ajax']['file']       = 'node.pages.inc';
}


Is it possible to embed a content creation form in views header?

It doesn't have to be in the view header. Just place it block above the view and adjust the css so they sit together.

If you use entity forms and entity form blocks, you can just place a block above the view block (or panel pane).

Rules will allow you to create a new node, set the current OG_context as the new new node's group and then redirect back to the same page or to the new node.


maintenance-page--offline template not working

This is caused when class_exists() is being called from within alpha_get_theme() and autoloading fails. I have a patch that fixes this by wrapping those calls in a try/catch block. I'm not quite sure what should be done in the case of an error though, so I have just done nothing.

See theme Omega issue => https://www.drupal.org/node/1722586

It is working for me, I had the same problem.


How can I redirect users upon login sometimes but not break the "Forgot password?" function?

You can do that with a rule like that:

{ "rules_after_login_redirect_to_news" : {
    "LABEL" : "After login redirect to news.",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "0",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_login" ],
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "^user\/reset\/",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "news" } } ]
  }
}


Customizing views output- rewrite output to show an image based on key value

You should be able to access the data from $row array from inside the template file. So:

$data = $row->field_field_acc_gender;

// This may not necessarily be the correct structure of your field's data.
// So you may want to do print_r($data) or dpm($data) to see correct structure.
$gender = $data[0]['raw']['value'];

switch($gender) {
  case 'M':
    print('Male');
    break;
  case 'F':
    print('Female');
    break;
}


open node reference links in lightbox/ popup

In Views Use this code in "Rewrite the output of this field"

[title]

Note: add  "Node:Path" field before the Rewrite field.

You can also set the width and height of the popup window, see the read-me file in Lightbox2  module folder.

hope you will get idea from the above!!


Clean URL leads to duplicate URL after migration to another hosting

To correctly enable/configure Clean URLs, refer to Configure Clean URLs in the installation guide.

If you're not familiar with Clean URLs yet, I suggest to review that documentation in the installation guide carefully (for the version of Drupal that you're using) and make sure your server is correctly configured before proceeding.

Here is a summary of common steps/issues:

With Apache HTTPD as web-server, you have to enable mod_rewrite and configure the necessary rewrite rules in the .htaccess file.
Usually, theses rules are applied automatically, when mod_rewrite is enabled. But in some cases, the AllowOverride directive is too restrictive to allow this.


How to define my own block regions for original, custom front page layout?

If you just need it on your front page, doing it in page template is wrong.
You can do in in Panel - create new panel for logged and not logged users; use there blocks; and views' display 'panel pane' for using views which need argument from context.
Yes you can
It can, but sending view argument this way is really painful. I recommend use panels panes.
You set it in panel.


How to rewrite View SQL query to bypass MySQL query cache (SELECT SQL_NO_CACHE)

I don't want to say that this is impossible, but it's very close to be true.

The problem is that Views uses the Drupal SQL builder, so when making a select query, it utilizes the SelectQuery which again uses PDO from PHP. PDO can be used in two ways, either you feed it a query, or you can use it to build a query by instantiating the class and dosing stuff like

$query = ...;
$query->addField(...);
$query->addCondition(...);
$result = $query->execute();

The challenge is that you need to tell PDO that you don't want to make a regular SELECT query but instead an SELECT SQL_NO_CACHE query. I don't know if that is possible of how you would do it if it were. Even if it is possible, you still need to figure out how to do it through all the abstractions of classes created by PDO and Drupal and Views.

Drupal has a hook you can use to alter queries in general which probably will be the easiest route if you can figure out the above: hook_query_alter, alternatively you can subclass views_plugin_query_default defined in Views, where you can add alter how the query is created to add SQL_NO_CACHE. Again PDO and abstractions is the challenge.

If you are using Drupal 6 this should be more simple and you can probably use something like hook_db_rewrite_sql.


Update all nodes with a default field after adding a new field to the content type

Sadly, there's no very simple way to do this (besides VBO/rules), but here's the code I use in update functions in my custom module install files when I need to prepopulate field values for a certain node type after adding a new field (in this case, 'page' nodes):

<?php
// Get all nodes of 'page' type, populate the field with a value of '1'.
$pages = db_query("SELECT nid, vid FROM {node} WHERE type = 'page'")->fetchAllAssoc('nid');
foreach ($pages as $nid => $values) {
  $fields = array(
    'entity_type' => 'node',
    'bundle' => 'page',
    'deleted' => 0,
    'entity_id' => $values->nid,
    'revision_id' => $values->vid,
    'language' => LANGUAGE_NONE,
    'delta' => 0,
    'field_page_new_field_value' => 1,
  );
  db_insert('field_data_field_page_new_field')
    ->fields($fields)
    ->execute();
  db_insert('field_revision_field_page_new_field')
    ->fields($fields)
    ->execute();
}
?>

Another manual method mentioned in this answer uses EntityFieldQuery and loads/saves each node. More Drupal-y, but way less performant... (requires a full node load and save operation for each node!).


How to create an article with "show on demand" part of the text of the article?

For your use case, there is no module for it. You will need to use custom jQuery

SEE MY DEMO

For Example:

HTML

Merci

Thank you

jQuery

$( document ).ready(function() {
 $('.french-flag, .english-flag').css("cursor", "pointer");
 $('.french-text, .english-text').hide();

$('.french-flag').click(function() {
  $('.french-text').show();
  $('.english-text').hide();
});

$('.english-flag').click(function() {
  $('.english-text').show();
  $('.french-text').hide();
});

});

but in drupal you need to wrap your js code inside

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

So your Drupal JS code (example.js) needs to be

(function ($) {
     $( document ).ready(function() {
     $('.french-flag, .english-flag').css("cursor", "pointer");
     $('.french-text, .english-text').hide();

    $('.french-flag').click(function() {
      $('.french-text').show();
      $('.english-text').hide();
    });

    $('.english-flag').click(function() {
      $('.english-text').show();
      $('.french-text').hide();
    });

    });
})(jQuery);

To add/load your jQuery/java script to drupal, there are various methods, see/read Working with JavaScript and jQuery


Globally rewrite broken image links in node bodies

Assuming MySQL, you can fix that up with a search and replace SQL query.

Perhaps easiest from the MySQL command line, though could also use db_query.

The pattern is:

UPDATE tablename SET fieldname = REPLACE(fieldname, 'search', 'replace');

Something like:

UPDATE field_data_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

UPDATE field_revision_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

Backup the database first.

You may need to do it one image style at a time, or else make all the images uses a new standard style.

More info: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace


Hierarchy management solution(s)? (node or taxonomy)

Yes, the wonderful Taxonomy Manager module. I don't start a big project without it these days:

  This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

It's packed with features, there's a list of them on the module page. I think this one in particular will be of interest to you:

  Double Tree interface for moving terms in hierarchies, adding new translations and switching terms between different vocabularies


How to display more than 1 chart on the same page when using Google Chart Tools?

I finally managed to achieve this using the dev version of the Views Dataviz module. Of course there are other solutions but these require coding so i guess this is the easiest way of showing multiple charts in the same page.


How to add different field values in views?

create a block view of content B By overiding fields and render a content of block in A's view page.


Can I use Panels context keywords in PHP functions?

Just call the function without any argument and it will return the unread message count for the current user.


Can we use double quotes for strings inside t()?

A string is a string... PhP allows strings to be defined four ways, but the two that apply here are 'xxx' and "xxx"... both are valid strings that will be passed to the t() function.  The function cannot determine how the string variable was created, it only gets the content between the delimiters.  So you can use either one.

That said, some people like the convention of using single quotes for straight constant strings since '$foo' = $foo... while "$foo" = value of $foo.  AFAIK, Drupal coding standards do not specify what can be used for a string.

Adendum:  Note that the string being passed to the t() function should be a static string in order to be translatable.  E.g. if you use "$foo", this would be impossible to translate.  That's what the placeholders are for.


How do I force-indicate a vocabulary as a source for node breadcrumbs?

You can try Crumbs instead of taxonomy breadcrumb.
You can be bold and try the 7.x-2.x branch (*)

Documentation for Crumbs + Taxonomy: http://drupal.org/node/1984484

I have not personally tried it in combination with taxonomy menu, but think it should work ok.

To solve the problem on node pages:

Install Crumbs
Visit Admin > Structure > Crumbs to adjust the plugin priorities (*).
The taxonomy.termReference.field_vocab_B.node.certain_node_type (**) needs to be moved up, into the "Enabled" section.

You can do more stuff with Crumbs (you could even replace taxonomy menu with menupoly), but one question at a time.

(*) The crumbs-7.x-2.x, among other things, has a revamped admin UI to set the plugin priorities. It is still not perfect, which is the main reason there is no 7.x-2.0 stable yet.

(**) Thanks to the wildcard system, you could also move taxonomy.termReference.field_vocab_B.node.* or even taxonomy.termReference.field_vocab_B.* into "Enabled", instead of taxonomy.termReference.field_vocab_B.node.certain_node_type. Doing that would activate this behavior for other node types and/or other entity types that have field_vocab_B.


Warning: in_array() expects parameter 2 to be array, string given in _drupal_http_use_proxy() (line 1100 of /var/www/html/includes/common.inc)

This is the code for _drupal_http_use_proxy

function _drupal_http_use_proxy($host) {
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
}

The status message warns that $proxy_exceptions is not an array.

You can configure this setting on your settings.php file, this way:

$conf['proxy_exceptions'] = array('127.0.0.1', 'localhost');

Have you changed this variable to anything other than an array?

 $conf['proxy_exceptions'] = '127.0.0.1'; // For example

Maybe there is a contributed module which do this...

Try to insert a dpm on $proxy_exceptions or execute this on /devel/php  to show the value of this variable:

dpm(variable_get('proxy_exceptions'));

If you want to reset this variable:

variable_set('proxy_exceptions', array());

or

variable_del('proxy_exceptions');


Simplest way to create a Commerce shopping cart icon showing the number of items

The way I would do it, is that I would make the total number of products in the shopping cart available in the page.tpl.php file, and print it there directly.

Here's example code:

function YOUR_THEME_preprocess_page(&$variables) {
  $cart_count = 0;
  $order = commerce_cart_order_load($variables['user']->uid);
  if ($order) {
    $wrapper    = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $cart_count = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
  }
  // Make the number of products in the shopping cart available to our template.
  $variables['products_in_shopping_cart'] = $cart_count;
}

Then in your page.tpl.php you would use this code to show the number of products in current user's cart:

<?php print $products_in_shopping_cart; ?>

Note: second argument passed to the commerce_line_items_quantity() is updated per Clive's note.


Unable to update header value using hook_views_pre_render?

$view->display['page']->handler->handlers['header']
             ['area_1']->options['content'] = $my_values;

please change the value of the area_1 if anyone want change the header value programmatically .

Just hover the Global: Unfiltered text (Global: Unfiltered text) header value and you will get the area_1 value .


How can I have two nodes of different content types update to each other?

You can try Corresponding node references.

I used this to sync up Events and Venues on one of my sites, and whenever I switch a venue for an event it automatically changes the node reference on the other node, so I only have to change the node reference once, instead of twice. Keeps things tidy, works with multiple.


How do I create a system message for a user's first failed login attempt?

The error messages are always created when a user tries to login.

If the error message doesn't show, you must have a custom module, that removes the messages some how. Maybe via redirection or something similar.


How do I update the URL after changing the hosting of a website?

There are a couple of possibilities when this happens. The first is to make sure that you still have an .htaccess file, as moving between hosts sometimes doesn't include the hidden files.

If you do have it, depending on the server, the Symlinks may need to be changed. For instance my Ubuntu server needs the .htaccess file to be changed to this in order for it to work

#Options +FollowSymLinks // Commented out
Options +SymLinksIfOwnerMatch

The next possibility is that the DNS propagation hasn't finished yet. It can take up to 72 hours with some hosts before everything is fully refreshed and pointing the right location.


Given that you're using a custom controller for your page, you have the option to load the block from your controller, or place the block in another region outside of that part of the page that the Controller controls.

For blocks such as global elements such as headers and footers, I would recommend you place them through the CMS at /admin/structure/block

For blocks that sit above or below the content that your controller loads, you can also place them from /admin/structure/block or you can load them from within the the controller.

If you need to place content above and below your block, you'd probably want to load it programmatically in your controller.

Here's a guide on loading blocks programmatically.

basically in your myPage() method that is returning the build array, you'd want the build array for the block you want to load.

$build['events'] = \Drupal::service('plugin.manager.block')
  ->createInstance('my_events_block')
  ->build();

$build['recent_insights'] = \Drupal::service('plugin.manager.block')
  ->createInstance('recent_articles', ['title' => 'Some Recent Articles', 'offset' => 0])
  ->build();

return $build;

The code above works for the types of blocks that you custom create in your module, such as at /mymodule/src/Plugin/Block/RecentArticles.php

It doesn't work for loading an instance of a block that was created through the CMS.

For those you need to use:

$block = \Drupal::entityTypeManager()->getStorage('block')->load('myblock');
$build['myblock'] =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);


Why subscribe/unsubscribe button in the custom entity named group cannot appear?

Since you are taking over the display of Organic Groups nodes using your custom page callback path group/%, DrupalGap doesn't know to apply the field format view functions to your fields. Essentially you need to manually create/render your own widgets in your page_callback:

var content = {};
content.title = { /* ... */ };
content.subscribe = { /* ... */ };
return content;

There are helper functions in the og.js file related to joining/leaving groups that will be of help. From there just use simple HTML/CSS/JS to build your button(s) (perhaps with an onclick handler) to help the user interact with the group subscriptions.

If you want to call the og_ui_field_formatter_view() function directly (not recommended) you can, you just need to pass it all the correct parameters:

(entity_type, entity, field, instance, langcode, items, display)

the entity_type is typically 'node'
the entity will be the fully loaded JSON of the entity (already delivered to your page_callback)
the field and instance can be retrieved from http://api.drupalgap.org/7/global.html#drupalgap_field_info_field and http://api.drupalgap.org/7/global.html#drupalgap_field_info_instance respectively.
the langcode will most likely be und unless you are using a multi-lingual site
the items will be the value(s) within the field itself
the display you should default to { type: 'og_group_subscribe' }.

Not the easiest things to do to be honest, and you'll probably find yourself happier in the long run by building your own custom widget to subscribe/unsubscribe from the Group.

Feel free to copy any code you need from the og.js file to make your life easier.


Subtheme media query CSS in Omega Kickstart subtheme

I had similar issues like this. I ended up simply overriding the CSS file in my template.php. I created a helper for me to do this. Simply run hook_css_alter and replace the file you are targeting with your own. In this case, the omega theme's grid file is here:

sites/all/themes/contrib/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-24.css

And I am replacing it with:

sites/mysite.com/themes/my_theme/css/grid/alpha_default/wide/alpha-default-wide-24.css

This is the code in my template.php

/**
 * Implements hook_css_alter().
 */
function my_theme_css_alter(&$css) {
  $themePath = drupal_get_path('theme', 'my_theme');
  $newCSS = array(
    'sites/all/themes/contrib/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-24.css' => $themePath.'/css/grid/alpha_default/wide/alpha-default-wide-24.css'
  }
  _my_theme_replace_file($css, $newCSS);
}
/**
 * Helper function to replace an existing file with a new path
 */
function _my_theme_replace_file(&$files, $newFile) {
  foreach($newFile as $oldpath => $newPath) {
    if(isset($files[$oldpath])) {
      $files[$newPath] = $files[$oldpath];
      $files[$newPath]['data'] = $newPath;
      unset($files[$oldpath]);
    }
  }
}

The helper function _my_theme_replace_file simply loops through the array, finds the old path and replaces it with the new one.

I hope this helps.


Load The Drupal Database Schema in PostgreSQL

I am not sure this tutorial is up-to-date. You don't need to load database scheme, you can just choose to use PostgreSQL when running the installer at /path/to/drupal/install.php


How to add new items to existing menu using custom module

For Drupal 6 you do use menu_link_save:

$item = array(
  'link_title' => 'Menu title',
  'link_path' => 'menu/path',
  'menu_name' => 'menu_name',
  'module' => 'your_module',
);
menu_link_save($item);


Webform rules: compare a form field to a user field

I guess that you can enable Rules Forms support Submodule of Rules. This submodule shows the correct name of your form (above each respective form) to be used with Rules.

Also, see this answer, is related with Rules Forms support submodule and other steps to make a comparision form fields with rules, I think that could be useful.

Update: This is the address to download the module Rules Forms support for Drupal 7 http://drupal.org/project/rules_forms

this is an screen shot in Drupal 7 about when is enabled rules for a specific webform:


Configuring Drupal with a dynamic IP address

There's no need to use external DNS when working locally on a development box.

You can add the required mapping to your /etc/hosts file

e.g:

127.0.0.1 drupalsite1 drupalsite2 drupalsite3

Then you can access the site by visting, e.g http://drupalsite1 in your browser

You could even use something like

127.0.0.1 drupalsite1.no-ip.org drupalsite2.no-ip.org

If you'd prefer.

The /etc/hosts file is checked prior to external DNS lookup and will override / take precedence over the latter. There's a similar file in Windows as well.

More info: http://en.wikipedia.org/wiki/Hosts_(file)


You can use the Taxonomy : All Terms to display the terms each node has associated with a single vocabulary. You would have to spend some time on styling them properly.


I was confusing two different things. Because of the way Features handles permissions and roles, there are three pieces, not just two.

What I thought was happening:

I add Myrole to the Feature.
I add mypermission1, mypermission2, mypermission3, etc. to my Feature.
I save my Feature and user with Myrole will have mypermissions 1, 2, 3, etc.

What actually needs to happen:

I add Myrole to the Feature
I add mypermission1, mypermission2, mypermission3, etc. to my Feature.
I make sure that Myrole's permissions in my current config actually include mypermissions 1, 2, 3, etc.
I save my Feature and user with Myrole will have mypermissions 1, 2, 3, etc.

The first one exports whatever the state of mypermissions 1, 2, 3, etc. is at the moment of the export which means that if the role in your config does not actually have those permissions, your Feature will specify that your role does not have those permissions, explicitly. Backwards from what I was trying to do.


Not 100% exactly what you're asking for, but it may solve your requirement:

The IMCE module allows you to upload documents (and images) and integrates them in the body text. You don't need a separate file field if all you need is a document integrated into your text via a link.


How to display multiple taxonomy fields in a view

If you are willing to use Display Suite then you can get the kind of result you are asking for with configuration only (but with some limits on flexibility). The other alternative would be to do something with Views PHP.

The steps for configuring Display Suite to show taxonomy terms as images (from an image field you've added to the taxonomy) are:

Create a view mode for your taxonomy (or reuse, say, the tokens view mode). This view mode needs to show just your image image field. You can format it here, e.g. to a thumbnail or whatever works for you.
Create a view mode for your content type (or content types if more than one is involved). You could use the standard teaser view mode or add a custom one for this purpose. Add the fields you want from your node and also add the term reference field.
For the term reference field select the Rendered taxonomy term FORMAT option. This then gives you a choice of view mode for rendering the term. Select whatever you used in step 1.
In you View select Show: Content | Teaser under the FORMAT section. (If you've made a custom view mode, then replace 'Teaser' with the name of your custom view mode.)

By using the Content option you lose some of the flexibility of using the Fields option Views. If that's an issue you may need to go the Views PHP route. Although, if it's a case of doing the sort of thing that Views does with Rewrites, you may be able to do some or all of by using Display Suite code fields or block fields.

This approach, of course, also allows you to use the images for taxonomy terms (single or multiple) in your default view mode as well. If you're new to Display Suite, this might be a fairly tricky configuration task - but once you're used to DS it's a pretty quick job.


How to remove status messages from admin theme?

hook_page_attachments is not the correct hook. You want to implement hook_preprocess_HOOK, like the example below.

There are some caveats with this fix, especially if your site will be localized to other languages, see the comments within the code:

/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_status_messages().
 *
 * @param $variables
 */
function mymodule_preprocess_status_messages(&$variables) {
  if (isset($variables['message_list']['status'])) {
    $status_messages = $variables['message_list']['status'];
    $dummy_message_parameter_1 = '_parameter_1_';
    $dummy_message_parameters =       [
      '%dimensions' => $dummy_message_parameter_1,
      '%new_width' => 0,
      '%new_height' => 0,
    ];
    // The message could change eventually, but it is unlikely.
    // This logic *could brake* in a some language translations, if the %dimensions string is not the first parameter.
    $file_resize_message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.', $dummy_message_parameters);
    // $file_resize_message_start is the part of the message that won't vary.
    $file_resize_message_start =strtok((string)$file_resize_message, $dummy_message_parameter_1); ;
    foreach ($status_messages as $delta => $message) {
      if (strpos((string)$message, $file_resize_message_start) !== FALSE) {
        // The next commented line still leaves a green area
        // unset($variables['message_list']['status'][$delta]);
        // Removing all messages, the side effect is that you could be
        // missing on some relevant messages
        unset($variables['message_list']['status']);
      }
    }
  }
}

The message is set in the function file_validate_image_resolution at core/modules/file/file.module:447 (as of version 8.6.0-dev)

There is a good explanation about the hook implementation at Stack Overflow


create category and subcategory menu on the left sidebar

Views Tree would be worth trying.
Toggling of leaf terms can be handled by javascript.
To show content, you can declare ajaxified menu callbacks, which simply takes tid as argument and replace a certain section of DOM with the server reponse.


How can menu tabs be relocated to another region?

"I cannot identify a block that contains them." There is not a block that contains these. In Drupal 7, these tabs are a variable called $tabs found in /modules/system/page.tpl.php.

You could suppress these tabs by overriding page.tpl.php in your theme.

To put them in another region, you could:

Implement hook_preprocess_page(&$variables, $hook) in your theme's template.php or in a custom module.
Copy the contents of the $variables['tabs'] array key into another region.


Is there any preprocess hook for date api?

Date API introduces several theme functions:

theme_date_combo
theme_date_display_combination
theme_date_display_interval
theme_date_display_range
theme_date_display_single
theme_date_text_parts

All of which can be preprocessed.

If the output you need to override isn't the result of one of those functions, you'll need to look for a different solution (e.g. depending on context you might be able to preprocess a field template).


Create images defined by image styles on node save

I ended up creating a separate content type and a theme template file that solved this specific problem I had. I will update this if I ever find a way to do this in a module or other.

EDIT:

I ended up creating a module that solves this.

in hook_menu:

function mymodule_menu () {
  $items['node/%/generateimages'] = array (
    'title' => 'Generate images',
    'page callback' => 'mymodule_generate_images',
    'page arguments' => array(0, 1),
    'access callback' => TRUE,
  );
}

In the callback function:

function mymodule_generate_images ($arg1, $arg2) {
  $retval = '';
  $path   = drupal_lookup_path ("source", $arg1 . '/' . $arg2);
  $node   = menu_get_object ("node", 1, $path);

  drupal_set_title ('Generate images ' . $node->title);

  global $language;
  $lang = $language->language;
  $files = field_get_items ('node', $node, 'field_image');

  foreach ($files as $key => $media) :
    $url   = image_style_url ('related_thumbnail', $media['uri']);
    $thumb = theme ('image_style', array('style_name' => 'related_thumbnail', 'path' => $media['uri']));
    $retval .= $thumb;
  endforeach;

  return $retval;
}

After node creation, I manually have to go to thenodeurl/generateimages and images defined in the callback function is created.

I wish someone could tell me a better way to solve this :)


Missing Image module from the list suggest that it disappeared somehow from the system table which have the list of all modules.

To confirm that, double check that directly using the query, e.g.:

drush sqlq "SELECT * FROM system WHERE name='image'"

It's difficult to answer what causing that without actually debugging it. It depends what kind of modules you've installed, custom code and the environment it-self (e.g. caching).

To track the problem, you can try:

temporary disable external caches (memcached/redis),
temporary disable PHP caches (OPCache/APC/XCache/eAccelerator) or its settings which could interfere with Drupal internals,
disable any automated QA testing (such as Simpletests or Selenium) for affected environment,
disable useless non-stable modules,
temporary disable further modules which you can,
check if this is specific to environment (dev, stage, live),
if happens on all, could be some bug in the code, so follow the section below.

Debugging

This could be a tricky part to find out, so you probably need some tricky tools to debug it.

Here are my ideas:

watch the module lists and check when it's missing:

watch 'drush pml | grep -w image || echo Missing'

for example by sending your-self e-mail with the recent logs:

watch 'drush pml | grep -w image || { drush watchdog-show | mail -s missing-image drupal@niepodam.pl && killall watch; } '

run debuggers attached to MySQL which monitor everything to do withsystem table or image entry (note: it could be overwhelming for the system):

sudo strace -e recvfrom -s999 -fp $(pgrep mysqld) | grep -w image >> sql.log

run debuggers attached to PHP:

sudo strace -e sendto -s999 -fp $(pgrep -fn php) 2>&1 | egrep "system|image" >> php.log

Or simply enable log queries in MySQL configuration file.

Above is more useful if you've Devel installed, so there is an option to prepend a function name before the query (so you know exactly which function caused it).
install XDebug and enable tracing for the part which you suspect the most by adding xdebug_start_trace(); and xdebug_stop_trace(); in appropriate places (see sample ini config), suggested places would be:

system_list()
system_list_reset()

then analyse the trace files.


Webform show result table on webform node tpl

Try the Webform Report module, it looks perfect for what you need.

Or, Why not use views?

It would be easier to use webform 7.x-4.0-rc3 and create a view table for webform submission data. You can easily grab the separate values and arrange them into a table.

You also have the ability to create a reference so only the results from node 4 are being shown.

EDIT:
use $node->nid; , so...

$nid = $node->nid;

module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> $nid));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '
';print_r($row);print '
';
        print '
';print_r($data);print '
';
    }
}


"Check boxes/radio buttons" Widget is NOT displaying content in Drupal7

Never mind. I had a typo in the $content[] array element.
The one I set in the admin is slightly different than the one I declared in the template.
(small typo). Amazing!

My code above also works fine with check-boxes.


How do import and save term lineage using feeds and Hierarchical select?

I did some more research and testing decided to use the Term Set Lineage module so that it is set on import, then just changed to use the Hierarchical select module.


Installing module or modifying .tpl files are not required to get a simple search page.

Creating a view and using Exposed Filters setting will get the job done.

Providing you high level steps below, you may need to research a bit more to accomplish this task.

Steps

Create a View.
Choose "Table" in Format section.
Add "Certificate Name ,Certificate Number,Certificate,Issuing Date,Date of Expiry" in field section.
In filter criteria, select your content type.
Also add "Company name, Certificate number" in the Filter Criteria.
Click Advanced > Better Exposed Forms > Better Exposed Filters.

Expose the fields "Company name & Certification number" as text fields.
You can expose this fields as a Drupal Block and assign it anywhere in the page.


How can I (programmatically) display a custom block with user profile links in dropdown?

If you don't have any issue rendering a block of menu, you can just show up a menu there which I suppose you've got that covered. for the UID part there are couple of workarounds for this:

Using Views
Menu Token
Me (Drupal 7) only
Templating: Much easier approach

The Views way

Number 1, using views is a long story, I'll keep it short and I move on to number 2, my own approach. With views you can use contextual filters and build your own custom links using "Current logged in user" filter, you can randomly get a view from whatever and override it with the HTML structure of your need. in case you need a more in depth answer for this, let me know and I will update my answer

Menu Token

This module is exactly what we need, but we have to consider some bugs that it currently has, if you check the issue queue there are some major issues with it, but still, you can manage to get it working with a little bit of dirty hacking, using jQuery/JavaScript

The issue with this module is that you cannot use the token in middle of a string for instance: /user/{uid}/my-contents wouldn't work but simply /{uid} works just fine.

So in our case, we override the href attribute and hardcode the path we want to it as prefix and suffix, using the UID

This is not the best practice at all, but in case anyone wants a quick solution, this is what I suggest, in case you need help with the jQuery part, let me know and I will update the answer.

ME module - Drupal 7 only

for those who have this issue in Drupal 7, this module considers /me as the user ID if configured properly, so a link in question would become something like this: /user/me/my-contents

Templating

So let's say we edit our page.html.twig file so we can create our custom structure for our menu, then in our case, we can simply refer to the current user's UID like so:

Test menu item


Generate reports of similar web forms results

If Views can't do what you're trying to do, you might want to consider the Forena module (disclosure: I'm a co-maintainer) as a possible alternative.

As an example, create a custom "data block" (which is just an SQL statement) that fits your needs, to retrieve the webform data that you're interested in. Here is a (basic) example:

SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

Then create a Forena "report" that uses this data block (maybe you want to enable something like the "CSV" option, within "document types"). Here is the (basic) layout of such report to illustrate the idea:

          node
          submission
          component
          fieldvalue

          {node}
          {submission}
          {component}
          {fieldvalue}

After you saved the report specifications and then browse the generated report, you could have a "CSV"-hyperlink (upper right of the report). Just use that link and ... voilà, there is your CSV file (in this case with 4 columns, since that is what in my (basic) report I asked for).

If this makes sense, head of to the Community documentation of Forena to get you going (which includes pointers to video tutorials). Or use the documentation that comes with Forena.

Of course, building the appropriate SQL statement to perfectly fit your needs is going to be crucial. But apart from that, it's just basic usage of Forena.

Update

To "create a temporary table" (as in your comment below this answer, and also per your updated question), you may want to have a look at what's suggested (by David Metzler) in this feature request. Though I personally have no experience with using Forena to create such temporary tables.

Reminder: Forena is to query data (as in your first version of your question), not to update, delete, etc such data.


Get role label instead of "database value"

You can try like below:

function MYMODULE_field_template_preprocess_default_variables_alter(&$variables) {
  $variables['user_roles'] = user_role_names();
}

and in .twig file you can use as {{user_roles['ROLE_NAME']}}


Drupal 8 ajax form load error, context.querySelectorAll is not a function

The first argument to Drupal.attachBehaviors is an object representing a DOM element, context. You're currently providing it with a string.

In your case the correct code will probably be something like:

Drupal.attachBehaviors($('#comment-form-wrapper').get(0));

You don't pass data to behaviours through the attachBehaviors method, instead stash it somewhere in a global scope and pick it up later.

For example you might choose the window, drupalSettings, or some other object, depending on your general requirements and any other required uses of that HTML data.


Just make sure that the OPCache is selected as caching mechanism in MAMP preferences.

Click on "Preferences".
Click on the "PHP" tab.
Select "OPcache" under "Cache" field.


Create drupal content programmatically with custom entity ( assets )

I think you can try to use core and EntityAPI methods for this task like this:

$asset = entity_get_controller('asset');
$asset->type = 'MY_TYPE';
$asset->... = '...';
....

$asset->save();


I don't have the exact answer to your question but I can give you some advices to how you can do.

First option, UI way, You can try the "Rules" Module with "Webform Rules" Module.
It gives you the ability to do some operations on given context.
I don't know that module, but it seems to be the easiest solution.

Second option, Dev way, you can manually hook your webform and add php code.
You have to implement the "hook_form_FORM_ID_alter" hook
You can retrieve webform form_id by following this answer of this post.
In your hook implementation, add your custom submit function like the following snippet :

function YOUR_MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    if(isset($form['#submit'])){
        $form['#submit'][] = 'your_custom_function';
    }
    else{
        $form['#submit'] = array('your_custom_function');
    }
}

Some usefull links :

Drupal : Form API
Drupal : hook_form_FORM_ID_alter
Module : Webform Rules
Module : Rules


Drupal already has a login block, which displays the login form, which by default only is displayed for anynomous users. So all you really need to do is add a block with the User menu (all menus has a block with the items) next to the login block and have it show for only authenticated users.

This is one of the things where configuration will get you all the way.


Improving Site Speed and Cache for Authenticated Users

I created a presentation that covers some of the basics of of performance https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id. In your case I would make sure poormans cron in core is disabled, use an IP for your database connection (very important on IIS), make sure you have some sort of op code caching enabled, and follow this guide (linked in the presentation under Basic database tuning) to fix database issues at the drupal level, and be sure to adjust some MySQL defaults as well.


How can I change a form input to not be required?

The third argument to hook_form_alter is $form_id - which will hold the id of the form, not an attribute. You need to know the form id of what you are trying to alter, which is not the literal id of a form input field.

Once you identify what form is showing this field, you can do:

function alt_not_required_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id_foo') {
    $form['input_to_affect']['#required'] = FALSE;
  }
}

Also, once you know what the form ID is, you can use hook_form_FORM_ID_alter and eliminate that if statement.

Plus, in your example, since we are altering existing form elements, you do not need to declare it as an array. You just access its properties. $form['postal'] = array(...) would take any existing form item named 'postal' and obliterate it, which will likely cause errors in validation or submission.

It might be helpful in learning to use xdebug or devel to dump arguments and variables so you can see what they are. Otherwise, it will be difficult for you to step through this.


"Experimental modules found: Place blocks" but I am using core 8.6

The module is present since Drupal 8.2, but since Drupal 8.4 it has been marked hidden. That explains why you get the error, but you don't find the module: The module was enabled before updating to Drupal 8.4 or later, and it is still installed; once Drupal was updated to any version after 8.4, the module has been just marked as hidden (without changing its status of installed module).

If you look at the content of the block_place.info.yml file (core/modules/block_place/block_place.info.yaml), you will notice the following lines.

package: Core (Experimental)
version: VERSION
core: 8.x
hidden: true

If you remove the hidden: true line, and visit admin/modules to install a module that you then uninstall, you will see that module listed in /admin/modules/uninstall, and you will be able to uninstall it.
Installing and uninstalling a module is done just to force Drupal to clear the cache it uses to keep the list of found modules. In this case, Drupal will notice the module is not marked anymore as hidden, and it will show it again.


Massive spam users and spam entries despite triple layer protection

I recommend you try something different from the usual enter text Captchas.

  I personally use Are You A Human module. This is a video tutorial on how to set it up: Drupal 7 Are You a Human PlayThru
  Module - Daily Dose of Drupal episode 78.

If you want another option, I suggest you try Draggable Captcha here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam

A new one that came to my attention is reCAPTCHA. Uses the Google reCAPTCHA web service to improve the CAPTCHA system and protect email addresses.


I would have rather used a block and put it in a region, so to show up on all pages. This would keep my tpl fiels clean and also will allow me show/hide block on some pages.


There were 2 major changes on the code above

I changed the form name to listing_adform()
I changed the hook_menu to call my form not theme

  $items['ad-listing'] = array(
    //'page callback' => 'adlist_template',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('listing_adform'),
  );

Flushed the cache, and I saw my fields rendering using my template in form/adlisting.tpl.php


View author field (image) in a node view

You may do that using a Views Block and place it in the Main Content block region, right after the content block. Also, you'll need to create a relationship between the node and it's author, so only the correct user will be displayed. Below is a screenshot of a work I've done using Views for Drupal 7.42 that I think is close to what you're looking for:

1 - Create a new Block View to view Users (not Content)

2 - Filter Criteria should say User: Active (Yes)

3 - There is a default sort Criteria item. Remove it since it doesn't matter.

4 - Add a Relationship: Choose "User: Content authored"

5 - Add a Contextual Filter: Chose "Content: Nid"

6 - In the configuration options for the newly added Content: Nid, choose these options:
WHEN THE FILTER VALUE IS NOT AVAILABLE:
Provide default value
In the Select box, choose Content ID From URL.

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
Specify validation criteria
Validator select box: Content
Content Types: choose the content types you want the view to work with.
Filter Value Format: Node ID
Action to take if the filter value does not validate: Hide View

7 - Save the View.

8 - Go to Structure -> Blocks and configure the block to show on the types of content you want it to show on and position it wherever you want it to appear.

9 - Done.


Switch to Drupal Mobile Theme Programatically

The best option out there is to use module themekey that has all the tweaks to detect the user browser and serve the right theme. The performance hit is un-noticeable and it has already done all the hard work for you already.

Check a nice tutorial here: http://mustardseedmedia.com/podcast/episode52


Unpublished taxonomy term keep showing in main menu and contextual filter

It is my understanding the Drupal’s multilingual will fall back to the default language, meaning that if a translation is not available, the asset will be shown or rendered in the default language. I don’t think there is a workaround for that.


How can you find out in which module your code runs?

As Clive mentioned, a constant is your best bet. When I start up a new project, typically one of the first things I do is create an interface that contains constants that are applicable to the entire project. Usually the very first constant is for the module's machine name. I then use these constants, and not strings, throughout the project.

Here's a simplified and obfuscated version from one of my projects: (this file would be located in the folder my_module/src/MyModuleInterface.php)

<?php

namespace Drupal\my_module;

interface MyModuleInterface {

  const MODULE_NAME = 'my_module';
  const SERVICE = 'my_module.foobarbaz';
  const TAX_VOCAB_FOO = 'foo';
  const TAX_VOCAB_BAR = 'bar';
  const TAX_VOCAB_BAZ = 'baz';

  const PERM_ADMIN_FOO = 'administer foo';

  /**
   * Returns TRUE if the specified module is enabled.
   *
   * @param string $module_name
   *  The machine name of the module to check as enabled. Defaults to this
   *  module's machine name.
   *
   * @return boolean
   *  TRUE if the specified module is enabled.
   */
  function isModuleEnabled($module_name = self::MODULE_NAME);
}

The benefits to this approach are:

Consistency through your project as well as for any other projects
that might want to call on your module; they can also utilize the
constant.
Reduction of errors due to typos.
If you use an IDE such as PHPStorm, you can take advantage of auto-completion, which is convenient and speeds code writing.


Completing commerce order triggering other modules rules checkout complete

Updating to checkout_complete status, make the code works. Thanks.

+     $order = commerce_order_status_update($order, 'checkout_complete');
      commerce_order_save($order);
      commerce_checkout_complete($order->order_id);


$_FILES superglobal array key is not what file.inc expects

I don't think it's a bug.

$_FILES['files'] is hard-coded into file_save_upload().

I believe you need to change how you construct your #name property.  The usage example in the Form API does it like this:

'#name' => 'files[' . implode('_', $element['#parents']) . ']',


For anyone wondering about this, here's how to do it (code goes in your theme's template.php file):

function YOUR_THEME_preprocess_user_profile(&$variables) {
  $variables['YOUR_NODE_REGION'] = block_get_blocks_by_region('YOUR_NODE_REGION');
}

And then in your user-profile.tpl.php template:

<?php if ($YOUR_NODE_REGION): ?>
  <div class="custom-region">
    <?php print render($YOUR_NODE_REGION); ?>
  </div>
<?php endif; ?>


What replacement token to use for counting a specific content-type

I ended up creating a custom module for this to calculate the specific amount of items. Now I can use a token like [partner:partners].

/**
 * Implements hook_token_info().
 */
function partner_token_token_info() {
  $types['partner'] = array(
    'name' => t("Partner Tokens"),
    'description' => t("Tokens for partners."),
  );

  $partner['partners'] = array(
    'name' => t("Partners"),
    'description' => t("The count of partners."),
  );

  return array(
    'types' => $types,
    'tokens' => array(
      'partner' => $partner,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function partner_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'partner') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'partners':

          $query = db_select('node', 'n')
            ->condition('type', 'partner');
          $num_rows = $query->countQuery()->execute()->fetchField();

          $replacements[$original] = $num_rows;
          break;
      }
    }
  }

  return $replacements;
}


Changing Twig template of form items through the theme

You can use drupal_static() together with the following two hooks in your module or your theme to add template suggestions for input elements based on the block ID where the input element is used in (same would work with fieldsets or any other form/render element):

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_block(&$variables) {

  $bid = &drupal_static('block_id', TRUE);
  $bid = $variables['elements']['#id'];
}

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

  $bid = &drupal_static('block_id', FALSE);

  if ($bid) {
    $suggestions[] = 'input__block__' . $bid;
    $suggestions[] = $variables['theme_hook_original'] . '__block__' . $bid;
  };
}

For example the search form textfield:

<!-- FILE NAME SUGGESTIONS:
   * input--search.html.twig
   * input--search--block--neato-search.html.twig
   * input--block--neato-search.html.twig
   x input.html.twig
-->

For example the password textfield:

<!-- FILE NAME SUGGESTIONS:
   * input--password.html.twig
   * input--password--block--userlogin.html.twig
   * input--block--userlogin.html.twig
   x input.html.twig
-->


site-install error: /var/www/drupal7 does not contain a valid installation

The Documentation shows the steps you should do are:

Start with empty directory and prepared empty database (or user with permission to create database)
drush dl drupal --drupal-project-rename=example
cd example
drush site-install standard --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' --site-name=Example

You should not manually create, copy, move config files before executing drush site-install. And you should not use aliases like @drupal7 unless they are defined. In case of installation, I always set up site first, and aliass for it later, and it worked all right.


How to display nodes of specific terms and expose only those terms to the user (out of many other terms)

An exposed filter has no effect by default, so your simplest solution is to add another filter that is not exposed that limits the view to just the countries you want.

It's a useful trick with views to combine exposed and not-exposed filters and sorts.


You don't want different regions for every node.

Regions should be as generic and re-usable as possible.

However you don't have to include all regions in all templates.

Your page--front.html.twigcould have a different set of regions to page.html.twig

Maybe checkout the Drupal 8 theming guide.


Character escaping rules for $form_state['redirect']

The rule for query strings is pretty simple; you need a key, and a value. The format for this key/value pair is:

key=value

Both the key and the value will be URL encoded, so any special characters are escaped.

Take the = sign for example. Your sample code above uses:

circle_op=<&a%5Bvalue%5D=28&a%5Bl%50

as a key, and a value from the variable $location as a value. So without being escaped, your query string looks like this:

?circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D=VALUE_OF_LOCATION_VAR

Obviously if a browser was to encounter that URL it wouldn't know what to do; there are two equal signs, so it doesn't know what is supposed to be the key, and what is supposed to be the value. It can make a guess but that's not the point.

The URL that you are redirecting to is absolutely the correct one for the input you've given for your redirect URL.


Getting Error : "You must declare "ids" as a unique array of fields in your source settings." while trying to migrate for paragraph in Drupal 8

As the error message suggests, ids needs to be an array, e.g.

source:
  plugin: csv
  path: '/var/www/html/drupal/author.csv'
  header_row_count: 1
  ids:
    id:
      type: integer

Do note that you're in a YML file here; it looks like you might have tried to use PHP array syntax.


Non-admin user gets empty results when viewing other user data with views

Try the following,

There is an option in views to not take into account permissions when running the query (dunno if it is on the query level or display level though)

Edit your View at: Advanced/Query settings/, On Query settings page, check "Disable Query Rewritting"

Views UI: Advanced,

Query settings page,


Trying to create a static page for my module using page callback in hook_menu

$output = 'this is some output, etc…….’;

If you see in the above line, you are using wrong sign, which I have  highlighted after ...... That is wrong. It should be '

Above isuue is for sure!!!!

Other just my suggestion, As I am also learning Hooks, may be TOTALLY WRONG but for your attention.

I have changed code as below and after that, I have written my point..

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['admin/config/media/tsoundcloud/config/soundcloud_static'] = array(
    'title' => 'Semi Static Page',
    'description' => 'Temp page to show data',
    'page callback' => 'mymodule_semistaticpage',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );
    return $items;
 }

/**
 * Page callback
 */
function mymodule_semistaticpage(){
  $output = 'this is some output, etc…….';
  return $output;
}

The following points are for code which you have posted in main-question, and I have corrected those in above code,

See function name, it should start with module name.
The _page(), may creating confusion as some hook has _page() part..so I did change function name to mymodule_semistaticpage()
where is return $items;?
I think title do not need, t()?


Injecting additional content from multiple sources into a block using twig

I went with a hook instead. There must not be a way to do this in twig.

This section resides in a controller in the parent module:

$plugin_items = [];
// Call modules that implement the hook, and let them add items.
\Drupal::moduleHandler()->alter('flot_examples_toc', $plugin_items);
if (count($plugin_items > 0)) {
  $output['plugins'] = [
    '#title' => 'Plugins',
    '#theme' => 'item_list',
    '#items' => $plugin_items,
  ];
}

And this resides in the child [module].module file.

<?php
use Drupal\Core\Url;
function flot_spider_examples_flot_examples_toc_alter(&$item_list) {
 $options = [
      ':one' => Url::fromRoute('flot_spider_examples.example')->toString(),
    ];
 $item_list[] = t('Spider Chart (with spider plugin)', $options);

}

The parent creates an array and passes it to the children by reference. They can alter the array by adding elements to it. The parent then adds it to the render array.


Cannot configure settings for menu breadcrumbs

You should be able to find it at /admin/config/user-interface/menu-breadcrumb.

If nothing appears then clear your menu caches and try again, but it's definitely there in the code.

If that doesn't fix it, then this is a problem for the issue queue I'm afraid.


How long does it take for Drupal to unblock user after 5 failed attempts?

To answer your question:

  The amount of failed logins is recorded in the table 'flood'. You can
  either wait before trying to login again (6 hours) or clean the
  flood table with the procedure below.

Options for not having to wait:

  Execute the following query on the Drupal database:

  DELETE FROM 'flood'; If command above doesn't work try this:

  TRUNCATE flood RESTART IDENTITY; To execute this query it will be
  necessary to login to the database. This is typically done through the
  command line or through a GUI interface such as phpMyAdmin. If Drush
  is installed on your server, the drush sql-cli command provides quick
  access to an SQL command-line interface.

  From the command line, with Drush installed:

  drush php-eval 'db_query("DELETE FROM `flood`");' NOTE: The query
  above will delete ALL entries in the flood table. If you want to
  remove only a specific user's entries from the flood table, the
  following is more specific.

  DELETE FROM flood WHERE event = 'failed_login_attempt_user' AND
  identifier LIKE '1234-%'; (where 1234 is the UID of the blocked user)

Source: Login blocked after 5 failed login attempts

Want to change the settings for this? You can by installing Flood control


How bad is it to use Node_load in a loop in drupal 7?

You should never need to use node_load() in a loop, that's what node_load_multiple() is for:

$nids = array(1, 2, 3, 4, 5);
foreach (node_load_multiple($nids) as $node) {
  ...
}

It's hard to imagine a scenario where loading the nodes individually would be necessary or desirable.


I ended up solving this by running the field through the render filter first, then my custom filter. The text format filters are applied at the render stage, so now the custom filter runs after them. The finished order is:

{{ field | render | custom_filter }}


Updating a field value in database via submit handler doesn't update the user profile in UI

I think that's the caching. First try to clear the cache manually. If that helps you should use cache_clear_all() to clear the corresponding cache tables (e.g. cache_content, cache_views_data) after you update the db.


Use views to produce list of terms with descriptions

A easy workaround could be to attach a regular text-field to the terms, instead of using the hardcoded description.

Update: After taking a quick peek in the code, it does look like filtering on descriptions are not supported. This could just be a simple oversight.
There's an issue here, which claims this functionality has been added. I can't seem to find it, so I attached a new patch and reopened the issue.

Update 2: Dereine has commited my patch to D7. You should now be able to filter on term descriptions with the dev version.


Localhost Drupal Install on Linux shows file and not site

Just to get the question answered:

You missed the step about setting up Apache and PHP in the installation guide you read. In particular, you have to follow the How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 16.04 guide from DigitalOcean - linked to in the installation guide.


Solr Indexing Error showing "EntityMalformedException: Missing bundle property on entity of type taxonomy_term"

Drupal tries to index an invalid item and throws this error.
To find out what document is causing the error, you can implement the hook_apachesolr_index_document_build hook with a watchdog statement inside.

This is from apachesolr.api.php

/**
 * Build the documents before sending them to Solr.
 * The function is the follow-up for apachesolr_update_index
 *
 * @param integer $document_id
 * @param array $entity
 * @param string $entity_type
 */
function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

My guess is that the last item in your dblog will be the offending item.


How to manage reservations with Drupal for something that is not something like a room?

For Drupal 6 there is a stable release of Simple Reservation module.

  This module provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

For Drupal 7 you can try Reservations API.

  The core focus in on the Reservations API that enables any Content Type to be reservable based on a variety of default settings. A Reservation -> Confirmation -> Checkout -> Checkin workflows is included, but it is created entirely using Views. Additional modules can enforce custom validation, add pricing, or add additional availability to the basic hours of operation.


Variable to check if the page is of some other Content Type

Place this in your theme's template.php, replacing 'THEMENAME' with the name of your theme:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['some_html'] = '';
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['some_html'] = '
Hello world!
';
  }
}

And use this in your page.tpl.php:

<?php print $some_html; ?>

Alternatively, if you want to keep the HTML string in your template file, I would do this in template.php:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['print_extra_header'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['print_extra_header'] = true;
  }
}

And use this in page.tpl.php:

<?php if ($print_extra_header) : ?>
THIS GETS PRINTED
 <?php endif; ?>

Make sure to clear the cache after creating the THEMENAME_preprocess_page function, otherwise Drupal will not know it's there and it will not run.


How can I get data from ResultRow object in views template

There are two question. First how to get the title in the kint dump?

{{ row._entity.title.value }} should work, also {{ row._entity.gettitle }} or {{ row._entity.label }}, because getTitle() and label() are methods of the node object.

Second, could anyone please help me how could I iterate through row data in views twig template?

In Views two steps are needed, first get the field and then use the method getValue() on the field providing the result row as parameter:

{{ view.field.field_name.value(view.result[0]) }}


You can do this with some alter hooks in your themes template file.

/**
 * Implements hook_css_alter().
 */
function YOURTHEME_css_alter(&$css) {
  // Remove stylesheets not required
  unset($css['sites/default/themes/YOURTHEME/css/STYLESHEET.css']);
}

/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Remove scripts not required
  unset($js['sites/default/themes/YOURTHEME/js/SCRIPT.js']);
}


Google keeps indexing /comment/reply URL

I would try adding

RewriteCond %{HTTP_USER_AGENT} ^Googlebot
RewriteRule ^comment/reply/$ - [G,L]
RewriteRule ^comment/reply/(.*) - [G,L]

to .htaccess or Apache config to inform spiders that the links should be removed.  Just make sure to put it before the catch-all rule at the bottom of the standard Drupal .htaccess.  The problem is coming up with a list of spiders to add as [OR] conditions to the RewriteCond so that they get a 410 but Drupal handles normal requests.

Google Webmaster Tools has a URL removal tool, too, but I have never tried using it with patterns before.


How to get e-mail from Drupal.org about new Drupal releases?

Go to https://www.drupal.org/user , click on the "Edit" tab and from there, the "My newsletters" tab. This will allow you to subscribe to "Drupal newsletter" and "Security announcements".

Also to get notifications of Drupal core or module updates for a particular Drupal site that you run, go to Reports -> Available updates -> settings (/admin/reports/updates/settings) and enter your email address and the desired frequency (daily / weekly) and type (security / all) of updates.


How to write SoapClient request which has basic auth in it?

I believe the answer is nearly there for you, but ID and credential are the wrong keys in the options array.

       'login' => 'USERNAME',
       'password' => 'Password',

I suggest that you put the username and password into conf in your settings.php file so they are not in your codebase nor your site configuration data. See How secure are variable_get and variable_set? for details on how to securely have credentials in Drupal's config system.


Unable to index field in Search API settings in a commerce site

If you go to admin/config/search/search_api, then I guess you could see a server of type "Index".
Click on the Edit link against that and go to the "fields" tab(admin/config/search/search_api/index/product_display/fields).
Enable the checkbox against your new field and save.
You will have to index the whole content, which you can do by click the view tab and clicking the "Index Now" button.
I guess this would do.


drush config:import "There are no changes to import." for "content" view

The problem's source was the configuration file that configured the database as cache on CLI, while using redis when served via http.
This caused all kind of confusion, since clearing the cache in the browser did not do that for CLI :/


Programmatically execute an action set (Rules module)

If you have set it up as a rules component, you can use rules_invoke_component, alternative you can invoke an event, which could trigger mutiple rules by using rules_invoke_event.

Both is similar in that you pass first a name/id and the rest of the args is passed along, so something like

 rules_invoke_component('name', $node);

if your custom component rule has several parameters pass them one by one and separate them with comma as example

rules_invoke_component('rules_save_search_send_activation_sms',  'paramval1', 'paramval2', ....);

is properly how you need to do it. This again depends on how the rule/component is defined and configured.


Tokens are contextual based on where they are used, so it's not possible to reference arbitrary content. If you can add fields to the newsletter, the ideal way to resolve this would be to add a node reference field, then create your tokens by doing something like [newsletter:field_node[0]:entity].


Removing/Restricting for wrapper by role

If it's Role based, why not remove the permission for that Role to View or Post Comments under admin/people/permissions?

If you need more granular control, try the Comment Permissions Module (https://drupal.org/project/comment_perm)


if you overrided correctly element will contain all items in form--user-login.html.twig,

    <form{{ attributes }}>

hello world

            {{ element.messages }}
            {{ element.name }} {# username element #}
            {{ element.pass }} {# password element #}

                <input id="show_password" class="show_password" type="checkbox" />
                Show password
                Forgot Password?

            {{ element.form_build_id }} {# required #}
            {{ element.form_id }} {# required #}

                {{ element.actions.submit }}

    </form>

if the template is not valid, you should try to add it.
function Yourtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

then create form--user-login-form.html.twig in your theme.
do not forget to clear the cache.


How to list subpages on separate menu per page

Have a look at the Menu Block Split module.

  With this module you can split any menu block into two different blocks: a first block with the first level menu entries only and a second block with any second level and sub level menu entries. You can have as many splitted blocks as you need.

There is a Drupal 7 development version, just posted this evening.


How can I use postsave method extending WebformHandlerBase for submitting to account fields

$account = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($account->id());
    $data = $webform_submission->getData();
    $photo = $data['picture'];
    $user->set('field_photo', $photo);
    $user->save();
  }
The above code, for example, will take a webform element, key is 'picture' and set it to an account field, 'field_photo'.


Domain Access Login Redirect for main domain and subdomain

I solved this issue by creating two different roles and by adding a condition for "User has roles". So admin for one.example.com and sub-admin for two.example.com and three.example.com. Currently it works greats according to the condition. But is there any way to set the rules for same role with different actions?


I think  you are looking for this module Masquerade.

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

There is a module called Role Toggle to handle role toggle.

  This module gives you a page and a block to toggle (switch on and off) any role.


Why does the same Rule Calculating The Sell Price Of A Product fire multiple times?

This is because the price is calculated during preparation for display where the field is rendered on the page, for the Add to Cart form to determine product availability, and for recalculation of any instance of that product in your cart. I believe we tried caching calculated prices in the product entity at one point in time to avoid duplicate calculation, but that obviously didn't stick. I don't have a solid recommendation here, just wanted to provide the info requested. Also, note that cart price refreshing is adjustable but is intended to happen in realtime with the full cart context. I'd think you could safely find a way to eliminate the duplicate calculation between the price field and cart form, but you'd want to do it without interfering with the cart refresh.


Need to find and disable an email that may be coming from a module

If you have the Rules module enabled, go and check the rules

/admin/config/workflow/rules

It's very likely that there is a rule that is sending the emails. So just disable it.


Change the pager and the number of elements per page of a specific view

The following should work in hook_views_pre_build(&$view):

$view->set_items_per_page(5);


Content block doesn't show when query is added to the URL

I managed to fix this issue. I'm very new to Drupal and I'm administrating a site that someone else built. The problem was in template.php in a function called 'views_views_pre_execute'. Some code was checking for drupal path alias and some custom queries was built. I changed: '$path = substr(drupal_get_path_alias(request_uri()),1);' into 'drupal_get_path_alias($_GET['q']);' and now it works.


I recommend trying the Views Aggregator Plus module. It supports many useful aggregation functions. As an exmaple creating the following output:

Industry    Companies             Turnover
Food (2)    Heiny, McRonalds      $566,000,000
Clothing (1)Cenneton              $99,000,000
IT (2)      AcquiB, PreviousBest  $30,000,000
Totals              5             $695,000,000

From this source table:

Industry    Company Name    Turnover
IT          AquiB           $25,000,000
Clothing    Cenneton        $99,000,000
Food        Heiny           $66,000,000
IT          PreviousBest    $5,000,000
Food        McRonalds       $500,000,000

  With the grouping taking place on, say Industry, and aggregation
  functions TALLY, ENUMERATE and SUM applied on Industry, Company Name
  and Turnover respectively, the final result with a descending sort on
  the last column will display like below. Note that the module
  identified three groups. It also added a totals row, Views Calc style.


Is the MODULE.schema.yml required when you define the MODULE.settings.yml?

It is not absolutely required but strongly recommended to have one.

By default, Drupal doesn't validate the schema, but it does in tests and there is an issue that will enable it if you use the provided example.settings.local.php/development.services.yml. That's why you don't see an error right now when you install, but you'll see it when you write your first test.

It is currently used to ensure the saved configuration has the right data type (e.g. a float and not an integer); not doing that correctly can break stuff and the ability of translating the configuration. More things might follow later, for example a module that generates a settings form.


I guess you can put near the file your_module.module. Also your can put it into a nested folder. Keep attention: webform-form.tpl.php and that template engine is invoked at the last moment. It overloads all module templates.


Why is my content showing up below other blocks?

Try hiding the row weights and dragging the items around. Change them any way you want - then save configuration then go back in and change them to the way you want them to be and save again. Dont forget to clear your caches.


Adding a bulk discount to ubercart without adding a new module

After digging through various hooks and trying different things, this is what ended up working for me, which was actually pretty simple in the end.:

function hook_cart_item($op, &$item) {
    if ($op == 'load') {
        if ($item->nid == xxx && $item->model == 'xxxxxxxxxx') {
            if ($item->qty >= 100) {
                $item->price = round($item->price * .65,2);
            } else if ($item->qty >= 25) {
                $item->price = round($item->price * .75,2);
            }
        }
    }
}


This used to be handled by an external module called Commerce Checkout Admin 7.x-2.11 but since Commerce Kickstart 7.x-2.16 this apparently came as part of core. As a result, Commerce Checkout Admin 7.x-2.12 now does not include this feature.

Since updating my site the 'Add an Order' no longer seems to calculate tax, so I am looking for this solution as well. Using:

Drupal 7.30
Commerce Kickstart 7.x-2.16