# Question
Title: How to fire a Rule after adding a new file in multi-value field?
Working with Drupal 7.56, Rules 2.10, Conditional rules 1.0-beta2 and File Entity 2.4

I can't fire a rule when I add a new image in a multi-value Image field (related to File Entity for inline fields).

I need to act when a new file is added and also when an existing file is updated (each image has inline fields for caption and details) but I can't find the right way to build my Rule?

At the end, I need to fire a rule when a new image (file) is added to send data (fid, url, inline fields values) to an external database and I need another rule when I updated the inline fields of an image (file) to update the external database.

Does anybody has a tip here?

Already tested : Event "Before saving content", Condition "Data comparison" between updated and unchanged node (NOT equals returns always true...), module File Field Rules...

Related :

Using Drupal 7 Rules, how to react to a file upload and change a node field?

Writing custom PHP code in Rules to check if a file field has a new value

Here is my last try (a little bit modified for clarity) with a simple message on site to check if the rule fires :

```
{ "rules_image_insert" : {
    "LABEL" : "image insert",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_pictures" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-pictures" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "file", "id" : [ "list-item:file:fid" ] },
                "PROVIDE" : { "entity_fetched" : { "picture" : "picture" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "entity_is_new" : { "entity" : [ "picture" ] } },
                  "DO" : [
                    { "drupal_message" : {
                        "message" : "NEW picture!!",
                        "type" : "warning"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

# Answer
Here is my own solution to fire a Rule when adding new file through Image field (related to File entity module).

Actually, the main idea is to patch Rules with File events (patch here) so you may trigger actions on Saving a new file or Updating an existing one (if you have skills on coding Rules events in a custom module, maybe this patch is not necessary). Be aware that the File is saved as an entity as soon as it is uploaded through your content type form.

So, in my case, I also needed to act on inline fields (alternative to field collection or another content type to add captions or copyrights on Image) and I have to create a second rule, based on the "host node" updating (the node using the new file) to fetch the file by ID and then gather all data from File inline fields for my purpose (using tokens).

Besides, be careful about the File bundle to avoid firing the rule for any kind of file (document, audio, etc) if you just need to act when an image is added. So you may have to add a condition on the first rule (Entity is of bundle, here File is of bundle image).

Finally, if you need to fire the Rule only when an image is added for a specific content type, I added a last condition to the first rule (when saving new file) : the file path contains the name of the folder where your image is going to be stored. With this condition, the Rule will fire only if the new image has been stored in the right folder, specifically designed for the Image field of your specific Content type.

Hope this would help someone.
> 0 votes

# Answer
To process a multi-value field with Rules, you should use a completed different approach, which is related to the Rules Condition "List contains item" (and/or its negations).

Have a look at this rules example (in Rules export format), which processes a multi-value field also, though in my case it is a list of eMail Ids (replace "eMail ID" by "picture" to match your case):

```
{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-email-addresses" ] },
          "ITEM" : { "previous_email_id" : "Previous eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node:field-email-addresses" ],
                      "item" : [ "previous-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [previous-email-id:value] was removed from the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

If you just replace the machine name "`field-email-addresses`" by "`field-pictures`" (prior to import), you should be able to experiment with this rule in your own site to see it at work.

Here is a sample of the messages I get when I update an article, and while doing so I add 1 more eMail ID and at the same time I remove an existing eMail Id:

```
Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

```

So the clue to make this work is:

1. first iterate over all field values of your field of the ***unchanged node*** (to find the removed values).
2. then also iterate over all field values of your field of the ***changed node*** (to find the inserted values).

Obviously, this does note explain how to find the "updated" values. But think about my sample scenario: another way to look at it is that I updated value `user3@example.com` to `user2@example.com`. Not sure if it is a complete answer to your question, but admit it is already pretty close, no?

Note: As an alternative to using the Conditional Rules module (as you also seem to be doing already), you can also rework the relevant part of my Rules example into performing equivalent Rules Components. For more details on using Rules Components instead of Conditional Rules, refer to the answer to "What's the alternative to using the Conditional Rules module?".
> 1 votes

---
Tags: 7, rules, media, files
---


# Question
Title: How can I wrap form content in bootstrap divs?
I am fairly new to Drupal and I want to change the "add article" form a bit. Currently I have the following displayed:

I want to wrap these `<input>` fields in a few `<div>` so that I can apply bootstrap to it. I don't exactly how to do this, so I tried to alter the `.twig` files that are being called. For example `MY_THEME/templates/form/input.html.twig`. However all I can see is an `<input>` calling `{{ children }}`

If I place this in a div, it just wraps the whole form in this div. Is there a way to place the individual `<input>` fields in separate divs so that I can apply bootstrap to it?

# Answer
> 0 votes
The way you are suggesting works fine. (I just tested it). Try to clear your cache and hard refresh the page. If you do:

```
<div class="my_custom_class"><input{{ attributes }} />{{ children }}</div>

```

you will have your form inputs wrapped in that div.

The other options is to use the form-element.html.twig or you can use the `hook_form_alter` and add prefix and suffix to your fields.

---
Tags: theming, nodes, forms
---


# Question
Title: Permissions to Upload images in text field
The Administrator role has no problem with this, but a lesser role (Editor) that I created cannot upload an image in the basic html text box. They ARE ABLE to upload images as files and images, however. What is the permission setting that I am overlooking here? I should mention, this is Drupal 8.

The basic html option does work for uploading in-line images - for the Administrator. Permissions on the in-line folder are correct. Allowing my Editor role to use full html and even restricted HTML does not answer.

Just a further note, Editor can insert an in-line image in source code mode.

# Answer
You need to use Full HTML in order to accept upload images in a text box. Basic HTML doesn't allow img tag.

The other option is to add img tag in basic Html format, check:

> admin/config/content/formats/manage/basic\_html

or create a new text format which will be available to other roles and will allow img tag.
> 0 votes

---
Tags: 8, media
---


title: Panelizer setup

text:
# Question
Title: Panelizer setup
I have installed Panelizer, Panels and Chaos Tools. However, I still can't find an interface where I can begin to configure and override page layouts.

I suspect there is a missing menu link.

Can someone tell me if I'm missing something?

# Answer
Drupal 8 panels and panelizer is very different than you are used to in Drupal 7. There are no global configuration pages under the structure menu. To panelize a content type you go the manage display tab of the content type you want to panelize. From there, you have a checkbox called panelize this display. Once you check that option you get the panelizer configuration options. As far as managing blocks etc inside of layouts, you use IPE from the node view. I much prefer the Drupal 7 way but once you get used it you find that works OK.
> 0 votes

---
Tags: theming, 8, panels
---


title: Store field values in a JSON file?

text:
# Question
Title: Store field values in a JSON file?
I'm building a booking calendar module, and want to get back arrival & departure datefields values to highlight reservations on the calendar, passing to a library the variables.

```
public function showCalendarAction() {
        return [
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.popperjs']],
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.bootstrap']],
            '#attached'=> ['library'=> ['my_booking_calendar/my_booking_calendar.bootstrap_year_calendar']],
            '#markup'=>$this->t('<div data-provide="calendar"></div>')
        ];
    }

```

I intended to store all the dates(linked to one hotel/house) in a json file, that I would call in ajax.

If it's a good Drupal 8 practice, how to do this ?

Else, what would be the good way to store and pass the variables to my module library ?

# Answer
You could use the routing system and create a custom route and output your json within the controller.

After that you can load the url in your ajax call.

module.routing.yml (path\_to\_module/):

```
  module.content:
  path: '/json-output'
  defaults:
    _controller: '\Drupal\module\Controller\ModuleController::content'

  requirements:
    _permission: 'access content'

```

ModuleController.php (path\_to\_module/src/Controller/):

```
<?php

namespace Drupal\module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class ModuleController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function content() {
    // Load your json content here.
    $json = module_get_json();

    $response = new Response();
    $response->setContent($json);
    $response->headers->set('Content-Type', 'application/json');
    return $response;

  }

}

```

Now you can load your json via /json-output. It is also possible to pass variables to the controller via the url.
> 1 votes

---
Tags: 8
---


# Question
Title: How can I automatically assign users to a node based on a taxonomy?
I've Googled this but might just not be using the right search phrases. I'm building an RFP repository for my company. Each RFP question will have a Category assigned to it. Within Drupal, I'd like to:

1. Automatically assign one or more users as the SME (subject matter expert) based on the Category that was assigned to the question, e.g. if Category = Analytics, then automatically assign user 'John Smith' as the SME upon node creation. The users assigned to the question should be viewable on the node.
2. To do this, I'd need to have a mapping of Category =\> SME(s) table I'd assume.
3. The end goal, would be to use something like the Flag module to be able to notify those users via email if an RFP question that they are the SME for needs updating.
4. Ideally, there would be a way to automatically update existing nodes with the most current mapping of Category =\> SME (people leave, new people come onboard, etc.)

# Answer
> 1 votes
I would do something like this:

* **RFP question** is a custom content type.
* **RFP question** includes a term reference/entity reference to a taxonomy vocabulary called **Category**.
* **Category** has an entity reference field (to users) called **SME**. This way, each term can be assigned to a user. If you do it this way, you also don't need to worry about updating existing nodes when the SME changes; you can simply update the term entry in the vocabulary **Category** once, and all relevant nodes will be changed.
* With this config, the SME won't be visible on the node, just the category. You can fix this by creating a block in Views and adding it to the node page.
* You can use Flag with Rules to automatically notify by email the user marked as SME when a node is flagged for updating.

---
Tags: taxonomy-terms, emails, flags, workflows
---


title: Render in page link

text:
# Question
Title: Render in page link
How can I render an in page link, like:

```
<a href="#xyz">abc</a>

```

I tried:

```
$options = array('fragment' => 'xyz');
$link = Link::fromTextAndUrl(t('abc'), Url::fromUri('internal:/', $options))->toString();

```

...but that gave me: `<a href="http://example.com#xyz">abc</a>`, I want just: `<a href="#xyz">abc</a>`

# Answer
Removing the slash from the URI works for me:

```
$link = Link::fromTextAndUrl(t('abc'), Url::fromUri('internal:', $options))->toString();

```

Produces:

```
<a href="#xyz">abc</a>

```
> 4 votes

# Answer
Example of multiple links in 1 column:

```

$edit_link = Link::fromTextAndUrl(t('Edit'), Url::fromUri('internal:/edit/' . $r['id']))->toString();

$remove_link = Link::fromTextAndUrl(t('Remove'), Url::fromUri('internal:/remove/' . $r['id']))->toString();

$push_link = Link::fromTextAndUrl(t('Push'), Url::fromUri('internal:/push/' . $r['id']))->toString();

$r['id'] = t('@linkEdit | @linkRemove | @linkPush', array('@linkEdit' => $edit_link, '@linkRemove' => $remove_link, '@linkPush' => $push_link));

```
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: Price field with Currency outside of commerce and ubercart
For a real-estate (realty) website I need to store and display the price, but the best D7 module for this is the price component of Commerce module. Is there a Price/Money field on D7?

I have found the following modules:

* Measured Value Field \- Cool idea spans a lot of value types - D6 only
* Units API \- Really more for measurement, integrates with MVF
* Format Number \- Most recent dev version but not sure how rough this version is

# Answer
I'd go with *Commerce Price* (part of Commerce). You don't need to enable the rest of Commerce. The price module itself is relatively small (while giving you price calculation, and Rules integration for free, if you need it), and the rest of Commerce won't be loaded, taking only space on your hard drive, which probably doesn't concern you much.

That's the beauty of Commerce separation, you can use only a few modules that give you exactly what you need. I've seen that happen in many projects.
> 5 votes

# Answer
A D7 port of the CCK Money field is being worked on: http://drupal.org/node/908480

One handy adjunct to the CCK Money field is the currency conversion jQuery widget which allows your visitors to convert the value to any currency, calculated on the fly via Yahoo finance, though you could implement something like that on your own using any of several existing jQuery scripts out there. Not sure if the D7 port includes the conversion widget. You can see an example of the widget on my real estate site here (look for the sales price and click the little icon): http://www.bigmangoproperties.com/thailand/pattaya/condominium/ad-hyatt/26041

If you just want a selection of a few currencies as a suffix label only, you can use the Double Field module, or for a single currency label just use a Decimal field type and use the suffix for the currency label.

For calculations you can use the Computed Field module, though using Commerce with Rules is arguably more powerful.
> 4 votes

# Answer
### Drupal 8

Checkout the Price module which provides a price field with different tweaks.

> A decoupling commerce\_price from commerce.
> 1 votes

# Answer
Try the Currency module.

Their project page states that their 7.x-2.x version provides "Currency conversion input filter, Amount/price display input filter, Amount/price form element", among others.
> 0 votes

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


# Question
Title: Strange symptoms after Drupal 8 core update
I'm new to Drupal 8.

After updating D8 Core to 8.3.2 when I try to access Block Configuration Page, I get this error:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.block.disable" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 190 of core/lib/Drupal/Core/Routing/RouteProvider.php).

Moreover, a new entered view path gives "page not found".

# Answer
You probably have the 8.x-3.0-alpha2 or an earlier version of the rules module installed.

Updating the rules module to 8.x-3.0-alpha3 or later should fix this issue too.
> 0 votes

---
Tags: updating
---


# Question
Title: Taxonomy: Show select options as a dropdown, not multiple
I am trying to display a dropdown where users can divide their article in a certain category. I have created a vocabulary called "category" and added s few fields to them.

I have added this to the content structure where the articles are defined. This works perfectly, however, the categories are not displayed as I desire:

When I inspect this element, there is a property used:

```
<select multiple="multiple">
    <option>...</option>
</select>

```

I don't want these options to be displayed together. I need a dropdown to let users select one of the categories.

I tried debugging and look for which `html.twig` file is being called, and tried to edit the `select.html.twig` but this did not solve the problem.

See select.html.twig

> How can I get these options to show as a dropdown?

# Answer
> 1 votes
To get a taxonomy entity reference to show as a dropdown, there are two things you need to do.

1. Go to the "manage form display" (admin/structure/types/manage/MY\_CONTENT\_TYPE/form-display) for your content type and make sure the **Widget** for the term field is set to **Select list**.
2. Go to the "manage fields" for your content type and click "edit" for the entity reference for your terms. Go to the "Field settings" tab and make sure the **Allowed number of values** is 1. If this is set to 2 or more, Drupal will give you a multiple select, not a dropdown.

---
Tags: views, theming, forms
---


# Question
Title: Where to adjust number of returned results on the /admin/people page? I know, don't hack core
I know, you don't need to tell me. **Don't Hack Core** but I just need to display 1000 user records rows on the /admin/people page **temporarily** and I'll switch it back. I promise...

# Answer
Install the Admininstration Views module; it converts that page to a View, which you can edit and set up with paging of your choice.
> 1 votes

# Answer
Goto /modules/user/user.admin.inc and search for limit and change the 50 to whatever number you like.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Convert Field Collections into Paragraphs during Migration
I have a content type that uses Field Collections in Drupal 7. I am migrating to Drupal 8. Is there a way to convert the Field Collection Entity into Paragraph during migration?

# Answer
> 0 votes
As more sites migrate from D7 to D8, this is definitely a needed functionality. I see that there is now a patch for Paragraphs that is attempting to address that: https://www.drupal.org/node/2911241

If you can test and/or contribute, we can get this moving along!

---
Tags: migrations, paragraphs, 8
---


# Question
Title: Can't get Emoijone ckeditor plugin to appear on WSYISYG editor
I am trying to add the Emojione CKEditor plugin on a Drupal 8.3.7 site. I've created a module using the CKEditor API. I modeled it after both the youtube and smiley CKEditor plugin modules.

In my custom module, I've added the file `src/Plugin/CKEditorPlugin/EmojioneCKEditorPlugin.php`:

```
<?php

namespace Drupal\emojione\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "emojione" plugin.
 *
 */
class EmojionePlugin extends CKEditorPluginBase {

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return array(
      'Emojione' => array(
        'label' => t('emojione'),
        'image' => 'libraries/emojione/icons/emojione.png',
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return 'libraries/emojione/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function isInternal() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getDependencies(Editor $editor) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getLibraries(Editor $editor) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return array();
  }

}

```

The above is basically what both the ckeditor\_youtube and ckeditor\_smiley have. The relevant methods seem to be `getFile()` and `getButtons()`.

I have the relevant ckeditor plugin sources under `libraries/`.

When I enable my module and clear the cache and go to configure text formats and editors at `/admin/config/content/formats`, I don't see the emojione button, but I do have buttons for smiley and youtube.

I've found this question and this answer, but in the answer, it isn't clear in what file the `Template` class goes. Also, the answerer mentions some custom js, but doesn't indicate where that goes either.

What am I missing?

# Answer
> 1 votes
You need to add annotation for ckeditor plugin (more info about annotations based plugins here).

Youtube plugin is using this:

```
/**
 * Defines the "Youtube Button" plugin.
 *
 * @CKEditorPlugin(
 *   id = "youtube",
 *   label = @Translation("Youtube Plugin")
 * )
 */
class YoutubePlugin extends CKEditorPluginBase {

```

So you will need to add an annotation like this:

```
 /**
  * Defines the "Emojione" plugin.
  *
  * @CKEditorPlugin(
  *   id = "emojione",
  *   label = @Translation("Emojione")
  * )
  */
 class EmojionePlugin extends CKEditorPluginBase {

```

EDIT (thanks @kevin): clear caches after changes.

---
Tags: 8, wysiwyg
---


title: Display Parent Menu Item in Menu Block

text:
# Question
Title: Display Parent Menu Item in Menu Block
I have a menu block that displays the sub-pages of a parent page. In addition to the sub-pages I would like at least the name of the parent page displayed but I cannot figure this out.

So in the image above, I would like to have 'About' displayed instead of the title of the block and with its sub-pages (children) below. It would be nice if I could do it in the block's template but I am sure it is more involved than that.

# Answer
I found the answer through a patch in the menu block module.
> 1 votes

---
Tags: navigation
---


title: Express block in region template

text:
# Question
Title: Express block in region template
I have `region--footer-sustain.html.twig` which is expressed in templates via `{{page['footer_sustain']}}`.

Client wants some content moved into the CMS so I added to `theme_info.yml` these regions:

`sustain_footer_left : 'Sustain Footer Left Col'
 sustain_footer_middle : 'Sustain Footer Middle Col'
 sustain_footer_right : 'Sustain Footer Right Col'`

I added the HTML to new Custom Blocks and assigned the blocks to the regions in the same way I have all over the site but no output was expressed.

I tried `{{page['sustain_footer_left']}}` and spitballing tried `{{region['sustain_footer_middle']}}` and later `{{sustain_footer_right}}`

After reading Place block region in node template I tried editing theme.theme with the following:

```
function theme_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

```

And then called it like so:

```
function theme_preprocess_node(&$variables) {
  $view_mode = $variables['view_mode']; // Retrieve view mode
  $allowed_view_modes = array('full'); // Array of allowed view modes (for performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to THEME_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    $allowed_regions = array('sustain_footer_left','sustain_footer_middle','sustain_footer_right');
    theme_add_regions_to_node($allowed_regions, $variables);
  }
}

```

Also tried commenting out the `if(in_array())` as a test. Also tried doing same in `theme_preprocess_page()`.

**UPDATE**

Also tried

```
  $variables['sustain_footer_right'] = entity_load('block_content', 'sustainfooterrightcolumn')->getPlugin()->build();
 $block = \Drupal\block_content\Entity\BlockContent::load('sustainfooterrightcolumn');
 // $variables['sustain_footer_right'] = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);

```

And also tried

```
 $custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('96');
 $variables['sustain_footer_right'] = $custom_block->field_myfield->value;

```

AND ALSO TRIED

```
  $block = \Drupal\block\Entity\Block::load('sustainfooterrightcolumn');
  if ($block) {
  $variables['sustain_footer_right'] = \Drupal::entityManager()
          ->getViewBuilder('block')
          ->view($block);
  } else {
    $variables['sustain_footer_right'] = 'x';
  }

```

Also in twig tried all of these, and yes, cleared cache every time.

`{{sustain_footer_right}}
{{page.sustain_footer_right}}
{{page['sustain_footer_right']}}`

I get no errors but also no output. How do I get the content of these blocks to be expressed in `region--footer-sustain.html.twig` ?

# Answer
Adding a new region to output blocks in does not require a whole lot of code other than the yaml definition you already have. From there, you just need to render the region in the page template:

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

```

If you make a custom region twig file, it needs to render also:

```
<div class="container">
  {{ content }}
</div>

```

Based on your region name, the twig template should be `region--sustain-footer-right.html.twig`.

This is all that is needed to render blocks in new regions. I would say eliminate all the custom code and starting from there.
> 1 votes

---
Tags: hooks, theming
---


title: Problem with ssl, broken site

text:
# Question
Title: Problem with ssl, broken site
I want to install Drupal in https, but I failed.The page is trying to open resources (css, etc) in http. How to solve this ?

# Answer
In Drupal 7 you could set the `$base_url='https://example.com';` in /sites/default/settings.php.

For Drupal 8 it looks like $base\_url has been removed in favor of trusted domain patterns which are protocol agnostic. Using .htaccess rules seems to be the recommended approach.

In .htaccess below `RewriteEngine on`

```
  # Redirect to HTTPS
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

That's from this page: https://www.drupal.org/https-information
> 2 votes

# Answer
You can call the CSS, javascript, and other files using '//' as a prefix to the source. This renders the files for both http and https depending on how the page was rendered.

```
<script src="//code.jquery.com/jquery-3.2.1.js"></script>

```
> 1 votes

---
Tags: installation, ssl
---


# Question
Title: allow specific user to access specific pages in custom module
I have created a custom module with custom database table in drupal 8 site. It has add, update, list and search pages.

I want to restrict as only admin or sub-admin can access the add, edit, list pages. Any user(non-registered also) can access the search page.

How to achieve this in the module i have developed itself in drupal 8? Or is there any common way in drupal 8 to add permission for a particular URL?

# Answer
I did that through routing.yml file. Thanks for the comments. I posted this just for reference that may help someone else.

```
notices.notices_form:
  path: '/notices/addupdate'
  defaults:
    _form: '\Drupal\notices\Form\NoticesAddUpdateForm'
    _title: 'Notices Form'
  requirements:
    _role: 'administrator'

notices.notices_search_form:
  path: '/notices/search'
  defaults:
    _form: '\Drupal\notices\Form\NoticesSearchForm'
    _title: 'Search Notices'
  requirements:
    _access: 'TRUE'

```
> 0 votes

---
Tags: 8, users
---


# Question
Title: How to securely authenticate content embeded in another site?
I need to embed password protected content to a second domain with an iframe. The content itself is a view which will be displayed on a third party site via an iframe and the content is prepared with a custom page and template handing the display. The use case is to present the view on the other site without the users needing to login. From my research, Oauth or Services seem like good candidates, but I don't have much experience with both and using a service to show a single view seems like it might be an over complication. Anyway, I haven't found much in the way of good documentation on the subject so I'm hoping for a good introductory overview of how to implement this. So, what is the best way to securely authenticate the drupal content on another site. I don't want to expose user credentials in the src=url in the frame for security purposes, so I know I need to use another authorisation mechanism. I've looked at the Entity Iframe module, which seems to have some of these features but the module mainly works drupal-to-drupal, and I haven't been able to tangle apart how the module handles the consumer/provider communication.

So, from researching this, I believe that I have to configure oauth and pass the token to the URL in the iframe. What I am unclear about is how to configure oauth access to the page and how to generate the token to be supplied to the iframe.

# Answer
> 3 votes
1- build the content structure well in your first site and create a view from admin/structure/views/add that return the data needed to the second site which acts like a client consuming your first site content.

2- Download and enable Services module and enable the submodule **Rest Server** and submodule **OAuth Authentication** now you can create secured resources to be consumed by any other sites.

4- create an end point from admin/structure/services/add and choose authentication type as your case "**OAuth Authentication**" will fit as you need to authenticate the client "the second site consumes your data".

3- Download and enable Services views module that will help you expose any view as a resource to be consumed and managed via services and

4- From the view you have created before click the button **Add** and choose services, now the view will appear as a regular resource in your site under admin/structure/services/list click edit resources to see it named with your view name enable it and choose the required authentication and authorization.

Now any authenticated client client site or App can consume that resource from **http://YOUR\_SITE\_DOMAIN/END\_POINT/VIEWS\_SERVICES\_URL**.

The last and the most important part in your requirements is to configure the authentication method and test it will I recommend below helpful tools and articles.

Chrome rest client extension to test the webservice.

Very helpful article about services module

Another helpful article

# Answer
> 0 votes
I think you should create a service on your first site to export the view's data as JSON via REST, grab it on your second site, and display it. That is a more secure way.

In your REST service you can use OAUTH and request tokens, or a username and password.

Blog/Using REST Export With Views In Drupal 8 could help you.

---
Tags: 7, services, importing-exporting, security, authentication-authorization
---


# Question
Title: Commerce multiple stores and multiple carts for B2B customers
i have a problem with multiple stores. i set up 2 stores of the same type. store **B2B** for B2B customers and store **B2C** for B2C.

all products are sold in store **B2B** and just a few also in store **B2C**.

when i add to cart products from **B2B** store, in cart page i have only one commerce\_cart\_form view. when i add a product sold also in **B2C** store, i have 2 commerce\_cart\_form view.

the first one with products sold in **B2B** store and the second one with products sold in **B2C** store.

why are there 2 carts?

it seems that built multiple stores to manage B2B and B2C is not the right choice. thanks

# Answer
According to the Commerce 2 documentation, stores are optimized for two use cases:

> We optimize for the two use cases:
>
> One business that has one or more locations or 2. The marketplace model (where you have sellers)
>
> **One or more locations** This is the most common eCommerce situation where we have a single person, company, or organization that is taking payments online.
>
> **Marketplace model** The marketplace model is where you have many sellers who are taking payment for unique products.

Each store can have a different currency, payment method, order flow, and so on. So, each store also has a separate, unique cart.

It seems there are two ways to do what you want.

* Keep two different stores, one for **B2B** and one for **B2C**. If the configuration is mostly the same, you will have to duplicate a lot of config between the two stores. You will also need to keep the two stores separate so that B2B customers see the **B2B** store and B2C customers see the **B2C** store.
* Just have one store. Add a select field to the products for admin to indicate whether it is a B2B product, B2C product, or both. Then, modify the views that show the products so that B2B customers see B2B products and B2C customers see B2C products. This way, you don't have to duplicate the config for the payment flow and so on.
> 1 votes

# Answer
The 2 separate carts into 1 cart solution has not been developed. Please refer to this discussion: How to checkout 2 carts at once like Etsy does on Commerce 2.x?
> 0 votes

---
Tags: 8, commerce
---


title: Hiding a <div> in mobile only

text:
# Question
Title: Hiding a <div> in mobile only
I inherited a Drupal site recently that I'm having a bit of trouble with. Essentially, I need to hide a menu in a mobile view, but still remain visible on a desktop. So far, I've added this to my css file:

```
/* Mobile Hide */
    @media (max-width: 991px) {
        .mobile-only {
          display:none !important;
          }

          .desktop-only {
            display:block !important;
          }
        }

```

Using Chrome, when I apply the "mobile-only" class to the div I'm trying to disappear, it works perfectly. The only problem is I have no idea how to actually apply this class to the real div in the server's files. How can I apply this to an actual file in Drupal?

Thank you.

# Answer
You shouldn't need a specific class to complete this. Just assign the div to something like

```
@media (max-width: 991px) {
    #menu{display: none;}
}

```

If you need to add the class to the div you can use jquery.

```
$('div').addClass('mobile-only');

```
> 3 votes

---
Tags: theming, files
---


title: Comparison in twig templates

text:
# Question
Title: Comparison in twig templates
I have a list field for a custom content type that looks like this:

Field **Machine name** is: `field_app_os`

```
key|label
Win|Windows
Android|Android

```

I can access the `key` in Twig template by using `content.field_app_os` or Twig Field Value and the output of both is `Android`:

> Twig Field Value allows Drupal 8 themers to get partial data from field render arrays. It gives them more control over the output without drilling deep into the render array or using preprocess functions.
> Filters:
> \- field\_label : Returns the field label value.
> \- field\_value : Returns the render array of the field value(s) without the field wrappers.

```
/* with use of Twig Field Value module */
{{ content.field_app_os|field_value }}  {# outputs 'Android' #}

 /* without use of Twig Field Value module */
{{ content.field_app_os }}  {# outputs 'Android' #}

```

However, if I do a simple comparison, the output of both is False.

```
{% set app_os = content.field_app_os|field_value %}
{{ kint(app_os == 'Android') }} {# outputs 'bool FALSE' #}

```

Or When I use:

```
{% set app_os = content.field_app_os %}
{{ kint(app_os == 'Android') }} {# outputs 'bool FALSE' #}

```

What's wrong in my code?

# Answer
{{ content }} is a render array, where you find the label of the key/label pair probably here:

```
{{ content.field_app_os[0]['#markup'] }}

```

But this is not ideal for logic:

1. The position in the render array can change, for example if you install a layout module.
2. The content of #markup depends on how the field formatter is configured in the view mode.
3. The label is translatable, so the logic breaks on a multilingual site.

So it's better to use the database value in:

```
{{ node.field_app_os.value }}

```

This is the first part of the key/label pair, which is untranslatable and you can access the value independent on how the field is configured in the view mode.
> 2 votes

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


# Question
Title: node_save() casing 500 Internal Server Error - 48s when using with AJAX
```
global $user;
$node = node_load($_POST['expire_offer']);
$node->field_status['und'][0]['value']=0;
$node->field_expire_date['und'][0]['value']=time();
$node->revision = TRUE;
$node->uid = $user->uid;
$node->log = 'This offer expired from rate manager expire ' . date('m-j-Y');

node_save($node);

```

When I remove `node_save($node);` it loads properly.

# Answer
> 0 votes
Sorry, I don't have enough reputation points to comment so I should post this as an answer.
Obviously your 500 error comes from the script. The `node_save($node);` does not cause your error, it's just the trigger.
If you want to follow the best coding practices, you should use `try` and `catch` blocks to catch your errors before you try to modify your database.
If the "dblog" module is activated you could follow the error stack to debug your script or else you could comment out all of the lines that are assigning new values to your variables and start re-executing your script by uncommenting one line at the time utill the error is reproduced.
I hope that this helps a bit. We have all been there. Cheers.

# Answer
> 0 votes
Since `node_save()` usually requires a lot of resources and time to process the data, most likely you hit some PHP resource limits.

So first of all, try increasing the following PHP options in your `php.ini`:

* `memory_limit = 1G`
* `max_execution_time = 120`

Note: To identify your `php.ini`, check in *Reports*, *Status* and click on PHP link which will redirect you to `phpinfo()` page.

Then restart your Apache server. If won't work, please check your Apache and PHP log files, eventually *Recent logs* in Drupal for further details about your error.

If increasing limits helped, to lower the resource requirements, at first try the followings:

* disable unneeded modules (like Devel, etc.),
* install cache service (Memcached/Redis).

See: How do you improve Drupal performance?

---
Tags: hooks
---


# Question
Title: How to redirect Add to Cart link to product page?
I am working with E-Commerce module of Drupal 7. I want to redirect `Add to Cart` button link to product page only those products which have attribute otherwise I want to add product direct to cart.

# Answer
> 2 votes
**Using Drupal Rules Module:**

To redirect directly to checkout after a user clicks 'add to cart'

1. Admin -\> Configure -\> Rules -\> Add New Rule
2. Give it a title of 'Add to Cart - Redirect to Checkout'
3. Set React on event to: After adding a product to the cart
4. Add new Action - set this to 'Page redirect'
5. Give it a value of 'checkout' and save.

Now when users click your add to cart button, they will be taken directly to checkout. Alternatively, you can send them to /cart by change the value in step 5.

# Answer
> 0 votes
You need to add view php options in your listing page and then you can get your attributes in that php field, you put the conditions and make the link as you want

# Answer
> 0 votes
Add a hook form alter that changes the add to cart form to add another #submit callback. In this callback, add your logic to check attributes, if you need to redirect, set $form\_state\['redirect'\]

See https://drupal.stackexchange.com/a/128001/42761 for more on how to alter the form

---
Tags: 7, commerce
---


# Question
Title: Drupal 7: Local site URLs all point to production site
I've been trying to figure this out for a while on this one particularly large site.

Every single URL on every page and menu, even the admin menu as the wrong url. I've tried this with WAMP, MAMP, Vagrant, Docker and Docksal with the same results.

A better explanation: I'd expect all urls to be what I've setup on my local machine as the base. Like mysite.loc, or for docksal, mysite.docksal.

But when I pull the repo for this site and set it up, then load it...all urls are the production urls. Anything I click on goes to production. All submit buttons goto production. Almost like they are saved in the DB, but the definitely aren't.

I've tried setting the base URL. That doesn't work.

I've turned off all the modules, both contrib and core. That doesn't work.

I've changed themes. That doesn't work.

It's something within the filesystem of this site but I'm not sure where to look at this point. Probably a hack someone put in somewhere.

Any thoughts of where to look?

# Answer
> 1 votes
I found the issue.

If you're using the module "Domain Access", the uninstall hooks do not work properly (or at least they didn't on our site).

You'll need to go into your DB and change the domain settings after you've disabled your module.

All of the Domain module tables that have your production (or old URL) in them need to be changed. Removing those tables will likely corrupt your DB and make the site unusable.

---
Tags: 7, configuration, uri
---


title: D7 - Calling Form Into User Page

text:
# Question
Title: D7 - Calling Form Into User Page
We are trying to create a single page that has all the available user related forms available without have to click between pages.

We have been able to render some forms, like change password, but we are trying to include other forms rendered outside of the user module.

Specifically having trouble with rendering commerce\_addressbook existing values and the 'add new address form'. https://www.drupal.org/project/commerce\_addressbook

Could anyone please outline the correct way to do this?

# Answer
> 1 votes
What you will want to do is add a preprocess hook to the theme for the user page, and inject some new variables to the template.

Example:

In template.php:

`$variables['address_form'] = drupal_get_form('form_id', $arg1, $arg2, $arg3...);`

In your template tpl:

`<?php print render($address_form); ?>`

You will need to know the form id of the forms you want to call. The optional second argument to `drupal_get_form` will pass those arguments to the form, like say, user object, or user id. Each form will have their own requirements; some don't need any additional arguments at all.

---
Tags: hooks, theming
---


title: How add Placeholder to login form

text:
# Question
Title: How add Placeholder to login form
I need to add *Placeholder* property to Drupal 7 login form from template.php. Not to use a module. and also want to know how to add other attributes like *Required* etc.

# Answer
I think it cannot be done unless using the module. You can try like this

1) Adding the hook\_form\_FORM\_ID\_alter in the module to add placeholders, required and some other form attributes.

