# Question
Title: form_alter and #element_validate inside .module file
Inside my `.module` file, I have created a hook for alter `register_form` and add a *password* field with a custom field-validation:

```
function xenforo_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['password'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#required' => true,
    '#element_validate' => array('check_password'),
    );
}
function check_password($element, &$form_state) {
  if ($element['#value'] != 'test') {
    form_error($element, t('Error: TEST'));
  }
}

```

I use #element\_validate, and when I submit my form with a bad value `$element['#value'] != 'test'`, I don't have an error and the registration is completed, why `#element_validate` don't work here please ?

Thanks.

**EDIT:**

I have find a solution:

```
  function xenforo_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form['password'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#required' => true,
      '#attributes' => array('autocomplete' => 'off'),
      //'#element_validate' => array('check_password'),
      '#process' => array('processPasswordConfirm'),
    );
  }

  function processPasswordConfirm(&$element, \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form) {
    $element['pass1'] =  array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
      '#required' => $element['#required'],
      '#attributes' => array('class' => array('password-field')),
    );
    $element['pass2'] =  array(
      '#type' => 'password',
      '#title' => t('Confirm password'),
      '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
      '#required' => $element['#required'],
      '#attributes' => array('class' => array('password-confirm')),
    );
    $element['#element_validate'] = array('check_password');
    $element['#tree'] = TRUE;

    return $element;
  }

  function check_password($element, &$form_state) {
    if ($element['#value'] != 'test') {
      //form_error($element, t('Error: TEST'));
    }
  }

```

But I have again the error with form\_error() and password as displayed as two field without

# Answer
> 0 votes
As per @Clive comment, it's probably because `password_confirm` isn't a single element, it gets converted into two separate fields in a process callback, and doesn't apply the `#element_validate` to either of those because it can't reconcile which one you were referring to.

---
Tags: forms, 8
---


# Question
Title: Cannot figure out role-based pricing rule for custom Product Display/Variation in Commerce Kickstart
After working thru the Commerce tutorial and understanding roles, I thought it would be straightforward to set up a pricing rule based on user role, but I cannot seem to build the correct "Action" in Rules.

I want to reference a "Dealer Price" field in a Product Variation is the User Role = "dealer"

Error: Data selector *commerce-line-item:commerce-product:field-dealer-price:amount* for parameter *amount* is invalid.

Here are the steps I took to get to my current spot:

1. In a custom Product Variation "Bikes", I created a new field "Dealer Price" that mirrors the "Price" field that is already part of Commerce Kickstart Dealer price Field Type: Price Widget: Price with Currency 2, Created role "Dealer"
2. Initiated creation of pricing rule Store Settings \>\> Pricing Rules Add Pricing Rule Add Event: Calculating the sell price of a product Add Conditions: 1. User has role(s): Parameter: User: \[site:current-user\], Roles: dealer; 2. Entity has field: Parameter: Entity: \[commerce-line-item\], Field: commerce\_product; 3. Entity has field: Parameter: Entity: \[commerce-line-item\], Field: field\_dealer\_price
3. Then, I get stuck with Add Actions:
4. Select action to add: Commerce Line Item: Set item to specific amount
5. Line Item: Data Selector: commerce\_line\_item (Already inserted)
6. Amount: \[Click on Switch to Data Selector\]: commerce-line-item:commerce-product:field-dealer-price:amount **or** commerce-line-item:commerce-product:field\_dealer\_price:amount **or** commerce-line-item:commerce-product:field-dealer\_price:amount

I get an error msg when trying to reference the new price field "Dealer Price".

I feel like I am missing a connection within Commerce that ties the Product Variation to the *commerce\_line\_item*, but I haven't been able to identify the missing link. My products show up correctly in the shopping cart, so that hasn't been an issue.

Any help in tying the concepts of "Roles", "Rules", and "Commerce Kickstart" together is appreciated.

Thanks,

# Answer
> 1 votes
> 3. Entity has field: Parameter: Entity: \[commerce-line-item\], Field: field\_dealer\_price

Your price field won't be on `commerce-line-item`. It will be on `commerce-line-item:commerce-product`. You need to check for it there.

> 6. Amount: \[Click on Switch to Data Selector\]: commerce-line-item:commerce-product:field-dealer-price:amount or commerce-line-item:commerce-product:field\_dealer\_price:amount or commerce-line-item:commerce-product:field-dealer\_price:amount

So since the `field_dealer_price` is on the product instance, you'd be looking at this: `commerce-line-item:commerce-product:field-dealer-price:amount`

An example, without the role condition, would look like this:

```
{ "pricing_from_another_field_example" : {
    "LABEL" : "Role based pricing example",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-product" ],
          "field" : "field_dealer_price"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : [ "commerce-line-item:commerce-product:field-dealer-price:amount" ],
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```

---
Tags: commerce, rules, users
---


# Question
Title: Issue for a "two dimentionnal 'add another item' " with FormStateInterface::getTriggeringElement()
I'm learning drupal 8. I want create a page who contain a 'two dimensionnal' 'add another item' form. My code works well almost, but I have a strange behavior when I add rooms to a house (there is a strange value in my debug logs from the FormStateInterface::getTriggeringElement(), see to the bottom for the code and log)

First : I have two structures, houses and rooms. The user can create some houses and for each house, he can create some rooms :

When I add some houses, the form works fine :

When I add some rooms to the last house, the form works fine too :

But when I add some rooms to any "no-last" house, the form doesn't work fine (in the screenshot, I click one time to the "add room" in the block house '1', the label of the "house 1" became "house 2" (?!) and on click add 5 rooms (?!) :

Here my code and a strange debug log, I don't explain why I get this value (from the getTriggeringElement() in the room\_addMoreSubmit callback and this is the problem I think)

```
<?php

namespace Drupal\projet\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class HouseForm extends FormBase {

  public function getFormId(){
    return 'custom_rooms_form';
  }

  function buildForm(array $form, FormStateInterface $form_state) {

    $house_count = $form_state->get('house_count');

    if (is_null($house_count)) {
      $house_count = 1;
      $form_state->set('house_count', $house_count);
    }

    $form['house'] = array(
        //'#tree' => TRUE,
        '#prefix' => '<div id="house-replace">',
        '#suffix' => '</div>'
    );

    for ($house_delta = 0; $house_delta < $house_count; $house_delta++) {
      if (!isset($form['house'][$house_delta])) {

        $room_count[$house_delta] = $form_state->get('room_count_'.$house_delta);

        if (is_null($room_count[$house_delta])) {
          $room_count[$house_delta] = 1;
          $form_state->set('room_count_'.$house_delta, $room_count[$house_delta]);
        }

        dd($room_count, "room_COUNT");

        $form['house'][$house_delta]['room'] = array(
            '#type' => 'fieldset',
            '#title' => t('house : '.$house_delta),
            //'#tree' => TRUE,
            '#prefix' => '<div id="room-replace-'.$house_delta.'">',
            '#suffix' => '</div>'
        );

        for ($room_delta = 0; $room_delta < $room_count[$house_delta]; $room_delta++) {
          if (!isset($form['house'][$house_delta]['room'][$room_delta])) {
            $room = array(
                '#type' => 'textfield'
            );
            $check = array(
                '#type' => 'checkbox'
            );
            $form['house'][$house_delta]['room'][$room_delta] = array(
                '#type' => 'fieldset',
                '#title' => t('room : '.$house_delta.'.'.$room_delta),
            );
            $form['house'][$house_delta]['room'][$room_delta]['text'] = $room;
            $form['house'][$house_delta]['room'][$room_delta]['check'] = $check;
          }
        }

        $form['house'][$house_delta]['room']['add'] = array(
            '#type' => 'submit',
            '#name' => 'add',
            '#value' => t('Add room'),
            '#attributes' => array('class' => array('field-add-more-submit'), 'house_delta' => array($house_delta)),
            '#submit' => array(array(get_class($this), 'room_addMoreSubmit')),
            '#ajax' => array(
                'callback' => array($this, 'room_addMoreCallback'),
                'wrapper' => 'room-replace-'.$house_delta,
                'effect' => 'fade',
            ),
        );

      }
    }

    $form['house']['add'] = array(
        '#type' => 'submit',
        '#name' => 'add',
        '#value' => t('Add house'),
        '#attributes' => array('class' => array('field-add-more-submit')),
        '#submit' => array(array(get_class($this), 'house_addMoreSubmit')),
        '#ajax' => array(
            'callback' => array($this, 'house_addMoreCallback'),
            'wrapper' => 'house-replace',
            'effect' => 'fade',
        ),
    );

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

    return $form;
  }

  public function room_addMoreSubmit(array $form, FormStateInterface $form_state) {
    dd($form_state->getTriggeringElement(), "room : getTriggeringElement()"); // below, the log when I add a room to the house '1' (result see above  with the last screenshot: "the house 1" became "house 2" and one click add 5 rooms)
    $house = $form_state->getTriggeringElement()["#array_parents"][1];
    $c = $form_state->get('room_count_'.$house) + 1;
    $form_state->set('room_count_'.$house, $c);
    $form_state->setRebuild(TRUE);
  }

  public function room_addMoreCallback(array $form, FormStateInterface $form_state) {
    $house = $form_state->getTriggeringElement()["#array_parents"][1];
    return $form['house'][$house]['room'];
  }

  public function house_addMoreSubmit(array $form, FormStateInterface $form_state) {
    dd($form_state->getTriggeringElement()["#array_parents"], "house : getTriggeringElement()");
    $c = $form_state->get('house_count') + 1;
    $form_state->set('house_count', $c);
    $form_state->setRebuild(TRUE);
  }

  public function house_addMoreCallback(array $form, FormStateInterface $form_state) {
    return $form['house'];
  }

}

```

