# Question
Title: How to limit the products available to choose from, in the inline entity form of a product display
Drupal Commerce, when adding/editing a product display, allows for the creation of new products and the selection of existing products, using the inline entity form.

I have created a marketplace website in which multiple sellers can create their products and product displays.

*Question: how to limit the available products to those created by the logged in user? When a seller creates or edits a products, he should be able to only select his own products in he 'add existing product' field.*

I would have expected that the field would allow for the selection of an entityreference view, but that seems not implemented in the module.

Alternatives to accomplish the same are welcome! Thanks

# Answer
> 1 votes
When you are adding an existing product to a product display there is an autocomplete field that you can use to search existing products.

This field is called entity\_id. If you use `hook_form_alter()` and inspect the form you'll see this field has a property called `#autocomplete_path`.

e.g.

```
$form['product_display_variations'][LANGUAGE_NONE]['form']['entity_id']['#autocomplete_path'] = 'inline_entity_form/autocomplete/node/product_display_variations/product_type';

```

You can visit that URL and see it just returns a set of json formatted results.

You can create your own path with `hook_menu()` and then use your path instead of the default one (make this change in hook\_form\_alter).

In your custom menu callback you can apply any additional logic (e.g. filtering by uid) to just return a sub-set of products. Then use drupal\_json\_output() to return your dataset.

---
Tags: 7, commerce, entities
---


# Question
Title: How To Create 'Node 1 vs Node 2' 'Node 1 vs Node 3' nodes etc as quickly as possible to compare their fields?
I want to create a node for each comparison of 2 nodes, so you end up with site.com/node-1-vs-node-2 and then on that page it shows both the node 1 and node 2 fields side by side in a table to compare them.

What am i looking at to get this done as quickly as possible? I have 50 nodes in total and want to do node 1 vs node 2, node 1 vs node 3, node 1 vs node 4, etc all the way through.

Would it be views, or entity reference which shows a table format for each output?

I'm using Drupal 8

# Answer
> 2 votes
You could achieve this quite easily with a custom module. In this example I'll use Drupal console to simplify settings every thing up.

1. Create a module:

drupal generate:module

Call it whatever you want.

2. Create a controller:

drupal generate:controller

Sample answers for this may be:

* Controller class name: ComparisonController
* Method title: CompareNodes
* Action method name: compare\_nodes
* Route path: test/compare\_nodes/{id1}/{id2}

Now edit your newly created controller. At the top add a use for the node module:

```
use Drupal\node\Entity\Node;

```
3. Edit the compare\_nodes method.

Here is some sample code:

```
public function compare_nodes($id1, $id2) {

  $node1 = Node::load($id1);
  $node2 = Node::load($id2);

  $fields_to_compare = ['body'];

  $build = [];

  foreach($fields_to_compare as $field) {
    $build['comparisons'][$field] = [
      '#type' => 'container',
    ];
    $build['comparisons'][$field]['value1'] = [
      '#markup' => 'Node 1 value: ' . $node1->get($field)->value,
      '#prefix' => '<div>',
      '#suffix' => '</div>',
    ];
    $build['comparisons'][$field]['value2'] = [
      '#markup' => 'Node 2 value: ' . $node2->get($field)->value,
      '#prefix' => '<div>',
      '#suffix' => '</div>',
    ];

  }

  return $build;

}

```

You can edit the list of fields to compare as required and also make any changes to the markup required.

Enable your module and now when you visit: `/test/compare_nodes/1/2` you can compare the values of node 1 with node 2.

You can replace 1 and 2 with whatever ids you would like to compare.

# Answer
> 1 votes
Assumptions

* Node 1 is always the first target of comparison.
* Nodes 2 to 50 are the "other" node.

If you actually want to create nodes to be the "vs" nodes, you need to use Entity Reference-- views alone can't create nodes.

Make a "vs" content type. Add two entity reference fields.

* Field 1- "Node 1" (set the default value of the entity reference to node 1)
* Field 2- "Other node"

Then create the 50 nodes by quickly referencing each node in order. This is a little painful but shouldn't take too long for just 50 nodes.

Now you need to create the display for these "vs" nodes that shows the comparison table. This you can use Views for-- create a View (of content: vs content type) page that overrides the path of the "vs" node. Use a contextual filter to grab the vs node ID, and then attach relationships to each entity reference.

Then you can build the comparison table in Views with the node fields.

*This is not an exact step-by-step list, but should give you a general idea of what you need to do.*

---
Tags: nodes
---


# Question
Title: How do I redirect users after they submit a form?
How do I redirect users after they submit a form? I tried the following code, but it doesn't work. It says the route doesn't exist.

```
public  function submitForm(array &$form, FormStateInterface $form_state){
   $url = Url::fromRoute('/mon-profil/obtenir_document'); // == /node/1
   $form_state->setRedirectUrl($url);
}

```

# Answer
> 0 votes
You are using the wrong method: `Url::fromRoute()` is expecting the route name, as Kevin said.
If you really need to use a path alias, which would allow you to change the redirect without editing your code (which would keep referring the same path alias), you need to use `Url::fromUserInput()` that accepts a path starting with /, which also include a path alias, if you remember to add a slash at the beginning.