2) In the template file you can call that form using drupal\_get\_form('form-id', args1, args2, etc..)

3) Finally, pass the form to the tpl file.

Example:

1) In .module

```
function yourModule_form_user_login_alter(&$form, $form_state) {
  $form['name']['#attributes'] = array(
    'placeholder' => array (
       t('Username')
     )
  );
  $form['name']['#required'] = TRUE;
  /* Add other attributes like this*/
}

```

2) In template.php

```
$variables['login_form'] = drupal_get_form('user_login');

```

3) In .tpl.php

```
<?php print render($login_form); ?>

```

I hope this will work !!
> 4 votes

---
Tags: forms
---


# Question
Title: Do new routes require a static first portion?
Using mymodule.routing.yml, I can successfully create a custom route at /foo/{bar}/{baz}, but I cannot use /{bar}/{baz} or /{bar}/foo/{baz} as path for a route; they just return a 404 error.

Why? Is there any way to create a route for /{bar}/{baz} (with strict requirements for bar)?

I've read the entirety of the routing API and I can't seem to find any answers.

# Answer
> 9 votes
In the routing system you can't do this. What you can do is path aliasing.

Inbound: `/{bar}/foo/{baz}` -\> `/foo/{bar}/{baz}`

Outbound: `/foo/{bar}/{baz}` -\> `/{bar}/foo/{baz}`