The log ('dd' in the room\_addMoreSubmit) when I click on the "add room" button in the house "1":

When I click on the "add room" button in the house number 1, getTriggeringElement return the array parents of the add button. And, as you can see, the parent is "2" not "1" (the house 1) So when I click on the "add room" button of the house 1, this is the house "2" which is identified and not the house "1".

I don't understand why...Use the getTriggeringElement is not the good way ?

# Answer
I don't know, if this is the error, but i always try to make the names unique when building forms, for example:

```
$form['house'][$house_delta]['room']['add'] = array(
            '#type' => 'submit',
            '#name' => 'add-room-to-house' . $house_delta,

```
> 1 votes

---
Tags: forms, 8
---


# Question
Title: Display certain taxonomy terms in Select List?
I have my content type set up something like this:

```
type (select):
  type1
  type2

taxonomy_term_reference (select):
  term1
  term2
  term3
  term4
  term5
  term6

```

When a user fills out my node and chooses type: type1, I want only these terms to show up as options:

```
  term1
  term4
  term5

```

When a user fills out a my node and chooses type: type2, I want only these therms to show up as options:

```
  term2
  term3
  term6

```

Is there any good way of doing this? The only way I can think of is with custom code via hook\_form\_alter()?

# Answer
> 0 votes
Try **reference-option-limit** module. It has the ability to limit your reference field value.

Another approach is to use entity reference instead of term reference and add an entity reference display to a views and select what items you'd like. Then in your content type reference field setting and under entity selection select the views you just created.

I hope this will help.

---
Tags: 7, nodes, taxonomy-terms
---


title: What Happened To Disqus?

text:
# Question
Title: What Happened To Disqus?
I'm using Drupal 7.38 with the Disqus (version 7.x-1.12) module.

Disqus simply fails to load. No trace of it in the console, elements or sources.

Disqus visibility is set to appear in block as per `/admin/config/services/disqus` and block is configured. Its "permissions" are configured properly also.

Disqus was previously working.

# Answer
Did you add the disqusapi library to /sites/all/libraries (or a similar location)? This happened to my site. Our Disqus comment block stopped loading on existing nodes, and I could not turn on Disqus comments for new nodes.

Then I noticed the message in the Disqus config (/admin/config/services/disqus) that I needed to have the Libraries module installed and api files.

Once I added those files, the Disqus block loaded again.
> 1 votes

---
Tags: comments
---


# Question
Title: Put eform's label and textfield(input) separate
I'm working on creating a table with eForm in Drupal 8.

Since label and textfield(input) stick together, can I insert label and textfield(input) into separate `<td>`?

# Answer
> 0 votes
The Render API, similar in Drupal 7, allows you to add a #theme property to use a hook\_theme defined template. The theme definition should use "render element", and that will be available in the template preprocess function. The way that it's usually done is to modify or create the render array in the preprocess function, and set #theme to table (in Drupal 7 calling theme('table') was possible).

Edit: Removed second paragraph which referred to modifying the theme.

---
Tags: 8, entities
---


# Question
Title: Content:author Relationship Not Showing Fields for Comments View
I have created a view to show a nodes comments in a block.

Authors on my site have different roles, and they can create a single business page. On that page, other users can leave comments.

For site authors that have a "**Free Listing**" role, I want to hide the ability for other users to post comments.

To do this, I have added a view to display comments, then added a relationship for **Comment:Content**, then a relationship for **Content:Author**.

In my previous experience, this should give me a field **(Content)Author:Role** to filter results by. Instead, I get no additional fields, just the standard Content:Author ID field, which then tells me..."If you need more fields than the uid add the content: author relationship", I have!!!

Have I uncovered a bug? Or am I missing something?

Any advice appreciated.

# Answer
> 1 votes
You need to filter for a *User* fields if I understand correctly (i.e. you want to display only comments on the current node when the node author has a certain role).

Select *User: Roles* as the filter and make sure the **Relationship** select box is set to the identifier for *Content: Author*. That will let you filter the comments by the node author's role.

---
Tags: views, comments
---


# Question
Title: How to make global math expresssion in views searchable?
I did manipulation calculation on webform submission data in Views by using Global Math Expression. I need to use filter of this Math Expression field, but I could not find it in the filter field. I tried to define in relationship also not available.

How can I use the global math expression in view filter?

# Answer
> 0 votes
views doesn't allow to filter data based on computational field. In your case you are using global math function which is a calculated field.

I would suggest to use **computed\_field** module and calculate your value in this field then you can easily filter your result based on this field.

---
Tags: views
---


# Question
Title: Drupal generating broken URLs containing "http" twice
My drupal site website started recently generating broken links/URLs within markup. It might have happened after I updated to version 7.41 or due to recent module update. I'm not sure.

Example:

```
<link rel="canonical" href="http://www.mydomain.nethttp:/" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.nethttp:/sites/default/files/css/css_xE-rWrJf-fncB6ztZfd2huxqgxu4WO-qwma6Xer30m4.css" media="all" />

```

Any idea what is going on? My drupal is hosted at the top of domain and not in a subdirectory. I was fine for years and didn't have to set $base\_url in settings.php or anything.

My site uses clean urls and I double checked that rewrite apache module is on and working correctly.

I did try setting the $base\_url in settings.php, this made the front page load correctly, however when I visit any node the apache returns 404, e.g. in access.log I see: "GET /content/some-nice-article-i-had HTTP/1.1" 404

I'm using Apache/2.4.17 and PHP 5.6.14 on Archinux.

Any ideas?

# Answer
> 0 votes
It appears that Apache 2.4.17 break rewrite functionality when fastcgi PHP is used. With mod\_php everything is working fome but I'm looking forward to Apache 2.4.18 or 2.5.

---
Tags: theming, uri
---


# Question
Title: How to tell what module is running from a function call?
I wrote a piece of shared code, and I am trying to figure out which module is actually calling the specific function. I am looking to have a mode to turn on debug inside of the shared module if it is being called from a particular module. Also this is in Drupal 7.

To call the shared module, I am using the following to call the function, made generic:

```
module_load_include('inc','rest_api','rest_api');
_rest_api_do_request();

```

# Answer
You could get the calling function from calling debug\_backtrace(). Another way would be to pass it in:

```
_rest_api_do_request(__FUNCTION__);

```

However, either seems like a bad pattern. It's fine for debugging, but a function shouldn't require knowledge of what it is calling it. That's an unnecessary dependency.
> 1 votes

---
Tags: 7
---


# Question
Title: Order total field, transactions and balance
In drupal commerce, using the commerce payment payment module, I would like to display the amount paid and order balance in paid order like on the example below.

> Subtotal ------------- 20
>
> TAX --------------------- 3
>
> Total ------------------ 23
>
> **Amount paid ----- 23**
>
> **Order balance ---- 0**

How could I achieve this ?

I'm close to get what I want. I created a module
I still have an issue : I don't know how to get the order\_ID ?

```
<?php

/**
* @file
* Commerce Order Total and Balance Module.
*/

// implement hook_commerce_price_formatted_components_alter()
function commerce_order_total_and_balance_commerce_price_formatted_components_alter(&$component_types) {

// TO DO : retreive the order ID (or the order object)
$order_id = 142;

// load the order
$order = commerce_order_load($order_id);

// get the balance
$balance = commerce_payment_order_balance($order);

// rename and reorder component_type
$component_types['base_price']['title'] = 'Total HT';
$component_types['base_price']['weight'] = -90;

// rename and reorder component_type
$component_types['tax|20_vat']['weight'] = -80;

// rename and reorder component_type
$component_types['commerce_price_formatted_amount']['title'] = 'Total TTC';
$component_types['commerce_price_formatted_amount']['weight'] = -50;

if ($balance['amount'] <= 0) { // we display total payments and order balance only if order balance is zero or less
  // add component_type "total_paid"
  $component_types['total_paid']['title'] = 'Montant payé';
  $component_types['total_paid']['weight'] = -40;
  $component_types['total_paid']['price']['currency_code'] =      $component_types['commerce_price_formatted_amount']['price']['currency_code'];
  $component_types['total_paid']['price']['amount'] = $component_types['commerce_price_formatted_amount']['price']['amount']-$balance['amount'];

  // add component_type "order_balance"
  $component_types['order_balance']['title'] = 'Solde';
  $component_types['order_balance']['weight'] = -30;
  $component_types['order_balance']['price'] = $balance;
 }
}

```

# Answer
> 0 votes
There is no way via the user interface that I'm aware of to add lines to the order total display that lists out price components like this. However, via code you have the ability to alter the array of formatted price components however you want at the point of display.

Drupal Commerce 1.x includes `hook_commerce_price_formatted_components_alter()` for this, letting you alter existing rows in the components list or add some to it that wouldn't otherwise be included. You can add lines that check the payment transactions associated with an order to see how much has been paid and that use `commerce_payment_order_balance()` to show the balance.

# Answer
> 0 votes
I was looking for the same

In the doc api for drupal commerce there is

```
<?php
  function hook_commerce_price_formatted_components_alter(&$components, $price, $entity) {
    // No example.
  }
?>

```

in $entity you will have your order !

have a look there hook\_commerce\_price\_formatted\_components\_alter

---
Tags: commerce
---


# Question
Title: Change node language from Language neutral to English in bulk using VBO
I have enabled entity translation and multi-language feature to an existing Drupal site. Currently all nodes in the site are set as Language Neutral, so the translation tab wont appear. If I edit a node and manually change the language to English the translation tab will appear and I can add the translated content for other languages.

I've tried the VBO - Modify entity values operator method mentioned at How can I set the language of nodes in bulk to existing content when making a site multilingual? but after changing the language from language neutral to English via VBO, the body content is not displaying when I edit the node later. The body content will appear if I change the value back to language neutral. It looks like the language of the field body is not change with the view bulk operations.

