# Question
Title: How to build my SQL statement to export all webform submissions using Forena?
I am using Drupal 7.54. and my users are grouped together through a custom **user** field.

I want to export all webform's submissions for a given group of users in one CSV.

So as suggested in the post How do I programmatically export all webform submissions into a single csv?, I plan to use a custom datablock that fits my need.

I am new to Drupal and don't have much knowledge about how it works and how Drupal stores custom fields in the database.

I couldn't build the right SQL.

What would be the appropriate sql statement in this context?

# Answer
> 2 votes
Have a look at this example SQL, which is a so called "Data Block" I created using the Forena module (disclosure: I'm a co-maintainer), and starting from relative path `admin/structure/forena/data`:

```
SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

```

Some details about the example I'm using here:

* `5` in the WHERE-clause is the ***node id*** of the webform (which I can edit via `node/5/edit`). For this webform, I want to query some of its submissions (= results (which I can browse via `node/5/webform-results`).
* `3` in the WHERE-clause is the ***component id*** of the webform (which I can edit via `node/5/webform/components/3`). This particular component is configured as an eMail field, and these collected eMail IDs is what I want to export to a CSV file.

Adapt the hardcoded values `3` and `5` (in the WHERE clause) to fit your requirements. Or transform them in parameters contained in a data block (use this link if you wonder how to do that). Then save this data block with whatever name you want, eg `drupal_cust/webform_submissions_data`.

Use it as a prototype to build your custom report from it, using the Forena Report designer in which you select the `webform_submissions_data` data block mentioned above. Which just a few click you could create a report with a "layout" for which the design (in XHTML format) looks like so (also note the "tokens" shown within the `td`-tags):

```
<body>
  <div id="webform_submissions_data_block" class="FrxTable" frx:block="drupal_cust/webform_submissions_data">
    <table>
      <thead>
        <tr>
          <th>node</th>
          <th>submission</th>
          <th>component</th>
          <th>fieldvalue</th></tr></thead>
      <tbody>
        <tr id="webform_submissions_data" frx:foreach="*">
          <td>{node}</td>
          <td>{submission}</td>
          <td>{component}</td>
          <td>{fieldvalue}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

```

Don't forget to select the "document types" you want to enable (to export the report), such as "CSV" (as in your question).

For the sake of completeness: the "layout" of a report is what is contained with the `<body>` and `</body>` tag. Similar to a regular HTML file, Forena will add an appropriate `<head>` and `</head>` tag in front of it, and surround everything with `<html>` and `</html>` tag (and also adds a few more lines at the beginning, to make it an XML file. So that when you save your report specifications, the entire file gets saved in your file system as a so called ***`FRX`*** file (FRX = Forena Report XML). For the above report layout, this is how the corresponding FRX file looks like:

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY nbsp " ">
]>
<html xmlns:frx="urn:FrxReports">
<head>
<title>Webform Export</title>
<frx:category>Webform</frx:category>
<frx:options/>
<frx:parameters>
</frx:parameters>
<frx:docgen>
  <frx:doc type="csv"/>
  <frx:doc type="pdf"/>
</frx:docgen>
<frx:fields>
</frx:fields>
<frx:menu/>
<frx:cache/>
<style/>
</head>
<body>
  <div id="webform_submissions_data_block" class="FrxTable" frx:block="drupal_cust/webform_submissions_data">
    <table>
      <thead>
        <tr>
          <th>node</th>
          <th>submission</th>
          <th>component</th>
          <th>fieldvalue</th></tr></thead>
      <tbody>
        <tr id="webform_submissions_data" frx:foreach="*">
          <td>{node}</td>
          <td>{submission}</td>
          <td>{component}</td>
          <td>{fieldvalue}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>

```

For the report we designed here, apart from that table in the report body, about the only extra spec we entered in this example is that we want to enable export options for format "CSV" and "PDF". That's what's indicated via what's between the `<frx:docgen>` and `</frx:docgen>` tag. And since we don't use things like report parameters, menu items, special fields, etc, the corresponding frx tags (`frx:parameters`, `frx:menu`, `frx:fields`, etc) have no values specified in FRX file.

Bonus tip: for this scenario, because of the hardcoded values `5` and `3` (in the WHERE clause of the SQL), the report columns titled ***node*** and ***component*** are always the same (= `5` and `3`). So if you'd want to quickly get rid of those columns in the report, just delete their corresponding lines in the FRX files (with the `th` and `td` tags), using your favorite editor (no need to go back to the WYSIWYG report editor, unless you prefer to use that editor). Save the FRX file, and refresh your report ... done.

That's about it ... Sorry the above doesn't give you an idea about how it is like to prototype your data block, or to design your actual report using that data block.

# Answer
> 1 votes
Thank you Pierre.Vriens for your detailed answer.

After some digging in the Drupal database I found the SQL statement to build a datablock with Forena that fits my need.

Here it is if someone have a use case close to mine.

```
SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM users u JOIN webform_submissions s ON u.uid=s.uid
JOIN webform_submitted_data d ON d.sid=s.sid
JOIN field_data_field_groupe f ON u.uid=f.entity_id
JOIN taxonomy_term_data t ON t.tid=f.field_groupe_tid
WHERE t.name=:grpname

```

**field\_data\_field\_groupe** is a custom user field linked to a taxonomy\_vocabulary.

In the WHERE-clause i am using a parameter "**:grpname**" wich let me specify the group. Then it will export all submissions of users associated to the "**:grpname**" parameters.

Then i can use the url below to set up button or anything i need to download all user's submissions associated to my parameter.

http://localhost/drupal-7.54/reports/rapport360.**xls**?t.name=**group1**

Here the file format is **xls** and the parameter is: "**group1**" as you can see.

tips:

1. You can use tokens for the parameters.
2. Evoid using a string as parameter to evoid transliterate problems.

---
Tags: 7, webforms, forena
---


title: Display Search Block in template

text:
# Question
Title: Display Search Block in template
**DRUPAL 8 VERSION**

Hi i am trying to display the search block in a custom view named as `menu--main.html.twig`. Below is the code in my theme function

```
function bootstrap_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('bootstrap_search');
  $variables['block_search_form'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

```

I am able to display the search block in `page.html.twig`. But i want to display the block in `menu--main.html.twig` Can someone guide me how can i achieve this?

# Answer
I was using the wrong hook as suggested by kevin. The hook to be used there was `bootstrap_preprocess_menu__main` .... It all became cleared after reading this comment https://api.drupal.org/comment/62602#comment-62602
> 0 votes

---
Tags: theming
---


# Question
Title: Use the same image 2 times in image styles
A tricky question regarding image styles.

I need to do a thumbnail with 2 layers:

1. background: a cropped picture with a blur effect.
2. foreground: overlay with the same picture and scale effect.

If you have some hints, or you know how to do it programmatically in a custom ImageEffect plugin I would appreciate any help.

This is an example how the image should look like:

# Answer
I have solved the task currently without a custom image style. Only custom code:

```
/**
   * Applies an image effects blur, scale and crop.
   *
   * The result is am image with 2 layers:
   *   - background: a cropped picture with a blur effect.
   *   - foreground: overlay with the same image and scale effect.
   *
   * @param int $width
   *   Result image width.
   * @param int $height
   *   Result image height.
   * @param int $radius
   *   Result image blur radius.
   */
  public function blurScaleAndCrop($width, $height, $radius) {
    $image = $this->getImageFactory()->get($this->path);
    if (!$image->isValid()) {
      throw new \InvalidArgumentException("Image {$this->path} is not valid");
    }

    // Create the background image.
    $image->scaleAndCrop($width, $height);
    /** @var \Drupal\system\Plugin\ImageToolkit\GDToolkit $toolkit */
    $toolkit = $image->getToolkit();
    $resource = $toolkit->getResource();
    // Apply blur.
    if ($radius) {
      for ($i = 0; $i < $radius; $i++) {
        imagefilter($resource, IMG_FILTER_GAUSSIAN_BLUR);
      }
    }
    $image->apply('gaussian-blur', ['radius' => $radius]);

    // Create the foreground image.
    $foreground = $this->getImageFactory()->get($this->path);
    if (!$foreground->isValid()) {
      throw new \InvalidArgumentException("Image {$this->path} is not valid");
    }
    $foreground->scale($width, $height);

    // Merge the 2 image layers.
    $dst_im = $image->getToolkit()->getResource();
    $src_im = $foreground->getToolkit()->getResource();
    $f_width = $foreground->getWidth();
    $f_height = $foreground->getHeight();
    $x = ($width - $f_width) / 2;
    $y = ($height - $f_height) / 2;
    imagecopy($dst_im, $src_im, $x, $y, 0, 0, $f_width, $f_height);
    $image->save();
  }

```
> 1 votes

---
Tags: 8, media
---


title: Alternate of using "delivery callback"

text:
# Question
Title: Alternate of using "delivery callback"
```
$items['mymodule/%user'] = array(
  'title' => 'My Module',
  'page callback' => 'mymodule',
  'page arguments' => array(1),
  'access arguments' => array('access user profiles'),
  'type' => MENU_CALLBACK,
  'delivery callback' => 'mymodule_ajax_callback',
);

```

Above code is from D7, I've used "`mymodule_ajax_callback`" as my "`delivery callback`" in D8 but I'm unable to find a way.

Tried finding solution here Structure of routes but I'm unable to get the solution.

# Answer
> 2 votes
You are looking for responses. For example, in a controller, you can return a renderable array, a Symfony Response object, or specific responses (AjaxResponse, JsonResponse) to respond to the request.

For example, AjaxResponse in the docs, and here is an example of a controller responding with it:

https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8

---
Tags: 8, routes, hooks
---


title: Retrieve field value in a view twig

text:
# Question
Title: Retrieve field value in a view twig
I would retrieve the value of a field of the first row, like this:

```
rows[0].field_name..

```

but the 'array is too large and kint breaks.

# Answer
> 1 votes
You can look up the structure of the view result in your question Get result view with formatter programmattically. (there was no feedback, did it work?)

If you want to use this in twig, it would look like this:

```
{{ view.field.field_name.value(view.result[0]) }}

```

---
Tags: views, theming, 8, entities
---


# Question
Title: Accidentally changed the path of an RSS feed page in Views to refer to a menu link item and cannot access Views menu anymore
I cannot access views from the Structure Menu in Drupal 8 anymore. I accidentally changed the path of an RSS feed page in Views to refer to a menu link item and cannot access the Views menu anymore.

How does one fix this? I get an error that says "The website encountered an unexpected error. Please try again later when trying to access View Menu."

The report log says the following:

"InvalidArgumentException: The internal path component 'http://localhost/drupal/News-Press' is external. You are not allowed to specify an external URL together with internal:/. in Drupal\Core\Url::fromInternalUri() (line 409 of C:\xampp\htdocs\drupal\core\lib\Drupal\Core\Url.php)."

# Answer
> 0 votes
You can export your configuration to files, then edit the file that holds wour faulty view, edit the URL, save it and import the configuiratin again.

To do this:

1. Go to `/admin/config/development/configuration/full/export` and click 'Export'. Your browser should donwload tar.gz file.
2. Uncompress the file to see all your site configuration splitted in multiple files.
3. The file that holds your faulty view file should be views.view.NAME\_OF\_THE\_VIEW. Edit it and look for a line with the view path. It should be:

> path: {wrong path}
4. Change to the right path and save the file.
5. Compress again all files to get again a tar.gz file. Is the same that you downloaded but with the file you have just updated.
6. Go to `/admin/config/development/configuration/full/import` and upload your tar.gz file with the new configuration.

Drupal should update the configuration and change that view url.

**Udpate**

Unfortunately it seems there's a bug with views that can arise when editing file in Windows (an probably Mac): Importing tar file causes Archive\_Tar error

> I had the same problem and I found that I could not open the tar neither. So I tryed other exports. I found that when I don't export views settings, the tar is good. It's only when I put some specific views in the export that the tar does not work.

**Second update** As @user3531869 says, it's possible to update one single file of configuration to avoid the mentioned bug. To do this go to `/admin/config/development/configuration/single/export` and select the element you want to export (in this case select View as configuration type, Aggregator RSS Feed as configuration name), copy the the code that Drupal returns, edit to fix the path and the go to `/admin/config/development/configuration/single/import`, select View as configuration type, paste the edited code in the text area and clicj `Import`.

---
Tags: views, debugging
---


# Question
Title: Use a 3rd part library when uninstalling a module
my module uses several third part PHP libraries, loaded by using the `library` module supported by the `x_autoload` (several third part libraries are based on composer, so this support directly pointing to the composer file).

Just to provide you with an example:

```
function mymodule_libraries_info() {
  $libraries = array();
  ...
  $libraries['mongo-php-library'] = array(
      'name' => 'mongo-php-library',
      'vendor url' => 'https://github.com/mongodb/mongo-php-library',
      'download url' => 'https://github.com/mongodb/mongo-php-library/releases',
      'path' => 'src',
      'version arguments' => array(
          'file' => 'RELEASE-1.0',
          'pattern' => '/RELEASE (\d+\.\d+\.\d+).*/',
          'lines' => 1,
      ),
      'versions' => array("1.0.4"=>array()),
      'xautoload' => function($adapter) {
        $adapter->composerJson('composer.json');
      },
  );
  ...
  return $libraries;
}

```

Everithing works fine (I can use this library in my working code) except for the "uninstall" part.

In fact, I need that the `hook_uninstall()` can access to this library in order to perform several operations, but I receive a `WD php: Error: Class 'MongoDB\Client' not found` error.

I guess this is related to a specific problem: when I try to uninstall the module, it has already been disabled, so its libraries are no loger available when I call the "uninstall".

How can I deal with this problem?

# Answer
For future readers I found a solution fitting my needs, and I'm here to share.

The Early-bootstrap class loading (expert only) page explain how to use the `x_autoload` for loading module classis when uninstalling a module.

There you can read:

> Solution: Put this in your mymodule.module or mymodule.install: `xautoload()->registerModule(__FILE__);`

In any case it works only for module classes.

Starting from that I was able to find an interesting method to get what I desire: `xautoload()->adapter->composerJson('sites/all/libraries/mongo-php-library/composer.json');`

I know it is not very elegant for several reasons:

* the library path is hardcoded -- sadly `libraries_get_path(...)` can't work, because the library is not declared
* we can't be sure the `x_autoload` module is still enabled: it is declared as a dependency of my module, but a user can disable my module, then disable `x_autoload`, then try to uninstall mine

In any case this solution currently fits for me. In the future I can try to deep investigate, but for now it is a proper tradeoff.
> 0 votes

# Answer
Not knowing what "operations" you are performing with this composer lib, I suggest you might want to just think of when you actually want to perform these operations. Doing it on Uninstall seems like a bad idea. Why not utilize `hook_disable`, instead of `hook_uninstall`, which should allow you to do things just before the module gets disabled.

If you really want to do it in a `hook_uninstall`, then you can load your `.module` file using `drupal_load()` and call the functions in your .module file from `hook_uninstall`.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Same CSS file generates under different folder when I flush
A question from a newbie:

I am using a theme in my site and I made some changes in the CSS file. The CSS file I am modifyiing is `Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css`

and it is in the folder: `/sites/default/files/less/1TKupTVXZyLFbxdskTDq5OyCMsRMsIZmPQc_nx40j0Y/sites/all/themes/XXXXXX/less`

So when I flush the caches, a new folder named randomly like above appears in

```
/sites/default/files/less/

```

with the unmodified version of my CSS file `Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css` in it.

Where is the source of this `Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css` so I can modify it for ever?

# Answer
> 1 votes
It's in a theme, module, library, Drupal's misc folder, or basically anywhere that the web server can read; that's as much as can really be said without more info.

To get that info, turn off css aggregation in Configuration -\> Development -\> Performance, then try inspecting the page again. Now you should see the original, unaggregated source file of the rule.

Bear in mind that if you're compiling Sass/Less to CSS, the file you find might not necessarily be the last place you need to look - it depends how the compilation actually happens in your application. But it gives you a good starting point at least.

Also bear in mind the nature of *Cascading* Style Sheets - if you introduce an identical rule with new styles after the original, it will take precedence. So as an alternative to tracking down the original, you could just add a new css file to your theme and give it an appropriate weight so it loads last and your styles "win".

Don't forget to switch aggregation on again afterwards if you need it.

---
Tags: caching, theming
---


# Question
Title: Change a div content after click on another div
I would like to achieve, if is possible, change the content of a div with another content of the same type. For example I have two nodes whose content type are "news" but i want them to render on the same page after clicking on their links.

Tried to achieve with jQuery but i have an undefined error.

This is my code:

```
  $(document).ready(function() {
    var selector = '.title-noticia a';

    $(selector).click(function(e) {
      e.preventDefault();

      $.ajax({
        url: $(this).attr('href') + '?ajaxrequest',
        success: function(data) {
          $('.region-content').replaceWith(data);
        }
      });
    });
  });
})(jQuery);

```

But it doesn't seem to work, is there any way to achieve that without the use of AJAX links API? (It's to slow for me). Thanks in advance!!!

**UPDATE 1:**

After some research, i managed to make it work (on the console), but the content doesn't replace on the page view.

This is my new code:

```
(function ($) {
  Drupal.behaviors.mybehavior = {
    attach: function (context, settings) {

      $('.title-noticia a').click(function(e) {
        e.preventDefault();

        $.ajax({
          url: $(this).attr('href'),
          type: 'post',
          data: {
            view_name: 'articulos_actualidad',
            view_display_id: 'page_2'
          },
          dataType: 'json',
          success: function (response) {
              $('.region-content').replaceWith(data);
              Drupal.attachBehaviors(); //Check on the console
          }
        });

      });
    }
  }
})(jQuery);

```

But the only result i have is:

```
XHR finished loading: POST "http://www.example.com/somerenderedpage".

```

So it literally works but i cannot see the results on the page.

Hope you can help me. Thanks!

**UPDATE 2:**

I will post what i want to achieveI have a headache :) trying to make it work. What i want to achieve is to display the content of the selected link on a div. So i made a graphic so you can understand.

When i click on link 1, i want to display on the main div the content of the link 1, the same with link 2, 3 and X.

Is there any way to achieve that? tried with jQuery AJAX but the performance is poor, the same programatically making an ajax call.

I know i can do something like an slideshow but with content, but i cannot figure it out. Could you lend me a hand please? I will appreciate it. Thanks!

# Answer
You need to conform to the coding standards and make it anonymous so it doesnt conflict with jQuery.

```
(function ($) {
  Drupal.behaviors.mybehavior = {
    attach: function (context, settings) {
      var selector = '.title-noticia a';

      $(selector).click(function(e) {
        e.preventDefault();
      }

      $.ajax({
        url: $(this).attr('href') + '?ajaxrequest',
        success: function(data) {
          $('.region-content').replaceWith(data);
        }
      });
    });
  });
})(jQuery);