You need a pattern to apply a regular expression on the path inbound, so `/{bar}/{baz}` is only possible if the parameters themselves have a distinctive pattern.

I didn't find a tutorial how to build a path processor, but you can use the PathProcessorFront class as example.

Register both as tagged service in the .services.yml file for the module.

```
services:
  path_processor_front:
    class: Drupal\Core\PathProcessor\PathProcessorFront
    tags:
      - { name: path_processor_inbound, priority: 200 }
      - { name: path_processor_outbound, priority: 200 }
    arguments: ['@config.factory']

```

# Answer
> 3 votes
See Routing System on Drupal.org.

> Path (required): The URL to the route, with a leading forward slash (e.g., path: '/book'). You can use dynamic properties by including them in curly braces. (e.g., path: '/node/{node}/outline'). These will be passed along as arguments via parameter converters to the controller/form (see below). **Note that the first item of the path must not be dynamic.** You can also define optional parameters at the end of your path (See 'Optional Parameters' on this page).

I hope this is enough to understand that routes cannot start with a slug. It must be a static value.

---
Tags: 8, routes
---


# Question
Title: drupal 7: how to add a field that displays a message when user is not logged in?
I need a way to set up a field available only for logged in users. When anonymous user reach the page that contains this field, drupal must display a message that request to hte user to login or register to display this field. This is the same that appens for comments. There is a module that impelments this for single fields?

