# Question
Title: Webform translation while keeping single node
I want to translate a Webform. I know it's very easy to achieve if there are separate Webform nodes for each language but I don't want to do that, I want to keep a single node.

I have already tried the Webform Localization module:

As per the readme of this module, it says to keep a single node enable
**"localization by string translation" fieldset in the form settings**

Which I have done.

I have also refreshed the **i18n\_string**, as suggested in module readme.

Issue here is, even with above settings when I click on translate tab of the Webform node, it creates new node.

**So are there any other settings I'm missing or this module is not working as its currently in under development.**

# Answer
The method in the documentation is working:

1. Go to the Webform Form settings at node/1/webform/configure
2. Check "localization by string translation" and "Expose webform component strings suitable for translation."
3. If dealing with an existing webform, then go to Go to Configuration -\> Translate interface -\> Strings
4. Enable "Webform localization" checkbox (this is important)
5. And Refresh Strings Then you will be able to see the string in Configuration -\> Translate interface -\> Translate

At least this works for me.
> 4 votes

# Answer
If you have "localization by string translation" then it will create additional nodes each with their own title, path etc, but they will share a single webform. Use the translate tab just to change the node title etc, but to translate elements in the webform, go to /admin/config/regional/translate/translate and search of each field label etc in turn.
> -1 votes

# Answer
Might not be an efficient way, but I don't get any other way to do that.

Here is a solution to keep a **single** Webform node with multilingual functionality:

Adding translated strings for each Webform element label not worked.

So I done something like that in form alter hook:

```
if(strpos($form_id, 'webform_client_form') !== false) {
    $form['#submit'][] = 'gt_custom_contact_webform_submit';
    $form['submitted']['your_name']['#title'] = t($form['submitted']['your_name']['#title']);
    $form['submitted']['your_e_mail_address']['#title'] = t($form['submitted']['your_e_mail_address']['#title']);
    $form['submitted']['subject']['#title'] = t($form['submitted']['subject']['#title']);
    $form['submitted']['message']['#title'] = t($form['submitted']['message']['#title']);
    $form['actions']['submit']['#value'] = t($form['actions']['submit']['#value']);
  }

```

Add translated strings for each Webform element label from here:

/admin/config/regional/translate/translate

Now if you are using **language switcher** block, you will see it will not allow to change the language.

To solve that:

```
function gt_custom_menu() {
  $items['contact-us'] = array(
    'title callback' => 'gt_custom_contact_form_title',
    'page callback' => 'gt_custom_contact_form',
    'access callback' => true,
  );
  return $items;
}

function gt_custom_contact_form() {
  return '';
}

function gt_custom_contact_form_title() {
  return t('Contact us');
}

```

And make that Webform available into a block from here: /node/nodeid/webform/configure

Advance settings -\> Available as block

Now open block admin page, find that block, set **Visibility settings** to show that block on contact-us page only, make that block translatable using **Make this block translatable**.

Now language switcher block allow you to switch the languages.

And the main thing is Webform node will remain **same**.
> -1 votes

---
Tags: 7, webforms, i18n-l10n
---


# Question
Title: Passing variables from modulefunction to theme
I have a custom theme and a custom module. The module shows users. Every user has its specific image (that can be uploaded, changed). The location/name of this file is in the database.

I have an template with specific layout for that page: page--uspage.tpl.php In this page, I need the location from the database when I access uspage.

```
$items['uspages'] = array(
    'title' => 'User pages', //page title
    'description' => 'User pages',
    'page callback' => 'show_uspages'
);

$items['uspage/%'] = array(
    'title' => 'User page',
    'description' => 'User page detail',
    'page callback' => 'show_uspage',
    'page arguments' => array(1),
    'access callback' => TRUE,
     'type' => MENU_CALLBACK,
);

```

I have a lot of other pages that doesn't need that. So I can't use preprocess\_page.

What's the easiest and best way to pass an array with the backgroundinformation from the function show\_uspage to page--uspage.tpl.php ?

# Answer
Short but painfully: there is no way to achieve that. The page.tpl expects that your part of the code is a renderable array or HTML output fully generated in your page callback show\_uspage(). Your part of the code is injected into the $variables of hook\_preprocess\_page() where ever the content block is placed in region settings for your theme. Your page callbacks really just handles the part of the output where the content block is placed. You can not store any data from your page callback for later use in theme layer or send the data by any mean to the page preprocess function or any other theming function for the page.tpl.

The only way would be to use hook\_preprocess\_page() and to add any data here again. You must use this hook even when you add data just for a specific page - you just need to assure to do that in this case and not on every page. Maybe by checking on which path the user is (like `if(current_path == 'uspages')`).

Another way would be to store the data in session in re-use it in hook\_preprocess\_page.
> 0 votes

# Answer
You can try to use **Context** module It provides a centralized set of API functions for setting and retrieving a static cache. You can set own variable in one module and retrieve in another. This is interesting article about this. https://www.phase2technology.com/blog/passing-variables-between-different-drupal-hooks-using-context-api/
> 0 votes

---
Tags: 7, theming
---


# Question
Title: drupal http_request give solr parse exception
typing a WS uri into the navigator return the json correctly

but the same adress in $url

```
 $result=drupal_http_request( $url );
 var_dump($result->data);

```

gives a parse exception

> Cannot parse 'docid:(7000': Encountered \\"\\" at line 1, column 11.\nWas expecting one of:\n ...\n ...\n ...\n \\"+\\" ...\n \\"-\\" ...\n ...\n \\"(\\" ...\n \\")\\" ...\n \\"\*\\" ...\n \\"^\\" ...\n ...\n ...\n ...\n ...\n ...\n ...\n \\"\[\\" ...\n \\"{\\" ...\n ...\n \\"filter(\\" ...\n ...\n ","code":400}

it must have smthg to do with whitespace or some special characters because it works with docid:(7000) but not docid:(7000 OR 7001)

How to somehow encode the url so that the solr WS server is happy with my request?

the same url works with drupal 8 code

```
   use GuzzleHttp\Client;
      $client = new Client();
      $response = $client->request('GET', $url);

```

# Answer
i found out I have had to urlencode the bracket part of my url for it to work

```
urlencode('(7000 OR 7001)'

```
> 0 votes

---
Tags: 7, search
---


# Question
Title: How to call jQuery functions from my form with Ajax?
There is an ajax callback which occurs on change of a field in my drupal 8 form. This populates a wrapper with information from the server. however I also want to excecute a jquery command to make the visibility of another field be visible after that . How can this be done?

I tried this `$form['ajax-wrapper']['#attributes'] = array('visibility'=>'initial');`

but that doesnt have any effect I need to be able to run this jquery command or this javascript but dont know how to trigger it after the ajax

```
document.getElementById( 'ajax-wrapper' ).style.visibility = 'initial';

           $("#ajax-wrapper").show();

```

# Answer
> 3 votes
You need to read the documentation as you are conflating the idea of `ajax` and what the AJAX capability of Form API is. A form item needs to add an `#ajax` item to perform `ajax` callbacks (php), and those functions can trigger AJAX commands *some of which* can trigger external JS functions.

On top of that, your actual JS code needs to conform to Drupal JS / behavior format so that it is leveraged by Drupal properly. The minimum here is it at least has to be enclosed in an anonymous function to prevent a jQuery conflict:

```
/**
 * @file
 */
(function ($) {

  "use strict";

  // All the JavaScript for this file.
  $("#ajax-wrapper").show();
  // other code or behaviors

})(jQuery);

```

Plus, if you have form fields that are dependent on other fields as far as being *visible*, you might be able to just use `#states`.

Here are resources:

---
Tags: 8, forms, javascript, ajax
---


# Question
Title: How to escape markup with check_markup in a twig template?
I am getting following error in drupal 8 :

The website encountered an unexpected error. Please try again later.

Twig\_Error\_Syntax: Unknown "check\_markup" function.

Twig template line :

```
{% set featured_portfolio_text = check_markup(featured_portfolio_array['field_portfolio_link_text']['#items'][0]['value'],'full_html') %}

```

Is there any alternative to check\_markup function for twig?

# Answer
> 0 votes
This seems like something you could do in a preprocess function and create that variable. At that level, you can use check\_markup to check it.

Be sure to see the two notes on the docs page:

> Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using $format-\>access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.
>
> Note: this function should only be used when filtering text for use elsewhere than on a rendered HTML page. If this is part of a HTML page, then a renderable array with a #type 'processed\_text' element should be used instead of this, because that will allow cacheability metadata to be set and bubbled up and attachments to be associated (assets, placeholders, etc.). In other words: if you are presenting the filtered text in a HTML page, the only way this will be presented correctly, is by using the 'processed\_text' element.

Here is a similar question/answer (albeit from 2014) that may still apply.

---
Tags: theming, 8
---


# Question
Title: Grouping Content Panes in Views For Theming
I've created a view for a specific content type. This view has a number of Content Panes associated with it.

I need to apply a row template file to about half these panes but the only tpl name suggestions the "Theme: Information" section gives are shared across all panes.

Is there a way to delineate certain panes for templating purposes? Machine name kind of works but I don't want to end up with `views-view-fields--machine-name-1.tpl.php, views-view-fields--machine-name-2.tpl.php, ....`

Thank you!

# Answer
> 0 votes
In Views you can change this by giving the View a name, which will change the display name from `views-view--view_id--page_1` to `views-view--view_id--my_display_name`. You can do this in the Advanced section of a view display config, and changing the 'Machine Name' value.

---
Tags: 7, views, theming
---


# Question
Title: Is there a successor module for 'Upload Image'?
I have 'inherited' a d5 site that I would like to relaunch on d7. It made heavy use of the module Upload Image, turning attached images into nodes.