As side note, if you want to redirect users using a route, you don't first need to get a `Url` object: Use `FormState::setRedirect()`, which accepts a route name.
Using a route (for example the one used by Kevin's example), your code would become the following one.

```
public  function submitForm(array &$form, FormStateInterface $form_state){
   $form_state->setRedirect('entity.node.canonical', ['node' => 1]);
}

```

In my example, I hard-coded the node ID, but real code would probably get it in a different way. For example, the module could create a node, store its node ID using the state API, and use the state API to retrieve it.

# Answer
> 2 votes
You're getting that error because `fromRoute()` takes the route name as the argument, not a literal path.

Assuming you know the node id you want to redirect to:

```
$url = Url::fromRoute('entity.node.canonical', array('node' => $node_id));

```

You don't ever want to redirect to internal paths like that (in your question) because they are subject to change.

---
Tags: forms, redirection
---


# Question
Title: How to sort view using already sorted array in hook_views_query_alter
I have the following code to alter a view and filter IN only specific nodes

```
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if($view->id() == 'myview'){
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == "node_field_data.nid") {
          $condition = array(
            'field' => "node_field_data.nid",
            'value' => [2,4,6,1,3,5],
            'operator' => 'in',
          );
          break;
        }
      }
    }
    //this does not work
    //$query->addOrderBy('node_field_data','nid', 'ASC', '', [2,4,6,1,3,5]);
  }
}

```

and I want to sort them with this specific order `[2,4,6,1,3,5]`

I tried not putting any sorting field but the view sorts the nodes by created date. How can I tell the view to sort them in this manner ?

I think I need to use `ORDER BY FIELD('node_field_data'.'nid','2','4','6','1','3','5')` in sql but I don't know how its done in drupal

I have seen this answer but don't know how it applies to my case

any help would be appreciated

# Answer
OK I figured it out

```
$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,2,4,6,1,3,5)', 'ASC', 'order_field');

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: Composer not working all of a sudden with MAMP v3.5
For a couple of days now I have trouble using composer. It keeps throwing these errors when downloading a new package, yet a few weeks ago I used composer without a problem.

I have not upgraded anything, not composer, not PHP or anything else, so I cannot say what the problem is.

I simply want to download the devel module via `composer require drupal/devel`

but then this happens:

```
The "https://packages.drupal.org/8/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Failed to enable crypto
failed to open stream: operation failed
https://packages.drupal.org/8 could not be fully loaded, package information was loaded from the local cache and may be out of date
Using version ^1.0 for drupal/devel
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
The "https://packages.drupal.org/8/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Failed to enable crypto
failed to open stream: operation failed
https://packages.drupal.org/8 could not be fully loaded, package information was loaded from the local cache and may be out of date
Updating dependencies (including require-dev)

Installation failed, reverting ./composer.json to its original content.

  [Composer\Downloader\TransportException]
  The "https://packages.drupal.org/8/drupal/chosen%2443436dc3d5791cbc3bb366ffeca450e3265c4cbbc1507b404d68ec9bf9d68c4d.json" file could no
  t be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
  error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
  Failed to enable crypto
  failed to open stream: operation failed

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

```

I saw this post Getting errors in drupal console while installing commerce module via Composer in localhost which has been marked as a duplicate but with no reference to the solution

Using MAMP Pro v3.5 Composer version: 1.5.2 Mac OS: 10.12.6

Does anybody have an idea?

# Answer
> 0 votes
I was able to solve this problem by updating MAMP vom v3.5 to the newest 4 version.

As Mohammad AlQanneh has stated, it has to do with the problem of an old OpenSSL. Pretty much all PHP versions of MAMP v3.5 are bundled / compiled with OpenSSL 0.9.8 and that does not support TLS or the encrypted connection which Drupal's packagist is using.

Upgrading the system's OpenSSL version (for example through brew.sh) does not work, because the old OpenSSL version is compiled with PHP.

# Answer
> 0 votes
Problem should b solved after updating openssl to latest version. Check: This Issue

---
Tags: composer
---


# Question
Title: How do I avoid mydomain.com/node/1 or mydomain.com/node/4 is used?
I am using the Pathauto module for creating user-friendly and SEO-friendly URLs. Therefore, I do not want and there is no need that the "old URL" like mydomain.com/node/1 or mydomain.com/node/4 is any longer public. So, how do I hide this and make only the path aliases public?

# Answer
> 0 votes
You need to create patterns for pathauto and go back to those nodes and save them, ensuring “generate new alias” is checked off on the node form.

# Answer
> 0 votes
I solved the problem using the Redirect Module. It comes with three modules. I enable the Redirect Module and the Redirect Domain Module. Then I create in tab Domain Redirect a redirect from subdomain /node/\* to front-page (using alias of front-page). It works and this solution is ok for me.

---
Tags: 8, path-aliases
---


title: Reloading module's services.yml

text:
# Question
Title: Reloading module's services.yml
I am trying to reload the .services.yml file of a custom module without having to reinstall the module.

Is there a Drush command or another way to achieve this? Does `drush cr` also clear the services.yml files information? It's really hard for me to tell.

# Answer
Ok. After testing and more research "drush cr" does the job. Service.yml is reloaded after clearing the cache.
> 1 votes

---
Tags: 8
---


# Question
Title: How to load translated entity values in Twig for SEO purpose?
How can I get access for the english values of my entity in the french version of my twig template. This is for a tracking task.

Let say I want to print the node title en english on the french version.

I was hoping I could do something like this : `{{ node.languages.en.label }}` but this doesn't work.

I'd rather avoid using preprocess if possible (I know how to do it with preprocess).

# Answer
You can get the translated node with getTranslation():

```
{% if node.hastranslation('en') %}
  <p>{{ node.translation('en').title.value }}</p>
{% else %}
  <p>No translation<p/>
{% endif %}

```

If you are not sure that the translation exists, check first with hasTranslation(), because a missing translation throws an exception.
> 4 votes

---
Tags: theming, 8, i18n-l10n
---


title: Print image with alt text

text:
# Question
Title: Print image with alt text
In the node template, I print an image gallery. I need to add the *alt* text.

```
<div class="field--name-field_gallery">
  {{ content.field_gallery }}
  {{ content.field_gallery.alt_field }}
</div>

```

There are many images, which are printed, but the *alt* text is not printed.

How can I print it?

# Answer
Print the image field in the node template like any other field:

`{{ content.field_gallery }}`

And then use a field twig to loop through multiple field items:

field--field-gallery.html.twig

```
 <div class="row expanded">
  {% for item in items %}
     {{ item.content }}
     {{ item.alt }}
    {% endfor %}
  </div>

```
> 0 votes

---
Tags: theming, 8, media
---


title: bartik subtheme and css

text:
# Question
Title: bartik subtheme and css
I want to make some modifications to the bartik theme i am using D8 (like changing the logo position,etc) i created a subtheme named it "mytheme" following the instruction i found here:

https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme

So, first I created the mytheme.info.yml file containing:

```
name: mytheme
type: theme
base theme: bartik
description: subtheme for bartik
core: 8.x
libraries:
  mytheme/global-styling
regions:
  header: Header
  primary_menu: 'Primary menu'
  secondary_menu: 'Secondary menu'
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  highlighted: Highlighted
  featured_top: 'Featured top'
  breadcrumb: Breadcrumb
  content: Content
  sidebar_first: 'Sidebar first'
  sidebar_second: 'Sidebar second'
  featured_bottom_first: 'Featured bottom first'
  featured_bottom_second: 'Featured bottom second'
  featured_bottom_third: 'Featured bottom third'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_fourth: 'Footer fourth'
  footer_fifth: 'Footer fifth'

```

Next i created the mytheme.libraries.yml containing the following:

```
global-styling:
  css:
    theme:
      css/style.css: {}

```

i went to appearance and enabled "mytheme" as default, went back to site, looks identical to how bartik was so far so good

my problem now is, how do i move on with the customizations i want to do?

i created a folder called: "css" in "mytheme" directory, inside the css folder i created a blank file called "style.css" and there i wrote the first modification i want to do

```
.region-header .site-branding {
    float: none;
    text-align: center;
}

```

When i go back to site i see no difference, the logo remains on the left like it was on bartik

Can somebody help please?

I am not sure how to proceed and if what I did by creating a css folder, etc is the right way.

Thank you.

# Answer
> 1 votes
Not sure if this is still relevant or not but I was having the same issue and I was just missing a dash.

> libraries:
> mytheme/global-styling

to

> libraries:
> \- mytheme/global-styling

---
Tags: theming, 8
---


title: Define permissions for Actions?

text:
# Question
Title: Define permissions for Actions?
```
function custom_mod_action_info() {
  return array(
    'custom_mod_delete_user_cats' => array(
      'label' => t('Delete a users cats'),
      'type' => 'user',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

```

This action is later used as VBO in a View.

I've defined an action like above in a custom module. How can I set some permissions so only users with a specific role can run this action?

# Answer
> 0 votes
For D7, I can see two answer depending on what behaviour you prefer:

1. VBO has a sub-module action permissions. Enable this and it creates a permission for each action - see module page. If the user lacks permission then the action is not even available for them.
2. If you need more granular permission that depends on the entity, then the "function which performs the action" can enforce it. For example see `views_bulk_operations_user_roles_action`. If the user lacks permission for some of the entities then the action won't take effect for those entities. However there is typically not really any feedback to tell the user.

For D8, there is `ActionInterface::access`, see docs.

---
Tags: users, views, actions
---


# Question
Title: Using .tpl.php templates instead of Twig templates
Is there a way to use .tpl.php templates instead of Twig templates in Drupal 8, or is there a way to write PHP in a Twig file instead of that Twig language?

I am a beginner for Drupal 8, but I have worked with Drupal 7.

# Answer
> 3 votes
You don't need to write PHP in twig files. Twig is fairly expressive to the degree in which you need to template, for everything else, it should go into the .theme file, theme hook, and/or preprocess function.

There is virtually no reason to have PHP code in a template.

Spend a week with Twig and you won't go back.

Example:

```
<?php if ($page['content']): ?>
  <?php print render($page['content']); ?>
<?php endif; ?>

```

vs:

```
{% if page.content %}
  {{ page.content }}
{% endif %}

```

Much more readable.

I'll expand with a more advanced example.

Lets say you have list of things you want to output, but every 7 items, you want to make a new unordered list. The end goal is the CSS inlines these lists, think of a superfish menu where menu links are ordered top to bottom, then left to right.

```
  <div class="global-top__submenu">
    {% for chunk in items|batch(7) %}
      <ul class="global-top__submenu-col">
        {% for item in chunk %}
          <li>
            {{ link(item.title, item.url) }}
          </li>
        {% endfor %}
      </ul>
    {% endfor %}
  </div>

```

Where `items` is passed to the template. This small example will output a UL with 7 items until there is nothing left to print.

I have yet to run into an instance where I *cannot* accomplish something with Twig, or, *because* it's Twig.

Give it a shot and dive in, forget phptemplate.

# Answer
> 2 votes
To use custom PHP and display the result in a template, you must go through preprocessing functions (like `hook_preprocess_node()`) to override the display or add new variables to display in your template. You can create a custom module or use the MYTEHEME.theme file of your current theme to call preprocessing function.

If before you used a lot of PHP code in TPL files, it's bad practice because the files are used to display the data not to make hard particular/specific treatments inside.

---
Tags: theming, 8
---


# Question
Title: Programmatically modifying global custom text field in view
I have a (Apache solr) view with a `Global: Custom text` field in addition to my normal fields. This field is meant to get value from a custom function/existing field/passing an existing field to a custom function and using return value in one of my modules per each result and I am trying to accomplish this functionality without using Views PHP module.

I referred this very similar query and tried the following approach which did not yield me the result:

`hook_views_pre_render`:

```
function mymod_views_pre_render(&$view) {
  if ($view->name == 'mymodview' && $view->current_display == 'mymod_display') {
    $result = &$view->result;
    foreach ($result as $num_idx => $result_obj) {
      $result[$num_idx]->nothing = $result_obj->an_already_available_field_or_fxn_call;
    }
  }
}

```

Also tried the same code with `hook_views_post_execute` to no avail. Using `$view->field['nothing']->options['alter']['text'] = 'My custom text';` set the default text value to all fields which was not my desired result.

Based on the post linked earlier tried the following code in my theme's template.php

`template_preprocess_views_view_fields`:

```
function mytheme_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  if ($view->name != 'mymodview' && $view->current_display != 'mymod_display') {
    return;
  }
  foreach ($view->field as $id => $field) {
    $vars['fields']['nothing']->content = 'Some global custom text content';
  }
}

```

I am unable to determine what I am missing out on owing to my relative inexperience with views functionality and guidance on achieving this programatically would be much appreciated.

# Answer
> 0 votes
have you tried to use a custom handler? This way you don't need to override nothing.

Related to: Move php in views to module

# Answer
> 0 votes
If you are trying to change the value of the global text is quite simple. You have to use the one of the views hook.

```
function YOUR_MODULE_views_post_execute(&view)
{
   // You can change the value like this, if you have mutliple result you might want to wrap this inside a foreach loop.
   $view->field['nothing']->options['alter']['text'] = 'updated via php';
}

```

---
Tags: 7, views
---


# Question
Title: Same as shipping checkbox in admin is not showing
While creating an order from Drupal admin section, "Same as shipping" checkbox is not showing, but for normal checkout it is showing.

How do I show the checkbox in the administrative page?

# Answer
I'm guessing this checkbox is meant to copy the address from the billing address to the shipping address?

As Ryan pointed out on the frontend this will require ajax as the shipping and billing profiles could be on different steps, however on the backend they are both on the same page so all that is required is some javascript.

For example...

Add the checkbox and custom javascript to the page in a hook\_form\_alter:

```
/**
 * Implements hook_form_FORM_ID_alter() for commerce_order_ui_order_form.
 */
function MY_MODULE_form_commerce_order_ui_order_form_alter(&$form, &$form_state, $form_id) {

  // Add the checkbox
  $form['commerce_customer_billing'][LANGUAGE_NONE]['profiles'][0]['copy_from_shipping'] = [
    '#type' => 'checkbox',
    '#title' => t('Copy address from shipping'),
    '#attributes' => ['class' => ['copy-address-from-shipping']],
  ];

  // Attach our custom js
  $form['#attached']['js'][] = drupal_get_path('MY_MODULE', 'taronga') . '/js/copy-address-from-shipping.js';

}

```

And then for the javascript:

```
(function($) {

    /**
     * The Drupal behaviors to copy address from shipping to billing on admin order edit page.
     */
    Drupal.behaviors.copyShippingAddress = {
        attach: function(context) {

            // Only bind our click event handler once
            $('.copy-address-from-shipping').once(function(){

                // Bind the click event
                $('.copy-address-from-shipping').click(function () {

                    var $shipping = $('#edit-commerce-customer-shipping-und-profiles-0');
                    var $billing = $('#edit-commerce-customer-billing-und-profiles-0');

                    if($(this).is(':checked')) { // Copy values from shipping

                        // Loop over inputs & select in shipping fieldset
                        $shipping.find('input, select').each(function () {
                            // Skip any inputs without a name attribute (e.g. chosen)
                            if($(this).is('[name]')) {
                                // Get the name of this field and convert it to the billing name
                                var billing_name = $(this).attr('name').replace('shipping', 'billing');
                                var $billing_field = $billing.find('[name="' + billing_name + '"]');
                                // Make sure the billing field exists
                                if($billing_field.length) {
                                    // Replace the value
                                    $billing_field.val($(this).val());
                                }
                            }
                        });

                    }
                    else { // Clear values

                        $billing.find('input, select').each(function(){
                            $(this).val('');
                        });

                    }
                });

            });

        }
    };

})(jQuery);

```
> 1 votes

# Answer
Make sure to specify whether you're using Drupal 7 or Drupal 8 in your questions, as the feature sets in the Commerce modules do diverge. That said, in either case, this functionality is currently not possible. I doubt it will be added in Drupal 7 given the constraints of how the checkbox was implemented to be unique to the checkout form, but look for address book support on the back end in Commerce 2.x as soon as we resolve some tricky profile select element issues.
> 0 votes

---
Tags: commerce
---


# Question
Title: Panel frontpage overrides site front page after migration
I have migrated an old Drupal 6 site to Drupal 8.

On the old site I used a panel page as a front page.

Now on the new site there is no way to change this path.

No matter what I put in the "default front page" form on the "Basic site settings" page the front page keeps linking to the old panel node. And if I delete all panel nodes and the panel module itself I get a 404.

So I'm guessing this is some weird variable stored in the database but I have not been able to locate it. Any ideas?

# Answer
Managed to solve it by rolling back the "\***_d6\_i18n\_system\_site" So this seems to be some kind of hiccup between the panels and i18n migrations.
> 0 votes

---
Tags: migrations, panels
---


title: "Unpublish content" doesn't work

text:
# Question
Title: "Unpublish content" doesn't work
I have a content type 'company' which has a field: field-paid. This field is a integer list who only has 1 option: 'yes'

This is my export of my rule:

```
{ "rules_testv2" : {
"LABEL" : "Depublish when not paid",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_i18n", "rules_scheduler" ],
"ON" : { "node_update" : [] },
"IF" : [
  { "data_is" : { "data" : [ "node:type" ], "value" : "company" } },
  { "data_is" : { "data" : [ "node:field-lid-" ], "value" : "1" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_paid" } },
  { "data_is_empty" : { "data" : [ "node:field-paid" ] } }
],
"DO" : [
  { "drupal_message" : { "message" : "Testing" } },
  { "schedule" : {
      "component" : "rules_delete_company",
      "date" : 1508823060,
      "identifier" : "Unpublish node [node:nid]",
      "param_node" : [ "node" ]
    }
  }
]
  }
}

```

Now I've tried like this (without my component) but still not working:

```
 { "rules_testv2" : {
"LABEL" : "Depublish when not paid",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update" : [] },
"IF" : [
  { "data_is" : { "data" : [ "node:type" ], "value" : "company" } },
  { "data_is" : { "data" : [ "node:field-lid-" ], "value" : "1" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_paid" } },
  { "data_is_empty" : { "data" : [ "node:field-paid" ] } }
],
"DO" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

```

It unpublish all my nodes... But I have 2 nodes (for testing) that has value in 'field-paid' (checkbox) so normally those 2 nodes has to remain published...

# Answer
> 0 votes
There are multiple possibilities that may be causing your issue. So below is 1 hint for each of them to verify ...

### Hint 1:

To simplify your debugging, just for temporary unit testing, add a Rules Action (as the very first Rules Action) to "Show a message on a site", e.g to say 'Bingo, let the Rules party begin (we did find a combination of Rules Conditions to continue building on)'. This is much easier to do debugging then the ultimate set of Rules Actions you want to get to work.

### Hint 2:

Not sure if it is "the" reason why your rule doesn't work, but try to add an extra Rules Condition like ""entity has field" (for your `field-paid` field). And make sure this is added before any other Rules Condition in which you want to check the value of that field. The bets are open ...

### Hint 3:

As per your question, your `field-paid` field can only have value "yes" (or no value at all I assume). So replace your last Rules Condition (= "not empty") by a "data comparison" (to check if the value is NOT "yes", and note the NOT-negation here). Also note that after you applied hint 1, the "entity has field" will contradict your "not empty" (so both Rules Conditions can never be true together, so your Rules Conditions would never be executed).

---
Tags: rules
---


# Question
Title: Custom form not being validated on submission
So, I'm trying to implement a Salesforce generated Web-to-Case form on my Drupal site. I have implemented the form correctly so that it updates the Salesforce application cases, but for some reason the form doesn't get validated before submission. I have placed the form in a block with a custom module for portability and versatility. Here is the code for the form. Neither the required fields, nor my attempt to validate the form are enforced before submission. I'm pasting my code below stripped of extraneous fields to for demonstration.

```
function web_to_case_form($form, &$form_state){
  $form = array(
'#action' => 'https://webto.salesforce.com/servlet/servlet.WebToCase?encoding=UTF-8',
);
  $form['lastname'] = array(
  '#id' => '00N6A000009vWYv',
  '#name' => '00N6A000009vWYv',
  '#required' => TRUE,
  '#title' => t('Last Name'),
  '#type' => 'textfield',
  '#maxlength' => 30,
  '#size' => 20,
  );

   $form['maidenname'] = array(
  '#id' => '00N6A000009vWYM',
  '#name' => '00N6A000009vWYM',
  '#title' => t('Maiden Name'),
  '#required' => TRUE,
  '#type' => 'textfield',
  '#maxlength' => 30,
  '#size' => 20,
  );

  $form['email'] = array(
  '#id' => 'email',
  '#title' => t('Email'),
  '#name' => 'email',
  '#required' => TRUE,
  '#type' => 'textfield',
  '#maxlength' => 80,
  '#size' => 20,
  );

   $form['phone'] = array(
  '#id' => 'phone',
  '#title' => t('Phone'),
  '#name' => 'phone',
  '#required' => TRUE,
  '#type' => 'textfield',
  '#maxlength' => 80,
  '#size' => 20,
  '#element_validate' => array('element_validate_number '),
   );

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

function web_to_case_form_validate($form, &$form_state) {
  $email = $form_state['values']['email'];
  // Verify that the email address is valid.
  if (!valid_email_address($email)) {
    form_set_error('email', t('You must provide a valid email address.'));
  }
}

```

Is this because the form is being submitted to an external URL? If that's the case, how to I validate a form before submission? Otherwise, not sure what's going on here. I've even tried to add a validate element to one of the form elements, but that doesn't seem to work either.

# Answer
> 1 votes
> Is this because the form is being submitted to an external URL?

Yes, the submit handler for a form in your website won't be executed unless that form is submitted back to your website.

> If that's the case, how to I validate a form before submission?

If you mean server-side (non-JS) validation, and you want the user to continue on to the remote URL as if they'd submitted the form as normal, you can't. There's simply no way to do that.

If you don't need the user to be forwarded on to the remote URL after submission, and the remote website allows it, you could just send a POST request from the submit handler with the data you've received from the Drupal form submission.

If you're even luckier, they'll have an API you can use instead.

# Answer
> 0 votes
If anyone else runs into this problem Webform Remote Post does this painlessly.

---
Tags: forms
---


title: Import sub view to another view

text:
# Question
Title: Import sub view to another view
It's possible to export sub view and import it to another view? For example I have views "A" & views "B" and each one has sub views \[blocks - pages - ...etc\]. How to export sub view from A to B?

# Answer
You might be needing this module views\_field\_view to insert a sub view inside a view as a field.
> 0 votes

# Answer
Yes, how do you export a page view, into another page view so that it has 2 page views and they can share the same theme template?

Nevermind I don't think that would be possible because each view would have its own machine name and it doesn't look like there is a tpl suggestion that would work for 2 views. So not to hijack but is there any way to have more than one view share the same theme file?

OK so here is the solution I used:

https://www.drupal.org/project/views\_custom\_template

It does just what I need and probably you too.
> 0 votes

---
Tags: views
---


# Question
Title: Defining hook_menu() paths for specific base URLs
I have a multi-site; each site has its own database but they all share the same codebase. I would like to know if there is a way to define `hook_menu()` paths at specific base URLs.

Being it a multisite, I have created a common module used by all the sites. I wanted something like this in `hook_menu()`.

```
 if (base_url == 'wmc.en') {
   $items['wmc/contact-us'] = array('hook menu stuffs');
 }
 if (base_url == 'gmc.es') {
   $items['gmc/contact-us'] = array('hook menu stuffs');
 }

```

I tried this type of code, but `hook_menu()` doesn't seem to recognize `base_url` or `$_SERVER['SERVER_NAME']`.

Is it possible to achieve what I am trying to do?

# Answer
> 0 votes
In `hook_menu()` you can access `$base_url` (not `base_url`), if you first define it as global (i.e. putting `global $base_url` as first line of the function) or you access it as `$GLOBALS['base_url']`.

Keep in mind that `$base_url` doesn't just contain the domain name, but its content is similar to `'http://example.com/directory_where_drupal_is_installed/'`. If you want the domain name you get it with `parse_url($GLOBALS['base_url'], PHP_URL_HOST)`.

That said, I would not use wmc.en/wmc/contact-us and gmc.es/gmc/contact-us as routes, since the domain name makes already the difference between a route and the other one. I would rather use the domain name to execute different code.

```
if (parse_url($GLOBALS['base_url'], PHP_URL_HOST) == 'wmc.en') {
  // Show the contact form for this domain.
}
elseif (parse_url($GLOBALS['base_url'], PHP_URL_HOST) == 'gmc.es') {
  // Show the contact form for this domain.
}

```

# Answer
> 0 votes
If you want to use base url, you should first declare it as a global variable and then use it as $base\_url. You should also note that $base\_url will include the url scheme (i.e) http or https.

If you have a development or staging environment setup, your base url will probably differ between dev, stg and prod environments. In most of the cases, the production environment will be SSL enabled. So you may have to consider this as well while writing code.

In my opinion, as you have mentioned, you may use a different module and enable it only for the specific site. Or if you deliberately want it to be in a common module, consider using *access arguments* and define *hook\_permissions*.

---
Tags: 7, routes, multi-sites
---


# Question
Title: Override Another module's Template file using my Custom Module (Drupal 7)
**I'm willing to change the `user-profile-item.tpl.php` template provided by the `user` module.**

*I've created a new template file. Now my question is:*

1. Where do I put the new template `user-profile-item.tpl.php` template file? I've created a custom module, should I place it right in the custom module's directory?
2. Do I need anything to do so that Drupal picks up my template file instead of the default template file?

PS I got this link did not understand. Sorry I'm a newbie :(

**EDIT:**

I solved this using *preprocessors*, I figured out that I can use preprocessors easily without changing template file. I wrote following preprocessor in my module to achieve what I was looking for.

```
function MYMODULE_preprocess_user_profile(&$vars){
//    dsm($vars); // prints nice debugging information
    $vars['user_profile']['charity_link'] = array(
    '#markup' => l('Add Charity!', 'my/custom/link' . arg(1)),
    '#weight' => 10
    );
}

```

# Answer
I had to use the following snippet to get it to work. I think it may be due to the way I set up the original template.

```
<?php
//  unset the original template to set yours.

// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['template'] = drupal_get_path('module', 'MODULENAME') . '/TEMPLATE_TO_OVERRIDE';
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme path'] = drupal_get_path('module', 'MODULENAME');

}

```
> 3 votes

# Answer
This is easier to do in a custom theme.

As noted in the documentation, the registry keys for themes are set up in the following manner:

```
$theme_registry['user_profile'] = array(
  'variables' => array(
    'account' => NULL,
  ),
  'template' => 'modules/user/user-profile',
  'file' => 'modules/user/user.pages.inc',
  'type' => 'module',
  'theme path' => 'modules/user',
  'preprocess functions' => array(
    0 => 'template_preprocess',
    1 => 'template_preprocess_user_profile',
  ),
);

```

So basically, I believe you could simply replace `theme path` key with the path to your module, and your template would be used.

```
<?php
//  unset the original template to set yours.

// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme_path']  =>
    drupal_get_path('module', 'MODULENAME'))
}
?>

```

Now, you would have to find the proper variable in `$theme_registry`, this code example is not working code. You would also probably need to copy the original preprocess function in the module since the theme path is now overridden.

There is probably an easier way of doing this, but believe me doing this in a theme is way simpler, and less chances to break existing functionality of existing modules.

In a custom theme scenario, you would just need to have your copy of the custom template in your theme and it would be good to go.
> 1 votes

# Answer
@stefgosselin is absolutely correct but need a little correction in code section. i am writing the exact code which worked for me.

```
<?php
// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme path']  =
    drupal_get_path('module', 'MODULENAME');
}
?>

```

just try to implement this code inside your custom module and it will definitely work.
> 0 votes

# Answer
Here is an example of `mytemplate.tpl.php` located in my module's templates directory overwrites `toolbar.tpl`.

```
/**
 * Implements hook_registry_alter().
 */
function lml_node_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'my_module');
  // Override the default template with our own.
  if (isset($theme_registry['toolbar'])) {
    $theme_registry['toolbar']['theme path'] = $module_path;
    $theme_registry['toolbar']['path'] = $module_path . '/templates';
    $theme_registry['toolbar']['template'] = 'mytemplate';
  }
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Why does pagination create duplicates in Google's results?
I created multiple views to display different types of nodes on my site. On each of these views, I added a pagination, which creates duplicates in Google's results. Why?

I think this is bad for the SEO of my site. How can I avoid this?

# Answer
> 1 votes
This is definitely bad for SEO.

You need to set related links on the each page of the view so that google doesn't crawl all of the variations via parameters. Example:

```
<link rel="next" href="http://example.com/view?page=2">

```

Apparently the metatag module will help with this, or you can find some discussion about how to do it on this issue.

---
Tags: 8
---


# Question
Title: Update multiple fields when one field changed with AJAX dependent dropdown
I'm working on a D7 custom form with AJAX dependent dropdown, and I can't figure how to update two fields based on a selection from the first field. Here's the code so far:

```
/**
 * Implements hook_form().
 *
 * Form builder function for export form
 */
function mymodule_form($node, &$form_state) {
  $form = array();

  // Get list of available entity types.
  $entity_options = array('commerce_product' => t('Product'), 'node' => t('Node'));
  $selected_entity_type = isset($form_state['values']['entity_type']) ? $form_state['values']['entity_type'] : key($entity_options);

  $form['entity_type'] = array(
    '#type' => 'select',
    '#title' => t('Entity Type'),
    '#description' => t('Select the desired entity type'),
    '#options' => $entity_options,
    '#default_value' => $selected_entity_type,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      'wrapper' => 'bundles-replace'
    ),
  );

  if ($selected_entity_type == 'commerce_product') {
    $bundle_options['product'] = t('Product');
  }
  else {
    // Get available node types.
    $node_types = node_type_get_types();
    $bundle_options = array();

    // Create an array to populate the node options.
    foreach($node_types as $type) {
      $bundle_options[$type->orig_type] = $type->name;
    }
  }

  $bundle_options = _mymodule_get_bundles($selected_entity_type);
  // Get the $selected_bundle based on the entity field. Since there are multiple dependent fields in
  // this form,  we can't really depend on $form_state['values'].
  $selected_bundle = isset($form_state['triggering_element']) && $form_state['triggering_element']['#name'] == 'bundle'? $form_state['triggering_element']['#value'] : key($bundle_options);

  $form['bundle'] = array(
    '#type' => 'select',
    '#title' => t('Bundle'),
    '#description' =>t('Select the content type to export'),
    '#options' => $bundle_options,
    '#default_value' => $selected_bundle,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      'wrapper' => 'fields-replace'
    ),
    '#prefix' => '<div id="bundles-replace">',
    '#suffix' => '</div>',
  );

  $field_options = _mymodule_get_fields($selected_entity_type, $selected_bundle);

  $form['fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Fields'),
    '#prefix' => '<div id="fields-replace">',
    '#suffix' => '</div>',
    '#options' => $field_options
  );

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

  return $form;
}

/**
 * Since the controlling logic for populating the form is in the form builder
 * function, all we do here is select the element and return it to be updated.
 *
 * @return array
 *   Renderable array (the second dropdown)
 */
function mymodule_dependent_dropdown_callback($form, $form_state) {
  // The returned field depends on the triggering form field.
  switch ($form_state['triggering_element']['#name']) {
    case 'bundle':
      return $form['fields'];
      break;
    case 'entity_type':
      return $form['bundle'];
      break;
  }
}

/**
 * Helper function to populate the fields dropdown.
 *
 * @param string $key
 *   This will determine which set of options is returned.
 *
 * @return array
 *   Dropdown options
 */
function _mymodule($entity_type, $bundle) {
  // Get fields for the selected node type.
  $fields = field_info_instances($entity_type, $bundle);
  $return = array();

  foreach ($fields as $field) {
    $return[$field['field_name']] = $field['label'];
  }

  if (count($return) == 0) {
    $return['none'] = t('No fields for content type');
  }

  return $return;
}

/**
 * Helper function to populate the node_type dropdown.
 *
 * @param string $key
 *   This will determine which set of options is returned.
 *
 * @return array
 *   Dropdown options
 */
function _mymodule_get_bundles($key = '') {
  $return = array();
  if($key == 'commerce_product') {
    $return['product'] = t('Product');
  }
  else {
    $entities = entity_get_info();
    $bundles = $entities[$key]['bundles'];

    foreach ($bundles as $bundle_key => $bundle) {
      $return[$bundle_key] = $bundle['label'];
    }
  }

  return $return;
}

```

So what I want is to update both the `bundle` and `fields` fields when the `entity_type` field is changed. As it is now, the `bundles` field is updated when `entity_type` is changed, and `fields` is changed correctly when `bundles` is changed, but I can't get `fields` to update when `entity_types` is changed. When the code gets to where the `fields` field is built in the form builder function, the `#options` value has the correct values, but the page isn't updated with them. To try to accomplish that, I tried this code based on this answer:

```
function mymodule_dependent_dropdown_callback($form, $form_state) {
  // The returned field depends on the triggering form field.
  switch ($form_state['triggering_element']['#name']) {
    case 'bundle':
      return $form['fields'];
      break;
    case 'entity_type':
      return array(
        '#type' => 'ajax',
        '#commands' => array(
          ajax_command_replace("#bundles-replace", render($form['bundles'])),
          ajax_command_replace("#fields-replace", render($form['fields']))
        )
      );
      break;
  }
}

```

but the end result is that the `fields` field completely disappears from the page, even though `$form['fields']` exists at that point in `mymodule_dependent_dropdown_callback()`.

Based on this answer, I also tried replacing the entire form, like so:

```
function mymodule_form($node, &$form_state) {
  $form = array();

  $form['#prefix'] = '<div id="content-export-form">';
  $form['#suffix'] = '</div>';

  $form['entity_type'] = array(
    '#type' => 'select',
    '#title' => t('Entity Type'),
    '#description' => t('Select the desired entity type'),
    '#options' => $entity_options,
    '#default_value' => $selected_entity_type,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      'wrapper' => 'content-export-formt'
    ),
  );
       ...
}

function mymodule_dependent_dropdown_callback($form, $form_state) {
  return $form;
}

```

but that didn't replace either 'bundle`or 'fields` when `entity_type` was updated.

What do I have to change to get the `bundles` and `fields` fields to be updated on the page when `entity_type` is changed?

Thanks.

**UPDATE** . After looking through my code again, I realized I had a typo in the wrapper definition on the `entity` field:

```
'wrapper' => 'content-export-formt'

```

Once I fixed that, it worked, sort of. When I first change the `entity_type` field to `Node`, it changes the `bundle` field values appropriately and sets the options for the `fields` field appropriately. However, when I select a different value in `fields`, instead of replacing the form fields, it adds a new instance of the `entity_type` and `bundle` fields on the page, and this repeats for each time I select a new value from the `bundle` field.

# Answer
> 0 votes
In order to not be like this guy, here's how I got it working.

It turns out I was pretty close. The only thing I really had left to do was change the `#wrapper` setting for the `bundle` field to be `content-export-form` as well.. Once I did that, the form worked like I wanted. Here's the final form builder function:

```
function mymodule_form($node, &$form_state) {
  $form = array();

  $form['#prefix'] = '<div id="content-export-form">';
  $form['#suffix'] = '</div>';

  // Get list of available entity types.
  $entity_options = array('commerce_product' => t('Product'), 'node' => t('Node'));
  $selected_entity_type = isset($form_state['values']['entity_type']) ? $form_state['values']['entity_type'] : key($entity_options);

  $form['entity_type'] = array(
    '#type' => 'select',
    '#title' => t('Entity Type'),
    '#description' => t('Select the desired entity type'),
    '#options' => $entity_options,
    '#default_value' => $selected_entity_type,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      'wrapper' => 'content-export-form'
    ),
  );

  if ($selected_entity_type == 'commerce_product') {
    $bundle_options['product'] = t('Product');
  }
  else {
    // Get available node types.
    $node_types = node_type_get_types();
    $bundle_options = array();

    // Create an array to populate the node options.
    foreach($node_types as $type) {
      $bundle_options[$type->orig_type] = $type->name;
    }
  }

  $bundle_options = _mymodule_get_bundles($selected_entity_type);
  // Get the $selected_bundle based on the entity field. Since there are multiple dependent fields in
  // this form,  we can't really depend on $form_state['values'].
  $selected_bundle = isset($form_state['triggering_element']) && $form_state['triggering_element']['#name'] == 'bundle'? $form_state['triggering_element']['#value'] : key($bundle_options);

  $form['bundle'] = array(
    '#type' => 'select',
    '#title' => t('Content Type'),
    '#description' =>t('Select the content type to export'),
    '#options' => $bundle_options,
    '#default_value' => $selected_bundle,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      'wrapper' => 'content-export-form'
    ),
  );

  $field_options = _mymodule_get_fields($selected_entity_type, $selected_bundle);

  $form['fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Fields'),
    '#options' => $field_options
  );

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

  return $form;
}

```

and here's the ajax callback function:

```
function mymodule_dependent_dropdown_callback($form, $form_state) {
  // We're returning the whole form since multiple fields are being updated.
  return $form;
}

```

---
Tags: 7, forms, ajax
---


# Question
Title: Uninstalling an entity "BaseFieldDefinition" on module uninstall
I'm attempting to create my first module, which doesn't do much. I'm looking to:

1. Add a couple of extra fields to a menu item.
2. Save them in to the *menu\_link\_content\_data* table.
3. Access them within theme templates.
4. Remove the items from the *menu\_link\_content\_data* table when the module is uninstalled.

I've managed (after **A LOT** of reading through the *awful* docs) to get 1-3 completed, but 4 is giving me issues.

Does anyone know how to do this?

I've tried the following in `my_module.module` file:

```
function detailed_menu_uninstall() {
  // Deletes the field storage for the 'detailed_menu_heading' base field.
  $definition = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('menu_link_content')['detailed_menu_heading'];
  \Drupal::service('field_storage_definition.listener')->onFieldStorageDefinitionDelete($definition);
}

```

Where `detailed_menu_heading` is the name of the table that was added to the *menu\_link\_content\_data* table (using `HOOK_entity_base_field_info()`, with `$fields['detailed_menu_heading'] = BaseFieldDefinition::create()`). But it doesn't seem to work.

If anyone could give some advice (while I still have a few homer-esque strands of hair left), that would be awesome!

# Answer
> -1 votes
Okay,

After a few more hours of head scratching and hair pulling, I think I've found (or so it would seem) the answer... I'm writing this for myself, as well as anyone else who might stumble across it by route of the all-mighty Google.

From what I can gather, the EntityManager Service has been split up in to several parts. As a result, the bit we're interested in lies within the Entity Field Manager service / class.

We can use this to grab the definition (which I believe is Drupal for - the set of instructions that provide relevant information about an entity \[or part thereof\]) of our custom entity field.

Now that we have a Drupal *readable* way of referencing the entity field we're interested in manipulating, we need to actually manipulate it.

Soo... There are a few ways to do this, but I believe the best way is to make use of Drupal's Field Definition Listener service, that seems to do the job we're after. What this listener will do is handle getting rid of all the places that the entity field has been buried away within Drupal itself. From the sounds of the service name it should be using the event dispatcher system somewhere, somehow; although, looking at the source I can't find anywhere that actually does this? (this is in contrast to `field_storage_definition.listener`, which *does* dispatch an event, but didn't seem to work, and would white screen with an SQL error, complaining that it can't find the given field when used...)

With these two pieces of the puzzle, it's just a case of putting them together to get the functionality working correctly.

I ended up with:

```
function detailed_menu_uninstall() {

  // Grabs the entity Field Manager service.
  $entityFieldManager = Drupal::service('entity_field.manager');

  // Grabs the Field Definition listener.
  $fieldDefinitionListener = \Drupal::service('field_definition.listener');

  // Ensures(?) that the field storage for the 'detailed_menu_heading' base field is deleted
  // properly when the module is uninstalled.
  $definition = $entityFieldManager->getFieldStorageDefinitions('menu_link_content')['detailed_menu_heading'];
  $fieldDefinitionListener->onFieldDefinitionDelete($definition);
}

```

One thing to note is that if I add more definitions to be installed, and consequently uninstalled in this hook, they don't actually need to be put in the uninstall hook, and I'm not sure why... It's as if Drupal just needs a nudge to be told that some things need to be removed from the entity properly, and Drupal does the rest to check what that is? I'm really not sure.

---
Tags: 8, entities
---


# Question
Title: How to change the widget of a multimedia asset from media browser to multiupload
On Drupal 7 I installed and enabled the multiupload\_imagefield\_widget Now I would like to alter the widget type for the news articles from "Media Broswer" to "Multiupload". I understand that I can add a new field and delete the old one, but I have a lot of previous articles with uploaded images to them. Or maybe I'm looking at this the wrong way?

Any help would be greatly appreciated.

Edit: screenhots

# Answer
> 0 votes
Did you check the field widget and change it from media browser to multiupload? You can change your widget without affecting the other nodes which has already images on it.

hope it helps.

---
Tags: 7, media
---


# Question
Title: How to get an image URL from a field in a twig template
I have a node that contains various fields. I am able to get the values of text fields but not an image field. Below is the relevant output of the node variable being dumped in the twig template:

```
 'field_main_image' =>
    object(Drupal\field\Entity\FieldConfig)[1312]
      protected 'deleted' => boolean false
      protected 'fieldStorage' => null
      protected 'id' => string 'node.homepage.field_main_image' (length=30)
      protected 'field_name' => string 'field_main_image' (length=16)
      protected 'field_type' => string 'image' (length=5)
      protected 'entity_type' => string 'node' (length=4)
      protected 'bundle' => string 'homepage' (length=8)
      protected 'label' => string 'Main image' (length=10)
      protected 'description' => string '' (length=0)
      protected 'settings' =>
        array (size=12)
          ...
      protected 'required' => boolean false
      protected 'translatable' => boolean false
      protected 'default_value' =>
        array (size=0)
          ...
      protected 'default_value_callback' => string '' (length=0)
      protected 'itemDefinition' => null
      protected 'constraints' =>
        array (size=0)
          ...
      protected 'originalId' => string 'node.homepage.field_main_image'     (length=30)
      protected 'status' => boolean true
      protected 'uuid' => string 'f40a7a65-18a5-4ced-85b0-ab1cdc41b2f5' (length=36)
      private 'isSyncing' (Drupal\Core\Config\Entity\ConfigEntityBase) => boolean false
      private 'isUninstalling' (Drupal\Core\Config\Entity\ConfigEntityBase) => boolean false
      protected 'langcode' => string 'en' (length=2)
      protected 'third_party_settings' =>
        array (size=0)
          ...
      protected '_core' =>
        array (size=0)
          ...
      protected 'trustedData' => boolean false
      protected 'entityTypeId' => string 'field_config' (length=12)
      protected 'enforceIsNew' => null
      protected 'typedData' => null
      protected 'cacheContexts' =>
        array (size=0)
          ...
      protected 'cacheTags' =>
        array (size=0)
          ...
      protected 'cacheMaxAge' => int -1
      protected '_serviceIds' =>
        array (size=0)
          ...
      protected 'dependencies' =>
        array (size=2)
          ...

```

I have seen similar questions on SE, like this one Getting the image URL from a field\_image on a node, but none of the answers have worked for me.

Thanks in advance for any responses.

# Answer
> 31 votes
An image field stores the file id in `target_id`. You can access the file id with:

```
{{ node.field_main_image.target_id }}

```

There is a second property in the image field. It is for the referenced entity, in this case the file object. This is not visible in the debug output, because it is computed:

```
{{ node.field_main_image.entity }}

```

In the file object you find the field uri

```
{{ node.field_main_image.entity.uri.value }}

```

which you can use the get the url of the original image

```
{{ file_url(node.field_main_image.entity.uri.value) }}

```

or the url of an image style

```
{{ node.field_main_image.entity.uri.value | image_style('thumbnail') }}

```

The filter for the image style is part of this module which you have to install:

https://www.drupal.org/project/twig\_tweak

## Different entity template

If you don't have a node but a different entity type, for example a paragraph, replace node with the entity name:

```
{{ file_url(paragraph.field_main_image.entity.uri.value) }}

```

## Custom block content

If the field is in a block content type there is no entity template available. The `block` template is for the configured block plugin, which has a different variable structure. In this case, you find the content entity here

```
{% set block_content = elements.content['#block_content'] %}

```

and then

```
{{ file_url(block_content.field_main_image.entity.uri.value) }}

```

# Answer
> 9 votes
You cannot get image url directly in twig template as image fields have just image file id. Every image in Drupal 8 is a file entity.

You can try in `template_preprocess_node()`:

```
$image_file_id = $variables['node']->field_image[0]->target_id;
$image_file = \Drupal\file\Entity\File::load($image_file_id);
$uri = $image_file->uri->value;
$variables['url']=file_create_url($uri);

```

# Answer
> 1 votes
```
<article{{ attributes.addClass(classes) }}>
<div>
    <img src="{{ file_url(node.field_image.entity.uri.value) }}">
</div>
<div{{ content_attributes.addClass('content') }}>
    {{ content|without('field_image') }}
</div>

```
1. {{ file\_url(node.field\_image.entity.uri.value) }}

By this you can get the image field of node in twig template.

2. {{ content|without('field\_image') }}

By this you will get the contents without node image field.

---
Tags: theming, media
---


# Question
Title: How to fetch taxonomy details from uuid or from taxonomy alias
How canI fetch the taxonomy details from the uuid or from taxonomy alias. My url looks like

```
http://test.com/jobs/finance-accounting?job_category=a4c24884-d2g7-41c6-99f5-eb9783d6b992

```

which is a search result page and is a view output. Here I want to add meta tags if the job category is enabled which is a taxonomy term. I have added the meta tags from back end. For this I am trying to update template\_preprocess\_html to inject meta tags.

But I can't get the taxonomy details since there is no direct way to fetch tid. Please let me know if there is any way to get the details from job category uuid or from taxonomy alias.

# Answer
> 0 votes
You can get taxonomy ID from path alias like below.

```
$path = \Drupal::service('path.alias_manager')->getPathByAlias('YOUR ALIAS PATH');
$explode = explode('/',$path);
$tid = $explode[3];

```

You can also replace "taxonomy/term/" with the empty value (str\_replace) and get tid.

After getting TID from path alias you can get details of taxonomy.

---
Tags: views, taxonomy-terms, meta-tags, theming
---


# Question
Title: Route that renders a node has title of route rather than node title
I have a route that takes a wildcard $product and then loads a default node that is stored in config. This is working (i.e. the node is rendered on that path) but instead of the node title it is displaying the route title 'Default Product List'.

Any ideas?

**Routing.yml**

```
default_product_list.generate_default_product_list:
  path: '/destinations/{region}/{area}/{town}/{product}'
  defaults:
    _controller: '\Drupal\default_product_list\Controller\DefaultProductListController::generateDefaultProductList'
    _title: 'Default Product List'
  requirements:
    _permission: 'access content'
  method: [GET]

```

**Controller**

```
 /**
   * Generatedefaultproductlist.
   *
   */
  public function generateDefaultProductList($region, $area, $town, $product) {

    $vars = [
      $region,
      $area,
      $town,
      $product
    ];

    $config = $this->config('default_product_list.defaultproductlist');

    $data = $config->get();

    if ($product === 'accomodation') {
      if (isset($data['default_accomodation_product'])) {
        $node = $this->defaultProductListUtility->loadDefaultNode($data['default_accomodation_product']);
        if (isset($node)) {
          $view_builder = $this->entityTypeManager()->getViewBuilder('node');
          $build = $view_builder->view($node);
//          kint(array($build));
          return array($build);
        }
      }
    }

  }

```

# Answer
Put a dynamic title callback in the controller:

**Routing.yml**

```
default_product_list.generate_default_product_list:
  path: '/destinations/{region}/{area}/{town}/{product}'
  defaults:
    _controller: '\Drupal\default_product_list\Controller\DefaultProductListController::generateDefaultProductList'
    _title_callback: '\Drupal\default_product_list\Controller\DefaultProductListController::title'
  requirements:
    _permission: 'access content'
  method: [GET]

```

**Controller**

```
  /**
   * Generatedefaultproductlist.
   *
   */
  public function generateDefaultProductList($region, $area, $town, $product) {

    // build content

    return $build;
  }

  /**
   * Provides the page title for this controller.
   *
   */
  public function title($region, $area, $town, $product) {

    // build title

    return $title;
  }

```

This dynamic title callback works in all places, also where the content is not rendered and doing so only to retrieve the title would be too expensive, for example in breadcrumbs.

It's also the preferred way and might sometimes be the only way, see Discourage $main\_content\['#title'\] in favor of route titles and title callbacks:

> **Proposed resolution**
>
> Remove the ability to set a dynamic page title using #title, always use \_title or \_title\_callback.
> 1 votes

# Answer
As it is routing path, Drupal will always look for the title in routing.yml, if you want to set title for this you can do as follows,

```
$build['#attached']['html_head'][] = [
    [
      '#tag' => 'title',
      '#value' => "Node title"
    ],
    'title'
  ];

```

OR

```
$build['#title'] = 'Node Title';

```

Here you can replace "Node Title" with your dynamic node titles.
> 2 votes

---
Tags: theming, 8, routes
---


title: How to change the title of breadcrumb?

text:
# Question
Title: How to change the title of breadcrumb?
I have a route that renders a node. Unfortunately in the breadcrumb the route title is rendered rather than the node title. When I preprocess in hook\_preprocess\_breadcrumb() inside my module only the preceding links are available inside $variable (*not* the current route title).

However, if I go to do hook\_preprocess\_breadcrumb() in my theme, the route title *is* inside $variables. So I could change it there but I want the functionality to be encapsulated inside my module, not split between module and theme.

I tried to create my own custom breadcrumb builder but I don't want to build it from scratch as there is some complex functionality built by other developers. I want to get the current breadcrumbs and then just replace the last one (the current page title) with my own.

I tried hook\_system\_breadcrumb\_alter() as well but again the current page title is not showing up in variables inside my module.

```
<?php

class DefaultProductListBreadcrumbService implements BreadcrumbBuilderInterface {

  /**
   * Whether this breadcrumb builder should be used to build the breadcrumb.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   *
   * @return bool
   *   TRUE if this builder should be used or FALSE to let other builders
   *   decide.
   */
  public function applies(RouteMatchInterface $route_match) {
    // TODO: Implement applies() method.
    return true;
  }

  /**
   * Builds the breadcrumb.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   *
   * @return \Drupal\Core\Breadcrumb\Breadcrumb
   *   A breadcrumb.
   */
  public function build(RouteMatchInterface $route_match) {
    // TODO: Implement build() method.

    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));

    return $breadcrumb;
  }

}

```

For reference, I'm using bootstrap as the base theme with multiple sub themes (it's a multisite). I can't find anywhere that's adding the page title in the theme. I'm also using easy\_breadcrumb module but I checked there and the page title is also not shown there.

# Answer
> 1 votes
You could use a title callback, like for example this one from the core node controller:

*\Drupal\node\Controller\NodeViewController::title*

```
  public function title(EntityInterface $node) {
    return $this->entityManager->getTranslationFromContext($node)->label();
  }

```

Your title callback would have other route parameters, so that you can find the correct node, see also https://drupal.stackexchange.com/a/248687/47547.

When using the default option in the Bootstrap theme to display the page title you might need to add cache metadata to the breadcrumb, see Breadcrumbs are cached, which depends on how you determine the node to display.

---
Tags: 8, breadcrumbs
---


title: How to get User Profile form?

text:
# Question
Title: How to get User Profile form?
How do I get the user Profile form? I tried the following:

```
$form = \Drupal::formBuilder()->getForm(ProfileForm::class);

```

but this results in :

> Fatal error: Call to a member function getEntityTypeId() on null in /www/project/docroot/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

# Answer
> 4 votes
Try this to load the user form programatically:

```
$user = \Drupal::currentUser();
$user_entity = \Drupal::entityTypeManager()
  ->getStorage('user')
  ->load($user->id());

$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'default')
  ->setEntity($user_entity);

$form = \Drupal::formBuilder()->getForm($formObject);

```

# Answer
> 4 votes
You need to use it's namespace, like

```
use Drupal\user\ProfileForm;

 ..

$form = \Drupal::formBuilder()->getForm(ProfileForm::class);

```

Or prefix the class, like

```
$form = \Drupal::formBuilder()->getForm(Drupal\user\ProfileForm::class);

```

Or get it by 'name', like

```
 $form = \Drupal::formBuilder()->getForm('Drupal\user\ProfileForm');

```

---

> To fix your error, you need to pass a user object there, like this (for the current user)

```
Drupal::formBuilder()->getForm(ProfileForm::class, Drupal::currentUser());

```

# Answer
> 1 votes
### Drupal 7

I suggest another approach that seems easier.

```
global $user;
$user = user_load($user->uid);
// Loading the module to have access to the form.
module_load_include('inc', 'user', 'user.pages');
// Get the form.
$user_form = drupal_get_form('user_profile_form', $user);
// Render the form.
return drupal_render($user_form);</code></pre>

```

With that you just have to know the `$form_id` by using `hook_form_alter()` and you can call all forms you want.

This solution is for Drupal 7.

# Answer
> 1 votes
For entities like users use `entityFormBuilder()`:

```
$form = $this->entityFormBuilder()->getForm($user);

```

`entityFormBuilder()` is available in all Controllers.

The first parameter is an entity, like node or user.

As second parameter you could choose a form. If empty 'default' is used and this is `ProfileForm` as defined in the user entity:

```
 *     "form" = {
 *       "default" = "Drupal\user\ProfileForm",
 *       "cancel" = "Drupal\user\Form\UserCancelForm",
 *       "register" = "Drupal\user\RegisterForm"
 *     },

```

# Answer
> 1 votes
This is how I did it in my custom controller:

```
class UserEditController extends ControllerBase {

  /**
   * Display the page content.
   *
   * @return array
   */
  public function content($user) {
    $entity = \Drupal::entityManager()
      ->getStorage('user')
      ->create(array());

    $formObject = \Drupal::entityManager()
      ->getFormObject('user', 'default')
      ->setEntity($entity);

    $form = \Drupal::formBuilder()->getForm($formObject);

    return [
      '#theme' => 'template_user_edit_form',
      '#user_edit_form' => $form,
    ];
  }
}

```

In the routing file I did:

```
 entity.user.edit_form:
   path: '/user/{user}/edit'
   defaults:
     _controller: '\Drupal\cusotm_module\Controller\UserEditController::content'
     _title: 'Update your profile'
   requirements:
     _permission: 'access content'

```

Big thanks to 4k4 who helped me getting the "default" to call the form !

---
Tags: users, 8
---


# Question
Title: How to track the published/unpublished status for node revisions?
I am ultimately looking for a way to create a report in Views showing what nodes were active on the site at what times but thus far have been unable to accomplish this. I've done a fair bit of research and experimentation but it seems the main obstacle is that node revisions in Drupal don't capture whether the node was published or not at the time of the revision. Can anyone offer some guidance on how to do such a thing in Drupal 7?

As an example for clarification - though not my exact situation - imagine a classifieds site where the managers need to know how many listings (i.e nodes) were currently published (not published on a particular date, but "live" on the site) for the month of January. Or, perhaps to see what listings were active the week of January 1st-7th, who posted them, and what the headlines were.

Any pointers in the right direction? Or is this something reasonably achievable with custom development (I am just a site builder not a developer!).

# Answer
Try this hope it helps.

First create a Views page

Second add the fields you want to display based on your node. Add relationship 'author' so that you can add a user:name which is related to the author of the node.

Third change your use pager to 'page by date'. Next add a contextual filter Date: date(node). After adding do this.

And your output should be like this.

Additional, you can add exposed filter date so that you can filter on what month you want to check.

Hope this helps you in your problem.
> 2 votes

# Answer
A possible approach to address your challenge, is to create your own ***custom logging*** to:

(a) capture relevant events, and

(b) store relevant data about them.

And this by using a combination of these (commonly used) modules:

Long story short:

1. Use the Message module to create a "Message Type" that you'll use for creating some type of custom logging (for the events you're asking about, i.e. when a node gets published, or when it gets unpublished). Up to you to decide if you want to use:

* a single Message Type (+ extra field to indicate *published* or *unpublished*),
    * or rather 1 Message Type for *published* and another of *unpublished*.
2. Use the Rules module to capture these events, with Rules Actions to create appropriate messages (= records in your custom log).
3. Use the Views module to browse the messages that got created.

For a variation of your question, where a similar technique can be used, refer to my answer to "Is there a way to send emails when someone logs in?" (which includes examples of the relevant Message Types, Rules and Views.

BTW, no need for custom coding.
> 1 votes

---
Tags: 7, nodes, log-messages
---


# Question
Title: Make taxonomy lists collapsible in a views BEF
Similar to the module Term Reference Tree is there a way to make long taxonomy list filters collapsible? My use case would be for pages similar to kobejet.com/speakraku - where the list is so long it makes the filter unwieldy for users.

# Answer
You might consider the Chosen module. Doesn't make things collapsible but it does make finding options in long lists easier. Will work across all forms automatically so even helps with admin forms.

One of my standard modules to install on all sites.
> 0 votes

# Answer
Woot! The simple hierarchical select module - https://www.drupal.org/project/shs currently works fantastically with views in d8. You can see my working example here - www.kobejet.com/lessons
> 0 votes

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


title: Display drupal 7 site in iframe?

text:
# Question
Title: Display drupal 7 site in iframe?
I have a Drupal 7 site and a Facebook page. I have created a tab on the Facebook page which should allow me to display a page from my Drupal site within the tab. On Microsoft Edge I get a warning saying that the site doesn't allow iframes, on all other browsers I have tried nothing displays at all.

I have enabled Security Kit, disabled X-XSS-Protection, allowed cross-site request from https://facebook.com and disabled X-Frame-Options.

I enabled the iFrame entity module and allowed nodes to be iFramed.

And I have put `$conf['x_frame_options'] = '';` in my settings.php.

I still am unable to display a node from my site on an iframe.

How do I get around this?

Thanks

# Answer
I put this towards the end of settings.php (Drupal 7). It worked for me:

```
$conf['x_frame_options'] = 'ALLOW-FROM .facebook.com';

```

(I also use SSL/https (Let's Encrypt) on this site.)

`x_frame_options` don't allow for multiple values, i think. So `'allow-from domain.com'` might disallow SAMEORIGIN. From this post it looks like the module Security Kit allow for setting Allow-From dynamically based on the current page request. I haven't tested it myself.
> 0 votes

---
Tags: social-network
---


# Question
Title: Query and sort by field on entity referenced object
I have a custom content type that has an entity reference field, that refers to an existing node from a different content type.

I'm performing the query like so

```
$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue');

$nids = $query->execute();

```

Each of these issue nodes have a field\_publication field that refers to a publication node. Each of these publication nodes have a field\_permission\_category that I'm grabbing like so.

```
foreach ($nids as $nid) {
   $node = NODE::load($nid);
   $pub = $node->field_publication->entity;
   $pub_permission = $pub->field_permission_category->value;
}

```

But I want to be able to order the results of the initial query by the value of field\_permission\_category from the referenced field, but I'm not sure how to go about that, and I'm not even sure that's possible. Basically I want to be able to do

```
$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue')
->sort('field_publication->entity->field_permission_category->value', DESC);

```

Can you sort a query by a field inside a referenced node?

# Answer
> 4 votes
The answer by Clive is correct. I used this query for a project :

```
$query->sort('field_projets.entity.field_date_mise_en_prod', 'DESC');

```

'field\_projets' is the field name of the entity reference field on my node.

And 'field\_date\_mise\_en\_prod' is the name of a date field belonging to the referenced entity .

You can also use this syntax on conditions. Exemple :

```
$query->condition('field_tags.entity.name', 'cats');

```

You asking for a tag with the name 'cats'.

---
Tags: nodes, 8, database
---


# Question
Title: Concatenate two fieds in an EntityQuery condition
I'm trying to query some nodes by a given string checking if the string is either in the node title OR if the string is an exact match of concatenating the value of two strings.

I know this should be possible in normal mysql but not sure it can be translated in an entity query. Has anyone stumbled upon this problem before?

Is there some sort of 'free text' condition which is not tied up to fields.

At the moment the below code complains about the fact that CONCAT\_WS(...) is not a field which is true.

Maybe there is a simpler solution to this but I'm just not seeing it.

```

$query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'CONTENT_TYPE');

$group = $query->orConditionGroup()
        ->condition('title', $string , 'CONTAINS')
        ->condition("CONCAT_WS('',FIELD_1,FIELD_2)", $string);

$query->condition($group);
$nids = $query->execute();

```

# Answer
> 0 votes
I don't think it's possible this way. I would rather split the $string in two parts, and check the two fields with each part.

```
$query->condition("FIELD_1)", $string_1);
$query->condition("FIELD_2)", $string_2);

```

You have many ways to separate the string in two. Is this helping you ?

---
Tags: entities, database
---


# Question
Title: How do I OR a group result in query alter?
This is the code that I have made so far.

```
 $query->where[1]['conditions'][]=array(
            'field'=> $payment_field,
            'value' => 16184,
            'operator' => '=',
        );
        $query->where[1]['conditions'][] = array(
            'field' => $covered_region,
            'value' => $region_id,
            'operator' => '='

        );
 $query->where[1]['conditions'][]=array(
            'field'=> $payment_field,
            'value' => 16185,
            'operator' => '=',
        );
        $query->where[1]['conditions'][] = array(
            'field' => $covered_region,
            'value' => $region_id,
            'operator' => '=',
        );

```

How can I group the following and do as the query below?

```
    AND (
     ((field_data_field_home_care_payment_plan.field_home_care_payment_plan_tid ='16184')AND (field_data_field_covered_regions.field_covered_regions_tid IN  ('65')))
OR   ((field_data_field_home_care_payment_plan.field_home_care_payment_plan_tid ='16185')AND (field_data_field_covered_regions.field_covered_regions_tid IN  ('65')))
)

```

# Answer
> 1 votes
Any particular reason you're manually adding to the where array rather than using the add\_where function?

I believe you should be able to do something like this:

```
$db_and_1 = db_and()
  ->condition($payment_field, 16184)
  ->condition($covered_region, $region_id);

$db_and_2 = db_and()
  ->condition($payment_field, 16185)
  ->condition($covered_region, $region_id);

$query->add_where(1, db_or()
  ->condition($db_and_1)
  ->condition($db_and_2)
);

```

The important part is the db\_or function.

---
Tags: views, database
---


# Question
Title: How do I bulk delete field collection items that are part of a content type?
I have a Drupal 7 site with a content type that is for adding courses and courses have a field collection that has multiple fields for Date, Venue, Location(Province)

Each course can have 1 or many dates, venues and locations and these get updated, usually by the company offering the course(User managed content). I can update the course content and field collections for them using feeds module but the problem I have is that the old dates are not being overwritten. So we end up with old dates which are no longer relevant plus the new dates.

The question, is there a way to delete the old dates in bulk? I can't seem to get VBO and views to do this. Am I missing a module that would allow me to select all the field collection fields for a particular node and delete all without having to delete them 1 at a time?

# Answer
I created a view that lets us filter by username(so that we can delete for a particular company/user) and course dates(so that we can filter courses with selected dates). It will delete all fields within the field collections for the selected courses. Courses display in rows for each date instance, e.g. if a course has many dates then it displays in a new row with each date field collection item.

I created a content view with a relationships to the field collections-field collection items, author and content field of the field collections attached to my content type for which I selected Delta=All).

I then added fields with the course title, date, venue, location and field collection item ID and displayed in a table with the VBO set to delete the selected field collection items for each instance.

I have filter criteria for the content type, username(author)-exposed, and field collection item for the date-exposed so that I can filter by date to delete old items.

I hope I was able to explain the solution that worked for me so that it can at least offer a clue to someone else with a similar problem.
> 1 votes

---
Tags: feeds, views, entities
---


# Question
Title: Configuration override not work from settings.php
I add the following to the end of my settings.php

```
$config['system.site']['name'] = 'Drupal 8 DEVELOPMENT';

```

When I run `drush cget system.site name` it still displays the old site name.

Any idea why it wouldn't be overriding?

# Answer
You can use the --include-overridden option to show overridden config, for example:

```
drush cget --include-overridden system.site name

```
> 9 votes

# Answer
This is intentionally. `settings.php` doesn't change the configuration in database. It overrides the configuration only for the actual request.

If you remove the line from settings.php, you restore the configuration to the original value.

You can even edit the original configuration in UI, while it is overridden in settings.php.

You can check this:

```
drush ev "var_dump(\Drupal::config('system.site')->get('name'))"

```

has the result: Drupal 8 DEVELOPMENT

But if you use these commands:

```
drush cget system.site name
// is the same as
drush ev "var_dump(\Drupal::configFactory()->getEditable('system.site')->get('name'))"

```

the result will be the site name configured in *Basic site settings*.
> 4 votes

# Answer
Because I haven't found it spelled out clearly anywhere in the docs, I'm gonna write it here for posterity.

In settings.php:

* Use `$config` to override a value which you would access from `\Drupal::config()`
* Use `$settings` to override a value which you would access from `\Drupal::settings()`
* Values accessed from `\Drupal::state()` cannot be overridden from settings.php
> 4 votes

---
Tags: 8, configuration
---


title: EntityTypeManager database transaction

text:
# Question
Title: EntityTypeManager database transaction
I am using `\Drupal::EntityTypeManager()` in Drupal 8 to save data provided from a form into a content type. The following code saves the information in the content type `news`:

```
$data = [
  'type' => 'news',
  'title' => $title,
  'body' => ['value' => $content, 'format' => $format],
];

$node = \Drupal::EntityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

```

Now I need to get the nodeID of the node that was just saved. How do I do that ? Furthermore, I need to insert another set of data into a second content type that needs to store the nodeID I just mentioned.

```
$node2 = \Drupal::EntityTypeManager()
  ->getStorage('node')
  // $data2 contains the $node->id()
  ->create($data2);
$node2->save();

```

Outside of Drupal I am used to mysql transactions to make sure that both things only get stored together and get rolled back if there is an error with either of them. Is there a way to achieve this 'all-or-nothing' functionality with `\Drupal::EntityTypeManager()`?

Do I genrally need to put this in a `try{}catch{}` block in Drupal?

# Answer
You can create the node without saving it. You wouldn't really need a try catch if you know what types of data you're saving.

```
    $node = \Drupal::EntityTypeManager()->getStorage('node')->create([
      'type' => 'news',
      'title' => "hello world",
      'field_some_textfield' => "Here's some text",
    ]);

    $node->set('status', 1);
    $node->set('field_site_section', [['target_id' => 6]]);
    $node->set('field_first_name', $data->firstName);
    if (!empty($data->middleName)) {
      $node->set('field_middle_name', $data->middleName);
    }
    $node->set('field_last_name', $data->lastName);

```

When you're satisfied that your node is set up properly, then you can call:

```
$node->save();

```

At this point, you can get the node id this way:

```
$nid = $node->id();

```
> 1 votes

---
Tags: 8, entities, database
---


title: Convert to Entity Query Drupal 8

text:
# Question
Title: Convert to Entity Query Drupal 8
I want to get the created column from the file managed table of the node field which stores file.Can we have entity query for the same.

```
SELECT file_usage.id AS file_usage_id, node_field_data.nid AS nid, file_managed_node__field_image.fid AS file_managed_node__field_image_fid
FROM
node_field_data node_field_data
LEFT JOIN node__field_image node__field_image ON node_field_data.nid = node__field_image.entity_id
LEFT JOIN file_managed file_managed_node__field_image ON node__field_image.field_image_target_id = file_managed_node__field_image.fid
LEFT JOIN file_usage file_usage ON node_field_data.nid = file_usage.id AND file_usage.type = 'node'
WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN  ('article')) AND (file_managed_node__field_image.changed <= 1473325611+157766400) ))

```

# Answer
> 3 votes
You can not query file usage with entity query, it is not entity data.

You can also not do reverse joins or load specific data. Entity query gives you entity IDs, which you need to load, and then from that get the data you want.

Meaning, to do what you are doing in an enitty query, you need to build an entity query that gives you the nodes you want, then load them, then get the referenced file and then get the created value from that.

# Answer
> 1 votes
About the need to load the nodes to have access to the referenced file, maybe it's not necessary. You can access the referenced entity this way :

```
$query->condition('field_referenced_entity.entity.field_of_referenced_entity', 'value');

```

For exemple : this condition is about a tag (referenced entity) with the value 'cats', for his field 'name'.

```
$query->condition('field_tags.entity.name', 'cats');

```

But it's working for entity reference, I don't know if this will work with File reference... (maybe in combination with Media).

---
Tags: 8, database, entities
---


title: use entityQuery within a Block plugin

text:
# Question
Title: use entityQuery within a Block plugin
I'm attempting to use queries within a block plugin to avoid using views for performance purposes.

```
namespace Drupal\my_plugins\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Query;

/**
 * @Block(
 *   id = "basic_text",
 *   admin_label = @Translation("Basic Block")
 * )
 */

class Basic extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function defaultConfiguration() {
        return array(
            'bodytext-submit' => $this->t('Enter text here'),
            'layout' => array('pane-type-submit' => 'box'),
            );
    }

    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state){
        include 'StyleForm.php';

        $form['bodytext'] = array(
          '#type' => 'text_format',
          '#title' => $this->t('Block contents'),
          '#format' => 'full_html',
          '#description' => $this->t('This text will appear in the block.'),
          '#default_value' => $this->configuration['bodytext-submit'],
        );
        return $form;
    }

    public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['bodytext-submit']  = $form_state->getValue('bodytext');
        }

    public function build(){
        $query = \Drupal::entityQuery('node');
        $nids = $query->execute();
        return array(
            '#type' => 'markup',
            '#markup' => $this->configuration['bodytext-submit']['value'],
        );
    }
}

```

I ultimately want to be able to perform a query and display a list of nodes that fulfill a certain requirement. As a test I performed an empty query for all nodes without displaying any of the results. But when I add

```
$query = \Drupal::entityQuery('node');
$nids = $query->execute();

```

to the build() function. It makes it so I can't render the block. I would like to be able to perform entity queries and display the results within the block.

# Answer
> 2 votes
Sorry Maouna, but don't you need to load the nodes and not just find the nids ? Something like :

```
$build = [
   '#theme' => 'item_list',
   '#items' => array(),
  ];

    $entity_type = 'node';
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $nodes = $storage->loadMultiple($nids);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $view_mode = 'teaser'; // You can change for another view_mode if that suits you. You can considere creating one.

    foreach ($nodes as $node) {
      $build['#items'][] = $view_builder->view($node, $view_mode);
    }

return $build;

```

# Answer
> 2 votes
There are brackets missing:

```
$nids = $query->execute();

```

In my block this works:

```
 public function build() {
   $query = \Drupal::entityQuery('node');
   $nids = $query->execute();

  $build = [
   '#theme' => 'item_list',
   '#items' => $nids,
  ];

 return $build;
}

```

---
Tags: 8, entities, blocks
---


# Question
Title: How to debug TransactionOutOfOrderException: in DatabaseConnection->rollback() in database.inc?
I'm just trying to create an order in code like this:

```
$selected_month = $form_state['values']['month'];
$selected_year = $form_state['values']['year'];
$order = commerce_order_new($form_state['values']['user'], 'checkout_checkout');
commerce_order_save($order);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$product = commerce_product_load($form_state['values']['product']);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper->commerce_line_items[] = $line_item;
dpm($order_wrapper->value());
$order_wrapper->save();

```

This in inside an form submit callback, so I have all the data needed like `productId`, `userId`, etc., but suddenly it stopped working. Apache says nothing and can't see MySQL logs but i contacted my provider and says that there is no logs either.

I'm using `commerce_addressbook`, but not using `commerce_coupon` or `commerce_discount`. Not altering the `order_id` in rules.

Looks like some kind of `order_id` problems but not sure, it looks like the second order\_save (with wrapper function or `commerce_order_save`) tries to save the order but with the same `order_id`.

In the database the order is created with its line item

I've tried to clear all the caches, same result.

A thing which i find strange to me, is its revision id, in the database even tought `order_id` is `160`, for example, its revision id is `552`.

Another strange behaviour i found is that the `commerce_order_total` is not set at all, the row in the table is created but with `0` amount.

Same result for both saving functions, tried both but it is always in the second call of the order save, I comment that line and it works.

Commenting that line works, but of course no line items, **but** the rows are created for **both** entities, commerce\_order and `commerce_line_item`. I mean, i see them in the data base but in the edit page of that created order, there is no line items

Here is the content of `$order_wrapper->value()`:

# Answer
> 2 votes
Basically the `TransactionOutOfOrderException` exception is triggered by transaction being rolled-back (see: `rollback()`) called by Commerce module which was triggered by inability to save your entity (such as validation errors like saving empty values for required fields). Check `commerce_line_item.controller.inc` or `commerce_order.controller.inc` files for more details when exactly rollback is triggered.

Since you're using entity metadata wrappers, it is strongly recommended that you should implement `try...catch` section to catch exceptions and add debugging errors into watchdog. Here is the sample syntax of saving node wrapper:

```
try {
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $price = $node_wrapper->field_product->field_price->value();
}
catch (EntityMetadataWrapperException $exc) {
  watchdog(
    'MODULE_NAME',
    'EntityMetadataWrapper exception in %function() <pre>@trace</pre>',
    array('%function' => __FUNCTION__, '@trace' => $exc->getTraceAsString()),
    WATCHDOG_ERROR
  );
}

```

So adequately your code should look like:

```
if (empty($form_state['values']['product'])) {
  drupal_set_message(t('Missing product on the submit form! Form values: @values',
    array('@values' => print_r($form_state['values'], TRUE)), 'error');
  return;
}
// @todo: Do above condition for other parameters as well.
$selected_month = $form_state['values']['month'];
$selected_year = $form_state['values']['year'];
$order = commerce_order_new($form_state['values']['user'], 'checkout_checkout');
commerce_order_save($order);

try {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $product = commerce_product_load($form_state['values']['product']);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  commerce_line_item_save($line_item);
}
catch (Exception $e) {
  drupal_set_message(t('Error saving line item: @item, message: @error.',
    array('@item' => print_r($line_item, TRUE), '@error' => $e->getMessage())), 'error');
  watchdog_exception('mymodule', $e);
}

try {
  $order_wrapper->commerce_line_items[] = $line_item;
  $order_wrapper->save();
catch (Exception $e) {
  drupal_set_message(t('Error saving order: @order, message: @error.',
    array('@order' => print_r($order_wrapper, TRUE), '@error' => $e->getMessage())), 'error');
  watchdog_exception('mymodule', $e);
}

```

Note: Test the above code first on your testing environment.

So basically by implementing more logging into your code, you can see further what's missing and why it's failing.

For further debugging, ideally you should setup your local environment with copy of the database and reproduce the problem on your development machine.

Since you're dealing with submit handler, for easier debugging, you can use *DevTools* (in the supported browser) where you can repeat XHR requests, so you can see results after code changes without filling out the complex forms. If your form will require different token on each submit, ideally you should add `die()`/`exit();` to prevent the form being completely submitted, this way you can test your form using quick and repeatable method.

For more sophisticated debugging, you should use step-by-step debugger by using some IDE editors which can support that, by enabling XDebug PHP extension. Or generate the trace file which can help you to find out more about your issue.

---
Tags: 7, commerce, entities, database
---


title: Infinite scroll change parameter

text:
# Question
Title: Infinite scroll change parameter
My question is about drupal7 and infinite scroll module. When I click on a button more news is loaded and html changes like this:

```
<ul class="pager pager--infinite-scroll ">
  <li class="pager__item">
    <a href="/about/media?page=1">Load More</a>
  </li>
</ul>

```

My browser makes ajax request and receive some response:

```
view_name:blog
view_display_id:page
view_args:
view_path:about/media
view_base_path:about/media
view_dom_id:a2acec59ca7b252cfd911b770bc558bc
pager_element:0
page:2

```

I need to change `page` on frontend. How can I find where is this parameters set? OR can I change him on front end. I assume there is some hidden div related to this parameter, but I don't know how to find it.

# Answer
> 0 votes
I'm not sure I understand your question. If it helps: this is a view. You can access views list from `/admin/structure/views` and that specific view from `/admin/structure/views/view/blog/edit/page`

There you'll be able to change the output of page display.

---
Tags: 7, ajax
---