# Answer
> 0 votes
You can try the following 2 modules: Field Permissions and Markup.

1. Define the field.
2. Directly behind, define the markup field that shows the message to log in.
3. Use field permissions to allow access to the target field for authenticated users only.
4. Use field permissions to allow access to the markup field for anonymous users only.

That workaround should solve you issue.

---
Tags: entities
---


# Question
Title: Programmatically adding argument to view that already uses a context filter
I have a view that uses the id of the currently logged in user as a contextual filter. This was set using the Drupal UI and works well. Then I wrote a custom module that adds another parameter (a specific node id) to all views on my site. All views need this second parameter (and it needs to be added programmatically). This approach works well for all views that only use the programmatically added parameter as a contextual filter. However, the view that needs 2 filter values does not work, because I think I do not handle the order of parameters in the args array correctly. How do I set up views that already use filter values, but I need to add more programmatically (I set $args\[0\], but I guess this might be the problem) ?

I should say that I do not want those filters to appear in the URL.

testmod.module:

```
function testmod_views_pre_view($view, $display_id, array &$args) {
  ...
  $args[0] = $value;
}

```

I thought I could just read the view's $arg array and add my special argument to it programmatically, but for the view that already uses the logged-in user as a contextual filter, when I print print\_r($args) it is an empty array, although the view is working correctly (and only shows results for the current user). Are contextual filters that I set up via the UI stored in a different place than $args ?