I'm now looking for a solution to implement that functionality – but so far I couldn't find a proper successor to the *Upload Image* module. Why I need the attached images to be nodes: the user uploading the images should only fill in 1 form – but users viewing the pages should be able to vote on every image separately (fivestar). I'm currently a bit lost. Maybe I'm overthinking this?

Any pointers / suggestions appreciated. Thank you!

# Answer
Maybe try Image module, it has similar functionality

**Notes**:

* I looked in code of this module. Unfortunately it contains some legacy code and obsolete functions. In this case try the Image Attach module.
* Quote from Image Attach README.txt:

> You should use Image Attach if:
>
> + You want images that you attach to content to also be pieces of content in their own right, that can be viewed separately.
>     + You want reusable images (note that other ways of doing this exist).
>     + You want images that have meta-data, such as a title, description, author, and so on.
>     + You want to be able to change the file for an image, while keeping it attached to other content and keeping the rest of its data.
> 1 votes

---
Tags: 7, rating
---


# Question
Title: How do I avoid the maintenance screen on database errors?
As I'm working on a D7 site, I'll occasionally hit a database-related bug in my code. When this happens, I get thrown to a version of my site's maintenance page; the error information doesn't show up on the page, but just in Watchdog. This makes sense for a production site, but it's a pain during development. Is there any way to turn this behavior off, so that the error messages show up on the page I'm working on? Thanks!

# Answer
If you have a serious / fatal database error, you're probably not seeing the 'maintenance page' but the db\_offline page which usually displays errors direct to screen. What kinds of database errors are you experiencing?

Assuming your site is not in maintenance mode, few things you can check and set:

* Check the settings under admin/config/development/logging and make sure you have it set to display 'all messages'
* Make sure you have php set to display errors -- you can add the following in your settings.php file to increase your error\_reporting level:

---

```
error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```
> 2 votes

# Answer
We utilise static error pages, to which the reverse proxy in front of drupal (varnish) serves on behalf of drupal whenever a

* error 403
* error 404
* error 5xx

error occurs. This seems to solve the problem very elegantly
> 0 votes

# Answer
Install Xdebug to get a full stack traces if you hit a serios (PHP) problem.

Check http://drupal.org/node/158043 if you get an entierly blank page.
> 0 votes

# Answer
My issue was that everytime I logged in, it would hit me to the maintenace page, but never showed an error.

In my case, I had pending database updates I didn't do with file\_entity. I had to see the errors initially by adding this to settings.php at the bottom:

```
error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

I then saw the errors that pointed out that it couldn't find the file\_entity table. If its not there, that means it was never created and that means an update db didnt happen. I went and did a 'drush updb' and resolved this issue.
> 0 votes

---
Tags: 7, maintenance-mode
---


# Question
Title: How to render a view programmatically and set as node field?
I am trying to render custom view and put the result as content of the node.

Here is my code

```
function my_theme_preprocess_node(&$variables)
{
    if (isset($variables['node']) && $variables['node']->getType() == 'custom_type') {
        $reference_view = $variables['node']->field_reference_view->first();
        if (!empty($reference_view)) {
            $view_name = $reference_view->getValue()['value'];
            $view = \Drupal\views\Views::getView($view_name);
            $view->setArguments(array());
            $view->setDisplay('block');
            $view->preExecute();
            $view->execute();
            $variables['embedded_view'] = $view->buildRenderable();

        }
    }

}

```

But this code shows only debug message and when I try to get output in a twig template file it is empty

```
    {{ node.embedded_view }}

```

What is wrong with my code. How can I render a view and set it as a content of node or just node field in order to print it in a twig template file.

# Answer
> 3 votes
Because your variable reference is incorrect. It should be:

```
{{ embedded_view }}

```

Since you added it to the $variables array as `$variables['embedded_view']`.

As an alternative you can get the Twig Tweak module. Example on the docs page:

```
{# You can pass arguments to the view if needed. #}
  <dt>View:</dt>
  <dd>{{ drupal_view('view_name', 'page_1') }}</dd>

```

# Answer
> 2 votes
I think that the better way is create a pseudo-field, is easy and very simple to arrange the field in the views modes.

Why you will create 2 templates when you can use only the node template?

> Template files should only be considered when:
>
> Adding & editing regions. Making global layout changes. Customizing your layout structure.

Why pseudo-field are useful?

> Pseudo-fields are great if you have some content or data that you need to render together with that of a particular entity. And since you don't want to be hacky and hardcode all of this inside a template or preprocessor, you can use pseudo-fields to expose some control over this to the UI. This means that you can use the core drag-and-drop functionality to control their visibility and position relative to regular entity fields.

Example:

```
/**
 * Implements hook_entity_extra_field_info().
 */
function MY_MODULE_entity_extra_field_info() {
  $extra = [];

  $extra['node']['custom_type']['display']['pseudo_field_name'] = array(
    'label' => t('My own pseudo-field'),
    'description' => t('My pseudo-field'),
    'weight' => 100,
    'visible' => FALSE,
  );

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MY_MODULE_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  // Creating the pseudo-field
  $reference_view = $entity->field_reference_view->first();
  $view_name = $reference_view->getValue()['value'];
  $view = \Drupal\views\Views::getView($view_name);

  if (is_object($view)) {
    $view->setArguments([]);
    $view->setDisplay('block');
    $view->preExecute();
    $view->execute();
    $content = $view->buildRenderable('block', $args);
  }

  $build['pseudo_field_name'] = $content;
}

```

Clean the cache and enjoy ;-)

Reference:

---
Tags: views, theming, 8, nodes, hooks
---


title: Tokens for Profile 2 field

text:
# Question
Title: Tokens for Profile 2 field
I created a field for users using the Profile 2 module with machine name "field\_user\_country"

I created a block on my user profile page and i need to dynamically display the country of the currently viewed profile.

I have tried various tokens and they do not work.

What token can I use to get the country of the currently viewed user profile?

Thank you.

# Answer
> 1 votes
I'm having the same issue at the moment. Looking into including a few fields from a Profile2 content type into a Display Suite custom code field.

I used the following PHP code in the custom code field (using php filter format and enabling tokens, just in case). Then I was able to view a collapsed tree of all tokens available to that node.

You could prabably do the same in a block and have it displayed when you need it.

```
<?php
$output .= 'Available tokens:';
$output .= theme('token_tree', array('node'), TRUE, TRUE);
return $output;
?>

```

I'm sure there's a better way, but that quickly worked for me! gOOD LUCK.

---
Tags: users
---


# Question
Title: change node field value without node->save or without causing hook_entity_presave infinite loop
Have `CONTENT_TYPE_NAME` with `field_counter` that the user can set when editing a node. If a user edits and updates that field I want all other nodes that have this field set (to an equal or higher value) to increment their values by 1. I am overriding `hook_entity_presave` for this purpose.

As you can see in the following code I am getting all nodes of the same content type using `entityQuery` exluding the node that was about to be saved. For all the nodes found I am getting the entity and incrementing the field value by 1 and setting the field value and saving the node.

```
    function MY_MODULE_entity_presave(EntityInterface $entity){
      if ($entity->getEntityType()->id() == 'node') {
        $changed_field = array(
            "field_counter",
        );
        $nid = $entity->id();
        foreach($changed_field as $field ){
          $value = $entity->{$field}->value;
          if(isset($value) && $value !=""){
            MY_MODULE_change_field_value($field,$value,$nid);
            //...
          }
        }
      }
    }

    function MY_MODULE_change_field_value($field,$value,$xeid){
      $query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'CONTENT_TYPE_NAME')
        ->condition('nid', $xeid,"<>")
        ->condition($field,$value,">=");

      $nids = $query->execute();

      foreach ($nids as $nid) {
        $node = \Drupal\node\Entity\Node::load($nid);
        //or
        //$node = \Drupal::entityTypeManager()->getStorage("node")->load($nid);

        $old_value = $node->{$field}->value;
        $old_value++;
        $node->{$field}->value = $old_value;

        $node->save();
      }
    }

```

This code works with but has a problem. All nodes updated programmatically will call entity\_presave again and cause an infinite loop.

I did not find a way to update field value without calling `node->save()` if there is a way please let me know (I know there was a way in drupal 7 `field_attach_update` which is deprecated as of 8.0.x I think)

Is there a way to call `node->save()` which does not call `hook_entity_presave` ?

or alternativelly what checks can I do in the `hook_entity_presave` to know if the field was just updated programmatically and not from user edit ?

# Answer
I think I have found a simple solution

add revision message with UNIQUE string before saving the node

```
    //...
    $node->setNewRevision(TRUE);
    $node->revision_log->value = "AUTOMATED-UPDATE ". $field." incremented to ".$old_value ;
    $node->save();