```

See more: https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

Your behavior will be called automatically, so there is no need for `$(document).ready`.
> 1 votes

---
Tags: javascript
---


# Question
Title: Can't add assets to my Bootstrap sub-theme
I'm currently struggling to include `*.css` and `*.js` files to my Bootstrap sub-theme.

I use *Drupal 8* and the *Bootstrap 3* base theme. I followed the instructions of the official documentation and went to create a custom *SASS* sub-theme for my site.

I could quickly use my newly created sub-theme in the admin panel. Great.

However it seems none of the assets registered in my `*.libraries.yml` are included in any page.

My `SUBTHEME.info.yml` file:

```
core:       8.x
type:       theme
base theme: bootstrap

name:         'My custom sub-theme'
description:  'This is a sub-theme of Bootstrap, using the Sass starter kit.'
package:      'Bootstrap'
version:      'alpha'

regions:
  navigation:             'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header:                 'Top Bar'
  highlighted:            'Highlighted'
  help:                   'Help'
  content:                'Content'
  sidebar_first:          'Primary'
  sidebar_second:         'Secondary'
  footer:                 'Footer'
  page_top:               'Page top'
  page_bottom:            'Page bottom'

libraries:
  - 'SUBTHEME/global-styling'
  - 'SUBTHEME/bootstrap-scripts'