What needs to be done to tell the view how to use the 1. and 2. filter values correctly ?

**Edit:** I read that hook\_views\_pre\_view() is too early to find contextual filters in the arg array (at that point you would only see arguments in that array passed via URL). Which hook would be best to achieve what I'd like to do ?

# Answer
> 2 votes
I now have a better understanding and found a solution. `hook_views_pre_view()` is indeed too early to see arguments that are NOT passed to the view via URL. That explains why $view-\>args was empty in my case. In `hook_views_post_build()` you do see ALL arguments (URL+nonURL) passed to the view. However, the way I solved my issue is still using `$args[0] = $value;` in `hook_views_pre_view`. That means the first argument passed to all views will always be `$value`. For views that are using additional arguments, Drupal will add them to `$args` later on. In my special case I have views that might not necessarily need the first argument that I pass, so I had to add a contextual filter `Global: Null` (at the first position) that allows a contextual filter value to be ignored (and as a default I set 0). This way each view does have the correct number of contextual filters and the order is correct, whether the view needs to use the very first argument or not. It might not seem intuituve to pass an argument to every view, even though not all views really need it, but adding a `Global: Null` dummy filter is easier than excluding views in an `if()` statement and always having to modify the module code when a new view has to be added later on.

---
Tags: 8, views
---


# Question
Title: Limiting node access to certain users based on an entity reference field. Which hook to use for when node is viewed?
Scenario:

"Teams" content type has user entity reference field.

"Manager" role can add teams to nodes they have created and the teams will change often.

Members of the team can only view the nodes (and nodes that reference that node through another entity reference field) whenever their team is assigned to them.

For these content types, performance isn't an issue. What I want to do is use a series of `views_get_view_result` when the node is viewed and redirect away from the node if necessary. That part is easy.

What is the best hook to use for when the node is viewed and I can run my views to find out if the user should view it?

Thanks

# Answer
In similar situation I used hook\_entity\_access. Also there is hook\_ENTITY\_TYPE\_access so you can use the `hook_node_access`.
> 0 votes

---
Tags: nodes, hooks, users
---


# Question
Title: Drupal 7 Themeing - template.tpl.php vs template.php - variables
I am interested in learning what disadvantage, if any, there are in calling variable fields directly within the template.tpl.php files.

Is it ok to place a field variable within the template.tpl.php file if doing it as simply as:

```
<?php
//--------------------------------
// COLOR
if(!empty($content['product:title']['#product']->field_taxonomy_color['und'][0]['taxonomy_term']->name)): ?>
    <div id="color-wrapper">
    <?php
        $max_length = count($content['product:title']['#product']->field_taxonomy_color['und'])-1;
        for($x = 0; $x <= $max_length; $x++){
            echo '<div class="color">'. $content['product:title']['#product']->field_taxonomy_color['und'][$x]['taxonomy_term']->name .'</div>';
        }
    ?>
    </div>
<?php endif; ?>

```

My understanding is that this code should be placed a preprocess function and called into the tpl.php file such as:

**TEMPLATE.PHP**

```
function theme_preprocess_node(&$variables) { $variables['color'] = ... }

```

**TEMPLATE.TPL.PHP**

```
<?php echo $color; ?>

```

If this is the case, how would i return all values of the loop from template.php into template.tpl.php?

---------EDIT---------
Should I create complex logic within its own field--template.tpl.php file, set the field to a variable in template.php and call upon the variable inside the node--template.tpl.php? Would there be a problem with creating over a hundred field--template.tpl.php files?

# Answer
> 2 votes
The disadvantage is you leak a lot of PHP code processing Drupal inner structures to the template file.

I would preprocess $content in template.php to expose a simple array of strings as a custom variable:

```
$colors = $content['product:title']['#product']->field_taxonomy_color['und'];
$colorNames = Array();
for ($x = 0; $x < count($max_length); $x++) {
  $colorNames[$x] = $colors[$x]['taxonomy_term']->name;
}
$variables['color_names'] = $colorNames;

```

Then the template code could be:

```
<?php if ($color_names): ?>
<div id="color-wrapper">
  <?php foreach ($color_names as $cn)
    print '<div class="color">' . $cn  . '</div>'; ?>
</div>
<?php endif; ?>

```

---
Tags: theming
---


title: Dependency Injection and the Url object

text:
# Question
Title: Dependency Injection and the Url object
I'm making the leap from Drupal 7 to Drupal 8 and am still fuzzy on some core concepts, particularly relating to dependency injection (DI). I've read plenty of tutorials and have a grasp on DI with services, but am unclear on using DI with something like `\Drupal::Url()`.

For instance, I am using the following code in a class: `use Drupal\Core\Url;
...
$url = Url::fromRoute('<current>', [], ['absolute' => 'true'])->toString();`

From what I can tell, there is no Url service. So, what I am wondering is: Is it possible to access Url via DI? And if so, how?

**Bonus points**: I intend for the class I am writing to be used as a service. Does this have any impact on the answer?

**Edit:** Fixed erroneous code.

**Edit 2**: I should also point out that the purpose of this call is to retrieve the current absolute URL so that I can determine if it is HTTPS.

# Answer
> 5 votes
You can inject the UrlGenerator as service and use UrlGenerator::generateFromRoute, but in the linked doc you are discouraged to do so:

> @internal Should not be used in user code. Use \Drupal\Core\Url instead.

So the code in your question to create an url object is OK for a service, but not the `toString()` method. Render the url only with this method when the page rendering process has started, for example in a theme.

In a service you usually don't know this and you should return an unrendered url object, so that it can be rendered later in the rendering pipeline.

```
$url = Url::fromRoute('<current>', [], ['absolute' => 'true']);

```

`toString()` in the wrong place generates ugly error messages about early rendering which are hard to debug when this happens somewhere in a service.

---
Tags: 8, dependency-injection
---


# Question
Title: Form state redirect to node path plus fragment
How can I redirect a form to the canonical node path + fragment?

Redirect: /nodepathalias#tag

```
$form_state->setRedirect('entity.node.canonical',
  array('node' => $node->id()),
));

```

Where should I add the fragment information?

# Answer
> 3 votes
Use the third argument of the setRedirect function:

> array $options: (optional) An associative array of additional options. See \Drupal\Core\Url for the available keys.

And if you check that doc:

> @param array $options (optional) An associative array of additional URL options, with the following elements:
>
> * 'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
> * 'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.
> * 'absolute': Defaults to FALSE. Whether to force the output to be an absolute link (beginning with http:). Useful for links that will be displayed outside the site, such as in an RSS feed.
> * 'attributes': An associative array of HTML attributes that will be added to the anchor tag if you use the \Drupal\Core\Link class to make the link.
> * 'language': An optional language object used to look up the alias for the URL. If $options\['language'\] is omitted, it defaults to the current language for the language type LanguageInterface::TYPE\_URL.
> * 'https': Whether this URL should point to a secure location. If not defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP.

In your case you should use just `fragment`:

```
$options = [
  'fragment'   => 'tag',
];

$form_state->setRedirect('entity.node.canonical',
  ['node' => 8],
  $options
);

```

# Answer
> 2 votes
You must add 'fragment' in third argument of **setRedirect** method, **$options** (@see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AsetRedirect/8.2.x).

You can see how this option is used in https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x , in the method **toUriString()**

Example:

```
$form_state->setRedirect('entity.node.canonical',
  array('node' => $node->id()),
  ['fragment' => 'tag']
));

```

---
Tags: 8, forms
---


title: Migrate address field

text:
# Question
Title: Migrate address field
I am currently searching for a example to migrate data into an address field in Drupal 8 without any luck for now.

Has someone a hint for me on how to map the fields?

I tried the following:

my.migrate.yml file:

```
'field_date_address/address_line1': date_tmp_address_address_line1
'field_date_address/locality': date_tmp_address_locality
'field_date_address/postal_code': date_tmp_address_postal_code

```

Callback:

```
$row->setSourceProperty('date_tmp_address_address_line1', 'Teststreet 18');
$row->setSourceProperty('date_tmp_address_locality', 'Test locallity');
$row->setSourceProperty('date_tmp_address_postal_code', '12345');

```

# Answer
> 0 votes
I do migrate from json to drupal 8, hope this will help.

In the .yml I call the field on a single value :

```
id: my_id_migrate
label: My Label
migration_group: MyGroup
migration_dependencies: {}

source:
  plugin: json_source
  path: URL_TO_JSON_FILE
  headers:
    Accept: 'application/json'
  identifier: id
  identifierDepth: 0
  fields:
    - id
    - title
    - address

destination:
  plugin: entity:node

process:
  type:
    plugin: default_value
    default_value: my_node_type

  title: title

  field_geolocation : geolocation
  field_address : address

```

And 'address' is an array of all subfields :

.json source :

```
[
   {
      "id":1,
      "title":"Title 1",
      "address":{
         "address_line1":"adress 1",
         "address_line2":"",
         "postal_code":"11111",
         "locality":"City of lights",
         "country_code":"DE"
      },
   },
   {
      "id":2,
      "title":"Title 2",
      "address":{
         "address_line1":"adress 1 of number2",
         "address_line2":"",
         "postal_code":"11111",
         "locality":"City of lights",
         "country-code":"DE"
      },
   },
   {
      "id":3,
      "title":"Title 3",
      "address":{
         "address_line1":"adress 1 of number3",
         "address_line2":"",
         "postal_code":"11111",
         "locality":"City of lights",
         "country_code":"DE"
      },
   }
]

```