```

check on the `hook_entity_presave` that the revision was not AUTOMATED by checking in the log for our UNIQUE string

```
    if ($entity->getEntityType()->id() == 'node') {
        $log = $entity->revision_log->value;
        if( substr( $log, 0, 16 ) === "AUTOMATED-UPDATE" )
            return;
        ...

```
> 9 votes

---
Tags: 8, nodes, entities
---


# Question
Title: How to build an editable view of two entities linked together?
I started using drupal recently and i am stuck building an editableview.

In my view i have a table of users with a field of a content type **"survey"** associated to theim throught an entity reference field that i added to the user account's fields. i set up a view of user with a relationship to my entity reference field.

I want to edit the field **"active"** wich is a field of content type **"survey"**

At the moment i can edit the field but it will set the value for every content.

i wish to edit the value of desired content not for all the content of this content type.Is their a way to achieve the desired result?

# Answer
> 0 votes
You are making a relation and editing a field of the relationed content "Survey", if a "User" is relationed to the same Survey content, will change on all of them.

If it is a different node "Survey" for each "User", it should't change all of them. I just did a test with your conditions and everything is going great. Could you give more information like configuration, multivalued, etc. of those fields?

---
Tags: 7, views, entities
---


# Question
Title: How to remove shipping service with rules?
I have a Commerce site running on D7 that has three shipping services, two product specific flat rate services, than then one service using the Postal Code and Weight Module. The problem I'm running into is how to remove one or the other shipping service so that the customers cannot choose between the services (and then choose the less expensive one!).

At the moment, here are the three rules I have:

**Shipping Service 1:** contains one product, does not contain the other . The logic here is to check if the cart contains the product for the lower cost special shipping, and not the product for the higher cost special shipping.

**Shipping Service 2:** contains one product. This one just checks if the order contains the product with the higher shipping rate because it's ok if the cart contains the other product, we'll just apply the higher shipping rate.

**Shipping Service 3:** This should apply the weight based shipping pricing specified in the Postal code and weight module if the card doesn't contain either of the special shipping products. Here I was trying to check the cart for the presence of the two special shipping products, and if they're not included, then apply the rule; but it doesn't seem to working. Both shipping services are placed in the checkout pane and the users are allowed to choose between the services. I want to only apply one service, based on the contents of the cart. What am I missing, and what's the best way to do this?

**Update** Here are the exports for the rules and their individual component. Essentially, there should be a primary conditional based on the cart contents If cart contains special shipping items: use flat rate; else use weight rate.

```
: Export of flat rate rule:
    { "commerce_shipping_method_flat_rate" : {
        "LABEL" : "Collect rates: Flat rate",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "REQUIRES" : [ "commerce_shipping" ],
        "ON" : { "commerce_shipping_collect_rates" : [] },
        "DO" : [
          { "commerce_shipping_method_collect_rates" : {
              "shipping_method_name" : "flat_rate",
              "commerce_order" : [ "commerce-order" ]
            }
          }
        ]
      }
    }

```

Export of Weight based rule

```
{ "commerce_shipping_method_postal_code_weight_shipping_method" : {
    "LABEL" : "Collect rates: Postcode weight shipping method",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "1",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_shipping" ],
    "ON" : { "commerce_shipping_collect_rates" : [] },
    "IF" : [
      { "OR" : [] },
      { "NOT commerce_order_contains_product" : {
          "commerce_order" : [ "commerce_order" ],
          "product_id" : "1100.4.1",
          "operator" : "\u003E=",
          "value" : "1"
        }
      },
      { "NOT commerce_order_contains_product" : {
          "commerce_order" : [ "commerce_order" ],
          "product_id" : "1700.6.1",
          "operator" : "\u003E=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_method_collect_rates" : {
          "shipping_method_name" : "postal_code_weight_shipping_method",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```

Padfolio Shipping Component:

```
{ "commerce_shipping_service_padfolio_shipping" : {
    "LABEL" : "Rate Padfolio Shipping",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "type" : "commerce_order", "label" : "Order" } },
    "IF" : [
      { "commerce_order_contains_product" : {
          "commerce_order" : [ "commerce_order" ],
          "product_id" : "1700.6.1",
          "operator" : "\u003E=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "padfolio_shipping",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```

Export of License component

```
{ "commerce_shipping_service_license_plate_holder_shipping_ra" : {
    "LABEL" : "Rate License Plate Holder Shipping Rate",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "type" : "commerce_order", "label" : "Order" } },
    "IF" : [
      { "NOT commerce_order_contains_product" : {
          "commerce_order" : [ "commerce_order" ],
          "product_id" : "1700.6.1",
          "operator" : "\u003E=",
          "value" : "1"
        }
      },
      { "AND" : [] },
      { "commerce_order_contains_product" : {
          "commerce_order" : [ "commerce_order" ],
          "product_id" : "1100.4.1",
          "operator" : "\u003E=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "license_plate_holder_shipping_ra",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```

Export of Weight based component

```
{ "commerce_shipping_service_postal_code_weight_shipping_service" : {
    "LABEL" : "Rate Postcode weight shipping service",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [
      { "OR" : [
          { "NOT commerce_order_contains_product" : {
              "commerce_order" : [ "commerce_order" ],
              "product_id" : "1100.4.1",
              "operator" : "\u003E=",
              "value" : "1"
            }
          },
          { "NOT commerce_order_contains_product" : {
              "commerce_order" : [ "commerce_order" ],
              "product_id" : "1700.6.1",
              "operator" : "\u003E=",
              "value" : "1"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "postal_code_weight_shipping_service",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```

# Answer
A possible alternative to trying to "remove" these shipping services, is to combine those rules so that in all scenarios you only have 1 shipping service.

The way to do so, is to rework those rules in a singe rule, in which you take advantage of the Conditional Rules module. By using this module, you can include any relevant conditional logic (and Rules Conditions!) as part of your Rules Actions. So if you do want to consider such rework of your rules, all you need to do is that in all possible scenarios, you will only select the (single) shipping service that applies.

For an example of a rule that uses this module, refer to "Part 2 (within Option 2)" of my answer to this question (which include a rule in Rules export format): How to include only an updated custom field in an email created using Rules?
> 0 votes

# Answer
So, the answer was a different rules configuration than I had tried.. I'm still not sure *why* this correct, but I got part of the answer from comments on my first question and part of the answer from the #drupal-commerce IRC which tipped me off to using the rules debugger on the pages rather than checking in the log (which is super tedious).

Here is the export if anyone wants to see it:

```
{ "commerce_shipping_service_postal_code_weight_shipping_service" : {
    "LABEL" : "Rate Postcode weight shipping service",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [
      { "NOT commerce_order_contains_product" : {
          "commerce_order" : [ "commerce_order" ],
          "product_id" : "1100.4.1",
          "operator" : "\u003E=",
          "value" : "1"
        }
      },
      { "OR" : [
          { "AND" : [
              { "NOT commerce_order_contains_product" : {
                  "commerce_order" : [ "commerce_order" ],
                  "product_id" : "1700.6.1",
                  "operator" : "\u003E=",
                  "value" : "1"
                }
              }
            ]
          }
        ]
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "postal_code_weight_shipping_service",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```
> 0 votes

---
Tags: 7, commerce, rules
---


title: Mark a taxonomy term as "deprecated"

text:
# Question
Title: Mark a taxonomy term as "deprecated"
I have a taxonomy vocabulary "categories", and decide that one of the terms should no longer be used (because I introduced another field which covers this information).

I could delete the term, but then some existing content would no longer have a category.

What I would like is to "deprecate" the term, such that

* existing content can continue to reference the term.
* the term is still visible in things like search facets.
* the term can no longer be assigned in a term reference field.
* (optional) editing an existing node which references the old term will fail form validation on save, and force to change the term.

# Answer
Termsatus module can help you.

This add a status "publis" or "unpublish" on terms like nodes, and is handled by permission (that can solve first three points), views, etc.

I think the optional point need a custom code using hook\_node\_validate check the status of term an send the custom error message attached to the field.
> 3 votes

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


# Question
Title: How do I find the hooks used by this module?
How can I find out what hooks are available in the Entity Clone module? I want to modify the entity after it is cloned to change its author and workflow state.

# Answer
> 4 votes
As @Kevin says, modules should have a modulename.api.php file with examples that implement hooks that the module provides.

When this file is not available you can search for the code that creates a hook in Drupal.

### Drupal 8

Look for following functions of the ModuleHandlerInterface, usually implemented by the ModuleHandler class:

* invokeAll
* alter

Using grep it's easy; just go to the module's root directory and execute:

```
 grep '\->invokeAll(\|\->alter(' * -r

```

This command looks for the strings `->invokeAll` (creates regular hooks) and `->alter` (creates alter hooks).

For example, if you use this grep command with core's module User you get:

```
src/Entity/User.php:    \Drupal::moduleHandler()->alter('user_format_name', $name, $this);
user.module:  \Drupal::moduleHandler()->invokeAll('user_login', array($account));
user.module:    \Drupal::moduleHandler()->invokeAll('user_cancel', array($edit, $account, $method));
user.module:  \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
user.module:  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

```

So, this module creates the following hooks:

* hook\_user\_format\_name\_alter
* hook\_user\_login
* hook\_user\_logout
* hook\_user\_cancel
* hook\_user\_cancel\_methods\_alter

### Drupal 7

Same procedure, but in this case you have to look for the functions `module_invoke_all()` and `drupal_alter()`.

```
grep 'module_invoke_all\|drupal_alter' * -r

```

Keep in mind that this method is not 100% reliable, as some modules use their own hook creation implementation (I've seen this in Drupal 7 mainly), but it's a good starting point if the said `modulename.api.php` file is missing.

### Entity Clone

Unfortunately Entity Clone doesn't create any hook, and the command yields no results.

### invoke

There are certain hooks that are only invoked in a particular module, see ModuleHandler::invoke and module\_invoke. As they only affects certain modules they are less used than regular ones (they are some kind of internal use hooks).

# Answer
> 0 votes
Some modules provide a `modulename.api.php` file detailing any hooks, such as info hooks, theme hooks, and alter hooks, that a developer can use to integrate or extend. It is usually found in the root of the module.

It doesn't look like Entity Clone provides such a file.

---
Tags: 8, hooks
---


# Question
Title: Is there a special way to list Commerce Products?
* Drupal core 8.2.6
* Drupal Commerce 8.x-2.0-beta5
* Bootstrap 8.x-3.2

I tried making a View that renders Products in view mode (Grid of Products in Default view), but when I try to add a product to cart - if the product has no variations - often times a wrong product that has no variations gets added. If the product that I try to add has variations I get a php error: InvalidArgumentException: Unknown attribute field name "attribute\_period". in Drupal\commerce\_product\Entity\ProductVariation-\>getAttributeValueId() (line 260 of drupal/modules/commerce/modules/product/src/Entity/ProductVariation.php).

Other attributes pop up there as well if I add a different product to cart.

It seems like it still tries to add a different product but provides the right variation name, which the different product does not have, so it errors.

If I view just the product on its own - works just fine. So for now I have the view show a table of products with "View" link, but I'd really like to be able to add products to cart right from the view. Any ideas for how to make that happen? I can't seem to find any tickets about this issue.

# Answer
I believe we have this captured in an issue. The main issue was https://www.drupal.org/node/2831895 and is now in https://www.drupal.org/node/2827721.

Part of our blocker has been getting tests for this. We need to build a test for the use case then work towards a resolution.

There is a pull request in progress at https://github.com/drupalcommerce/commerce/pull/582. I have not reviewed this and not sure how close it is to a final solution.

The issue is unique form IDs.
> 0 votes

---
Tags: views, commerce
---


title: Checking if a view has view blocks

text:
# Question
Title: Checking if a view has view blocks
I created a view page; it displays titles and images from the photoset content type. Some of these nodes have a view block.

How can I highlight items on general page with view blocks? For me it's enough to add some classes to these items.

# Answer
> 0 votes
Set your views display style to **unformatted** and add preprocess function into your template.php, smthng like

```
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if ( in this place add your if statement ) {
      $vars['classes_array'][$id] .= ' added_extra_class';
    }
  }
}

```

You can check for every row needed condition

---
Tags: views
---


title: Why doesn't the view show every node?

text:
# Question
Title: Why doesn't the view show every node?
I have created a view as a page that I want to only show my blog posts. I filter the `Content: Has taxonomy term (= blog)` to limit to my blog posts. Now I want to add a search box that can search the title and body. I've tried using `Search: Search Terms` and `Global: Combine fields filter`, but neither seems to work properly. They don't bring up any posts that match the search, even if the text is in the title, body, or the exact name of a linked taxonomy.

How can I make a search box for my view that will search the title and body?

# Answer
I have just learned that in order to use `Global: Combine fields filter`, you must set "Show" (under the "Format" section) to "Fields". My issue was I had it set to "Content" and couldn't select the fields in the settings for the filter.
> 0 votes

---
Tags: views, search
---


# Question
Title: image style (imagecache) images are not being created
Currently i am unable to create images that get resized automaticaly according to the different image styles.

This includes the default styles such as thumbnail as well as the custom created styles.

I have checked the "Public file system path" as well as the "Temporary directory" (under Configuration \> File system).

Both of the directories exist. The file permissions are good on the directories (777).

The original file that's uploaded gets created. It's just the scaled images that aren't getting created.

Any help with this problem would be very welcome. If there is already a solution somewhere (which means i searched for the wrong terms), a link to that would be very appreciated.

edit:

I can't find anything in the logfile either, except for messages like :

type : page not found

message: sites/default/files/styles/thumbnail/public/fotoslider/slider\_images/testbeeld20130103005.jpg

# Answer
> 3 votes
The problem was fixed when I changed the theme to another one, and back, as per @MPD suggestion.

# Answer
> 2 votes
Same issue here. I can avoid images not being created by not using 'drush cr' but clicking 'admin \> config \> performance \> clear caches' instead.

(Drush Version 8.0.5)

# Answer
> 2 votes
**Missing 'itok' token in the query string**

Since Drupal 7.20 release image styles will not be generated unless the request includes a valid 'itok' token in the query string. (apparently this was DoS protection)

So if you upload a new image example.png and the theme does not use image\_style\_url() to generate the img src for an image style, you may be missing the token and the image style will not be generated.

# Answer
> 0 votes
For me the images were being uploaded to just the /files directory but wasn't generating in the styles folder for one of the image styles. all my permissions were correct too. This started happening after i updated my media module which did alot of updates from 1.x to 2.x --- what i found out was that the image style wasn't even created, which was why it wasnt showing up in the directory. Check your image styles page to make sure its there!

---
Tags: 7, media
---


title: Show only terms that have been used?

text:
# Question
Title: Show only terms that have been used?
In the exposed filter form of a view, I have a taxonomy term selector set as a drop-down (*you know, an HTML* `<select>`). By default, that dropdown includes all of the taxonomy terms in the vocabulary. Is there a way to limit the terms shown to only those that will return results (i.e. only show the terms that have been used)? Basically, I want to ensure that any of the available terms will return at least one result.

# Answer
> 1 votes
An easier approach without really coding a lot would be to create your search with Search API and/or Facets.

Facets are designed to expose only options that will return results.

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

While you would have to rebuild the View, it probably is not a huge deal - and you won't have to write a bunch of code every time you expose taxonomy or similar fields as facets.

# Answer
> 0 votes
Here's how I would do it in D7:

1. Use hook\_form\_views\_exposed\_form\_alter(&$form, &$form\_state, $form\_id)
2. Locate the #options list, it's in $form\['tid'\]\['#options'\]
3. Loop through each term, use this method to check which terms are actually used
4. Unset those unwanted terms.
5. Done :)

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


# Question
Title: Email Change Confirmation module -- Avoid confirmation email from user_login hook
I'm using the "Email Change Confirmation" (email\_confirm) module with Drupal 7. It works well. However, I also have a user\_login hook that sets certain users' email addresses, thus:

```
    user_save($user, ['mail' => '<new address>']);

```

In this instance, I want the change to take effect immediately, without the need for confirmation (via email or otherwise). The module already provides a configuration option to override sending a confirmation email when the address is changed via the interface by users with specified roles. I want it to behave like that when I change it via the login hook. Is there a way to override sending an email in this case?

# Answer
After looking at the email\_confirm code, I came up with a simple solution. A confirmation message isn't sent if an email address is changed to or from empty, so:

```
  user_save($user, ['mail' => '']);
  user_save($user, ['mail' => '<new address>']);

```

does the trick.
> 1 votes

---
Tags: emails
---


# Question
Title: Adding new website as multiwebsite under existing drupal website
I have an existing Drupal website. I want to add a new website as a sub website under the existing website. I want both websites to share single database / modules.

I googled about it but didn't get use full information about.

Can anyone please explain how to add a new website as a child website of existing Drupal website?

Thanks

# Answer
> 2 votes
Domain modules will be your best bet. It will allow you to use same codebase and database for all your sites. You will also have an option to push content to a specific site if need be.

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites

---
Tags: multi-sites
---


# Question
Title: How to get formatted total amount programmatically?
I want to get the formatted total amount of my cart items.

I used the following code

```
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$line_items = $wrapper->commerce_line_items;
$total = commerce_line_items_total($line_items);

```

It returns me `$4000` instead of `$40.00`.

On shoping cart page it display `$40.00`. How can I get the price in this format?

I want this in commerce way not some custom php like `number_format` etc.

# Answer
I had the same issue. I solved this issue by **dividing the total by 100**. You can see the total amount in the `field_revision_commerce_total` table. After dividing, I used `commerce_currency_format($amount,NULL,NULL)` to get the currency format.
> 1 votes

# Answer
Floats are inherently inaccurate, and thus unsuitable to use for money. Operations on accurate decimal types are very slow, and there is no guarantee all databases will do them right, some might use floats internally anyway, and only pretend. And `money` format is not popular, and is known to be sometimes implemented in a buggy way in some database engines. That leaves integers.

All you need to do is divide by 100 before you use it, and multiply by 100 before save. That's all, no more philosophy behind it.
> 0 votes

# Answer
You can always use:

```
commerce_currency_amount_to_decimal($amount, $currency_code);

```

`$amount`: The price to convert to a decimal value.

`$currency_code`: The currency code of the price whose decimals value will be used to divide by the proper divisor when converting the amount.
> 0 votes

---
Tags: 7, commerce
---


title: Changing Drush path

text:
# Question
Title: Changing Drush path
I previously had Drush working on my VPS, but for some reason since a server update Drush can no longer be located.

If I do **'which drush'** the output is **'/root/.composer/vendor/bin/drush'** which matches what is in my .bash\_profile:

```
PATH="$HOME/.composer/vendor/bin:$PATH"

```

My drush installation is actually at **/opt/drush-8.x/vendor/drush/drush**

This may seem like an obvious answer, but when I tried editing .bash\_profile to what made sense to me, something got broken (couldn't use any commands) and my hosts had to restore my old .bash\_profile for me. I may just have made a typo then, but wanted someone to confirm **exactly** what my .bash\_profile should say before I try again!

# Answer
This is really a Bash / shell question - how to modify the path or set an alias. Anyway, replace

```
PATH="$HOME/.composer/vendor/bin:$PATH"

```

with

```
PATH="/opt/drush-8.x/vendor/drush/drush:$HOME/.composer/vendor/bin:$PATH"

```

assuming you may have other stuff in `$HOME/.composer/vendor/bin` that you stil want to use.

If you want to be 110% sure that you don't break something, try it in Bash before modifying .bash\_profile - just copy and paste the line inside Bash.
> 0 votes

---
Tags: drush
---


title: How to stop negative user points?

text:
# Question
Title: How to stop negative user points?
I am using Drupal 7 and working on a rating site using Fivestar and Userpoints.

What I want is for a certain amount of points to be deducted from a user when he makes a post, and also points deducted from a user when he votes on a node.

The rating and points deduction works well, but the issue is negative points. I don't want any user's points to go below zero. I need to prevent users from having negative user points on the site.

# Answer
IMO you should only **allow** voting for users which have at least X user points. Here is a technique to get that to work:

* Grant some permission when a user's amount of user points reaches X, and take that permission away again if it gets reduced to some amount below that. The obvious permission to be used for this is by using the role which allows voting.
* Monitor changes in user points for a user, by using the Rules module like so:

+ Use the Rules Event that captures user points being rewarded (whereas such points can be negative also ...).
    + Use the Rules Event (or Rules Action!) as described in How to access current amount of earned userpoints in a Rules Condition? (be aware that there is no out-of-the-box Rules Condition like "does this user have at least X user points"?).
    + Perform a Rules Action to grant access to the role that allows voting, when the user's amount of user points is at least X (and revoke that access if it is below X). If you'd also use the Conditional Rules module, you can perform both types of Rules Actions (grant and revoke) in a single rule.

With that, all that's left is to pick a vaue for ... X!

**Note**: this approach does not require any PHP coding, so "programming experience" is not required (you only need to be a bit familiar with Rules, for which there are lots of free tutorials available.
> 0 votes

---
Tags: rules, userpoints, rating
---


# Question
Title: `Drupal\DrupalExtension` extension file or class could not be located
I got this error upon launching behat tests:

> \[Behat\Testwork\ServiceContainer\Exception\ExtensionInitializationException\] `Drupal\DrupalExtension` extension file or class could not be located.

Does any additional module is required? Found https://www.drupal.org/project/behat but for d7

# Answer
> 0 votes
The Drupal Extension requires no modules, only composer installation.

Execute:

`composer require drupal/drupal-extension='~3.0'`

See the docs for other setup information: https://github.com/jhedstrom/drupalextension/blob/master/README.md

**Update**

to install the latest version just use

```
composer require drupal/drupal-extension

```

\[version 3 is kind of outdated and in this time latest version is 4.1\]

---
Tags: 8, testing
---


# Question
Title: Drupal 8 - How to Reference Flags Twig Template without showing full content?
I'm using Drupal 8 to construct a page, where flags are required for *Adding Videos to Favorites.* I am using the ***Flags Module***, but it's a custom template, so I didn't use the {{content}} reference directly. Instead I'm using the machine names of each field in displaying and styling the node. I reference them using {{content.field\_*fieldname*}}

The problem is that I'm unable to reference the flags that I have created using the Flags Module. They are appearing on other basic pages and articles (when I turn on those areas while editing the flags), but they fail to appear in the custom template that I have created for a node.

Could anyone please help me with this? Any sort of help is highly appreciated. Thank you.

# Answer
**FOUND IT**

Alright guys, so it's simple.

You reference the flag this way in your Twig Templates:

```
{{ content.flag_machinename }}

```

Cheers.
> 6 votes

---
Tags: theming, 8, flags
---


# Question
Title: Is there any difference or advantages between use of libraries in theme or module level with using of "Libraries API" module instead?
Is there any difference between times that I define libraries in theme or module level with times that I use Libraries API module instead?
Is it necessary to use library module and I add/attach my libraries to it?
What's real purpose and usage of the Libraries API module?

# Answer
The real purpose of Libraries API module is to serve as a central point of information about libraries, so modules can rely on this module to request loading libraries. This avoids modules to include libraries in their module package and just ask Drupal for them.

The main advantage is it avoids conflicts and duplication between several modules shipping same library. With this module, both modules declare the need of a certain library, that should be installed in the Drupal librarires directorty.

Also, modules don't need to include code to detect and load the libraries, version detection, etc

See The ideas and design behind Libraries API 2.x for a detailed explanation.
> 4 votes

---
Tags: 8, theming
---


title: List ALL Taxonomy Terms with Views

text:
# Question
Title: List ALL Taxonomy Terms with Views
I am trying to figure out how to use views to list out ALL my taxonomy terms that are grouping node titles. Example:

Taxonomy Term 1 \- Node Title 1 \- Node Title 2

Taxonomy Term 2 \- Node Title 3

Taxonomy Term 3 -Message: There are currently no Node titles at this time, please check back

Taxonomy Term 4 \- Node Title 4 \- Node Title 5

# Answer
> 4 votes
1. Create a 'taxonomy term' view
2. Add 'Taxonomy term: Content with term' as a relationship (don't make it required, otherwise unused terms won't show up)
3. Add two fields, 'Taxonomy term:Name'(mark this excluded from display since we will group them in the next step) and 'Content:Title'
4. Go to Format settings: set 'grouping field Nr.1' to 'Taxonomy term:Name'
5. Now you get the data you want, you can use your preferred approach to style them.

---
Tags: views
---


# Question
Title: What hook should I use to attach a script to a content type?
I have this function from a standalone php script that redirects the user based off the user agent. In the process of merging this into Drupal and the script only needs to execute for a specific content type. Not 100% sure what is the best hook to use: `hook_node_presave()`, `hook_load()` or `hook_node_view()`?

Or should I run this as a template pre-process since this script requires the JS `window.location` embed?

Part of the code attached:

```
$web_user_agent = $_SERVER['HTTP_USER_AGENT'];
$current_page = $_SERVER['REQUEST_URI'];

if (!$web_user_agent = '[User Agent Placeholder]') {

    die;

} else {

    echo('<script type="text/javascript">

    if(self==top) {

            window.location = "'. $redirect_url .'";

    } else {

    }
    </script>');
    die;
}

```

# Answer
> 2 votes
It depends on how you want to approach it. Clive's question is still relevant, Javascript redirects are neither great or optimal. However, if it *must* redirect based on a User Agent, Javascript might be the only option.

I would advise you to do the agent detection on the client side, as the server value may not always be accurate. Your code above won't work.

To load a script based on content type, you can do:

```
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'mytype') {
    $variables['#attached']['js'][] = array(args);

    // or

    drupal_add_js('path/to/script.js');
  }
}

```

Your script itself also needs to be in a closure:

```
/**
 * @file
 */
(function () {

  "use strict";

  // All the JavaScript for this file.

})();

```

If jQuery or the Drupal scope is needed:

```
/**
 * @file
 */
(function ($, Drupal) {

  "use strict";

  // All the JavaScript for this file.

})(jQuery, Drupal);

```

See the docs page for more:

---
Tags: 7, nodes, hooks
---


# Question
Title: Give some users (e.g., teachers) access to nodes created by a unique subset of other users (that teacher's students)
My site has roles for administrators, students, and teachers. Students create nodes, and each student has exactly one teacher. Teachers should be able to view all content created by their students, but no content created by other students. In other words, I'd like to have some kind of per-user setting that allows me to select one specific other user who can access the first user's nodes.

This seems like a pretty common situation, but I can't figure out how to do it. I'm open to any suggestions. Here are some things I've looked at so far:

* I started out by using references to link each student to a teacher. However, I couldn't find a way to use that relationship for access control.
* The subuser module looks appropriate, but I'm leery since the D7 version is still in alpha. Has anyone used it for this purpose?
* Taxonomy access control looks like another possibility. The list of teachers is static, so it could be made into a vocabulary. But if Teacher is a per-student setting, is there a reasonable way to make that propagate down to the nodes created by that student?
* Any other suggestions about how to do this?

# Answer
> 3 votes
I've had success with multiple node authors using

## nodeaccess\_userreference

> Gives content access permissions to users for content that references the users with User reference or Entity reference.

and also with

## nodeaccess\_nodereference

> Gives content access permissions to users if they have access to content that is referenced with Node reference or Entity reference.
>
> Checks view, update, and delete grant operations, and can pass those on to the referencing content, or trigger a different grant configuration according to settings.

In combination with field\_permissions or hook\_field\_access, for restricting access to the reference field, that should enable the feature you're looking for there.

You may want to look at using Rules to set the reference field value on node save as well.

# Answer
> 2 votes
Similar ground is covered under this question on StackOverflow: https://stackoverflow.com/questions/2289004/how-do-i-give-a-specific-user-editing-rights-to-a-specific-node/13466946 You may get some ideas by looking at it.

As an alternative to Node Access (which is up to the task, but unsupported) you may want to look at the Flexi Access module. It gives you a straightforward way to set up access control lists (ACLs) for individal nodes.

What it doesn't (currently) give you is an *automatic* method of assigning ACLs. I.e. when a new node is created, someone with the right to administer nodes must manually create an ACL for the node.

Its development status is still alpha. However, there are no open bugs in the issue queue and I promise that any reported new bugs will be dealt with in an timely manner.

Disclosure: I'm the maintainer of Flexi access, but I hope this does not violate the site's policy on self-promotion.

# Answer
> 1 votes
Well, if nothing else will work, you can at least use Organic Groups and make a group around each Teacher, and put the students in those groups. You can then control the visibility of the posts made by students, because they will be in a specific group. Also, you must make all groups private, so people from one group cannot see posts in another group. Maybe the Teacher can also be the moderator or owner of her group.

# Answer
> 0 votes
modules needed: subuser module (needs relation) and Node Access Relation (node\_access\_relation). Set up subuser, add subusers, make a relation-type called 'share-content' (admin/structure/relation\_types/add), make it from user to node, set access as needed in node access relation. review your permissions. if you need more granularity add field permissions module.

to have total control of access both ways parent to child, child to parent, a detail way to do it is with some woodoo: add a hidden field entityreference trick field on contentype called "original-author", with rules allways set the content author the parent user, set trick field as real node-author. this way your content is acesible to all subusers as detail as needed, and you can access real node-author if needed. share content is done by relation module, views arguments are with entityreference and maybe need a default value with php contextual filter.

EDIT:with https://www.drupal.org/project/abt, i also succed to handle user and subuser access permission, you have to have a saved term reference field (same field, same tid) common in user account and in node. You have to have a diferent term reference field for every user role and this field must be present in user account and in node structure. Once to get it, you can handle with rules (long and complicated rules) to set these values on node save. Permissions are handeled in NODE term reference field settings. Set node term reference view to: yes, but allow..., and update to: yes, but restrict.... Set permissions for only term refrence field on node in the fields that are pointing to the user that you wish user to have access to your node. What happens under the hood is that node and user are conected by the same tid and grants accsess. So, for one group you have to have a set of taxonomy terms (on same taxonomy), for a diferent group, you nedd to add another set of terms. With such structure, group one won't have access to content on group two, etc. because tid's are diferent.

---
Tags: users
---


# Question
Title: Change on/off values for existing boolean checkbox
Trying to find most "soft" way to alter data for already existing checkbox field. Aiming to change the labels value for on/off but updating them from UI or programatically is not working out, field\_config contains proper allowed values array. Im not sure where else too look, on node view Im still seeing 0/1 values event though I changed the on/off values to string representations. I know I can do it on node view alter but I want more general solution, also deleting the field base and recreating is not an option here. Any hints?

# Answer
> 0 votes
Solution was to reexport into features field\_base and field\_instance proper labels, then to make sure field\_config and field\_instance\_config blobs are properly updated. I used update hooks to resave the fields with proper info, I loaded them with field\_info\_field, set the required properties and the used field\_update\_field. Also field config from list\_key must be changed to list\_default.

---
Tags: forms
---


title: Taxonomy URL incorrectly translated

text:
# Question
Title: Taxonomy URL incorrectly translated
On a multilingual site (source language: English) I have a view that displays a few product categories. The categories are represented by Taxonomy terms. If I display the (translated) category names linking to the respective category overview page, everything works perfectly: The links are being translated, too.

But when I introduce a category image (an extra field in our category Taxonomy type) the generated image link will never be translated. This means: My view renders the category name as link in the *Interface text language selected for page* (e.g. http://example.com/de/tastatur/xy-123) and the category image as link in English (e.g. http://example.com/en/keyboard/xy-123). I even have tried to set the *Rendering language* parameter to German, but the image link is always being rendered in English.

Is this a bug, or am I doing it wrong?

# Answer
> 0 votes
I found a workaround, but I hope someone will come up with a better solution.

If I include the Term ID as a hidden field …

… it is possible to rewrite the category image with a link generated by the router:

This works, but we are missing the *hreflang* attribute in the link, and the *alt* attribute of the category image is still English only.

---
Tags: 8, taxonomy-terms, i18n-l10n
---


title: Add attribute to html and body

text:
# Question
Title: Add attribute to html and body
I need to add `class="no-trans"` to body, also edit the html tag. How I can edit the `{{ html_attributes }}` and `{{ body_attributes }}` ?

my html.html.twig

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ body_attributes }}>

```

# Answer
The attributes variable is an object, that has some methods available. One of them is `addClass()`, which allows you to add additional classes from a string or array.

```
<body{{ attributes.addClass('no-trans') }}>

```

To add arbitrary attributes to the html tag, you can use the `setAttribute()` method. Multiple attributes can be set by chaining additional calls to `setAttribute()`:

```
<html{{ html_attributes.setAttribute('attrName1', 'attr1Value').setAttribute('attr2Name', 'attr2Value') }}>

```

---

Take a look at the community documentation on using attributes in templates.

You can also look at the node.html.twig template in the classy theme for an example of adding an array of classes with `addClass()`:

```
{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
  ]
%}
<article{{ attributes.addClass(classes) }}>

```
> 6 votes

# Answer
Here is a preprocess alternative (maybe you will need access to some info to make custom html classes).

```
use Drupal\Core\Template\Attribute;

/**
 * Implements template_preprocess_html().
 */
function MODULE_OR_THEME_preprocess_html(&$vars) {

  if (is_array($vars['attributes'])) {
    $vars['attributes'] = new Attribute($vars['attributes']);
  }

  $vars['html_attributes']->addClass('goes-to-HTML-tag');
  $vars['attributes']->addClass('no-trans');
}

```
> 9 votes

---
Tags: 8, theming
---


# Question
Title: How to avoid timeouts on real long page loads
I have a few custom modules for our systems administrators where they can select a script and it will remotely execute on a remote server, let's say restart WebSphere.

I would like the results to display, however some of these scripts can take 15 minutes or so to run, I've got a busy spinner running so they know something is running in the back ground, however after 15 minutes or so the page times out, if you reload the page the results display.

I display the results via `drupal_set_message()` in the "submit" hook.

# Answer
> 1 votes
The Drupal Batch API is a great solution for something like this. You can specify or count the number of actions that need to be done, display a progress bar, and prevent timeouts on long processes. Also there are many examples like this one you can utilize to create a good solution for your use-case.

# Answer
> 0 votes
For processes that long, you might need to execute them asynchronously, maybe using something like the Background Process module.

The module page displays several code examples, explaining how to call your process in an asynchronous way using that module.

---
Tags: 7, forms
---


# Question
Title: How to define jQuery in libraries for avoiding conflict with theme with library?
For use of most frameworks (Zurb Foundation, Bootstrap, etc) or libraries (Like Owl carousel, Slick, etc) within a theme, jQuery has to be added as a library.

Is it enough to add jQuery only once as dependencies in a `global` library and have it load on every page (imagine that I add this library in Library section of `ThemeName.info.yml`) Or would I have to add it as dependencies each time I define a new library again?

For example, is the below structure correct:

```
global:
  css:
      # The path to the css file.
      assets/css/stylesheets-1.css: {}
      assets/css/stylesheets-2.css: {}
  js:
    assets/js/myglobal.js: {}
  dependencies:
    - core/jquery

library-A: # Bootstrap Library.
  css:
      assets/css/stylesheets-3.css: {}
      assets/css/stylesheets-4.css: {}
  js:
    assets/js/myglobal.js: {}
  dependencies:
    - core/jquery

library-B: # Owl carousel Library.
  css:
      assets/css/stylesheets-5.css: {}
      assets/css/stylesheets-6.css {}
  dependencies:
    - core/jquery

```

Is there any problem If I add jQuery once as library in `js:` category and again as `dependencies:` in one library like `library-C` simultaneously? Something like below? Can it cause the conflict?

```
library-C:
  css:
      assets/css/stylesheets-c-1.css: {}
      assets/css/stylesheets-c-2.css: {}
  js:
    assets/js/myglobal.js: {}
    assets/js/jQuery.js: {}
  dependencies:
    - core/jquery

```

# Answer
Every library needs to have **all** it's dependency listed ! As libraries can be loaded independently.

> drupal will make sure to include every file only once.

So this is correct. yes.
> 4 votes

---
Tags: 8, theming, javascript
---


# Question
Title: having multiple instances of blocks with different settings in D7
I have activated Multiblock module, create an instance of one custom block. The admin/structure/block/instances say my new block instance is not 'multiblock enabled'

The doc say https://www.drupal.org/node/353565

> To get around this, you can make a block "multiblock enabled". To do this, you have to first add an $op to your hook\_block called 'mb\_enabled'. It should always return the string 'mb\_enabled'.

I don't quite get how to do that and I have tried that with no effect

```
/**
 * Implementation of hook_block().
 * @param string $op one of "list", "view", "save" and "configure"
 * @param integer $delta code to identify the block
 * @param array $edit only for "save" operation
 */
function amu_hal_block($op = 'list', $delta = 0, $edit = array()) {

    // set up an empty array which will contain the block contents
    $block = array();

    switch ($op) {
        case "list":
            // Generate listing of blocks from this module, for the admin/block page
            $block[0]["info"] = t('On This Date');
            break;

        case "view":
            break;

        case "save":
            break;

        case "configure":
            break;

            case 'mb_enabled':
                return 'mb_enabled';
                break;
    }

    return $block;
}

```

Is hook\_block present in D7 at all?

# Answer
There's no hook\_block in Drupal 7. However if you take a look at your README file inside your D7 version of multiblock module, you can find how to do it:

> Example implementation of hook\_block\_info:
>
> ```
> function hook_block_info() {
>   $blocks['powered-by'] = array(
>     'info' => t('Powered by Drupal'),
>     'weight' => '10',
>     'cache' => DRUPAL_NO_CACHE,
>     'mb_enabled' => TRUE,
>   );
>   return $blocks;
> }
>
> ```
> 1 votes

# Answer
to precise more, if it can help anyone:

```
    function amu_hal_block_info() {
            $blocks ['last_hal_publications'] = array (
                    'info' => t ( 'Liste des dernières publications HAL' ) ,
                    'mb_enabled' => TRUE,
            );

    function amu_hal_block_view($delta = '',$edit=array()) {
        $block = array ();

        $suffix = '';
        if ($edit && isset($edit['multiblock_delta'])) {
            $suffix= '_' . $edit['multiblock_delta']['#value'];
        }

        switch ($delta) {

            case 'last_hal_publications' :
                $block ['subject'] = t ( 'Dernières publications' );
                $docids = variable_get ( 'docids_publis' . $suffix);
                //code
                break;

   function amu_hal_block_configure($delta = '',$edit=array()) {

    $suffix = '';
    if ($edit && isset($edit['multiblock_delta'])) {
        $suffix= '_' . $edit['multiblock_delta']['#value'];
    }

    $form = array ();
    switch ($delta) {
        case 'last_hal_publications' :
            $form ['docids_publis'] = array (
                    '#type' => 'textarea',
                    '#title' => t ( 'Publis significatives' ),
                    '#description' => t ( 'Pour des publis significatives, entrer un HAL docid par ligne' ),
                    '#default_value' => variable_get ( 'docids_publis'. $suffix, '' )
            );
            break;

function amu_hal_block_save($delta = '', $edit = array()) {
    $suffix = '';
    if ($edit && isset($edit['multiblock_delta'])) {
        $suffix= '_' . $edit['multiblock_delta']['#value'];
    }

    switch ($delta) {
        case 'last_hal_publications' :
            variable_set ( 'docids_publis'. $suffix, $edit ['docids_publis'] );
            break;

    }
}

```
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Getting error 'The requested page could not be found' after https is enabled
The link to my content is lost

default settings:

`# Set "protossl" to "s" if we were accessed via https://. This is used later
 # if you enable "www." stripping or enforcement, in order to ensure that
 # you don't bounce between http and https.
 RewriteRule ^ - [E=protossl]
 RewriteCond %{HTTPS} on
 RewriteRule ^ - [E=protossl:s]`

my serversupport suggested:

`#Rewrite everything to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]`

both didn't work, when comment out everything. My link to the content is fixed using http.

how to solve this?

# Answer
> 1 votes
> The link to my content is lost

So you enabled HTTPS and you can no longer see your Drupal website? It sounds like you have uploaded your Drupal installation in public\_html and are now serving content from the private\_html folder.

If you are on a Direct Admin installation you can toggle the `symlink private_html to public_html configuration` That should make sure the correct files are served via HTTPS as well.

## Enabling HTTPS

The rewrite rules that ship with Drupal are intended for mix-mode HTTPS (in which case your site supports both HTTP and HTTPS).

If you want the best security, just redirect everything to HTTPS. See the 3rd bullet point of Enabling HTTP Secure (HTTPS):

> For best possible security, set up your site to only use HTTPS, and respond to all HTTP requests with a redirect to your HTTPS site. Drupal 7's $conf\['https'\] can be left at its default value (FALSE) on pure-HTTPS sites. Even then, HTTPS is vulnerable to man-in-the-middle attacks if the connection starts out as a HTTP connection before being redirected to HTTPS. Use the HSTS module or Security Kit module, or set the Strict-Transport-Security header in your webserver, and add your domain to the browser HSTS preload list, to help prevent users from accessing the site without HTTPS.
>
> You may want to redirect all traffic from http://yourdomain.com and http://www.yourdomain.com to https://youdormain.com. You can do that by adding this to your .htaccess file:
>
> ```
> RewriteCond %{HTTPS} off [OR]
> RewriteCond %{HTTP_HOST} ^www\.example\.com*
> RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
>
> ```
>
> Put that below `RewriteEngine on`.

# Answer
> 0 votes
Don't remove the original rules that were shipped with Drupal. To enforce HTTPS, you can do this:

```
# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\.(?!well-known)" - [F]

  # Force all traffic to HTTPS, except a local instance
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteCond %{HTTP_HOST} !^mysite\.local$ [NC]
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

The addition here is:

```
  # Force all traffic to HTTPS, except a local instance
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteCond %{HTTP_HOST} !^mysite\.local$ [NC]
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

The third `RewriteCond` prevents a redirect for local development sites, which you may or may not want.

This is the basic idea and may also work, in lieu of the previous statement, if `%{HTTP:X-Forwarded-Proto}` is not available on your server:

```
  # Force all traffic to HTTPS, except a local instance
  RewriteCond %{HTTPS} off
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

You can test rewrite rules with this handy tool.

I would have suggested Secure Pages because that is sometimes easier for people to configure, but it looks like only a sandbox port of it exists.

Anyway, I have used both rules with success - and they should work for you unless something is wrong in your server/dns/ssl setup.

Note that any redirects to https should occur *before* this statement in .htaccess:

```
  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

```

---
Tags: 8, .htaccess, ssl
---


# Question
Title: How can I retrieve parameters from the path?
I have a path

```
 /step/4?guide=6

```

How can I get parameters 'guide' and '6'in PHP?

# Answer
> 1 votes
If this is Drupal 8, you can simply do:

```
$foo = \Drupal::request()->get('guide');

```

---
Tags: 8
---


# Question
Title: How do I create a download link from data in memory?
I need to create a Controller that serves data as a download when accessed. That file is not in the file system but in memory; that's why I need a Controller instead of just serve file.

How do I create a download link from data in memory?

# Answer
> 8 votes
My approach is to use a Symfony Response obejct as explained here: The HttpFoundation Component: Serving files.

Firts setup the routing:

```
mymodule.download_item:
  path: '/myitems/{item_id}/download'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::downloadItem'

```

So the controller looks like:

```
class MyController extends ControllerBase {
 public function downloadItem($item_id) {

    $fileContent = functionToObtainExternalContent($item_id);
    $response = new Response($fileContent);

    $disposition = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.txt'
    );

    $response->headers->set('Content-Disposition', $disposition);

    return $response;
  }
}

```

---
Tags: 8
---


# Question
Title: hook_menu URL giving 404 error on running site randomly
I have a hook\_menu URL exposed as a URL and I am also calling the same callback function separately in code The URL returns 404 at error at sometimes and starts working fine after a cache clear. What could be the possible issue ? hook\_menu Implementation

```
  $items['test_link/get-response'] = array(
    'title' => t('Get Response'),
    'page callback' => 'get_response',
    'page arguments' => null,
    'access callback'   => true, // available to all
    'type' => MENU_CALLBACK,
  ); // end

function get_response($funParams=array(),$res='json'){
  $allParams = drupal_get_query_parameters($_GET);
  if(isset($funParams['pincode']))
  $allParams=$funParams;

  $result = array();
  $result["status"] = TRUE;

  // Processing on allParams and builds the response array
  return displayJSONResponse($result,$res);
}

function displayJSONResponse($response,$res='json'){
    if($res=='nojson')
        return $response;
    $res = '';
    if(defined('JSON_PRETTY_PRINT'))
    $res = json_encode($response, JSON_PRETTY_PRINT);
    else
    $res = json_encode($response);
    $json = str_replace('\\/', '/', $res);
    echo $json;
    exit;
}

```

# Answer
Page arguments, if specified, should always be an array. If you do not want to pass any arguments to your callback you should either code an empty array or omit the parameter. From experience I am fairly confident that this is your problem.

Also, the correct way to return a JSON response is to return NULL from your callback after printing the JSON, rather than exiting. This ensures that cleanup tasks can be run.

Your code does not comply with Drupal standards, and I would strongly advise you to follow them. It's a major part of learning to work with the framework. https://www.drupal.org/docs/develop/standards
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: How to make user picture editable without opening edit profile page?
I wanted to allow users to edit profile without going to edit profile page. I found few useful modules like Editable field and Editable fields as link. These modules provide field formatter which make the field editable without leaving the page except the user picture. I am not able to use this technique with user pictures because It is not a normal field as other fields.

How can I make user picture an editable field without going to edit profile page?

**Note: I have created a custom profile page using panels. There is a module Picture Changer which allows users to change picture in a modal, but it does not work with panels.**

# Answer
You would have to write your own form where a user can upload the picture and save it as profile picture.
> 0 votes

---
Tags: 7, users, entities, media, panels
---


# Question
Title: Why doesn't the pagination work for a comment type, but it works for the other one?
I have a custom content type with multiple comment types.

1. Query comments
2. Discussion comments

I set the pagination limit for the both the comments as 10. The node detail page, when the number of comments exceeds 10, shows the pagination. For the discussion comments, only 10 comments are shown, even if they are more; no pagination is shown.

Why does this happen?

# Answer
If you have more than one listing on a page, the pager ID for each needs to be different. This applies to views, but also comment lists.

The way to change this is under your content type's display settings (`admin/structure/types/manage/MYTYPE/display`). For the comment fields, click on the gear icon and you should see this configuration option:

So long as each comment type uses a different ID, the pagers should work independently of each other.
> 2 votes

---
Tags: 8, comments
---


title: Restructure Language Prefix

text:
# Question
Title: Restructure Language Prefix
I'm building an international site and am running into trouble with the language detection. I need to have urls structured like the below examples for SEO purposes, but nothing I've found will allow for that. I wrote a little module that hooked into pathauto to prepend the code to the alias, but it didn't seem to be recognized... I'm using Organic Groups and Domain Access to manage the multiple countries, and Entity Translation and i18n for the languages. I also have Global Redirect in place to help keep out duplicate content links. One requirement is that for some countries the default language should not be prefixed at all.

Has anybody had experience with urls like this? It seems like it should be possible without hacking into the core...

```
Country     |   Language    |   URL

Austria     |   German      |   www.domain.com/at
Belgium     |   Dutch       |   www.domain.com/nl-be
Belgium     |   French      |   www.domain.com/fr-be
Canada      |   English     |   www.domain.com/en-ca
Canada      |   French      |   www.domain.com/fr-ca
........
Global      |   English     |   global.domain.com/en
Global      |   French      |   global.domain.com/fr

```

# Answer
> 0 votes
I was able to accomplish this by creating a new language negotiation provider. It was mostly a matter of just copying the hooks and callbacks with only minor changes and a lot of trial and error. There wasn't much documentation that I could find on it... The only thing is that the first part of the url MUST be a language, though it can also be a directory.

# Answer
> 0 votes
I'm currently working on a project that needs to achieve the exact same URL-structure as you mention in your question.

Below you'll find what I have so far. If you could let me know of any pitfalls you experienced that would be awesome!

* all content-types get a country-field that saves the target country (just a simple drupal.org/project/country field. no OG or anything fancy)
* my pathauto-pattern for all content is something like this: \[ISO-country-code\]/\[node-title\]
* all content can be translated into all available languages (for now: Dutch, Vlamish (nl\_be), English and French)
* I wrote a small module that uses hook\_url\_\*_alter
* I hade to change the module weight to something very high (99) so my url\_\*_alter hooks are being called AFTER locale\_url\_outboud\_alter from locale.module

This is my module code:

```
function flexas_cypaths_url_inbound_alter(&$path, $original_path, $path_language){
    $args = explode('/', $path);
    if(preg_match('/^([a-z]{2})_([a-z]{2})/', $args[0], $matches)) {
        $args[0] = $matches[1];
        $new_path = implode('/', $args);
        if($internal_path = drupal_lookup_path('source', $new_path, $matches[2])){
            $path = $internal_path;
        }
  }
}

function flexas_cypaths_url_outbound_alter(&$path, &$options, $original_path){
    $args = explode('/', $path);
    $c_list = array('nl','en', 'be');
    $system_paths = array('admin', 'user', 'sites', 'system', '<front>', '', 'js');
    $exclude_paths = array('node/add', 'sitemap');
    if (in_array($args[0], $system_paths) || strposa($path, $exclude_paths)) {
        // do nothing;
    }else if (in_array($args[0], $c_list) == false) {
        $country_prefix = '';
        $lang = NULL;
        if(isset($options['language'])){
            $lang = $options['language']->language;
        }
        if($alias = drupal_get_path_alias($path, $lang)){
            $alias_args = explode('/', $alias);
            if(preg_match('/^([a-z]{2})$/', $alias_args[0], $matches_first)){
                $country_prefix = $alias_args[0] . '_';
                array_shift($alias_args);
                $path = implode('/', $alias_args);
                $options['alias'] = 1;
            }
        }
        if(isset($options['prefix']) && !empty($options['prefix'])){
            $options['prefix'] = $country_prefix . rtrim($options['prefix'], '/') . '/';
        }
    }
}

function strposa ($haystack, $needles) {
    $bool = false;
    foreach ($needles as $needle) {
        if (strpos($haystack, $needle) !== false) {
            $bool = true;
        }
    }
    return $bool;
}

```

---
Tags: path-aliases, i18n-l10n
---


title: Get arguments from a view

text:
# Question
Title: Get arguments from a view
I have a view object and I'd like to get the contextual filters that were passed to it.

I have this tidbit of code that prints out the arguments field name.

```
if (!empty($view->argument)) {
  foreach ($view->argument as $id => $arg) {
    print $arg->field;
  }
}

```

I'm trying to get the values of those fields.

# Answer
`$view->args[0]` returns the first argument.
> 10 votes

# Answer
A dynamic solution:

```
foreach ($view->argument as $id => $arg) {
  $pos = $arg->position;
  print $view->args[$pos];
}

```
> 5 votes

# Answer
For Drupal 8 I've used such variant based on the answers above.

```
foreach ($view->argument as $arg) {
    if ($arg->getPluginId() != 'node_nid') {
      continue;
    }
    $node = Node::load($arg->getValue());
    break;
}

```
> 1 votes

# Answer
Maybe you could use:

```
$info = $view->get_items($type);

```

Where $type is some type from here: https://api.drupal.org/api/views/includes%21view.inc/function/views\_object\_types/7

Probably for your case could be:

```
$contextual_filters = $view->get_items('argument');

```

Ahother option could be to target a specific contextual filter for performing some alterations (i.e. hook\_views\_whatever): In that case you could probably use:

```
$my_filter = $view->get_item($display_id, $type, $id);

```

Perform whatever you want to do with that filter, and then:

```
$view->set_item($display_id, $type, $id, $my_filter);

```
> 0 votes

---
Tags: views
---


# Question
Title: How can I detect whether the install process is running?
I'm looking for a way to reliably detect whether Drupal's install process is currently running, either via `drush site-install` or `install.php`.

The immediate problem I'm trying to solve is that I have some settings (using Redis as cache backend) in `settings.php` which cause the installation to fail. So I'd like to wrap that block of settings in something like `if (!drupal_installation_is_currently_running()) { … }`

I have not managed to figure out how that can reliably be determined. Any suggestions?

# Answer
You're probably looking for `drupal_installation_attempted()`:

> Returns TRUE if a Drupal installation is currently being attempted.
> 4 votes

# Answer
I think I found a solution:

```
if (defined('MAINTENANCE_MODE') && constant('MAINTENANCE_MODE') === 'install')

```

If null, or another value, then not in install mode. Unfortunately, there is some code that executes before the install.php redirect is triggered. So you might still run into problems before the `define('MAINTENANCE_MODE', 'install');` is called inside of install.php.

This solutions is working well for me in that it allows me to set `$conf['preprocess_js'] = true` when `$_SERVER['PANTHEON_ENVIRONMENT']` equals 'test' or 'live'.
> 1 votes

---
Tags: 7, installation
---


# Question
Title: How do I get the title of an entity in hook_entity_presave?
I am trying to get the title of an entity and I can do a dsm of the $entity, but when i do a dsm of $entity-\>values , nothing shows up.

# Answer
If the entity is a node, you can do:

`$entity->getTitle();`

Or:

`$entity->get('title')->value;`

Here are a list of methods for the Entity object, and for the Node object.
> 9 votes

---
Tags: 8, entities
---


# Question
Title: How to print a block inside the node body?
I need to insert a block(webform) inside basic page nodes (wysiwyg body). How can do it?

# Answer
Try to use Insert Block module. It has Drupal 8 version
> 2 votes

# Answer
Webform have an option to display it in a block. You dont need an additional module for that. Once you configure it to display as block you can assign it to region based on your requirement.
> 0 votes

# Answer
Don't use a webform block, this is when you want to place a webform in the block layout. What you need is a content type with a webform field. Install the submodule

> **Webform Node**
>
> Provides a Webform content type which allows webforms to be integrated into a website as nodes.

this is an example for such a content type.
> 0 votes

---
Tags: 8
---


# Question
Title: Migration query works but migration fails due to sourceid not being found
Here is my migration class:

```
class TaxonomyPrice extends SqlBase {
  /**
   * {@inheritdoc}
   */
  public function query() {
    $table1 = $this->select('venue', 'v')
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->fields('v', ['price']);

    $table2 = $this->select('item', 'i')
      ->fields('i', ['price'])
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->union($table1);

    $table3 = $this->select('nodes_venues', 'nv')
      ->fields('nv', ['price'])
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->union($table2);

    return $this->select('sc_article', 'sca')
      ->fields('sca', ['price'])
      ->isNotNull('price')
      ->condition('price', '', '!=')
      ->groupBy('price')
      ->union($table3);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {

    $fields = [
      'price' => t('Term name'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'price' => [
        'type' => 'string',
      ],
    ];
  }
}

```

When I run `drush ms` I can see the correct number of items being counted.

```
$ drush ms taxonomy_price
 Group: Taxonomy Migrations  Status  Total  Imported  Unprocessed  Last imported
 (taxonomy_migration)
 taxonomy_price                Idle    121    0         121

```

But when I try to run the migration it gives me an error related to the sourceid.

```
$ drush mi taxonomy_price
Migration failed with source plugin exception: SQLSTATE[42000]: Syntax error or access violation: 1055     [error]
'drupal_8.map.sourceid1' isn't in GROUP BY: SELECT sca.price AS price,
map.sourceid1 AS migrate_map_sourceid1, map.source_row_status AS migrate_map_source_row_status
FROM
{sc_article} sca
LEFT OUTER JOIN drupal_8.migrate_map_taxonomy_price map ON price = map.sourceid1
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_0) AND( (map.sourceid1 IS NULL ) OR
(map.source_row_status = :db_condition_placeholder_1) )
GROUP BY price UNION SELECT nv.price AS price
FROM
{nodes_venues} nv
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_2)
GROUP BY price UNION SELECT i.price AS price
FROM
{item} i
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_3)
GROUP BY price UNION SELECT v.price AS price
FROM
{venue} v
WHERE  (price IS NOT NULL ) AND (price != :db_condition_placeholder_4)
GROUP BY price; Array
(
    [:db_condition_placeholder_0] =>
    [:db_condition_placeholder_1] => 1
    [:db_condition_placeholder_2] =>
    [:db_condition_placeholder_3] =>
    [:db_condition_placeholder_4] =>
)

```

I read through the documentation for `getIds()`, but I didn't see anything there that would help me figure out what's wrong.

# Answer
The relevent part of the error message is "'drupal\_8.map.sourceid1' isn't in GROUP BY". Let's look at the query as executed:

```
SELECT sca.price AS price,
map.sourceid1 AS migrate_map_sourceid1, map.source_row_status AS migrate_map_source_row_status
...
GROUP BY price

```

SQL requires that all columns being selected be part of the GROUP BY. The SqlBase class has determined that your source query can be joined directly to the migration's map table, and thus performs the join as an optimization, adding the map table fields to the columns returned. However, it doesn't add them to the GROUP BY. There's an issue for that: https://www.drupal.org/node/2844595. For now, you can set

```
ignore_map: true

```

in your source plugin's configuration to prevent the join and it will work.
> 1 votes

---
Tags: 8, database, migrations
---


# Question
Title: How do I get a list of all taxonomy terms assigned to a node?
I have a node and want to get all the taxonomy terms assigned to the node.

In drupal 6 I could use `$node->taxonomy` and the `taxonomy_*` functions but these don't exist in drupal 7.

# Answer
> 21 votes
Taxonomy terms are implemented in fields in Drupal 7. Assuming you have defined a taxonomy field named field\_category for your content type, you can access it as:

```
$language = 'und'; // or will be provided by some Drupal hooks
foreach ($node->field_category[$language] as $delta => $value) {
  $term = taxonomy_term_load($value['tid']);
}

```

If you don't have access to the field name, probably the easiest way *for nodes* is to query the database directly:

```
$results = db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid', array(':nid' => $node->nid));
foreach ($results as $result) {
  $term = taxonomy_term_load($result->tid);
}

```

Keep in mind though, that you may end up dealing a jumble of terms from different vocabularies if you have more than one taxonomy field.

# Answer
> 2 votes
Here's a very generic way to grab all terms without specifying field names and no db\_query:

```
function example_get_terms($node) {
  $terms = array();

  foreach (field_info_instances('node', $node->type) as $fieldname => $info) {
    foreach (field_get_items('node', $node, $fieldname) as $item) {
      if (is_array($item) && !empty($item['tid']) && $term = taxonomy_term_load($item['tid'])) {
        $terms[] = $term->name;
      }
    }
  }
  return $terms;
}

```

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