```

My `SUBTHEME.libraries.yml` file (unchanged):

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

bootstrap-scripts:
  js:
    bootstrap/assets/javascripts/bootstrap/affix.js: {}
    bootstrap/assets/javascripts/bootstrap/alert.js: {}
    bootstrap/assets/javascripts/bootstrap/button.js: {}
    bootstrap/assets/javascripts/bootstrap/carousel.js: {}
    bootstrap/assets/javascripts/bootstrap/collapse.js: {}
    bootstrap/assets/javascripts/bootstrap/dropdown.js: {}
    bootstrap/assets/javascripts/bootstrap/modal.js: {}
    bootstrap/assets/javascripts/bootstrap/tooltip.js: {}
    bootstrap/assets/javascripts/bootstrap/popover.js: {}
    bootstrap/assets/javascripts/bootstrap/scrollspy.js: {}
    bootstrap/assets/javascripts/bootstrap/tab.js: {}
    bootstrap/assets/javascripts/bootstrap/transition.js: {}

```

I strongly believe my folder hierarchy is right ; I use the base bootstrap `themes/bootstrap/templates/system/html.html.twig` which embarks the following header:

```
<head>
  <head-placeholder token="{{ placeholder_token|raw }}">
  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token|raw }}">
  <js-placeholder token="{{ placeholder_token|raw }}">
</head>

```

The CSS / JS aggregation option in the admin/config/development panel is disabled.

I compiled `sass/style.scss` and I do have a corresponding `css/style.css` file, however it never shows up on my pages. Even worse, it seems none of the libraries assets are included either.

No, I didn't forget to clear the cache. I also tried to solve my problem by reading other questions, like this one or this one ; however the questions are either not resolved or do not apply to my case.

I tried to add the following lines to my `SUBTHEME.info.yml`, unfortunately it doesn't work either:

```
stylesheets:
  - 'css/style.css'

```

I tried to use the Drupal/Twig tag `attach_library` with no success.

Interestingly, assets added from third-party modules are successfully added in a way almost identical to what I'm trying.

I'm quite sure I'm missing something simple here. Any help deeply appreciated.

# Answer
> 0 votes
Found the answer here.

Long story short, in Drupal 8, after being compiled, module and theme libraries are thrown together at the same place without namespaces, causing overriding errors with the assets.

To anyone facing a similar problem: don't ever, ever, give the same name to a module and a theme.

This is clearly a Drupal 8 bug ; hopefully it will be corrected in the future. I didn't explored its extent but to be on the safe side you should avoid giving a theme the name of any module, custom or third-party.

# Answer
> 0 votes
I see that you don't include global-scripts in .info.yml file. You should have something like this at the beginning of your .info.yml file:

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

global-scripts:
  js:
   js/URI.min.js: {}
    js/jquery.waypoints.min.js: {}
     js/global.js: {}