Works with all subfields, and works fine for all fields in drupal 8 that have subfields (like geolocation fields for example)

# Answer
> 0 votes
Here is a working example with a user profile migration (not Drupal user account).

`Adress` is an array of subfields. You can check in database all the possible subfields because i don’t use all of them (ex : `field_profile_address_family_name`)

.yml file :

```
field_profile_address/country_code:
     plugin: default_value
     default_value: FR
   field_profile_address/langcode:
     plugin: default_value
     default_value: fr
   field_profile_address/address_line1: adresse1
   field_profile_address/address_line1: adresse2
   field_profile_address/locality: ville

   field_profile_address/postal_code: code_postal

```

---
Tags: 8, migrations
---


# Question
Title: Commerce 2.x attribute translations cause product duplicates in views
If I add a translation for an attribute entity my views display duplicates products. I've tried to find an attributes delta filter, but there is none. If I add a relationship for the attributes there is still no delta available in filters. Even if there was, I would need to add a relationship and filter for each attribute entity which would result in a rather massive view. I have also tried distinct views query and it does not work. How can I filter my product views on attributes language delta or another way to eliminate the duplicates?

# Answer
> 1 votes
I found a way to solve this. You must:

1) ensure you have a variations delta filter set.

2) add the field variations and ensure that the Display all values in the same row is NOT CHECKED under Multiple Field Settings. you can then hide this field if you do not want to display the output.

3) in the view display's Query settings tick the check box Distinct.

This configuration will remove product duplicates when the Product Variation relationship is used. This is the resulting query, i am not sure how efficient this configuration is but at least it works.

`SELECT DISTINCT commerce_product__variations.delta AS commerce_product__variations_delta, commerce_product__variations.langcode AS commerce_product__variations_langcode, commerce_product__variations.bundle AS commerce_product__variations_bundle, commerce_product__variations.variations_target_id AS commerce_product__variations_variations_target_id, commerce_product_field_data.product_id AS product_id, commerce_product_variation_field_data_commerce_product__variations.variation_id AS commerce_product_variation_field_data_commerce_product__vari
FROM
{commerce_product_field_data} commerce_product_field_data
LEFT JOIN {commerce_product__variations} commerce_product__variations ON commerce_product_field_data.product_id = commerce_product__variations.entity_id AND (commerce_product__variations.deleted = '0' AND commerce_product__variations.langcode = commerce_product_field_data.langcode)
LEFT JOIN {commerce_product_variation_field_data} commerce_product_variation_field_data_commerce_product__variations ON commerce_product__variations.variations_target_id = commerce_product_variation_field_data_commerce_product__variations.variation_id
WHERE commerce_product__variations.delta = '0'`

---
Tags: 8, commerce, views
---


# Question
Title: In hook_user_presave how to check if account is being activated and account is new?
Currently in Drupal 7 I have two conditions in hook\_user\_presave,
1. Is account is being activated
2. Is account new

```

function hook_user_presave(&$edit, $account, $category) {
    if (isset($account->is_new) && !empty($account->is_new)) {
        //If account is new then execute my code here
    }

    if ((isset($account->uid)) && (isset($account->status)) && ($account->status == 0) && ($edit['status'] == 1)) {
        //If account is being activated for the first time then execute my code here
    }
}

```

I want to convert this code to Drupal 8, What should be the conditions?

```

function hook_user_presave($account) {

    //Condition 1

    //Condition 2
}

```

Is there any other way to achieve this?
Any help would be appreciated. Thanks.

# Answer
To check if the user is new:

```
$account->isNew()

```

To check if the user is active:

```
$account->isActive()

```

See User API isNew or User API isActive for more information.
> 5 votes

---
Tags: 8, hooks
---


# Question
Title: D7 views node references. Do not displays first node
I have 2 content types: Page and Paragraph. Page has field node reference which made through view(outputs as checkboxes). View has contextual filter - Paragraph node author id (uid). I create user, then create 2 nodes of type Paragraph.

Then I create node of type Page and in node reference field I see only one node of type Paragraph. I search for my Paragraph nodes in http://example.com/admin/content and open each paragraph in devel.

Both of Paragraph nodes are published. Both has user id in uid. But in the field I see only one of them.

Trying to figure out what's happening I call views\_get\_view\_result with my view. And see only the second node.

Any help appreciated, thanks!

# Answer
After hours of googling found how to deal with this issue. Thanks to this Actual output in view is different than preview

In view settings go to other section -\> query settings -\> Disable SQL Rewriting.

After saving the view I've seen all my nodes into the node reference field.
> 0 votes

---
Tags: 7, views, nodes
---


# Question
Title: Output array data on drush error when showing stack trace
I'm trying to install a module, but its giving me errors during a drush enable. It shows the stack trace log and I can see it has something to do with the flag\_lists\_type during the install process. I can see there is an array in the output, but how do you print\_r() this so I can get more debugging information?

# Answer
You can use XDebug PHP extensions with the following suggested settings:

```
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=1       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=256        ; int: Controls the protection mechanism for infinite recursion protection.

```

Since you're experiencing *Exception* type of error, enabling `show_exception_trace` will show a stack trace whenever an Exception or Error is raised (even if this Exception or Error is actually caught, so you can always disable it). Enabling `collect_params`, will display the parameters passed to functions when a function call is recorded (including content of the arrays).

See: Xdebug documentation page.

To verify your XDebug settings from CLI, run:

```
php -i | grep xdebug

```
> 0 votes

---
Tags: 7, drush, debugging
---


title: Where are the default emails?

text:
# Question
Title: Where are the default emails?
I am using Drupal Commerce in Drupal 8.

Where can I find the default email and rules related to order activities, like on completion, processing etc.

# Answer
Email templates can be found in module subdirectories: https://docs.drupalcommerce.org/commerce2/developer-guide/orders/customize-order-receipt-emails

For D8, commerce is not using rules any more, but states machine and event subscribers, check order workflows / checkout flows https://docs.drupalcommerce.org/commerce2/developer-guide/orders/workflows
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How to let users post questions and appear anonymous?
I want logged in users to be able to post questions or answers using the Answers module "anonymously"... that is, to appear anonymous but actually still be logged in, be able to follow their post, etc.

Edit: I thought this module could already do this but am not finding any settings for it.

Using Answers 7.x-4.0-rc2

Criteria:

* anonymous/not logged in users should **not** be able to post
* I want to give users the option to post anonymously but default to show the author
* if a user posts "anonymously", the post would have do something about their avatar

+ on a per-post basis
* Our site is complex with many other features, such as blogging, so changing usernames isn't an option; we want their usernames to show up everywhere else

# Answer
To my knowledge, the Answers module (you know the drill .. Disclosure: I'm a co-maintainer) does not have such setting that you were looking for. However, by using the Rules module (also), you should be able to get this to work, as further detailed below ...

### Step 1: Create a (blocked) user 'Somebody'

Create an extra user with a user name that will be shown instead of the user name that you want to *appear anonymous*. I decided to name such user "Somebody", and it was created with `uid=68`. Moreover, I decided to make it a blocked user (not to be used for any other purpose).

### Step 2: Add a dedicated field to relevant content types

For every content type for which you want this facility to be available (e.g for types *Question* and *Answer*), add an extra field that an editor (author) of a node can use to indicate if the node should *appear anonymous*.

In my case I have a selection list field with machine name `field_optionlist` and which has 2 possible values, like so:

* A (= Appear anonymous).
* S (= Standard author display).

### Step 3: Create a custom rule

Below is custom rule (in Rules export format) that will set the node author to "Somebody" (= the user name from Step 1) whenever value "A" is selected via the dedicated field from Step 2 (and whenever a node of type Question or Answer is saved):

```
{ "rules_optionally_hide_node_author" : {
    "LABEL" : "Optionally hide node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : {
              "answers_answer" : "answers_answer",
              "answers_question" : "answers_question"
            }
          }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : "68" },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "user-fetched" ] } }
    ]
  }
}

```

Adapt the `uid=68` value in the above rule to fit your dedicated user, and replace the machine name of `field_optionlist` to fit your case (prior to trying to import the above rule).

*That's it* ... at least to make it work in my setup.

### Step 4: Extra refinements

For the sake of completeness, you should create a variation of this custom rule to set the node author to "current user" whenever the field value is different from "A".

### Bonus feature ...

By using the above approach, and by using a user name like ***`Wiki`***, you can implement logic that is pretty close to "wiki" questions / answers on SE-sites also. Because for those kinds of questions/answers the original author will not have any user points (like *reputation*) changes anymore for any upvotes or downvotes of such question or answer.
> 2 votes

# Answer
Have you tried setting user permissions and giving anonymous users access to create content using the Answers module?
> 1 votes

---
Tags: 7
---


# Question
Title: Trouble getting a drupal 7 view template to render for a machine readable block
i'm using drupal 7. I have created a content type called **Title and content navigation**.

I have setup a template override in **/sites/all/themes/themename/templates/views/title-and-content-navigation/block/views-view-fields--title-and-content-navigation.tpl.php** which works correctly for all of the displays which are blocks.

I have one of the displays for this view which has a machine readable name of **block\_8**. I am trying to have a separate template file for this but I cannot work out what I need to name the file. I have tried many suggestions from SO and I can't get this to work. I have been flushing all caches. What to name the template files is very confusing.

Thanks in advance

# Answer
Click on "Theme: Information" under "Advanced" on the right hand side of the View edit page.

All the available template suggestions for the View and its displays are listed in the resulting modal.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How only 1 checkbox can be allowed to check in the group of checkboxes in Webforms
I have added a set of options yes,No, Sometimes with the type checkboxes.But the user is supposed to tick only one checkbox.When I disable multiple selections for the field, by default it considers it as radio buttons. The radio buttons are ideal for this.But the requirement is checkboxes only. Can anyone help me on this.

# Answer
> 0 votes
Tell your client that radio buttons ARE checkboxes where the user can only select one option. You are therefore satisfying the requirement. See this simple explanation that you can pass along to your client. I would also look at @Neograph734's suggestion that you use radio buttons (as they are semantically correct based on the requirements you have) but make them look like checkboxes using CSS as described here. That should avoid any pushback from your client and get you the functionality you need.

You can also point out to your client that if you start messing with javascript to use actual check boxes but limit the user to only checking one that you run a high risk of making your site no longer accessible to people with disabilities. Its very complicated to make js work in that way and remain accessible.

Time to educate your client :)