Is there any way I can can do a bulk operation and change the language of the nodes in bulk so that the nodes are translatable?

Thanks

# Answer
> 2 votes
Oh, yes, I remember this pitfall. Here's what happens: assuming the default language of your site is English, any Language Neutral node is assumed to be English. If you look at the node table in the database, you'll see that their language is 'und'. This is per content type, so let's say we have Language Neutral Basic pages. If you now add a Basic page with language English, its body won't be displayed, though if you check the database, you'll see that it's there (and the node's language is 'en').

The moral: all English-language nodes of the same content type *must* have language set to either 'und" or 'en', or the ones set to 'en' won't display. On our site, we set the critical content types to Require language (Don't allow Language Neutral). (Under Admin -\> Structure -\> Content types -\> Edit -\> Multilingual settings.)

# Answer
> 2 votes
Here's how I bulk set the language on my site:

1. Using Views Bulk Optimization, select all nodes you want to change, use the 'Change value' option and then change the value to language you want.
2. After you've done this, the field values will not appear when editing the nodes, so you need to run a script, e.g. `UPDATE database.field_data_body SET language='en' WHERE bundle='page'` (use your db name, field name, and bundle as appropriate).

IMPORTANT: If you have any custom url aliases, they will be overwritten with this approach, due to a problem with pathauto, but there's a work-around: first go to /admin/config/search/path/settings, and change the 'Update action' option to 'Do nothing. Leave the old alias intact.', then change this value back once you've run your Views Bulk Operations action.

# Answer
> 0 votes
Here's one way to do this that doesn't involve writing any code.

* Install the VBO module.
* Create a new view showing Content of whatevercontent types you need to convert. Use the Fields display method.
* Adda field Bulk operations: content.
* Check Modify entity values and select Language.
* Choose Apply.
* Save the view (add any other filters

if necessary to limit the selection) and go to the created view page. From the view page, choose the option to select all items on all pages and execute the Modify entity values action.

Choose the language and click next. If you have an extremely large number of nodes, you may need to play around with the queuing settings so that not everything is executed at once, but I would try doing it in one pass first because hey, if it works, you're done (note: always test on a backup first!)

> this post get from another post on stackexchange orginal post

---
Tags: 7, i18n-l10n, views
---


title: Taxonomy parent terms - pathauto

text:
# Question
Title: Taxonomy parent terms - pathauto
Pattern for taxonomy terms is `[term:parent]/[term:name]` where car is parent and BMW is child

Path is looking like this when I am on child term page: **www.mysite.com/car/bmw**

In menu I have link to /car and when I am there it displays a list of all child terms. Thats fine.

But when I generate XML sitemap I see /car/bmw (all good), but for strange reason there is link taxonomy/term/1 and which leads to page without any content or terms in it, while it should redirect to /car.

There is no /car link found.

To avoid duplicate content I am not sure how to avoid this. I tried recreating all paths bit no luck

*Edit:*

To elaborate in more details. Vocabulary has several parents, each 100 childs. Childs are displaying correctly as i have described above. For each parent i created separate view to display several fields. Filter is set to Taxonomy Term: Parent term. Is equal to "value", where value is taxonomy tid. Lets say that for this view value is 1 (term car) I also have relationship with Identifier: Parent. Require this relationship is on.

Path is set to /car Menu to Normal menu item "CAR".

When i go on homepage and click on menu item CAR everything is fine.

In meantime i deleted and bulk updated all taxonomy and now instead of getting old /taxonomy/term/1 or "/car" path for tid 1, i got "car-0".

View that is in menu "CAR" is still displaying ok, path is ok ("car"), but sitemap cant find this url but instead finds "car-0". Going to path "car-0" displaying nothing, not the terms nor the content it is tagged with.

# Answer
After testing out for a day various combinations it was a problem with a view page that had path same as taxonomy/term/1.

So I renamed the view page path to car/bmw12, deleted taxonomy aliases and recreated them.

It was easy thing to do. I did not think of it earlier as i was lead by assumption that when you use pathauto to recreate paths it would do it for terms no matter if the path was taken in views already.
> 0 votes

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: Unable to use Composer (for Drush) on Bluehost - install problem
I apparently successfully installed Composer (for use with Drush) on bluehost. See messages below. It does not work, however. When I type composer.phar I get nothing or "command not found" among other error messages. See below.

I am a newbie so it may be that install worked just fine, but I just don't know how to properly execute composer to make sure it works.

I am using instructions found at http://avantidevelopment.com/install-composer-on-bluehost/ & https://www.drupal.org/node/2366283.

```
columck5@columbiablooms.org [~/bin]# cd ~
columck5@columbiablooms.org [~]# mkdir ~/common
columck5@columbiablooms.org [~]# cd ~/common
columck5@columbiablooms.org [~/common]# curl -sS https://getcomposer.org/installer | /ramdisk/php/54/bin/php54-cli
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: /home5/columck5/common/composer.phar
Use it: php composer.phar
columck5@columbiablooms.org [~/common]# which php-cli
/usr/bin/php-cli
PHP Version     5.4.24

columck5@columbiablooms.org [/ramdisk/php/54/bin]# cd ~/common
columck5@columbiablooms.org [~/common]# ls -l
total 1164

drwxr-xr-x  2 columck5 columck5    4096 Oct 29 08:37 ./

drwx--x--- 21 columck5 nobody      4096 Oct 28 09:15 ../

-rwxr-xr-x  1 columck5 columck5 1176136 Oct 29 08:37 composer.phar*

-rw-r--r--  1 columck5 columck5     575 Oct 29 08:38 error_log

columck5@columbiablooms.org [~/common]# composer.phar

-bash: composer.phar: command not found

columck5@columbiablooms.org [~/common]# composer
columck5@columbiablooms.org [~/common]# php composer

Status: 404 Not Found
Content-type: text/html

No input file specified.

columck5@columbiablooms.org [~/common]# php-cli composer.phar
columck5@columbiablooms.org [~/common]# php-cli composer

Could not open input file: composer

```

# Answer
Content-type:text-html means your script is running from CGI instead of CLI.

so try to fix your install so that the PHP in the path uses a CLI

One simple way to do is to write php path to php-cli instead of php-cgi.

```
# .bash_profile
export DRUSH_PHP=/ramdisk/php/54/bin/php54-cli

```
> 2 votes

# Answer
What finally worked was adding the following to .bash\_profile.

```
alias composer="/ramdisk/php/54/bin/php54-cli ~/common/composer.phar"
export DRUSH_PHP=/ramdisk/php/54/bin/php54-cli
alias drush=”~/.composer/vendor/bin/drush”

```
> 0 votes

---
Tags: composer
---


# Question
Title: How to add user info along with address info in a single form using 2 content types?
I have a content type '**Person**', one field of which has a entity reference to a content type '**Address**'.

I would like an anonymous user to add their information along with their address in a single form using these two content types. What should I use to do that? Do I have to code it or does a module or a combination of modules help me?

Also similarly, for a logged-in user, I would like them to be able to edit their information which was previously saved. How do I do that?

**Notes**:

* I would like the anonymous users to register and also provide a few more pieces of profile information. Of course, I do limit what else they can do till they get approved by the administrator.
* I could capture the address information in the same content type but the reason I am thinking of separate content type is because two people can have the same address and I don't want to have redundant information. It would also provide me a way to figure out people who live in the same household. Also, I don't want to lose the address if someone moves and decides to update their address. It looks like I can add/edit two different nodes in the same page. If not reference, how? Do I have to code for it or there are modules that can do it?
* My choice of 'address' as an example was a bad one. My broader question is: Given two tables with one of the fields as a foreign key into the other, in Drupal, how can I create, update, delete corresponding rows in the two tables at the same time. The interface being user friendly UI for end user. Does I have to do this in code, or is there a single module or a set of modules that can be used to accomplish this? I am not looking for a full solution as much as pointers in the right direction.

# Answer
It sounds to me that you should have a look at the Entity connect module. Here are some details about it (from its project page):

> Entity Connect now expands both
>
> fields by adding "add new content" and "edit current content" buttons.
>
> It will work with all default widgets provided by Entity reference and References.
>
> The Drupal module will allow you to dynamically create and edit entities (see bellow for the list of currently working entity types) which should be referenced into an Entity reference field.
>
> It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.
>
> The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.
>
> The "edit" button will take the user to the edit form of the referenced entity. Once the user is done editing, he is sent back to the previous form.

Refer to Creating related records on the master for a first impression/intro about this module. This article is part of the illuminating Relativity Model for Drupal, for which this is an introduction to it (quoted from this linked page):

> The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:
>
> * Data architecture and data modeling merging as a single step through a documentation procedure.
> * Customized user interfaces that cater to individual workflows throughout permission roles.
> * Multi-level relational data structures that relate to other multi-level relational structures.
> * Mimicking the concept of database joins within Drupal's UI's.
> * Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The *small handfull of modules* (cfr. the last bullet) is detailed on Interface elegance and experience and is like so (apart from Drupal core):
> 0 votes

# Answer
You probably should have a look to Profile2 module. If you really want to use content types, you should have a look to Inline Entity Form and then configure permissions to be sure users can only edit their own content.

Hope that helps ;-)
> 0 votes

---
Tags: 7, users
---


# Question
Title: How do (or should) two separate modules implement the same external library using the Libraries 2.x API?
The **Libraries** module exists to make it easier for multiple modules to use the same library, but how is this actually done?

Do Module A and Module B both implement the library using `hook_libraries_info()` and `hook_requirements()`? If so, how do they avoid conflicting with each other? In my experience (trying to use Masonry API and Manual Crop modules), they conflict, even when both use the same namespacing, etc.

Or should a new module (Module C) be created that implements the library, and then Module A and Module B depend on Module C and use `libraries_load()`?

# Answer
Libraries API set out to separate external libraries from Drupal modules. The first step for that was separating the libraries from the module directories by providing the sites/all/libraries directory. Sadly, the separation between libraries and modules stopped there resulting in the problem mentioned above.

To mitigate the race conditions between hook implementations in different modules Libraries API provides the ability to use \*.libraries.info files placed in the sites/all/libraries directories which can provide the same information that is otherwise provided in hook\_libraries\_info(). While this completes the separation between modules and libraries in theory, we failed to provide a place to download and share these info files, thus leaving everyone on their own with that and - in effect - still requiring contrib module authors to implement hook\_libraries\_info().

We're trying to fix this situation in https://www.drupal.org/node/773508 so if you are interested in improving this situation please do help out (although that issue might be a little bit out of date, to be perfectly honest).

To specifically answer your question, there really is nothing that can be done but the two module maintainers coordinating so that the two modules provide an identical (or at least a compatible) library definition.

> Or should a new module (Module C) be created that implements the library, and then Module A and Module B depend on Module C and use libraries\_load()?

That would IMO at the moment - sadly - be the best solution, but often module maintainers are (understandably) reluctant to go forward with such a proposal.

(Full disclosure: I am the maintainer of the Libraries API module)
> 1 votes

# Answer
The Libraries module provides `libraries_load` which allows on-demand loading of libraries that are in `sites/all/libraries`. Libraries are defined by using `hook_libraries_info`.

It's a good idea to have a single module that defines `hook_libraries_info()` for a given library. For many modules, this is the primary module for Drupal. Take for instance Mailchimp or one of many commerce modules.

Alternatively, if you know that this module will be used by one or more modules that have no dependency on each other, you can define just a single module which defines the library and then have each module depend on that one.

As far as `hook_requirements` go, that is entirely up to you. I will say that if you do decide to put a requirement in each individual module, **please** namespace it. Lots of payment modules require the **cURL** extension and drop that requirement into `$requirements['curl']` instead of `$requirements['MYMODULE_curl']` this will cause a problem since requirements do not have an alter hook and a key collision will cause errors. So make sure you do the latter and not the former. However, if you're doing a single module, this wouldn't be a problem as you'd just do `hook_requirements` in it.
> 2 votes

---
Tags: theming
---


# Question
Title: How can I remove the tab "Subusers" in the profile?
I have installed the module subusers and appears a tab named "Subusers" in the profile. How can I remove this tab?

I tested this code in template.tpl.php and I didn't work:

```
function mytheme_preprocess_page(&$vars) {

$unwanted_tabs = array('user/%/subuser');
  foreach ($variables['tabs'] as $group_key => $tab_group) {
    if (is_array($tab_group)) {
      foreach ($tab_group as $key => $tab) {
        if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $unwanted_tabs)){
          unset($variables['tabs'][$group_key][$key]);
        }
      }
    }
  }
}

```

I tried with this code:

```
function mymodule_menu_alter(&$items) {
    unset($items['user/%/subuser']);
}

```

Thanks.

# Answer
> 4 votes
The tabtamer module provides an easy way to remove tabs, both those generated by core as well as those generated by modules.

# Answer
> 0 votes
Same issue I faced but I used patch for it which is still needs review but its work form me patch because Tabtamer hides tab from every user. So I downloaded the patch file in sites/all/modules/contrib/subuser

```
wget https://www.drupal.org/files/issues/subuser-remove-tab-if-no-permissions-148590-11.patch

```

and then applied patch with following command.

```
git apply -v subuser-remove-tab-if-no-permissions-148590-11.patch

```

---
Tags: 7, routes
---


# Question
Title: view 3: filter for datetime field is not working
I have created a customised module that export the content of a remote database tables to the view interface, every thing works fine except of the filter of the datetime field. In my file: mytable.views.inc

```
function mytable_views_data() {
  $data = array();
  $data['table1'] = array (
  'table' =>
   array (
    'group' => 'table1',
    'base' =>
     array (
      'field' => 'id',
      'title' => 'table1',
      'help' => 'table 1',
      'weight' => 10,
      'database' =>'database-name',
    ),
  ),
  'id' =>
   array (
    'title' => 'Id',
    'help' => 'Id',
    'field' =>
     array (
      'handler' => 'views_handler_field_numeric',
      'help' => 'Id',
      'click sortable' => true,
    ),
    'filter' =>
    array (
      'handler' => 'views_handler_filter_numeric',
      'allow empty' => true,
      'help' => 'Filter on <em class="placeholder">Id</em>',
    ),
    'argument' =>
    array (
      'handler' => 'views_handler_argument_numeric',
      'help' => 'Id',
    ),
    'sort' =>
    array (
      'handler' => 'views_handler_sort',
      'help' => 'Sort by <em class="placeholder">Id</em>',
    ),
  ),

     'date' =>
      array (
      'title' => 'Date',
      'help' => 'Datetime field',
      'field' =>
       array (
      'handler' => 'views_handler_field', // I tried also 'views_handler_field_date' and 'views_handler_field_datetime' but view displays the message field handler is broken
      'help' => 'Date',
      'click sortable' => true,
    ),
    'filter' =>
     array (
      'handler' => 'views_handler_filter_date',
      'allow empty' => true,
      'help' => 'Filter on <em class="placeholder">Date</em>',
    ),
    'argument' =>
    array (
      'handler' => 'views_handler_argument_date',
      'help' => 'Date',
    ),
    'sort' =>
    array (
      'handler' => 'views_handler_sort_date',
      'help' => 'Sort by <em class="placeholder">Date</em>',
    ),
  ),

);

return $data;
}

```

all the data fields are displayed properly in the view interface :

and the filter of the field datetime is displayed also:

The problem is the filter have no effect on the datetime field, I tried to filter the field but the filter has no effect and the data was not filtered, I think that there is a non compatibility issue between the field handler and the filter handler but once I tried to use the field handler: 'views\_handler\_field\_date' or 'views\_handler\_field\_datetime', the views didnt displayed the data of the datetime field and it has indicated that the field handler is broken, and with the handler 'views\_handler\_field' every things is displayed well but the filter is not working!

# Answer
> 1 votes
Try this handler **views\_handler\_field\_date**, then uninstall and reinstall the module and try. Otherwise your changes will not affect.

# Answer
> 0 votes
To allow `views_handler_field_date` to work with SQL datetime format, you can try:

* consider patch from Drupal issue (#2178287) which provides patch
* extend `views_handler_field_date` by your own (see this post), e.g. by JulienThomas

```
class module_handler_field_datetime extends views_handler_field_date {
 function render($values) {
     $value = $this->get_value($values);
return parent::render(strtotime($value));
 }
}

```

then add this file into .info file:

```
files[] = handlers/module_handler_field_datetime.inc

```

or check custom filter provided in this blog (gist) as example:

```
<?php
/**
 * Custom filter handler for views, that handles DATETIME
 */
class my_module_handler_filter_datetime extends views_handler_filter_date {
  function op_between($field) {
    if ($this->operator == 'between') {
      $a = intval(strtotime($this->value['min'], 0));
      $b = intval(strtotime($this->value['max'], 0));
    }
    else {
      $a = intval(strtotime($this->value['max'], 0));
      $b = intval(strtotime($this->value['min'], 0));
    }
    if ($this->value['type'] == 'offset') {
      // changed from original
      $a = (integer)time() + (integer)sprintf('%+d', $a); // keep sign
      $b = (integer)time() + (integer)sprintf('%+d', $b); // keep sign
      // changed from original ends
    }
    // %s is safe here because strtotime scrubbed the input and we might
    // have a string if using offset.
    $this->query->add_where_expression($this->options['group'], "$field >= '".date("Y-m-d H:i:s", $a)."'");
    $this->query->add_where_expression($this->options['group'], "$field <= '".date("Y-m-d H:i:s", $b)."'");
  }
  function op_simple($field) {
    $value = intval(strtotime($this->value['value'], 0));
    if (!empty($this->value['type']) && $this->value['type'] == 'offset') {
      $this->query->add_where_expression($this->options['group'], "$field $this->operator DATE_ADD(NOW(), INTERVAL $value SECOND)");
    } else {
      $this->query->add_where_expression($this->options['group'], "$field $this->operator $value");
    }
  }
}

```

or how it's implemented in birthdays\_field\_views\_handler\_filter.inc.

---
Tags: views
---


# Question
Title: Theme specific form field for custom content type
I have created a custom content type and added some fields to it. I want to theme one of the fields which I added from the "Manage Fields" section.

I want to remove the div wrappers when the form field is rendered.

Is there any form field specific theme function which I can override in `template.php` and make my changes?

# Answer
> 0 votes
If you want to do it in template.php, you would use `THEMENAME_field__fieldname__contenttypename()` as theme function. If you like to use a special template file, you would name it field--fieldname--contenttypename.tpl.php and put it into yours themes template folder.

All needed information can be found in Drupal API documentation.

---
Tags: 7, forms, theming
---


# Question
Title: all internal links won't work in a local-wamp site even after .HTaccess and mod_rewrite setup
I've imported a Drupal 7.41 existing site to my local machine on a wamp server. I've already imported it's .HTaccess (uncustomized), and have enabled mod\_rewrite in WAMP and restarted all services.

Yet, anytime I click on one of the internal links at the local site, I get, is some, 404 error, and in some WSOD.

When I tried to log in via localhost:8095/yoyo I got this error after filling the details and clicking on the log in button, I've seen the following error, but I don't know should I do with it exactly? (Adding some kind of a class manually?) Updating the theme maybe?

# Answer
> 1 votes
For the 404 errors on any internal links, have you edited the /rewritebase in htaccess? If the site now resides in a file, or in the root, this may need commenting out, or enabling.

As for the error. Are you certain you copied all files correctly?

Also, are you certain your mySql was dumped correctly?

Steps to try and fix can be...

1. Move files again.
2. Try dropping and reimporting the database.
3. Running registry rebuild. Note: this is not a module, this is something you can run with drush, or by placing the php in your directory and accessing it.
4. Try following this guys comment https://www.drupal.org/node/1323786#comment-5305922

---
Tags: navigation
---


# Question
Title: Regex field validation producing false (?) negative
I've also asked this question in the module issues, since I'm not sure if it is a bug or something I'm doing wrong.

I'm trying to use the Field Validation module to apply a regex control to ensure that a Philippines cell phone number is correct, and I'm getting what seems to me to be a false negative.

These numbers are 63, followed by 8 or 9, then followed by 9 digits. I've created a control using the Regex (PCRE) rule, with the following format:

```
 ^63[8-9]\d{9}$

```

and yet it persistently gives me false negatives, for example on this: 639121129374

I can't see anything wrong with the regex, and I've tried testing my numbers on regex101.com (cool tool) and they work fine. Is this a bug, or am I doing something wrong?

# Answer
When using the PCRE validator you need to add delimiters to your regular expression. For example:

```
/^63[8-9]\d{9}$/

```
> 2 votes

---
Tags: forms
---


# Question
Title: Need to add media with embed code and NOT URL - how to do it?
I'm trying to create an embedded soundcloud field in my drupal site but the embed is coming out **too LARGE**. In Soundcloud you can make the embed code reflect a smaller value in the sharing options, but there's no way to save it.

I can't find a way to actually use embed code in drupal. I've added the media module and the embedded media field module and the soundcloud module and the oEmbed module. None of them let me add embed code - they just accept a URL (and in fact they make me put the URL in twice for some reason). But the point is, they don't let me add embed code and I need to be able to add and tweak the embed code itself, not just add by URL.

I looked here and that doesn't help: how to add a cck field for youtube embed code?

Anyone know how to do this?

# Answer
Create a new field on your content type called "Embed code", and create a new text format called "code" where HTML is allowed, and no WYSIWYG modules are enabled.

Use css to change the width and height of the iframe of the soundcloud widget. it will adapt automatically.

**More control Using Views:**

1. Hide that field from display on the "manage display" tab of your content type.
2. Create a view block display.
3. In that view, bring in the embed code field.
4. Add a contextual filter to the view. Use the nid and provide a default value "content ID from URL".
5. Place the block on your page.
> 1 votes

---
Tags: media
---


# Question
Title: How to place a block in two different regions?
Working on a project I faced with a problem , in this project the front page looks completely different than the other pages and it consists some regions which are not exist in other pages.

Now the problem is that when I put an instance of a block in a region which only exist in front page then I cant use this block in other pages.Any idea how to solve this problem?

# Answer
> 3 votes
Multiblock will allow you to create multiple instances of the same block, so you can place it in different regions on different pages.

Alternatively, if the block in question is being generated by a view, you can create an additional block display.

# Answer
> 5 votes
As stated above you can certainly use Multiblock but the are a few other ways as well.

One is to use the Context module where you can create different contexts where any given context can render the same block or sets of blocks but with different conditions.

The other method I use is to use the module\_invoke function. You could invoke the module and block in a node or page preprocess function by creating a variable for the block display and then call the variable in a node or page template. An example would be something like this:

In your theme's template.php file. This example calls the Disqus module's comment block:

```
/**
 * Override or insert vars into the node template.
 */
function mytheme_preprocess_node(&$vars) {

  // Define the node.
  $node = $vars['node'];
  $nodetype = $node->type;

  // View mode check (Optional).
  if ($vars['view_mode'] == 'full') {

    // Content type switch check.
    switch ($nodetype) {

      case 'blog_post':
        // Disqus comments block.
        $block = module_invoke('disqus', 'block_view', 'disqus_comments');
        $vars['block_disqus_comments'] = $block['content'];
        break;

    }
  }
}

```

Here we created a template variable called `block_disqus_comments` for use in a node template. This calls a block that was created by the Disqus module called `disqus_comments`. You can now call that on one region in one template and in another region within another template. We set a case of the content type `blog_post` but theoretically you could add other content types or conditions depending on your needs.

We then can render this in our blog node template as:

```
<div class="disqus-wrap">
   <?php print render($block_disqus_comments); ?>
</div>

```

The nice thing about either of these methods is that they can be carried forth in code and sent to your code repo via Git. (For Context, you would need the Features module to do that).

---
Tags: theming, blocks
---


# Question
Title: What does this Omega theme warning / notice mean?
I’m getting this Notice repeatedly on my Drupal Commerce site, in various places. Not sure though exactly what is triggering the notice. This Notice is:

```
Notice: Undefined property: stdClass::$dir in omega_css_alter() (line 276 of /home/lovetrib/public_html/sites/all/themes/omega/omega/template.php).

```

And the line #276 in the Omega template file is

```
$pattern = $GLOBALS['language']->dir == 'rtl' ? '/\.no-query(-rtl)?\.css$/' : '/\.no-query\.css$/';

```

I believe it’s looking for a no-query.css file….?

To remedy I put a file named `omega.no-query.css` in the css folder. Since Omega is a base theme there is also a `mytheme.no-query.css` file in my theme’s css folder.

Can someone explain precisely what that line is doing and how to fix?

# Answer
The $pattern needs to be filled with one of the values to the right of the question mark. To find which value to use, Drupal checks the global variable `$GLOBALS['language']->dir` if it contains the value 'rtl'. If this is true, the first value is assigned, otherwise the second. Basically this is a short notation of if-else.

The problem is, that `$GLOBALS['language']->dir` does not exist, so php throws an error.

The lines part should read `$GLOBALS['language']->directory` There seems to be a fix here, which is from 2014, so there is a good chance this fix was already integrated into production.

You might be able to fix this issue by upgrading the Omega-Template to the latest stable or maybe development version (after creating backups!)
> 1 votes

---
Tags: theming
---


title: How to implement three level mapping?

text:
# Question
Title: How to implement three level mapping?
I have several Schools and each School have 7 Domains. Each Domain has 3 unique forms. Here is a graphical representation of it:

I want an **interface** in which I can **search a School** by using Views (this I can do). When I click a School, the next window comes with a **dashboard** which has these 7 Domains and each Domain has 3 forms which is associated with the selected School.

Can anyone tell me how I can achieve this?

# Answer
Your question seems like a variation of this Master Summary with drill down: change "Schools" by "States" and "Domains" by "Cities" to understand what I mean.

To illustrate the "drilldown" feature of it, just click, for any of the states included, on either the corresponding column (in the chart) or link (the *Total* in the tabular report below the chart). If you do so (e.g. for state "IL"), you'll get the details (another tabular report) for the state you selected. If on the last tabular report you want to switch to the details for another state (e.g. for state "Florida"), use the pull-down selection list within "Parameters" (near the top of the report), and change the selected value to "Florida".

Even though the sample here doesn't allow you to do so, it would be straight forward to replace the "number of users" for each of these cities to yet another hyperlink to another report (eg to provide the details of each of the users).

To further enhance the user experience, you can optionally combine this with the (amazing) dataTables jQuery plugin. A working sample of it (that you can use to experiment with it) is shown in the Customized Simple Table of States.

The magic behind this kind of drill down reports is NOT Views, but instead it is the Forena Reports module. One way of using it, is as a Views display format.

For more details about this module, refer to its Community Documentation. Or have a look at the module's documentation that comes with it, as in this demo site also.

Disclosure: I'm a co-maintainer of this module.
> 0 votes

---
Tags: views, taxonomy-terms
---


title: Matching a route with a "file path"

text:
# Question
Title: Matching a route with a "file path"
I'm trying to debug a route that should work like the one(s) used by the private: file scheme (i.e., a path like system/files/path/to/file, where path/to/file is an arbitrary string that *may contain '/' characters*). I more or less copied the the router definition. For private files:

```
system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

```

For my "knock-off", which uses a custom scheme called 'session:':

```
file_example.files.session:
  path: '/example/file_example/files/{filepath}'
  defaults:
    _controller: '\Drupal\system\FileDownloadController::download'
    scheme: session
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

```

As near as I can tell, my route is never matched; yet the private: case works. What's different here? How can I debug how the router makes its decisions?

Part of what I need to know is just what route got picked when the private: scheme actually works. So it would be handy to get a link to the current route. This is a fairly obvious thing to do, but I can't find a reference in the docs. How can I determine what the "current route" is for current request?

# Answer
This is a case where reading the routing file is a bit deceptive.

There are actually two similar routes defined in system.routing.yml:

```
system.files:
  path: '/system/files/{scheme}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
    scheme: private
  requirements:
    _access: 'TRUE'

system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

```

After watching in the debugger, it turns out that the matched route is actually `system.files`, and *not* `system.private_file_download`. But it will not match a tailed-URL at all without help.

The help needed is a "path processor", which is a routine that the router calls to let code do unusual things with route matching. Here's the one that's used for private: and temporary: files, among other users in Core:

*In core/modules/system/src/PathProcessor/PathProcessorFiles.php:*

```
class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

```

A path processor is a service, and needs a "tagged" service definition. Here's the one for Core's path processor for the `/system/files` subpath:

*In system.services.yml:*

```
  path_processor.files:
    class: Drupal\system\PathProcessor\PathProcessorFiles
    tags:
      - { name: path_processor_inbound, priority: 200 }

```

Once I'd added the correct route and service definitions, my custom URL scheme works the same way the Core file scheme URLs work.
> 4 votes

---
Tags: 8, files, routes
---


# Question
Title: Can the Flag module be used to lock content while editing to prevent concurrent edits?
We are trying to figure out a way to use the Flag module to prevent concurrent editing. In our research, we found the Content locking (anti-concurrent editing) module, but we thought since we are already using the flag module, that we could also use it for content locking.

The scenario would be if a user (person a) is already editing content A, and then another user (person b) tries to edit content A, then person b should not be allowed to edit content A until person a is done editing the content.

What is the best way to do this because we are having trouble trying to find the right combination to get this done? We were thinking once a content is being edited, a flag is set to lock the content and whenever another user tries to edit the content, they are prompted with a message "person a is already editing the content. please wait until they are done".

Is this possible with the Flag module? Would I need to use the Rules modules as well?

# Answer
> 2 votes
Below are 2 possible solutions (options) to address this question (which I assume is about D7) ...

# Option 1: Use the Rules and Flag modules

Yes you can implement such edit-in-progress (EIP) feature using the Flag module, but you'll also need the Rules module to get it to work. Read on for more details ...

# Step 1: Create an edit-in-progress flag

Create a global (not user specific) flag, and say you name (label) it **edit-in-progress** flag (='EIP' for short). The purpose of this flag is like so:

* If this flag is turned on for a node, it means "somebody is editing this node, so do not allow any additional edit sessions for this node to be started".
* If this flag is not turned on for a node, it means "the node is available for authorized users to start editing it".

# Step 2: Create a rule to disallow edit if the EIP flag is set

Create a rule to disallow edit of a node if the EIP flag for a node is already set. To recognize a request to start an edit session for a node, use an URL like `node/xyz/edit` (with `xyz` = `nid` of the node).

Refer to my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains a rule that is pretty close to what's needed for this rule here:

* Use the same Rules Event, i.e. "Drupal is initializing" (you want to catch this edit event via Rules BEFORE the edit session actually allowed to be started!).
* Slightly adapt the regular expression, by adding `/edit` to it.
* Add an extra condition to verify if the EIP-flag for this node is ALREADY turned on (which indicates some other edit session for this node was started already).
* Adapt the Rules Action to (a) issue an appropriate message (that some other edit session is already started) and (b) redirect the user to whatever other path that fits your needs (e.g: just `node/xzy`).

# Step 3: Create a rule to SET the EIP flag when an edit starts

Create a rule to SET the EIP flag for a node whenever an authorized user requests to start an edit session for a node. To recognize such request, use an URL like `node/xyz/edit` (with `xyz` = `nid` of the node).

Refer to my answer mentioned in Step 2, which contains a rule that is pretty close to what's needed for this rule here:

* Use the same Rules Event, i.e. "Drupal is initializing" (you want to catch this edit event via Rules BEFORE the edit session actually allowed to be started!).
* Slightly adapt the regular expression, by adding `/edit` to it.
* Add an extra condition to verify if the EIP-flag for this node is NOT turned on (which indicates no other edit session for this node exists).
* Adapt the Rules Action to SET the EIP flag.

# Step 4: Create a rule to UNSET the EIP flag when an edit ends

Create a rule to UNSET the EIP flag for a node whenever an authorized user requests to end an edit session for a node.

Here is a summary of this rule:

* Use Rules Event "after saving content".
* Use Rules Action to UNSET the EIP flag.

# Step 5: Merge Step 2 and Step 3 (optional)

Should you want to do/consider so, you should be able to merge the 2 Rules from **Step 2** and **Step 3** in a single Rule, using the Conditional Rules module. Refer to my answer to the question How to prevent a node being saved when using the Rules module? for a sample of how to use this module (for which not a lot of documentation seems to exist).

# Option 2: Use other modules

For anybody who does not want (or is unable) to use the combination of the Flag and Rules modules as described above, there are some alternative modules that may be worth considering.

Here are some of them (quotes are from their project pages):

* Content locking (anti-concurrent editing)

> Features:
>
> + **Block concurrent editing**: When a user is editing a node, any other user that attempts to edit the same node will be blocked from doing so, and notified that the content is already being edited.
>     + **By node type**: This module can be configured to only lock certain content types against concurrent editing.
>     + **By format**: This module can be configured to only lock specific input formats against concurrent editing.
>     + **Avoid losing content by accident**: If a user is editing content and attempts to leave the edit form without first saving it (e.g., closing the browser window/tab, clicking on a link, etc.), they will be notified. If the user confirms that they want to leave without saving the node, the edit lock gets automatically removed by an ajax call. This behavior can be disabled on the modules settings page.
>     + **Avoid forgotten locks**: Users are notified if they forget to unlock a node. They will be prompted to click on a link to unlock the node.
>     + **Views integration**: All open locks can be listed using Views.
* Conflict.

> This module allows parallel editing of nodes with field-level conflict detection and a trick to prevent accidental overwriting of fields when they are changed by another session while a node is being edited.
>
> This behavior is useful for things like issue queues where multiple people might be following up to an issue simultaneously. The original problem that lead to this module is #1559578: D7 solution for when multiple users are updating an issue simultaneously.
>
> It works by doing a 3-way comparison between the field data of the original node, the node as edited by us, and the node as edited by others.

# Answer
> 2 votes
You can do it by using the node\_validate function.

Your relevant part code is that :

```
if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }

```

---
Tags: rules, flags
---


# Question
Title: No release history available stops dependent modules download
I am creating my first make file to retrieve a custom module 'CUSTOM\_MODULE' from github and running into trouble getting the dependent modules to be installed.

Here is make file at the Drupal site to install the module:

```
api = 2
core = 7.x
projects[CUSTOM_MODULE][type] = "module"
projects[CUSTOM_MODULE][subdir] = contrib
projects[CUSTOM_MODULE][version] = 7.x-1.0
projects[CUSTOM_MODULE][download][type] = "git"
projects[CUSTOM_MODULE][download][url] = "http://github.com/to-git-repo.git"
projects[CUSTOM_MODULE][download][branch] = "master"

```

To Get the custom module

```
 drush make someMakeFile.build --no-core --contrib-destination=sites/all

```

This install the CUSTOM\_MODULE in sites/all/modules/contrib, however. It doesn't install all the dependencies as specified in the CUSTOM module local make file:

```
api = 2
core = 7.x
projects[] = audiofield
projects[] = block
projects[] = blog
projects[] = comment
projects[] = context
projects[] = jw_player
projects[] = libraries
projects[] = strongarm
projects[] = taxonomy
projects[] = text
projects[] = uuid_features
projects[] = video
projects[] = video_presets
projects[] = views
projects[] = node

```

When run in debug mode(--debug)

```
    ...
Found makefile: designssquare_com_blog.make [40 sec, 6.69 MB]                                                                                [ok]
Downloading release history from http://updates.drupal.org/release-history/audiofield/7.x [40.01 sec, 6.73 MB]                                                                  [notice]
/Users/maxit/.drush/cache/download/http---updates.drupal.org-release-history-audiofield-7.x retrieved from cache. [40.01 sec, 6.74 MB]                                          [notice]
Downloading release history from http://updates.drupal.org/release-history/block/7.x [40.06 sec, 6.74 MB]                                                                       [notice]
/Users/maxit/.drush/cache/download/http---updates.drupal.org-release-history-block-7.x retrieved from cache. [40.06 sec, 6.75 MB]                                               [notice]
No release history available for block 7.x
Returned from hook drush_make_process [40.06 sec, 6.7 MB]                                                                                [debug]
Command dispatch complete
    ...

```

From the first line, it is processing the local CUSTOM\_MODULE make file, however. It stops on second dependent module - 'block' and doesn't continue with the rest of the modules? While i would remove 'block' module as dependent (since it is part of core), my desired behavior would be it continue with the rest of the dependent module downloads, so the deployment completes with rest of the modules downloading. How I would specify such a behavior? Thank You

p.s. Drupal 7.x, Drush Master, Mac

# Answer
As per @jonhattan comment:

You need to specify projects to download in your makefile as `block` is not a project, but a module part of Drupal core. Same for `comment` or `node`. Simply remove them from the makefile.
> 1 votes

---
Tags: drush
---


title: How to use Coder with Drush?

text:
# Question
Title: How to use Coder with Drush?
I have unsuccessfully attempted to find how to use the Coder module with Drush. Does anyone know how should I use it?

# Answer
> 3 votes
`coder.drush.inc` exists in module, so yes, it can. Only command available is `coder-format`. Module provides following examples:

```
  'drush coder-format sites/all/modules/coder/coder.module' => 'Re-format coder.module according to Drupal coding standards.',
  'drush coder-format --undo sites/all/modules/coder/coder.module' => 'Restore coder.module from coder.module.coder.orig backup file (if existent).',
  'drush coder-format sites/all/modules/coder' => 'Recursively re-format Coder module files according to Drupal coding standards.',
  'drush coder-format --undo sites/all/modules/coder' => 'Recursively restore Coder module files from *.coder.orig backup files (if existent).',

```

# Answer
> 2 votes
Here are simple steps to install Coder (GitHub) and review your coding standards.

## 8.x-2.x

Which can be used for both Drupal 8 & 7 code checks as well.

### Installation

Recommended process of installation is by using Composer (similar to `drush`).

```
COMPOSER_BIN_DIR=~/bin composer global require drupal/coder

```

Change `COMPOSER_BIN_DIR` to where you want to install it (e.g. `~/bin` to install locally or `/usr/local/bin` to install globally).

Then we need to load the PHP\_CodeSniffer Sniff rules, e.g.:

```
phpcs --config-set installed_paths ~/.composer/vendor/drupal/coder/coder_sniffer

```

### Usage

To check Drupal coding standards and best practices:

```
phpcs --standard=Drupal,DrupalPractice --extensions=php,module,inc,install,test,profile,theme,js,css,info,txt,md /path/to/module

```

Which is equivalent to `drush` command:

```
drush dcs --extensions=<php,module> <path>

```

which will execute `PHP_CodeSniffer` with Drupal Coding Standards on a particular directory.

To automatically fix the coding standards, use:

```
phpcbf --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,js,css,info,txt,md /file/to/drupal/example_module

```

See: Command Line Usage

## 7.x-2.x

### Installation

```
drush -vy dl coder-7.x-2.x --destination=~/.drush

```

### Usage

```
drush coder --reviews=all --severity=major --no-empty .

```

Check `drush help coder` for more information.

However this branch is frozen, so it's advised to use 8.x-2.x instead.

# Answer
> 1 votes
There are submodules of Coder that contain the other Drush commands. Coder review is the one you want I think and provides:

```
drush coder-review [theme/module name] --minor

```

See coder/modules/coder\_review/coder\_review.drush.inc and coder\_sniffer for more.

---
Tags: drush
---


# Question
Title: How to define the right dependencies in .info, so drush can understand it?
Currently in my `booking_timeslots.info` I've the following dependencies:

```
dependencies[] = date
dependencies[] = date_views
dependencies[] = hierarchical_select
dependencies[] = hs_taxonomy
dependencies[] = hs_taxonomy_views

```

which fails with the following errors:

> No release history was found for the requested project (`hs_taxonomy_views`).
>
> No release history was found for the requested project (`hs_taxonomy`).
>
> No release history was found for the requested project (`date_views`).

when I'm trying to either enable the module, or installing it with `quick-drupal` command like:

```
drush qd --yes --core=drupal-7 testsite booking_timeslots

```

**How do I specify to which main project they belong to, so the installation process won't fail?**

---

Personally I know to which modules they belong, but I would like to automate this process, ideally by adding appropriate syntax into `.info` file so other services can understand its dependencies (such as `drush`). It seems running module in Simplytest sandbox can recognise these dependencies fine.

I can't find anything relevant in .info syntax docs apart of specifying `(major.minor)`.

# Answer
> 3 votes
You can declare the project name of the dependency using the following syntax:

```
dependencies[] = project:module

```

However, this this is a new feature that was added in Drupal 7.40, and as far as I can tell, Drush doesn't seem to understand it yet.

---
Tags: 7, drush, .info
---


# Question
Title: How to use metatag:image_src to share images on Facebook using the Service links module?
Image shared on Facebook via the Service links module is not showing up correctly when shared. I'm using Views with custom template to view this specific content.

Based on the Views configuration I can specify the image to be `[metatag:image_src]` in the metatag section. I have no idea where this syntax is going to get the image from, because I don't define this anywhere else, in the Views nor the Content type itself.

Another workaround I am looking at is to add a metatag tag in the head section via the `hook_html_head_alter()`. But I need more guidance on how and where to add this specifically, in detail.

The question about "How to change facebook og:image to post image link?" is not enough information for me. The issue about Support for facebook "title" and "image\_src" meta tags discusses the above. I don't know how to patch using Allow Views meta tags to "Use replacement tokens from the first row".

I'm still digging through Drupal and no experience in module creation.

Anyone can point me to a more detailed solution regarding this issue?

I also created support request Image not showing on facebook share in the Service links module issue queue.

# Answer
Try the approach suggested in Comment nr 1 of Issue nr 2387519, which is like so:

1. Install module Metatag (easy to understand module). Use the module and make your configurations.
2. Clear the cache.
3. Go to https://developers.facebook.com/tools/debug/og/object and click the "Fetch new scrape information" button to ping/update your meta tags to Facebook server.
> 0 votes

---
Tags: views
---


# Question
Title: How to allow registered users to enable / disable notifications for event nodes?
I have an event node type. The site needs to allow registered users to enable or disable notifications for this event. So on the event page (I have several views, etc) I would like to have a button is seen by registered users. It would be either show "Enable notifications" or "Disable notifications" based on its current value.

Ideally this would somehow associate the user and to the event (relation?) so that I can query db for all users who have enabled notifications for this event.

Any help or ideas on how to do this?

# Answer
This kind of functionality is definitely something for which you should use the Flag module (at least). Using a flag that can be set by individual users (not a 'global' flag). Together with a few modules as further detailed below.

# Message Stack

Have a look at the Message Stack, which consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

# Rules and Views

The tutorial about "How to allow users to manage their own Message Stack messages?" explains how to use the Rules and Views modules as a natural complement of it. And how, optionally, you can also use the Menu Badges module to show the number of Unread Messages via a (red) counter (similar to like on iOS).

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great (+ free) video tutorials Learn the Rules framework, organized in 7 chapters.

There is a similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.

And a set of 30 video tutorials about the Views module.
> 0 votes

# Answer
I would use the Flag module for this. It allows per user state toggling and integrates well with Views.

1. Create a Flag called `notify`.
2. Change the text that is shown to "Enable notifications" and "Disable notifications".
3. Use Rules and Views to send out your notifications.

For extra credit create a View that shows a User all of the nodes they are receiving notifications on.
> 1 votes

---
Tags: 7, notifications
---


# Question
Title: validating textfield input with ajax on every key entry
I'm new to Drupal and Javascript, so please bear with me. I have a simple class project to create custom validation on textfields without using select options or checkboxes. For one of the fields, the only valid inputs are 'right' or 'left'.

I have validation upon submit working, but I wanted to use ajax to check user input key by key, and display an error message before clicking the submit button. (As soon as it's clear the input will not be 'right' or 'left').

The function is working, but drupal pauses for a half second or so with every keyup while it does the ajax call, making it not very user friendly or practical to use. Hitting backspace to clear the field before drupal 'resumes' even navigates away from the page.

I have looked extensively online for resources on this, and have not found an example or module that seems to address this particular issue. Modifying autocomplete\_path seemed like the best option, but I can't figure out how to modify it for my purpose.

I have the module on my github here, or here are the parts in my module dealing with ajax. In my form:

```
$form['direction'] = array(
    '#title' => 'Direction',
    '#type' => 'textfield',
    '#description' => 'Enter the shift direction',
    '#element_validate' => array('validate_direction'),
    '#prefix' => '<div id="error_message">',
    '#suffix' => '</div>',
    '#required' => TRUE,
    '#ajax' => array(
            'event' => 'keyup',
            'callback' => 'validate_direction_callback',
    ),
);

```

and then the actual ajax callback

```
function validate_direction_callback($form, &$form_state){
    $commands = array();
    $commands[] = ajax_command_html('#error_message', render($form['direction']));
    $commands[] = array(
        'command' => 'validateDirectionCallback',
        'selectedValue' => $form_state['values']['direction'],
    );
    return array('#type' => 'ajax', '#commands' => $commands);
}

```

I didn't include the js file here because it didn't affect the pausing even when it was commented out. Thank You! Oh, and I am using Drupal 7.39.

# Answer
> 2 votes
The ajax callback in drupal is nearly as slow as a complete page load and this takes between 200 und 1000 ms. So checking every key stroke is no option.

If you don't check against the database, there is no need for an ajax callback. I would check "right" or "left" in javascript. If you need a server side check, you can write a stand-alone php file, that does this check without drupal, then your response time will be between 10 and 20 ms.

To replace the slow ajax with javascript you can start with this script:

```
val_left_or_right.js:

(function ($) {
  $('#edit-direction').keyup(function(){
    var direction_text = $('#edit-direction').val();
    if (direction_text != 'left' && direction_text != 'right') {
      $('#error_message').html('Please type left or right');
    } else {
      $('#error_message').html('OK');
    }
  });
})(jQuery);

```

attach the js to the form:

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'your_module') . '/js/val_left_or_right.js',
);

```

---
Tags: ajax, forms
---


title: Bandwidth Optimization options locked

text:
# Question
Title: Bandwidth Optimization options locked
I'm running a largely default Drupal 8.0.0-RC2 site. At `/admin/config/development/performance` the **"Bandwidth Optimization"** settings for "Aggregate CSS Files" and "Aggregate Javascript files" are disabled, so I cannot change their state. Extensive though fruitless googling suggests this is unusual, but I'm stumped on where to start. I'm using the Drude environment for my site.

# Answer
> 7 votes
There is a problem with the public directory, it is not configured or it is not writable. You can check this with drush:

```
drush ev "var_dump(is_dir('public://'), is_writable('public://'))"

```

Result should be:

```
    bool(true)
    bool(true)

```

If these two conditions are true, then the checkboxes will be available.

---
Tags: 8, performance, configuration
---


# Question
Title: How to create a family tree structure of nodes?
I have to create a family tree in Drupal. I am trying to use tree views module to do the same.

I have 3 nodes (A, B and C) of the contact type (I have created custom node), whereas C is son of A (Father ) & B (Mother).

I need to show the same in a tree like structure.

I have used relationship module and made these relations:

* A isFatherof C
* B isMotherof C

How do I show them as a tree like structure? Something like so:

```
A - B
  |
  C

```

I have tried using the *trees views* module.

# Answer
> 1 votes
I'm assuming you've tried to use the Views tree module (there doesn't seem to be a "*trees views*" module ...). To my knowledge, that module cannot create a *graphical* visualisation of a tree structure.

I'd recommend to create such tree structure using Graphviz diagrams, and use the Graphviz Filter module. Some more details about this module (from its project page):

> ... a little filter that treats input text as DOT syntax for Graphviz, converts it using Graphviz tools to the requested format(s) and renders it in HTML. It's useful to quickly create graphs dynamically from within Drupal nodes.

For more information, refer to the Community Documentation about Graphing Modules, which has a list of modules for creating either *Static* or *Dynamic* Graph Diagrams.

---
Tags: views
---


# Question
Title: Views: Highlight today's post based on previously referenced node
I have a weekly recipe list view, I manually create the list at the first day of the week.

for instance I assign `Node 1` for Reference field labeled with `Monday`, `Node 2` for `Tuesday` and so on using reference field in my `Weekly` content-type.

Next I made a page views of `Weekly` nodes and show the last node which contains that 7 referenced nodes previously mentioned.

What I want to do is to somehow determine today's date and change `display mode` of today's node along with `Views Sort`, like that if today is Sunday, the node referenced in `Sunday` field becomes highlighted and shows on top of the list.

Is there anyway to manage this using views, display suite or any other way?

# Answer
From what I understand your page view only displays a single (the last one) weekly node that in turn displays the fields with references. If this assumption is correct, what you can do (and what I would do in this case) is to create a node--weekly.tpl.php file in your theme folder based on node.tpl.php. Here you will be able to get the current day of the week in PHP. Based on that, use `render()` to display the reference fields in the order you wish, while adding the required html and css classes to make the current day highlighted.

More information about theming individual content types can be found here: https://www.drupal.org/node/17565

I don't know what's your experience with theming, but if you need help with the actual template, let me know.

\[later edit\] You can of course use a separate display suite template if you don't wish to override the general template of the weekly node. It's the same principle, but instead of having a `node--weekly.tpl.php`, you will have something like this: https://www.drupal.org/node/1098068 I think that the custom display suite layout involves a bit more work, but I may be wrong. Depending on your particular use case and how do you plan to display the "weekly" nodes across your website (e.g. if you will always have the same template or use multiple ways of displaying it), then you can choose one approach over the other. Both of them can help you accomplish what you need.
> 2 votes

---
Tags: views, datetime, display-suite
---


# Question
Title: How to create a combination chart with the Charts module if some X-axis values are missing?
I've been searching for a solution to my problem for a while without success so maybe someone here can help me.

I've already looked at the answer to the question about "How to combine 3 line charts in a single chart, using the Views integration of the Charts module?", but that didn't help to solve my issue.

I use the Charts module to create a chart in Views using the "*Chart*" display format. And I'm using Highcharts as my charting library to draw the number of "Passed" nodes (in green). I also created a chart add-on to represent the number of "Failed" nodes (in red) so that I can have multiple series in the same chart.

At this moment this is the chart that I have with the problem I will describe below:

As you can see in the table above, I have 4 different dates (Run Date and Time). The chart should show the 4 dates. Instead, it only shows 3 dates and this is why: The last date doesn't have "Passed" nodes, so the chart display (the parent) does not have that value on its axis. The chart add-on, representing the 2 Faileds on the last date, is then represented on top of the first display using the 3rd date and not the 4th, giving the error.

It seems that the x-axis values are irrelevant in this module.

The chart that I want should be something like this:

I made this chart in Excel and the difference that I see (that is giving me the wrong results in Drupal) is that I don't have a "**0 Passed**" or "**0 Failed**" but instead I have no results at all.

Is there a way to get this working correctly? I tried already many charts modules available and everyone has this problem as far as I know ...

Below is also a screenprint of my view:

Note: for the table below the chart I'm using module Views Merge Rows and it's clear that the top two dates don't show the "**0 Failed**" or "**0 Passed**" (as shown in the tabular display of my first screenprint) needed to have a correct chart displayed.

**EDIT:** I have found the same issue here and here. Hope it helps.

If there's need to have a solution like in the second link, i.e., construct the view in a way that both series will always have all labels, I'm open to it.

# Answer
# Step 1

Not sure if it's your "only" problem to get your chart right, but part of your problem is, pretty sure, that you have "holes" in your data, similar to what is detailed in Comment nr 12 of Issue nr 2052429.

### About the problem

To understand what that issue about "hole" is all about, consider these data to be charted:

Note that for the Types *Article* and for *Webform*, there is no row with Published = No (that is, there are no unpublished nodes for these types). So in this scenario we have 2 so called "holes" ... And that's were the trouble start:

* **Problem 1**: a column chart for these data looks like so:

The bar for "Article" (with value 1) is wrong, that bar is actually related to the value 1 for unpublished "Book pages". And the bar for "Book page" (with value 2) should actually be the bar for the 2 unpublished "Basic pages".
* **Problem 2**: a line chart for these data looks like so:

In this case, the line for "unpublished" suffers similar problems. So it doesn't matter what type of chart you're creating, all charts have this issue.

### How to solve this problem

Upgrade to the most recent Dev version to start with (which is much better / stable then the current rc1 version). Then apply the patch attached to the issue comment mentioned above, and check if that helps in your case. If it doesn't, know that it is a prereq for sure (without that patch you won't be able to get it to work). **Attention**: the patch doesn't seem to apply anymore to the most recent dev version. To make it work (again), do not use the above mentioned patch, but instead use the re-rolled patch attached to in Comment nr 31 of Issue nr 2052429.

Here is how the same column chart from above looks like after applying this correction:

And this is its corresponding line chart:

... Which I believe is the chart that exactly matches the tabular data shown above.

# Step 2

If upgrading to the most recent dev version and applying the patch is not sufficient, then I'd recommend you to (temporarily) disable that Views Merge Rows module you have enabled. And (temporarily) modify your view to show the values for PASSED and FAILED as 2 separated columns. And then verify if you get the correct results. That way we can verify if this Views Merge Rows module is the culprit (solve support requests is like taking away all possible causes, 1 at a time ...).

# Step 3

If step 2 doesn't help either, then I recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

> You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.

# Step 4

If none of the previous steps helps, then you may want to check the result you get by correcting your view like so:

* Create another display in the same view, let's say you name it "*Runs Chart (Total)*". It should be equal to all the specs of "*Runs Chart (Passed)*", but without the filter "*Content: Test Case Run Status (Passed)*". Obviously, it'll reflect the total Runs (both passed and failed). I'd make it a "line chart" (but that's a matter of personal preferences).
* Adapt the "*Chart settings*" of "*Runs Chart (Passed)*" to have it use "*Runs Chart (Total)*" as the parent chart.
* Adapt the "*Chart settings*" of "*Runs Chart (Failed)*" to have it use "*Runs Chart (Total)*" as the parent chart (instead of "*Runs Chart (Passed)*").

# Step 5

If the work around in step 4 helps as a work around, you may want to further refine the chart settings of "*Runs Chart (Total)*", by using a color for the line chart that matches the background of your chart (like white?). Possibly something similar for any of it settings like "Legend" (like set it to ` `?

Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.
> 1 votes

# Answer
I believe that what you need to do is construct the view in a way that both series will always have all labels.

To do this, all you need to do is make sure the "Count the number 0 as empty" field is unchecked. To find this field, click on the field name that you're counting to bring up its config overlay. Select "No Results Behavior" and make sure that the "Count the number 0 as empty" checkbox is unchecked. "Hide if empty" should also be unchecked.

Does that fix your problem? If not, it would be helpful if you exported your view and posted it, or at least the section regarding the field you're counting on.
> 0 votes

---
Tags: 7, views, charts
---


title: menu_alter did not work

text:
# Question
Title: menu_alter did not work
I try to use **menu\_alter** for changing **Delete option** in access callback. I clear cache many times but it still not working. I also tried some solution in this site but still got nothing. Please help me to solve this one.

```
function manage_child_menu_alter(&$items) {
   $items['comment/%/delete']['access callback'] = 'manage_child_comment_delete_access';
   $items['comment/%/delete']['access arguments'] = array(1);
   dpm($items);
}

```

Drupal Commons 3.28

Thanks.

# Answer
This is very common problem. What's your module weight? You can find the value in the table `system`. Try to change it to something more "*heavier*".

```
update DATABASE_NAME.system set weight = '99' WHERE name = "MODULE_NAME";

```

Standard approach hot to set a modude weight is to declare it in `MODULE_NAME.install` file:

```
/**
 * Implements hook_enable()
 */
function MODULE_NAME_enable() {
    db_update('system')
    ->fields(array('weight' => 99))
    ->condition('type', 'module')
    ->condition('name', 'MODULE_NAME')
    ->execute();
}

```
> 1 votes

---
Tags: 7, routes
---


# Question
Title: How to list all available reviews for coder?
I am using `drush` with Coder (7.x-2.x) and I would like to know what are available options for reviews:

```
$ drush help coder
...
--reviews Run the specified review(s), "all" runs all reviews, also accepts a comma separated list (no spaces).

```

Where I can find them?

# Answer
The list will depend on which modules you have that implemented `hook_reviews()`; hook implementations return a keyed array that has the name of the review. These items are combined with a default list that come from the coder\_review module.

The default list come from that dir is: `upgrade47`, `upgrade5x`, `upgrade6x`, `upgrade7x`, `upgrade8x`, `comment`, `druplart`, `i18n`, `i18n_po`, `production`, `security`, `sniffer`, `sql`, `style`
> 1 votes

# Answer
So far I've found the following `drush` command as workaround:

```
drush ev 'require_once dirname((new ReflectionFunction("drush_coder_review"))->getFileName()) . "/coder_review.common.inc"; print_r(array_keys(coder_review_reviews()));'

```

or:

```
drush ev 'require_once str_replace("drush.inc", "common.inc", (new ReflectionFunction("drush_coder_review"))->getFileName()); print_r(array_keys(coder_review_reviews()));'

```

Note: I'm not using `module_load_include()` in above examples, as Coder module could be downloaded outside of Drupal directory.

I've also raised feature request for Coder to achieve that in more convenient way.
> 0 votes

---
Tags: 7, drush
---