```

If this doesn't work, I would highly recommend you to get a fresh copy of SASS directory of starterkits(it is in themes/contrib/starterkits/sass) then check out all the THEMENAME and replace it with your custom theme name. Kind regards

# Answer
> 0 votes
Well, that might be right even though I have never encountered a bug like this. But I would follow the directory standards of Drupal 8 along with composer and drupal console when you need to install theme or module so you can avoid the dirty work.

---
Tags: .info, theming
---


# Question
Title: Inline Entity Form - How to Theme the referenced form edit screen with a tpl.php file?
Inline entity form (IEF) is a module that lets you create other nodes/entity inside of a node edit form (or reference them).

I would like to theme the form edit screen using a tpl.php file. (By form edit screen, I mean the place where the inline form is displayed for the user to input data and *not* the display that shows the finished form (e.g. so the 'edit' part and *not* the 'view' part),

This thread explains how to change values of the fields of the IEF creation screen. But it doesn't show how to use a tpl.php.file.

This tutorial and this tutorial explain how to theme forms. However, their knowledge doesn't seem to apply to Inline Entity forms (mainly because IEF forms don't use a form element).

# Answer
I found the following answer here: http://site-machines.ru/blog/temizaciya-inline-entity-form-v-drupal

===========================

When using Inline entityform time to time it is necessary to make it more beautiful, more than matching the concept of the site. There are several ways to implement this, segodyan I will talk about one of the - the use of theming template.

As Inline entityform is the usual form, so it has a minima must be some hook\_alter. See the documentation that is the way to be in the module - inline\_entity\_form.api.php. The documentation found the right hook - hook\_inline\_entity\_form\_entity\_form\_alter.

At the entrance is just fed our inline form.

The next step is adding theming function

/ \** * hook\_inline\_entity\_form\_entity\_form\_alter * / function sm\_inline\_entity\_form\_entity\_form\_alter (& $ entity\_form, & $ form\_state) { // Added theme function $ Entity\_form \[ '# theme'\] \[\] = 'inline\_entity\_form\_entity\_form\_'. $ Entity\_form \[ '# bundle'\]; dpm ($ entity\_form); } I almost forgot to say the magic is done in our template.php form.

I told him what happened, what we've done in the previous paragraph? We've added a feature to our temizaitsii inline form, not just for one but for all. devel dpm () function module will help us to examine the insides of our Inline form

The next step in our magic, it template.php create hook\_theme and declare it a template for our inline form

/ \** * Implements hook\_theme (). * / function sm\_theme ($ existing, $ type, $ theme, $ path) { $ Items \[ 'inline\_entity\_form\_entity\_form\_shoes'\] = array ( 'Render element' =\> 'form', 'Template' =\> 'inline-entity-form-entity-form-shoes', // This will set to module / theme path by default: 'Path' =\> drupal\_get\_path ( 'theme', 'sm'). '/ Templates / inline\_form', ); return $ items; } Just be sure to create our template file and we put him on the scullery indicated in the 'path' hook\_theme.

Then I inserted the following code template

\<-! Start inline-entity-form-entity-form-shoes.tpl.php -\>

\<-! @ See sm\_theme adn template.php -\>

Then we look at what we will give dpm (), continue using drupal\_render output fields in the required manner
> 1 votes

---
Tags: theming
---


# Question
Title: replacing article or basic page image with video
How can I replace the main image at an article or a basic page with a video? I used the Video Embed Field module but it only embeds the video in the body. What I need is the video to be in the place of the main image, not in the body of the content.

# Answer
> 0 votes
1. Here is a standard front page. The teaser view. I think this is what you see and where you would like to see the video instead of the image.

2. This seems like what you would like. On the preview, add the video.

3. This is the full node view. As you can see, the full text is here.

4. When you go to the content type `admin/structure/types/manage/article/display` the default display is the full node view

5. On the teaser display, `/admin/structure/types/manage/article/display/teaser` (this is for the article content type). At the top right it says teaser.

Here you need to add the *"Embed field"*. By default it was hidden.

You can move the image to hidden if you want.

And with this you get the image from the second screenshot.

I think that's what you want/need.

---

**Original answer. Updated above based on comments.**

If you want to upload, instead of embed, the video module has the option,

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

---
Tags: media
---


# Question
Title: Creating specific front pages for departments
The Drupal 7 site I am working on has its own company front page, and there are a couple of branches of the company in different location. I want to add specific front pages with "about / contact us / other menus" for each of those departments/branches of the company that will be displayed when each of the branches is accessed.

How can I achieve this?

# Answer
If you don't want to code, and you are familar with context module you can use this Context Reaction Menus. Add new context with a URL as a condition, for example "department1/\*" and as a reaction change the main menu, this will change in all pages that start with "deparmente1"
> 1 votes

# Answer
So basically you need different menu on different pages? First create different menus on Drupal backoffice, then check your template files on your theme folder and find where it prints the menu (usually page.tpl.php). Get the nid (node ID, in Drupal 7 the easier way is with args) and place and if/else condition, then print the menu following this
> 0 votes

---
Tags: navigation
---


title: Ignore template from base theme

text:
# Question
Title: Ignore template from base theme
I have written a D8 sub-theme. Base theme is bootstrap, but I don't think it really matters.

My base theme defines a very specific template field--node--field-image--article.html.twig that I would like to ignore, as if it did not exist. I would like to fallback to the next best match template, whatever that is.

I have already considered the following options, but they aren't entirely satisfactory.

1. Delete the unwanted template from the base theme. However I then have to remember to delete the file again every time I update the base theme.
2. Override the unwanted template with an identically named file in my sub-theme. In that file %include the preferred template. However this requires me to name a specific preferred template. I would rather let Drupal decide what template would be the best match excluding the unwanted one.
3. I have discovered the function hook\_theme\_suggestions\_alter. However I'm not sure that it solves my problem because I don't want to lose the ability to use any given suggestion in general - just that one very specific file.

I guess I will end up going with option 1) if I can't find a better idea.

# Answer
> 0 votes
One way to remove the template from being in the list of suggestions, and ultimately not being used, would be to implement `hook_theme_suggestions_alter`, and unset it from the `$suggestions` array. This should effectively remove it, and the next specific template will be used instead.

Alternatively, you can copy the template file in from the base theme, and overwrite it to be a default rendering that is preferable to you (without removing the suggestion) and it will be used instead.

---
Tags: theming, 8
---


title: Theming contact page form

text:
# Question
Title: Theming contact page form
How to add in Drupal 8 a custom (suggestion) default contact page template ?

Thank you

# Answer
> 2 votes
**Way 1: Use drupal template suggestion:**

You can enable the template suggestions by following changes as mention in https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Once you have the suggestions enabled you can see, drupal suggests few template possiblities for any page, you can use any of the suggested template.

https://cl.ly/1f2T0x1a1F2n

**Way2: Declare custom template suggestions**

Or you can customd define template based on any logic by implmenting `hook_theme_suggestions_page_alter()`.

**Example:**

https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html

---
Tags: 8, hooks, emails, theming
---


# Question
Title: Using Migrate API to select items from a JSON array
I have a module pulling a JSON feed into Drupal 8 using the Migrate API. However, one of the values in the JSON is an array.

For example, `coordinates`:

```
{
    "data": [
        {
            "id": "id:1",
            "position": {
                "coordinates": [
                    24.932974,
                    60.168495
                ],
                "type": "Point"
            },
            ...
        },
        {
            "id": "id:2",
            "position": {
                "coordinates": [
                    24.94416,
                    60.18831
                ],
                "type": "Point"
            },
            ...
        },
...

```

What sort of field selector is needed to get `coordinates`?

If I use `selector: position/coordinates` I get 24.932974.

* How would I get the second one: 60.168495?
* Should the `extract` plugin be used here?

# Answer
First, use a selector like this:

```
-
  name: position
  label: 'Position'
  selector: position

```

Then use this for the first value:

```
field_description:
  plugin: extract
  source: position
  index:
    - coordinates
    - 0

```

And this for the second value:

```
field_description:
  plugin: extract
  source: position
  index:
    - coordinates
    - 1

```
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: Preprocessed block not udpating after edit
I am preprocessing a block which seems to get cache and not showing the updated content on front end after getting edit.

My preprocess code looks like:-

```
/**
 * Implements hook_preprocess_block().
 */
function mymodule_aboutus_preprocess_block(&$variables) {
  $act_on_blocks = array(
    'myblockid',
  );
  if (!in_array($variables['elements']['#id'], $act_on_blocks)) {
    return;
  }
  $block = $variables['elements']['content']['#block_content'];
  $body = $variables['content']['body'];
  switch ($variables['elements']['#id']) {
    case 'myblockid':
      $variables['myblock_data']['field_title'] = t('Credits');
      $variables['myblock_data']['field_description'] = $body;
      break;
  }
}

- On Twig template
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {% include "@mytheme/myblock-partial" with {
      "title": myblock_data['field_title'],
      "content": myblock_data['field_description'],
    } only %}
  {% endblock %}
</div>

```

# Answer
**Drupal 8 caching background in breif:-**

Drupal 8 has **strong** and awesome caching mechanism.

Basically any renderable array is now get cached by default and drupal provides cache API to manage in what context (could be in context of user/route etc.)(cache contetx), when to invalidate the cache(cache tags) and till when it should be cached could be Permanent cache(max-age=-1) or no caching at all(max-age=0)

So the renderable array Cache API works around

1. Cache Context
2. Cache Tags
3. max-age

The problem with my code was excessive preprocessing on block content and then avoid `{{ content }}` to print on block twig template, so `{{ content }}` itself take care of `'#cache'` attribute but since I avoided it during preprocessing and printed only my custom exposed variables drupal was never able to figure out when to invalidate the cache, and blocks were permanent cached.

Solution: I just made sure I am also passing the '#cache' attribute to my renderable arrays and then used the same on twig template

```
  // - Example during preprocessing

    /**
     * Implements hook_preprocess_block().
     */
    function cfr_world_aboutus_preprocess_block(&$variables) {
      $act_on_blocks = array(
        'myblockid',
      );
      if (!in_array($variables['elements']['#id'], $act_on_blocks)) {
        return;
      }
      $block = $variables['elements']['content']['#block_content'];
      $body = $variables['content']['body'];
      switch ($variables['elements']['#id']) {
        case 'myblockid':
          $variables['myblock_data']['field_title'] = t('Credits');
          $variables['myblock_data']['field_description'] = $body;
          // Added drupal cache attribute
          $variables['myblock_data']['#cache'] = $variables['elements']['content']['#cache'];
          break;
      }
    }

    // - On Twig template
    <div{{ attributes.addClass(classes) }}>
      {{ title_prefix }}
      {% if label %}
        <h2{{ title_attributes }}>{{ label }}</h2>
      {% endif %}
      {{ title_suffix }}
      {% block content %}
        {# Added to pass cache attribute#}
        {{ myblock_data| without('field_title','field_description') }}
        {% include "@mytheme/myblock-partial" with {
          "title": myblock_data['field_title'],
          "content": myblock_data['field_description'],
        } only %}
      {% endblock %}
    </div>

```
> 1 votes

---
Tags: 8, caching
---


# Question
Title: Configuration successful but never gets imported
I have some changes in core.entity\_form\_display.node.news.default. When I run drush cim -y it says it is successful but it actually never imports it.

```
drush cim -y
Collection  Config                                      Operation
             core.entity_form_display.node.news.default  update
Import the listed configuration changes? (y/n): y
The configuration was imported successfully.            [success]

```

The changes are removing field groups from the form display.

If I try to import via UI it also says it is successful but it never gets imported. I don't get any errors in my error log.

I tried to make some other configuration changes like changing the site name and it works. It seems to be an issue with Field Group or at least when deleting a field from from a form display.

# Answer
> 4 votes
Sounds like a known core bug: https://drupal.org/node/2666392

---
Tags: 8, configuration, entities
---


# Question
Title: Why are not all stylesheets in mytheme.info being loaded?
I have a strange issue, when I include the last CSS file (`assets/fonts/montserrat/style.css`), then the `assets/css/style.css` doesn't get loaded. It seems to have to do with duplicate naming of files, when I rename the stylesheet to `montserrat.css`, the issue is gone.

How do I solve this issue while keeping the naming of files intact?

`mytheme.info`:

```
name = mytheme
description = My custom theme
core = 7.x

stylesheets[all][] = assets/plugins/bootstrap/css/bootstrap.min.css
stylesheets[all][] = assets/plugins/font-awesome/css/font-awesome.min.css
stylesheets[all][] = assets/css/style.css
stylesheets[all][] = assets/css/custom.css
stylesheets[all][] = assets/fonts/montserrat/style.css

```

# Answer
> 3 votes
the answer is in the drupal\_get\_css doco page:

> Themes may replace module-defined CSS files by adding a stylesheet with the same filename. For example, themes/bartik/system-menus.css would replace modules/system/system-menus.css. This allows themes to override complete CSS files, rather than specific selectors, when necessary.

If you look at the source code at the bottom of the page, the array that contains the css has the basename of the file as the key. So this is an intentional feature.

You will just have to keep the renamed file.

Hope this helps. :)

---
Tags: 7, theming
---


# Question
Title: Why are anonymous visitors logged in when they visit /user/[uid] page?
This seems to be a massive security floor in Drupal. I have the following display suite code in a Block which is added as a custom field to the User account display:-

```
    <?php
global $user;
$uid = arg(1);
$user = user_load($uid);
$roles = $user->roles;

if (in_array('RoleName1', array_values($roles))) {
 print "<a href='/xyz'><img src='/sites/default/files/image.png' style='max-height:200px;max-width:200px;'></a>";
}
if (in_array('RoleName2', array_values($roles))) {
 print "<a href='/xyz'><img src='/sites/default/files/image.png' style='max-height:200px;max-width:200px;'></a>";
}

?>

```

It checks for a couple of Roles and shows an image if they have a particular Role.

When an anonymous user now loads a user account page, they are logged in as that user! Visiting "/user/1" means they are logged in as the admin user!!!

# Answer
This is no security hole, it's the custom code you shared.

```
// When you load the global user object ...
global $user;
// ... and then assign another user object to the global $user object ...
$user = user_load(<any_uid>);
// ... Drupal basically changes the context of the current user.
// It's kind of a hacky login by code.
// Hacky because, till this code executes
// there's no log about the user login, until drupal writes the current session into the database.

```

Typically `$account` is advised to prevent accidents like this.

```
$account = user_load(<any_uid>);

```
> 3 votes

# Answer
So the actual answer is that loading the $user object in a display suite code block, with a different ID than the current session user, means they will assume the identity of that user along with all their permissions.

Then allowing this block to be displayed to anonymous users, e.g. a dynamic block on the public user profile page, means that even users without a valid login could potentially browse to the block in question and gain entry.

BEWARE site builders and copy-pasters!

As @Kevin posted below, the best way to do it is:-

```
$account = menu_get_object('user');

```

or

```
$account = user_load(arg(1)); -

```

Don't assign anything to the $user object. This shouldn't really be available to the code.
> 0 votes

# Answer
Be sure to read Safely Impersonating Another User, which describes how to do so securely for Drupal 6, 7, or 8. The code in the question is not secure.

If you do need to actually switch to a different user during a page request, then the following code will do so:

```
global $user;
$original_user = $user;
$old_state = session_save_session();
session_save_session(FALSE);
$user = user_load(array('uid' => 1));
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session($old_state);
// From here on the $user is back to normal so it's OK for the session to be saved

```

If however, switching the global user is not what you had intended then the answers by arpitr and Darren should be used.

Note that if the page is cached, then internal data can be leaked.
> 0 votes

---
Tags: security, display-suite
---


title: Front page redirects to user page

text:
# Question
Title: Front page redirects to user page
I just installed D8, but when I try to reach the Front Page as an authenticated user, I got immediately redirected (302) to the user page. As a anonymous user, it works as expected.

I do not know exactly what additional data I should provide for debugging this issue, but will happly provided any information I can.

# Answer
> 1 votes
In the "Default front page" field at /admin/config/system/site-information, instead of leave it blank, insert /node which is normally what drupal places by default.

---
Tags: 8
---


# Question
Title: How to create a view with 1 item in left column and 2 in right column?
I need to make a view of featured content. I'd like to make it so that two columns display: the left column with one item, and the right with 2 items. Essentially like this spot:

I've been trying with some different layouts, but for some reason this is escaping me. It can't be that hard, can it?

EDIT: I may not have been clear enough in my original post. The answers given so far seem to refer to formatting the fields in different positions, so that for each piece of content, field A would be on the left, and fields B and C on the right. That is not what I need.

What I need is instead of displaying three fields in this format, I need to display three pieces of content in this format. For this view, each image links to a different piece of content, so I'm only using a single field. I need to display the image for node A on the left, and images for nodes B and C on the right.

# Answer
If you are having `panels` module installed than the best would be to use the **Panels fields** as following:

1. Set the display style in your View to show Panel Fields.
2. Add the fields you want to show in your view.
3. Configure the settings of `Panel fields` as:
    * Select Panel layout: Two column stacked
    * Assign fields to the respective section (e.g: top, right, left), as per your requirement.
4. Save the view.

Check the attached screenshot for reference:
> 1 votes

# Answer
You could create 2 views; both with the same criteria, but the first one returns a single result, and the other one returns 4 results (or however many) in a grid, with an offset to skip the first result. Then just embed the views on a page using Panels.
> 1 votes

# Answer
you can use views\_fieldset module

> Creates fieldsets in Views fields output, to group fields, by adding a new field: "Global: Fieldset" and a few preprocessors. Also introduces a new template: views-fieldsets-fieldset.tpl.php where you can customize your fieldset output.

Once you install it ,it will allow you to have a fieldset/div or better to say grouping of fields inside different divs and then simply use css to give allign them.
> 0 votes

# Answer
This can also be done in your tpl file. Say you format your view as a grid you would use a `views-view-grid--your-view--your-display.tpl.php`.

Then you would modify your copied default tpl for the rows. Putting something like this just in front of your foreach that prints out the rows should be pretty close:

```
$first = array_shift($rows);
<tr class="row-class">
  <td class="col-class">
    <?php print $first['your-field']; ?>
  </td>
</tr>

```

Untested and from memory but should get you really close.
> 0 votes

# Answer
Use CSS to resize the result nodes and float result node 1 to left and/or 2 and 3 to right. No modules, no server processing...
> 0 votes

---
Tags: views
---


# Question
Title: How do I edit and delete entityform submissions?
I'm using entityform for a particular submission. I set the rule When submitting the entityform, which is stored in a particular content type. It works well, but when I edit and delete the particular entityform submissions it doesn't work.

Is there any rule or hook available to store entityform submissions to a particular content type?

# Answer
> 0 votes
use entityform hook\_form\_alter with devel module in this case i suggest to view your data before submit button ... and entityform hook\_form\_insert to view your data after submission button using devel module or drupal\_set\_message. You can actually alter in hook\_form\_alter button to store entityform submission to particular content type.

---
Tags: 7, entities
---


# Question
Title: How do I modify the HTML of my subtheme?
I created a bootstrap subtheme ouf of CDN. Modifying the CSS works, but how do I do it with the HTML? Where do I put new HTML elements? For example: I'd like to add some elements to my footer, make it background color black and have it the width of the screen (it's not by default in Bootstrap)

This is my subtheme folder:

# Answer
> 2 votes
A sub theme inherits its templates from the base theme. When you want to edit templates for your sub theme you simply copy over the desired template from the base theme's template folder into your sub theme's template folder, flush the cache and start editing it.

And then flush the cache again.

---
Tags: 8, theming, bootstrap-theme
---


# Question
Title: How to change the default navigation "active-trail" class to something different (or add an extra class)?
How do I change the default "active-trail" class on the navigation menu `<li>`-item to something different, or add an extra class to the current active item?

# Answer
> 2 votes
You can use the theme\_menu\_link function to add or remove classes from menu items. This will target all menu's on the page though.

Probably easiest is to target the menu directly with this function `theme_menu_link__main_menu`. You have to put display your menu as a block though. For bartik there is already a block available.

**Steps**

* Uncheck **Main menu** at *admin/appearance/settings/bartik*
* Put main menu block in a region (e.g. header region)
* Now you can do:

```
function bartik_menu_link__main_menu (&$variables) {
  $link = $variables['element'];
   if (isset($link)) {
    if (isset($link['#attributes'])) {
     $link_classes = $link['#attributes']['class'];
     if (in_array('active-trail', $link_classes)) {
      $variables['element']['#attributes']['class'][] = 'myclass';
     }
    }
   }
 return theme_menu_link($variables);
}

```

If you want to style the main menu when it's not in a block you could use:

```
function bartik_links__system_main_menu($variables) {
  $links = $variables['links'];
  if ($links) {
    foreach ($links as $link) {
      $link_classes = $link['attributes']['class'];
      if (in_array('active-trail', $link_classes)) {
        // add or remove classes here
      }
    }
  }
  // return themed links
}

```

---
Tags: 7, theming, navigation
---


# Question
Title: Accessing Leaflet maps from custom module
Trying to add to Leaflet map marker from the custom module. Leaflet map created with IP Geolocation Views & Maps module. I try to connect to the map as described here http://dripl.nl/blog/taming-leaflet-maps-drupal The message alert appears with the coordinates, but the map does not increase the zoom. What could be the reason?

I also tried to replace the string *myMap = lMap;* with *var myMap = Drupal.settings.leaflet \[0\] .lMap*; not help.

test\_module.module

```
function test_module_form_article_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo']['#element_validate'][] = 'test_module_validate_function';
}

function test_module_validate_function($element, &$form, &$form_state){
    $marker = [49.055688666667,34.338167222222];
    test_module_add_marker($marker);

}

function test_module_add_marker($marker) {
    drupal_add_js(drupal_get_path('module', 'test_module').'/test_module.js');
    drupal_add_js(array('test_module' => array('marker' => $marker)), array('type' => 'setting'));
}

```

test\_module.js

```
(function($) {
  $(document).bind('leaflet.map', function(e, map, lMap){
    myMap = lMap;
  });

    Drupal.behaviors.test_module = {
        attach: function (context, settings) {
            latlon = settings.test_module.marker;
            alert(latlon);
            myMap.setView(latlon, 14);
        }
    };

})(jQuery);

```

# Answer
I managed to solve the problem in the following way, I hope it save someone time:

```
(function($) {

var lMap = Drupal.settings.leaflet[0].lMap;

    Drupal.behaviors.test_module = {
        attach: function (context, settings) {
            latlon = settings.test_module.marker;
            //alert(latlon);
            lMap.setView(latlon, 14);
        }
    };

})(jQuery);

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to delete old images uploaded via FAPI
Consider the following bit of code in my custom module... It allows a user to upload an image, saves the fid as a variable, and in a custom submit function, it makes sure that the file in the file\_managed table is saved permanently.

This all works great, but when my users are uploading a file, then saving, then removing that old file and uploading another and saving, all of these files are left in the file\_managed table, with a status of 1.

```
function MYMODULE_admin() {
  $form = array();
  $form['style']['business_logo_fid'] = array(
    '#title' => t('Business Logo'),
    '#type' => 'managed_file',
    '#description' => t('Upload a logo for your business in one of the following formats: jpg png jpeg.'),
    '#default_value' => variable_get('business_logo_fid', ''),
    '#upload_validators' => array(
    'file_validate_extensions' => array('jpg png jpeg'),
    ),
    '#upload_location' => 'public://',
  );

  $form = system_settings_form($form);
  $form['#submit'][] = 'after_save_ui';
  return $form;
}

function after_save_ui($form, &$form_state) {

    $business_logo_fid = variable_get('business_logo_fid');
    if ($business_logo_fid) {
        $business_logo = file_load($business_logo_fid);
        $business_logo->status = FILE_STATUS_PERMANENT;
        file_save($business_logo);
    }

}

```

How do i mark these old images as unused after a new one has been saved in its place? Is there something I can do to get the fid from the old file and mark its status as 0 before the new one gets saved? or is this something that Drupal handles already for me?

# Answer
> 0 votes
Its always the way! You spend an hour fussing over it, but when you actually write the question down, you think of it in a different way!

Its a bit long winded, but my complete example is this...

```
 function MYMODULE_admin() {
      $form = array();
      $form['style']['business_logo_fid'] = array(
        '#title' => t('Business Logo'),
        '#type' => 'managed_file',
        '#description' => t('Upload a logo for your business in one of the following formats: jpg png jpeg.'),
        '#default_value' => variable_get('business_logo_fid', ''),
        '#upload_validators' => array(
        'file_validate_extensions' => array('jpg png jpeg'),
        ),
        '#upload_location' => 'public://',
      );

      $form = system_settings_form($form);
      $form['#submit'][] = 'after_save_ui';
      return $form;
    }

    function after_save_ui($form, &$form_state) {

        // Save the Business Logo Permenantly.
if (isset($form_state['values']['business_logo_fid'])) {
        $new_logo_id = $form_state['values']['business_logo_fid'];
        $old_logo_id = $form_state['complete form']['style']['business_logo_fid']['#default_value'];
          if (($old_logo_id != 0) && ($new_logo_id != $old_logo_id)){
            $business_logo_file = file_load($old_logo_id);
            if (!empty($business_logo_file)) {
              file_usage_delete($business_logo_file, 'webfroth_booking_ui', 'business', $business_logo_id);
              file_delete($business_logo_file, TRUE);
              drupal_set_message(t('Old Logo Removed.'));
            }
          }
          if (($new_logo_id != 0) && ($new_logo_id != $old_logo_id)){
            $current_business_logo = file_load($new_logo_id);
            if (!empty($current_business_logo->fid)) {
              $business_logo_file_id = $current_business_logo->fid;
              variable_set('business_logo_fid', $business_logo_file_id);
              file_usage_add($current_business_logo, 'webfroth_booking_ui', 'business', $business_logo_file_id);
              $current_business_logo->status = FILE_STATUS_PERMANENT;
              file_save($current_business_logo);
              drupal_set_message("New Logo Uploaded Successfully.");
            }
          }
        }
    }

```

This works great, but it CANT be the standard way to handle this everytime I want to use an image field in a custom module surely? Seems like a massive hassle!

---
Tags: 7, files
---


# Question
Title: How can you create a list of referenced nodes in a view?
I have a content type on my Drupal 7 site which has a field called field\_related, with a type of Node reference (I've installed References). This allows me to select nodes that are related to the one I am editing. I'd like to then display these in a view, but am coming unstuck with the setting up of the view.

I've set up a single document with some related nodes for testing. If I set a relationship up in my view as "Content: Related Nodes (field\_related) - reverse", I see a list of the related nodes I defined. But I see these same related nodes on every single page - not just the page they are defined for. ("Require this relationship" is ticked.)

If I set up the relationship as "Content: Related Nodes", nothing appears. I've tried a variety of filters, contextual filters and relationships, but that hasn't helped much.

I'm sure I'm missing something obvious ... can anyone enlighten me?

Some screenshots of the current setup, so you can see what I've got so far:

* View
* Contextual filter
* Relationship

# Answer
Got there in the end, thanks to a combination of the (very nice and helpful) Baysaa and keva. This was the method that got there in the end:

* Contextual Filter: **Content: Nid** (set to "do not use a relationship"; default value of "content ID from URL")
* Relationship: **Content: Related Nodes** (with "require this field")
* Then, I went to **Format** and changed **Show: Content** to anything else. Then I changed it back to **Show: Content** \- this allowed me to select the relationship I defined above (I couldn't define the relationship here without changing **Show: Content** to something else first).
> 3 votes

# Answer
On the settings of the "Content: Related Nodes" contextual filter, under "WHEN THE FILTER VALUE IS NOT AVAILABLE" have you selected "Provide default value" and set "Content ID from URL"?

EDIT: Sorry I meant under the "Contextual Filter". "Content: Related Nodes" should be a Contextual Filter, not a relationship.
> 2 votes

# Answer
It would help to know how you will be using the view. If you just want to show the related nodes (B,C,D) on node A - say in a sidebar block - then your view is getting over-complicated.

Remove the Contextual filters and Relationships you have, then ...

Add field:

* Content: Related Nodes
* Choose a formatter

Add Contextual Filter:

* NID
* WHEN THE FILTER VALUE IS NOT AVAILABLE \> Provide default value \> Content ID from URL
> 2 votes

# Answer
Contextual Filter: Content: Nid select \>\> Provide Default value \>\> PHP code

As we will be displaying related nodes block on a node view page for which we want to display related nodes. So we will load that node first and get all the related nids. Then we return the nids in string format like below '56 + 32 + 112'

```
$nid = arg(1);
$node = node_load($nid);
$str = "";
$related_nids = $node->field_related_nodes[$node->language];

if(is_array($related_nids) && sizeof($related_nids)){
  foreach($related_nids as $related_nid){
    $str .= ($str)? '+' .  $blog['nid'] :$blog['nid'];
  }
}
return $str;

```

Also click the More link in contextual filter and check "Allow multiple values"`enter code here`
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to alter commerce checkout form in a custom module?
I'm using commerce and want to alter the checkout form in a custom module to prepopulate certain fields and hide them.

However, I'm not able to do this using `hook_form_alter()` as well as `hook_commerce_checkout_pane_alter()`.

Here's my sample code:

```
function MYMODULE_form_alter($form, &$form_state, $form_id) {
  global $user;

  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
      // Rename the button for example.
      $form['buttons']['continue']['#value'] = t('Overridden value');
      break;
  }
}

```

How can I edit fields that are displayed on checkout?
Is there some other hook I should use?

Thanks!

# Answer
> 5 votes
I think you're looking for `commerce_checkout_form()` (`commerce_checkout_form_checkout` doesn't exist as far as I can tell from greping Commerce's code):

```
function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

```

or

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}

```

# Answer
> 1 votes
Use form\_alter to customize commerce checkout page submit button values.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
      if (isset($form['buttons']['continue']['#value'])) {
        $form['buttons']['continue']['#value'] = t('Overridden value');
      }
      break;
  }
}

```

---
Tags: 7, commerce
---


title: Why Drush cron go to view of nodes?

text:
# Question
Title: Why Drush cron go to view of nodes?
i have a simple function to return 404 on some content-type

```
function module_type_node_view($node, $view_mode, $langcode) {
  // variables
  $type = $node['#node']->getType();
  $userRole = \Drupal::currentUser()->getRoles();
  // if is events2/subsidiary
  if(($type === 'events2' || $type === 'subsidiary') &&
  (in_array('anonymous', $userRole))) {
    throw new NotFoundHttpException();
  }
}

```

But if i run drush cron i have this error:

```
Symfony\Component\HttpKernel\Exception\NotFoundHttpException:  in module_type_node_view() (

```

The crohn is performed anonymously, I have no way to create an exception

# Answer
I'm going to assume there is something running with cron like a search indexer or something handling nodes, and since it is run anonymously, it triggers this.
> 2 votes

---
Tags: 8
---


# Question
Title: Custom Entity field of type long_text not storing values
I created a entity.

```
$fields['supplemental'] = BaseFieldDefinition::create('text_long')
                ->setLabel(t('Supplemental'))
                ->setDescription(t('Answer description.'))
                ->setDisplayOptions('view', array(
                    'label' => 'hidden',
                    'type' => 'text_default',
                    'weight' => -3,
                ))
                ->setDisplayOptions('form', array(
                    'type' => 'text_textfield',
                    'weight' => -3,
                ))
                //->setRequired(TRUE)
                ->setDisplayConfigurable('form', TRUE)
                ->setDisplayConfigurable('view', TRUE);

```

And I'm saving data into this entity's field like

```
$mcq = Mcq::create(array(
           'supplemental__value' => $value->supplemental,
            'supplemental__format'=>'basic_html',
        ));
$mcq->save();

```

**Issue is** all fields gets populated except of type '`text_long`'. Am I missing something or there is any other way of populating entity field values.

# Answer
After realising few minutes later, the column name should be `supplemental` not `supplemental__value`.

I was mapping content by looking into database columns which was wrong.
> 3 votes

---
Tags: 8, entities
---


title: Drupal sessions in angular app

text:
# Question
Title: Drupal sessions in angular app
I'm developing an angular application which uses drupal as a backend. When user login to my webapp, they can able to get some data from the drupal backend. Also, I'm maintaining a session for that user in the drupal backend.

I want to get that session values of a user from drupal backend to my angular app. Is there any possibility to do this?

# Answer
> 2 votes
I didn't use any session data, but I have passed sections of `Drupal.settings` on into the Angular scope when declaring modules. It worked for my case. Here is an example:

```
angular.module('mypackage.name', []).constant('appConfig', Drupal.settings.custom_module.custom_module_config);

```

This lived within the libraries folder (attached to pages by Drupal) for 7.x.

But I am not sure that it really matters what backend you have here, this seems like an Angular question. Here is one that might help: https://stackoverflow.com/questions/14957450/maintaining-session-through-angular-js

---
Tags: services, sessions
---


# Question
Title: Does poll not allow multiple anonymous votes?
We're having a problem with the core poll module on drupal 7. We have a poll that we want anonymous users to be able to vote on. There is currently one anonymous vote, and now anonymous viewers only see the result (we've tried looking at it from outside our network).

We've checked the perms, and anonymous can vote and view results ( but not change vote). We've cleared the cache.

How does Poll work on D7 with regards to the anonymous user?

# Answer
The problem is that the poll module only allows one vote per anonymous IP address. In the case of your hosting provider I *suspect* that they are using some sort of proxy that sends all requests to Drupal from the same IP address.

The Poll Enhancements Module modifies this behavior to allow multiple anonymous votes from the same IP address. The documentation on this module's description page also suggests the Poll Improved Module may solve this as well, but it does not have a production release at this time.
> 5 votes

# Answer
If it works anything like the drupal 6 version it stores a single vote per uid in the database. The anonymous user is user 0 so all anonymous votes are considered to be one user.
> 0 votes

# Answer
I try with the Brent's answer but this don't works for me, then i modified poll module of core D7.

This module block the votes for ip, then this lines change this:

file: home\_site/modules/poll/poll.module

search the function "poll\_vote" and add a random number to the ip address and replace it in the db\_insert, like this:

`$ip_random = mt_rand(0, 100000);
 $ip_real = ip_address();
 $ip_new = $ip_real.".".$ip_random;
 global $user;
 db_insert('poll_vote')
 ->fields(array(
 'nid' => $node->nid,
 'chid' => $choice,
 'uid' => $user->uid,
 'hostname' => $ip_new,
 'timestamp' => REQUEST_TIME,
 ))
 ->execute();`

The module have a cache, then if u vote the browser will not let you vote again, but if u clean the cache or close the browser u can vote again.
> 0 votes

---
Tags: 7, polls
---


title: trusted host patterns in web hosting

text:
# Question
Title: trusted host patterns in web hosting
Do I need to add my IP in settings.php and change settings.local.php if I'm only doing web host? Because I would like to fix the status report about no trusted host patterns. Thank you all for helping

# Answer
> 1 votes
No, you only need to add the hostname patterns in settings.php for how the site is being accessed, which normally isn't by IP. settings.local.php shouldn't be involved, as that is typically just for local development (I never adjust trusted patterns for local dev, just staging and production).

Essentially, the portion of code that handles this looks at the HTTP `Host` header, which is the hostname portion of the URL you requested (unless your webserver does canonical Host normalization, which is different that the rewrite rule for canonical URL). The IP address never comes into play, unless you browse directly to the a URL where the "hostname" portion is the IP.

---
Tags: configuration
---


# Question
Title: Getting error on installing bootstrap subtheme?
Why i am getting this error **"Unable to install bootstrap\_subtheme, THEMENAME.settings has unmet dependencies"**. ?

Also my themename.theme file showing error on renaming **"The item could not be renamed."** for removing this error i created a clone blank file with name bootstrap\_subtheme.theme and copy content of original themename.theme file ,paste it into the bootstrap\_subtheme.theme file and finally deleted the original themename.theme file.

Still i am getting the following error **Unable to install bootstrap\_subtheme, THEMENAME.settings has unmet dependencies**.

# Answer
I was getting the same error message and here's how I fixed it. In your subtheme folder (docroot/themes/bootstrap\_subtheme) there's a config folder with two subfolders: install and schema. Each of these subfolders has a YML file with THEMENAME in the file name, I just changed THEMENAME to my subtheme name and then I was able to install my subtheme.
> 2 votes

---
Tags: 8
---


# Question
Title: Trigger jQuery "add more" multiple times
I have a form that I am filling with default values in `hook_form_alter`. Some of the fields are in a in a field group and I need to trigger the "add more" button using code.

I figured out how to send a value to the jQuery code via `$form['#attached']['js']`. I thought I could use that value to run a loop in the jQuery to trigger the "add more" as often as necessary but I only see the field group values twice.

For example if there should be four sets of field group values, I will see the first and second one but not the third or fourth. If I click on the add more button two more times I'll see them in the form.

Here is the code in the js file:

```
(function ($, Drupal) {
  // Custom functions and variables can go here
  Drupal.behaviors.example = {
    attach: function (context, settings) {
      // Put your document's onload code here
      //alert(Drupal.settings.example.clicks);
      for (var i = 0; i < Drupal.settings.example.clicks; i++) {
        //alert(i);
        $("#edit-fgm-node-example-form-group-stuff-add-more").trigger("mousedown");
      }
    }
  };
}(jQuery, Drupal));

```

This where I attach the js file

```
function example_after_build($form, &$form_state) {
  // TODO: Stuff!

  $settings['clicks'] = $_SESSION['count_of_items']; //the initial count of times to trigger jquery
  drupal_add_js(['example' => $settings], 'setting');

  // Add our JavaScript file, named after_ajax.js. This file
  // lives in the /js folder inside our module:
  $form['#attached']['js'] = [
    [
      'type' => 'file',
      'data' => drupal_get_path('module', 'example') . '/js/after_ajax.js',
    ],
  ];
  return $form;
}

```

Any advice on how I could trigger the "add more" multiple times? Or is what I want to do not possible?

# Answer
> 0 votes
It is possible that the ID of the "Add more" button you're targeting is changing as the first AJAX request comes back (the form will be rebuilt, so IDs of all elements will change). Try changing `'#edit-fgm-node-example-form-group-stuff-add-more'` to a class-based selector.

# Answer
> 0 votes
It because each time Ajax triggered JavaScript function attached again it will be several click handler, for prevent this problem use `once` function.

I mean put following statement on `once` function

```
for (var i = 0; i < Drupal.settings.example.clicks; i++) {
  //alert(i);
  $("#edit-fgm-node-example-form-group-stuff-add-more").trigger("mousedown");
}

```

Reference 1
Reference 2
Similar question

---
Tags: 7, forms, javascript
---


# Question
Title: Multi-site vs Large Single site for Intranet
Whenever I look at "Should I use Multi-site?", it always seems to depend on the use case. (I am using Drupal 7)

I have been developing a company's Intranet on a single Drupal install and it is getting larger and larger.

I have about 75 Content Types and over 500 fields.

The reason for the Drupal site having so many Content Types is to give each department access to manage nodes within specific content types. (Using Content Access).

There are also additional Content Types for workflows that are using with Rules.

I feel the greatest performance hit when managing fields on a Content Type. Other than that, the site still runs smoothly.

In a situation like this where there are going to be so many more fields and content types added, does it make sense to use Multi-site instead? Or is it perhaps the specs of my Server that are causing the slowness?

It is convenient having everything on one site since I can have a unified Dashboard, not have to re-make the User groups/roles on multiple sites, etc.

In this use case, is it worth converting my structure to a Multi-site setup?

# Answer
> 0 votes
Another alternative you may want to consider is to start using the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".

And because Group also integrates with the Rules module, you could probably transform your workflows related rules toward Group equivalents.

# Resources

---
Tags: entities, multi-sites
---


# Question
Title: How can i integrate geofield module in entityform?
Actually i have to add multiple locations in a form of a route and show it after the submit button in a single map using geofield module. How do i do that???The map should locate multiple markers after submit button in one map with their latitude and longitude... the image mentioned in the second is my first image which i am getting now whereas the image been showed at first should be my output image...

# Answer
> 0 votes
i got a better way to do this the thing i wanted was to create integrate multiple locations in one Maps and display the route.. I created this using a HTML file using HTML,CSS, JavaScript and using Markup module i integrated my code in my Entityform. I is working like a charm.

---
Tags: google-maps
---


# Question
Title: How to upload files which are other than English names?
In Drupal, how to upload files which are other than English names?

The problem I am facing is that when I upload files for which their name is other than English their name changes to an unknown format in the file directory, like:

```
áˆ¾áŒáˆ®á‰½áŠ“ áˆ¨á‹³á‰µ á‹¨á‰µáˆá áŠ á‰ áˆ  áŠ¨áŒá‰¥áˆ áŠáƒ_2

```

Any help?

# Answer
> 1 votes
Have a look at the Transliteration module. Here is a quote from its project page:

> Provides one-way string transliteration (romanization) and cleans file names during upload by replacing unwanted characters.
>
> Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

Here is a sample of what this module does for "**file names**":

---
Tags: commerce, files
---


title: CSS properties In-Place-Editor

text:
# Question
Title: CSS properties In-Place-Editor
Is there a possibility to get CSS properties at the In-Place-Editor of Panels in order to define a CSS class or are just the "stylizer" meant to be used?

# Answer
> 0 votes
Add `.panels-ipe-editing` before your css for it to only affect IPE.

eg.

```
.panels-ipe-editing .pane-title { margin: 0px; }

```

You might need to use `!important;`

---
Tags: panels
---


title: Indexing custom entity types

text:
# Question
Title: Indexing custom entity types
I have two custom content entity types that I've created with a module. Neither one of these content entity types extends Node.

Our site has a search bar, and we want to include these two custom content entity types in the core search results (searching within the name of the entity only).

The only demo I can find on this topic is this, but this doesn't seem to be working for me. I've modified the code to match the identifiers and properties of my custom entity type, placed the code in the module's src/Plugin folder, cleared the cache, but my entity type still does not appear as an option in /admin/config/search/pages. Only Content and Users continue to be available search pages. Additionally I am suspicious that this work for a custom content entity type since I am trying to match search index IDs with entity IDs in the queries within the code, but I think this consistency is only maintained for node entities.

I have also tried following this method of defining a search page through Views, but none of the options this poster has selected are available when I try to make a search page for a custom content entity type (for example "Search" as a filter criteria is not present).

I can't seem to find very much useful info on this topic and am wondering if there are any resources I'm simply missing or misunderstanding.

# Answer
> 2 votes
To answer the question, if an entity wants to be included in drupal search, it has to provide a search plugin, which is when discovered listed by the plugin manager from the search module. If not you should first check the annotations of the plugin, see for example the plugin from the node entity:

```
namespace Drupal\node\Plugin\Search;

/**
 * Handles searching for node entities using the Search module index.
 *
 * @SearchPlugin(
 *   id = "node_search",
 *   title = @Translation("Content")
 * )
 */
class NodeSearch extends ConfigurableSearchPluginBase implements AccessibleInterface, SearchIndexingInterface {

```

To debug this, clear the cache and list the discovered plugins:

```
drush ev "var_dump(\Drupal::service('plugin.manager.search')->getDefinitions())"

```

If all went well you have a third plugin here together with the node and user plugin and you should see it in the admin UI of the search module in the select box *Search page type*.

---

To give a recommendation, I agree with the commment from @Berdir. It's not worth the effort to write a custom search plugins, better use Search API:

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

---
Tags: 8, entities, search
---


# Question
Title: Is it safe to use php within a Rules condition?
Using Rules I need a condition which checks if the logged in user has authored a given content type.

It seems that I need some custom php for this and I found the code below from a post on drupal.org, which works as required and my rule now does exactly what I want it to do.

I had to enable php filter (for User 1) in order to get the code in to my rule. But I have read that php filter should be disabled on production sites but find that my rule ceases to work if this is done.

I am not a coder and am need to know what is the best way to deal this situation?

https://drupal.org/node/2052241

# Answer
> 5 votes
The PHP filter uses `eval()`. `eval()` gets a bad rap because it *can* be used insecurely. This post on SO goes into detail on that.

The answer to your question is that it could *potentially* be insecure, depending on the input provided, and how you have things configured. So getting rid of PHP filter altogether would be the ideal resolution (as it pretty much always is).

Getting your code out of the database and into version controllable files is extremely desirable, and is always considered better practice than using the PHP filter.

The proper way to provide rules conditions is to create a custom module, and implement `hook_rules_condition_info()`. If you're not a programmer then that might be a bit daunting, but at that point it's up to you to decide whether the risks outweigh either learning to do it yourself, or paying someone else to do it.

# Answer
> 4 votes
The PHP-module and its associated PHP filter may create security holes when *used improperly*.

The main reasoning behind the advice you've read about having it disabled on production sites, and it being removed from core in Drupal 8, is that it lowers the bar for creating PHP, making is simpler for non-programmers and unskilled programmers to add PHP to a site's code base (in particular, PHP code that don't sanitize user input).

However, the main risk is that by enabling it, some unthinking admin may give access to the PHP-filter for *all* users (not only the trusted user #1).

Given *improper use*, the site can be compromised by any script-kiddie. By leaving the PHP module completely disabled, you've eliminated that risk.

However, that being said, the PHP-module is useful in some situations (as you've discovered), and I think that it is over-cautious to *never* having it enabled on a production site. As long it is *only* allowed for user #1 (i.e. the implictly trusted super-admin), and the PHP that is added is safe (for the record, the code proposed at Create a Rule to Evaluate If a Logged-in User Has Created Content of Type X is safe), then the site is not put in jeopardy by having it enabled.

Just thread carefully, and make sure you you know enough about Drupal to understand that the PHP-filter should not be enabled for "Filtered HTML" or any other text format that untrusted users are allowed to use, and that the code you add to the HTML-textarea using this feature must by *itself* be safe.

PS: Some people seem to think that it is somehow "better" to add PHP to a site by writing a custom module instead of having it in the database. IMNSHO, it makes little difference where you keep it. A bad programmer is unfortunately perfectly capable of creating unsafe PHP *anywhere*. Having unsafe PHP inside a file instead of inside the database will not save you if the PHP-code happens to be unsafe in the first place - even if you've paid somebody to create it for you.

# Answer
> 0 votes
What's included in the previous 2 answers is "`true`", but IMO there is yet another possibility to "*deal with this situation*" (as in your question). I.e. try to come up with an alternative solution that doesn't require any "custom PHP".

Have a look at this quote from "Create a Rule to Evaluate If a Logged-in User Has Created Content of Type X" (= the HowTo you linked to in your question):

> ... the SQL query checks the database for a user who has created one or more nodes of the type configuration\_1. If one or more nodes exist for this user, the condition evaluates to false ...

Building a list of nodes using the Views module, with identical selection criteria, is rather straight forward (not further explained here). And if you then use the Views Bulk Operations (VBO) module to transform that view into a VBO view, you can use a Rules Condition "*** Check number of results returned by a VBO View\***" in which you can perfectly construct the Rules Condition you're looking for.

True, this requires 2 extra modules (which should be available in mostly any site anyway), but it requires zero custom code. And hence you avoid the need for the dangerous PHP filter.

PS: Have a look at "this answer" for an illustration of how this specific Rules Condition is used.

---
Tags: rules
---


# Question
Title: Rule to create a Node from a Webform Submission
Using Rules with Webform Rules enabled, how would I make a new node after a webform submission and use the submitted values as field values in the node?

In short, **how do I turn webform submissions into nodes using Rules.**

I've set up the Rule like this:

Where do I go from here? I can't seem to find a way to move webform submission values into the node's fields.

---

**Please note:** I have read "Using webform rules to create node after webform submission" and "How to create a node with submissions of a webform?". Unfortunately, neither address my question.

# Answer
Below is something I learned about using webform data in Rules, which may help you to get this to work ... (assuming this question is about D7).

You have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

So try to use similar tokens.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform).
* the *2nd attempt* explains what to do in case of Webform.

**Note**: if your target field is a multi value field, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "*Add item to a list*".
> 1 votes

---
Tags: nodes, rules, webforms
---


# Question
Title: How do I rewrite a facet item label using facetAPI bonus?
I am looking at the code example provided by Facet API Bonus module in the section Rewrite facet items via callback function

```
function HOOK_facet_items_alter(&$build, &$settings) {
  if ($settings->facet == "YOUR_FACET_NAME") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
    }
  }
}

```

How would I modify that to override the label of a specific facet item?

# Answer
> 1 votes
This snippet forces the output to be uppercase by using `drupal_strtoupper($item["#markup"]);`. And then sets `$build[$key]["#markup"]` to this new uppercased value.

If you need to check for a specific item, you could use:

```
function HOOK_facet_items_alter(&$build, &$settings) {
  if ($settings->facet == "YOUR_FACET_NAME") {
    foreach($build as $key => $item) {
      if ($item["#markup"] == 'my value') { // Check if this is the right item
        $build[$key]["#markup"] = 'my overridden value';
      }
    }
  }
}

```

---
Tags: 7, search
---


# Question
Title: Exposing webform submissions for Views, but not giving anonymous users permission to view all submissions
I have a webform set up in Drupal 8 and am trying to create a View that displays certain fields from form submissions. The webform and the view seem to be set up fine and are working.

The problem comes in when I want the view to be visible for anonymous users. I seem to be stuck with two options, neither of which are ideal:

* Option 1: Anonymous users can see the page created in Views, but there are no fields on it.
* Option 2: Anonymous users can see the page with the fields, but I have to grant the "View any webform submissions" permission, which then gives them access to view (and download) on the webform page itself.

Can anyone help me with an option 3, where the fields are visible in this View, but without granting the "View any webform submissions" permission to anonymous users?

# Answer
> -1 votes
You will have to give following permissions to anonymous users from permissions page. admin/people/permissions

View any webform submissions

Allows viewing all webforms and submissions.

---
Tags: views, 8, webforms
---


# Question
Title: Give a role permission to add and edit their terms in a taxonomy
In Drupal 7 I am trying to give users the ability to add terms to a taxonomy and then edit only the terms they have created.

I'm using the Taxonomy access fix module to give users permission to add terms in specific taxonomies. However, Drupal does not provide an "edit own terms" permission like it does for nodes. Users can either edit all terms in the taxonomy, or not have editing permission.

Is there any solution for this?

# Answer
> 1 votes
If drupal doesn't provide any "edit own terms" permission, then better do it programatically if you wish.

While accessing term page, load/check for the owner of term and allow them to access edit page.

# Answer
> -2 votes
There are a number of modules that do this that can be found through a simple google search.

https://www.google.com/search?num=100&q=taxonomy+access+drupal+permissions&oq=taxonomy+access+drupal+permissions

This looks great https://www.drupal.org/project/taxonomy\_access

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


title: Views References

text:
# Question
Title: Views References
I have a view that is shown in a block. This view-block shows nodes that have the same taxonomy term selected than the host node (the node thats shows the block).

Well that's the plan.

Node A \- has a field "my\_tax\_ref\_field" (tax\_term = 4)

The view should list... \- nodes with the field "my\_tax\_ref\_field" (tax\_term = 4)

I am lost...

I tried to set conditional filter on the node id. Then I set a relationship on the field "my\_tax\_ref\_field". I thought then the normal filter could pick up the relationship to filter for the term\_id.

But it just does not work like that.

What I am doing wrong?

Thanks

# Answer
> 1 votes
ok... it's easier than expected:

Choose " Provide default value " as action to take if arg is not given. Choose Term ID from URL" Check "Load default filter from node page, that's good for related taxonomy blocks" :)

https://stackoverflow.com/questions/11162196/create-a-drupal-view-that-loads-all-articles-that-share-any-one-taxonomy-term-c?rq=1

---
Tags: views, 8
---