---
Tags: webforms
---


title: I cannot turn off cache

text:
# Question
Title: I cannot turn off cache
I tried everything to turn the cache off. Even when using drushs command "cr" it does not help.

I used this guide: https://www.drupal.org/node/2598914

I cannot work like this. I also turned on devels theme rebuild on page view feature. Although I don't understand what is meant with this here:

> Rebuild the theme information like the registry While creating new templates, change the $theme.info.yml and theme\_ overrides the theme information needs to be rebuilt.

Example:

```
function theme_preprocess_taxonomy_term(&$variables) {
    kint("1");
}

```

When changing the number even "drush cr" does not help. I got to refresh like 4 times until the browser shows the change. Its not like that with kint - also "var\_dump()" needs it's 4,5 times.

Could anybody please tell me what to do?

# Answer
> 0 votes
Browsers can be pretty aggressive about caching. Provided you're not using some other caching layers like redis/memcache, varnish, or a CDN, I'd start by disabling the browser cache.

In Firefox, open the inspector and click on the gear icon in the top right to open the Toolbox Options menu. Under the Advanced settings section, check the 'Disable HTTP Cache (when toolbox is open)'. I think Chrome is very similar in this.

Also be sure to use the hard refresh option. For Firefox it's Ctrl+f5. https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly

---
Tags: 8, caching
---


# Question
Title: How to customize validation functions for some field?
I have the standard node add or edit form. The edited node has several fields. How can I customize validation functions for a field ? For example, I need to switch off or change validation function for some field. How can I do it ?

# Answer
> 1 votes
In order to add a validation for a entity field and that validation can work in any form you can use entity validation constraints, and add programatic validations.

```
/**
 * Implements hook_entity_base_field_info_alter().
 */
function foo_entity_base_field_info_alter(array &$fields, EntityTypeInterface $entity_type) {
  // Add Bar constraint to the user name.
  /** @var \Drupal\Core\TypedData\DataDefinitionInterface[] $fields **/
  if ($entity_type->id() == 'user' && !empty($fields['name'])) {
    $fields['name']->addConstraint('Bar');
  }
}

```

# Answer
> 0 votes
As @ivan-jaros says, you can use entity validation constraints to add new validations to a field. In the hook he mentions you can also get the current validations and remove what you don't need.

You can also use hook form\_alter of node edit form and use the #element\_validate (more info here) property to add / remove custom validations.

---
Tags: 8, entities
---


# Question
Title: Views 3 remove exposed filter programmatically
I've got several node types each of them referenced to different taxonomy term vocabulary. For category showing i use taxonomy\_display module.

For example, we've got two categories: cues and billiard balls.

Cues has price from, price to and wood type filters. But balls has no wood type filter.

So i need to remove wood type filter if taxonomy\_term tid referenced to billiard balls vocabulary.

Thus, I need to remove one of many exposed filters programmatically.

```
function modulename_views_pre_view(&$view, &$display_id, &$args) {
  // Some custom logic wich field_info_instances checking ...
  $filter_field = 'filter_id';
  // Removes from everywhere where i can find filter or filters properties
  unset($view->display[$view->current_display]->display_options['filters'][$filter_field]);
  unset($view->display[$view->current_display]->handler->options['filters'][$filter_field]);
  unset($view->display_handler->display->display_options['filters'][$filter_field]);
  unset($view->display_handler->options['filters'][$filter_field]);
}

```

Filter field removes successfully, but I've got php notice:

```
  Notice: Undefined index: field_wood_reference_tid in function views_handler_filter_term_node_tid->exposed_validate()

```

Also i try to remove field in hook\_pre\_execute(), but with the same result:

```
function modulename_views_pre_execute(&$view) {
  $filter_field = 'filter_id';
  unset($view->display_handler->handlers['filter'][$filter_field]);
  unset($view->filter[$filter_field]);
}

```

Also try with override\_option() method like here - http://groups.drupal.org/node/82219, but no result at all.

Any suggestions? Pls help =)

---

Thanks to everybody for reply but I still has no answer. Maybe something is not clear? =(

# Answer
I would use hook\_form\_alter using unset on the form object as you are in your example for the element that you want to remove.
> 5 votes

# Answer
Here is the tested snippet which will allow you to remove the filters from the views exposed form using form alter as mentioned by Scott Thomas,

```
/**
 *Implements hook_form_FORM_ID_alter().
 */
function hook_form_views_exposed_form_alter(&$form, &$form_state) {
  $filter_field = 'filter_id';
  // Get the filters list for the current view. Here page_1 is the display ID.
  $filters = $form_state['view']->get_items('filter', 'page_1');
  if (isset($filters[$filter_field])) {
    $info_key = 'filter-' . $filter_field;
    unset($form[$filter_field], $form['#info'][$info_key]);
  }
}

```

Apart from removing the form field you also need to remove the information for particular filter which is available in $form\['#info'\], So that it will remove the label also. If you remove the form element alone then the filter label will be displayed even though the field is removed, So always make sure that you're removing this information also.

Modify this according to your need. If you want to perform this one for particular view then add a condition for that too like ,

```
if ($form_state['view']->name == 'view_name') {
  // DO your operation.
}

```

Here $form\_state\['view'\] will give you the current view object which is being processed.

Hope this helps.
> 2 votes

# Answer
Follow the steps below

1. Firstly write a hook\_form\_alter in a custom module
2. Next try the following piece of code

unset($form\['#info'\]\['your\_field\_name'\]); $form\['your\_field\_name'\]\['#access'\] = 'FALSE';

Hope that helps.
> 1 votes

# Answer
You can remove exposed filter using template file as well.

Use this command:

```
cp sites/all/modules/contrib/views/theme/views-view.tpl.php sites/all/themes/costa/templates/views/views-view--<machine_name>.tpl.php

```

In the template file find this code:

```
  <?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

```

And remove it. Your exposed filter will be removed from display, but will keep working of you pass proper arguments in URL.
> 1 votes

# Answer
Correct me if I'm wrong because I'm not sure to fully understand your issue. So you would like to hide an exposed filter in a view depending on an other exposed filter's value? If so you can try Views Dependent Filters module. I used it several times and it does the job.

You can check our fiend Lullabot's review about this module.

If you really need to do it in code the exposed option should work: filter\[$filter\_id\]-\>options\['exposed'\] = FALSE;
> 0 votes

# Answer
The following did it for me inside hook\_form\_alter:

```
$info_key = 'filter-' . $fieldName;
unset($form[$fieldName], $form['#info'][$info_key], $form_state['view']->display_handler->options['filters'][$fieldName], $form_state['view']->display_handler->handlers['filter'][$fieldName], $form_state['view']->filter[$fieldName]);

```
> 0 votes

# Answer
**Method 1**

By using hook\_views\_query\_alter(). See the following example:

```
<?php
/**
 * Implements hook_views_query_alter().
 */
function foo_views_query_alter(&$view, &$query) {

  if ($view->name == 'foo_view') {

    // Allow any distance when the postcode it is not specified.
    if (empty($_GET['postcode']['postal_code']) || $_GET['postcode']['postal_code'] === 'All') {
      // Scan through the query.
      foreach ($query->where as $condition_group_key => &$condition_group) {
        foreach ($condition_group['conditions'] as $condition_key => &$condition) {
          $search_name = '(COALESCE(ACOS(';
          if (is_string($condition['field']) && strstr($condition['field'], $search_name) !== FALSE) {
            // Remove filter from the query.
            unset($query->where[$condition_group_key]['conditions'][$condition_key]);
          }
        } // end: foreach
      } // end: foreach
    } // end: if

    /*
     * Change the field conditions.
     * Possible field values: 1, 2, 3
     * Logic: When 3 is selected, then display 1, 2 and 3.
     */
    switch (@$view->display_handler->handlers['filter']['field_123_value']->value[0]) {

      case 3:
        foreach ($query->where as $condition_group_key => &$condition_group) {
          foreach ($condition_group['conditions'] as $condition_key => &$condition) {
            if($condition['field'] == 'field_data_field_123.field_123_value') {
              unset($query->where[$condition_group_key]['conditions'][$condition_key]);
              $query->where[] = array(
                  'conditions' => array(
                      array(
                          'field' => 'field_data_field_123.field_123_value',
                          'value' => 1,
                          'operator' => "=",
                      ),
                      array(
                          'field' => 'field_data_field_123.field_123_value',
                          'value' => 2,
                          'operator' => "=",
                      ),
                      array(
                          'field' => 'field_data_field_123.field_123_value',
                          'value' => 3,
                          'operator' => "=",
                      ),
                  ),
                  'args' => array(),
                  'type' => 'OR',
              );
            }
          }
        } // end: foreach
        break;

    } // end: switch

  } // end: if
}

```

**Method 2**

See the example by using hook\_views\_pre\_execute and custom function which trying to find the right field condition and return the reference to it:

```
/**
 * Implements hook_views_pre_execute().
 */
function foo_views_pre_execute(&$view) {

  if ($view->name == 'foo_view') {

    foo_get_view_filter_recursively(
      $view,
      $view->build_info['query']->conditions(),
      'field_data_field_123.field_123_value',
      $filter
    );

    // We want our filter to work as a bit mask.
    $filter[0]['operator'] = '&';

    unset ($filter);

    // Example of finding Proximity filter condition
    $search_name = '(COALESCE(ACOS(';

    foo_get_view_filter_recursively(
      $view,
      $view->build_info['query']->conditions(),
      $search_name,
      $filter
    );

    if (empty($_GET['postcode']['postal_code']) || $_GET['postcode']['postal_code'] === 'All') {
      // Allowing any distance.
      $filter[0]['value'][':distance'] = 10000000;
    }
    else {
      $filter[0]['value'][':distance'] = 80000;
    }

    unset ($filter);

    // Fetching single record?

    foo_get_view_filter_recursively(
      $view,
      $view->build_info['query']->conditions(),
      'node.nid',
      $filter
    );

    if (!empty($_GET['nid'])) {
      $filter[0]['value'] = (int) $_GET['nid'];
    }
    else {
      $filter[0]['operator'] = '<>';
    }

    unset ($filter);

    // echo '<pre style="font-size:11px;font-family: Monaco">'; print_r($view->build_info['query']); exit;
  }
}

/**
 * Custom function to find the field condition within the view
 */
function foo_get_view_filter_recursively($view, &$conditions, $field_name, &$filter) {

  if (!empty($conditions)) {

    foreach ($conditions as &$condition) {
      if ($condition instanceof DatabaseCondition) {
        if (foo_get_view_filter_recursively($view, $condition->conditions(), $field_name, $filter)) {
          return TRUE;
        }
      } else if ($condition['field'] instanceof DatabaseCondition) {
        if (foo_get_view_filter_recursively($view, $condition['field']->conditions(), $field_name, $filter)) {
          return TRUE;
        }
      } elseif (is_string($condition['field']) && strstr($condition['field'], $field_name) !== FALSE) {
        @$filter = array(&$condition);
        return TRUE;
      }
    } // end: foreach

  } // end: if

  return FALSE;
}

```
> 0 votes

# Answer
I'm removing it from template files. Override the views-view.tpl.php and remove the following code from it:

```
  <?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

```
> 0 votes

# Answer
I think the op was on the right track. I had a similar situation without exposed filters so I could not use the hook\_form\_alter method. Here is some example code for anyone else coming across this:

```
$view->set_item($view->current_display, 'filter', $filter_id, null);

```

The view object does not have a `remove_item` function but simply states in the code that you can set it to null in order to remove an item including filters: `views/includes/view.inc` on line `2526`.

Here is a full example for anyone that targets a specific view and display:

```
/**
 * Implements HOOK_views_pre_view().
 */
function HOOK_views_pre_view(&$view) {
  if($view->name == 'VIEW_MACHINE_NAME') {
    switch($view->current_display) {
      case 'VIEW_DISPLAY_MACHINE_NAME':
        $view_filters = $view->display_handler->get_option('filters');
        foreach ($view_filters as $filter_id => $filter) {
          if ($filter_id == 'my_filter') {
            $view->set_item($view->current_display, 'filter', $filter_id, null);
          }
        }
      break;
    }
  }
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to override configuration variables in settings.php
I need to override configuration variables declared in the settings.php. How this can be possible? Any help me on?

**Note**: I am trying to override a custom configuration variable, not any default one.

# Answer
> -1 votes
You can't overwrite the variables in settings.php.

---
Tags: configuration
---


# Question
Title: Composer packages changed, even though same version used
I'm sorry, but in my project, composer update is changing files in my vendor directory even though I'm getting the exact same version of the libraries before & after. I just want to ask, is this because the packages on packagist are changing, like a branch which is receiving new commits? Or, is it that something is going wrong in my project?

I thought that if you use composer.lock to keep the versions exactly the same, no files should be changed.

We have kept our libraries versioned, is it possible that a developer modified them incorrectly?

# Answer
> 3 votes
`composer update` without any argument tries to update everything.

If you want to use the packages specified in `composer.lock`, run `composer install` instead.

---
Tags: 8, composer
---


# Question
Title: What linux user accounts should be created prior to Drupal 7 install?
When preparing to install Drupal 7 on a clean linux installation (Centos 7 in my situation), what linux user accounts should be created?

I ask this question because I seem to be having problems with file permissions or ownership when installing new modules with Drush. When I do so I get an error like the following:

... /sites/all/modules exists, but is not writable. Please check directory permissions.

I only have 2 linux accounts on this system, root and myself, and typically run Drush as myself rather than root. I have run 'Drush fp' to fix file permission problems, but this error persists.

So what linux accounts besides root should be created for use with Drupal and what should the user file permissions be? Thanks

# Answer
With your own user is enough.

If you want know how setup permissions check securing file permissions drupal community doc. It's referenced in this related issue.

In that specific case (setting up permissions for modules folder), it says the following:

> drwxr-x--- 32 greg-user www-data 4096 2008-01-18 11:48 modules/

Now docs examples are for D8 but it works for D7 too.
> 1 votes

---
Tags: users, drush, files
---


# Question
Title: How can I load a javascript file into a Drupal 7 page using the Code per Node module?
What is the syntax for including Javascript from a remote location into a Drupal 7 page using the Code per node module?

I have seen this code `drupal_add_js('path/to/somescript.js')` at Managing JavaScript in Drupal 7 | Drupal.org, but it seems that is not for use on Drupal 7.

What would be the Drupal 7 equivalent?

# Answer
Code per node module is intented to use to have a custom JS for each node. The JS code must be placed inline, in the node add / edit form. You have this tutorial to see how it works.

If you want to add the same js to a specific content type you can create a module custom where you invoke preprocess node hook:

```
function YOUR_MODULE_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js('path/to/somescript.js');
  }
}

```

You can also do this in a custom theme, there are examples in this answer.

If you want see a module with drupal\_add\_js examples and a nice documenttion, you can see the module **js\_example** , which is a module inside Examples 7.x.
> 2 votes

# Answer
try this just change the link to whatever external library you are trying to import : `drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/ally.js/1.0.1/ally.min.js', array('type' => 'external', 'scope' => 'footer'));`

take a look at this : drupal.org/node/905994
> 0 votes

---
Tags: 7, javascript
---


title: Cannot get AJAX callback values to save

text:
# Question
Title: Cannot get AJAX callback values to save
I am using Drupal 7, and I have a content type called Case Record that has the following fields:

* Title (title, Node module element)
* Case Number (field\_cr\_case\_number, Text)
* Case Title (field\_cr\_case\_title, Text)

When the user creates a new node of this type and enters in a Case Number, an AJAX call is supposed to fetch the Case Title and populate it on the Case Title textbox. Here is my module code:

```
<?php
/**
 * @file
 * Module for Case Records.
 *
 * @category Examples
 *
 * @package Example Modules
 */

/**
 * Implements hook_form_alter().
 */
function case_records_database_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'case_record_node_form':

      $form['field_cr_case_number'] = array(
        '#type' => 'textfield',
        '#title' => 'Case Number',
        '#prefix' => '<div id="div-case-number-element-wrapper">',
        '#suffix' => '</div>',
        '#ajax' => array(
          'callback' => 'case_records_database_ajax_callback',
          'event' => 'change',
          'method' => 'replace',
          'wrapper' => 'div-case-name-element-wrapper',
        ),
      );

      $cs_short_title = "";
      if (isset($form_state['values']['field_cr_case_number'])) {

        // Code omitted. Use db_select to query the database and
        // get the real case title, but for now we'll just call it
        // "Some Case Title".
        $cs_short_title = "Some Case Title";
      }

      $form['field_cr_case_title'] = array(
        '#type' => 'textfield',
        '#title' => t('Case Title'),
        '#value' => $cs_short_title,
        '#prefix' => '<div id="div-case-name-element-wrapper">',
        '#suffix' => '</div>',
      );

      break;
  }
}

/**
 * AJAX callback.
 */
function case_records_database_ajax_callback($form, &$form_state) {
  return $form['field_cr_case_title'];
}

```

The AJAX call does indeed populate the Case Title text field with the dummy "Some Case Title" text. However, when I save the new node neither the Case Number field nor the Case Title field are saved with any values. They are both blank. What is wrong with my code?

# Answer
> 1 votes
That code is overriding the fields structure. That fields have a specific structure and that code is changing it completely, so in submit the values are not recognized.

I recommend you use devel module and use dpm function to inspect the structure of that fields:

```
  dpm($form['field_cr_case_number']);
  dpm($form['field_cr_case_title']);

```

To make your form changes you must only add the #ajax property to your field:

```
$form['field_cr_case_number'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'case_records_database_ajax_callback',
  'event' => 'change',
  'method' => 'replace',
  'wrapper' => 'div-case-name-element-wrapper',
);

```

And to add the wrapper and #value to your second field do something like this:

```
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#prefix'] = '<div id="div-case-name-element-wrapper">';
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#suffix'] = '</div>';
$form['field_cr_case_title'][LANGUAGE_NONE][0]['value']['#value'] = $cs_short_title;

```

In this question is also explained how to make the ajax callback.

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


# Question
Title: When setting up the Drupal 7 database (mySql/mariadb) what database user accounts should be created?
When installing the database (mariadb) for use with Drupal 7 on Centos 7, what database admin and user accounts should be created and with what permissions?

Do specific directory permissions or file ownerships need to be provisioned for these database user accounts? -Thanks

# Answer
> 2 votes
You just need one user allowed to create, drop tables, and mysql basic operations (INSERT, SELECT, UPDATE, DELTE, ALTER, INDEX...). In drupal installation tutorial you have more info.

---
Tags: database
---