# Question
Title: Use Condition in Computed Field with Field Collections
I have an entity with a field colleciton (fc\_details), and in that field collection I have fields amount(field\_amount) and Type (field\_type)

There are several examples to sum up field colleciton values in computed field like:

```
$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
  foreach($wrapper->field_fc_details as $collection) {
    $sum += $collection->field_amount->value();
  }

$entity_field[0]['value'] = $sum;

```

But I want to sum up values, where field\_type values = "Z".

I tried variations of "if($wrapper-\>field\_type-\>value()='Z' " inside foreach, but then site gives 500 error.

Any ideas ? Thanks in advance.

# Answer
Try the following and let me know how you go.

```
if($collection->field_type->value() == 'Z') {
  $sum += $collection->field_amount->value();
}

```
> 1 votes

# Answer
OK, I solved the problem by this way: When I try to fetch the value inside the if condition, it throws 500 error. So I first assigned a variable to the control value and used it in if condition, it worked.

```
$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
  foreach($wrapper->field_fc_details as $collection) {
   $type = $collection->field_type->value();
   if ($type == 'Z'){
    $sum += $collection->field_amount->value();
   }
  }
$entity_field[0]['value'] = $sum;

```

Still couldn't get the reason, but it works.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Upgrade Backup and Migrate from 2.x to 3.x
Is it possible to upgrade without losing profile settings? Or is it simply uninstall 2.x, install 3.x and recreate profile settings?

# Answer
It is possible to do that upgrade without losing any data.
> 0 votes

---
Tags: backups
---


title: Only the first result shows in my view

text:
# Question
Title: Only the first result shows in my view
I have a view with 2 fields, `node_title` and `node_related_content`. For the field `node_related_content` I use the `formatter = rendered node` and `view mode = Preview`. These *rendered nodes* are fetched from a multiple value field in a content type "product group" that I use for listing related products.

In the view I use a contextual filter that gives me all the node IDs that belong to this view.

Now, the view works fine for one result (one group of rendered nodes). But if I enter more than one node ID in the preview field it onlyt gives me the first group... I need to have all the products groups, not just the first one.

What do I do wrong here?

This is the resulting SQL query:

> SELECT node.title AS node\_title, node.nid AS nid, field\_data\_field\_koppla\_givare.delta AS field\_data\_field\_koppla\_givare\_delta, field\_data\_field\_koppla\_givare.language AS field\_data\_field\_koppla\_givare\_language, field\_data\_field\_koppla\_givare.bundle AS field\_data\_field\_koppla\_givare\_bundle, field\_data\_field\_koppla\_givare.field\_koppla\_givare\_nid AS field\_data\_field\_koppla\_givare\_field\_koppla\_givare\_nid, 'node' AS field\_data\_field\_koppla\_givare\_node\_entity\_type FROM {node} node LEFT JOIN {field\_data\_field\_koppla\_givare} field\_data\_field\_koppla\_givare ON node.nid = field\_data\_field\_koppla\_givare.entity\_id AND field\_data\_field\_koppla\_givare.entity\_type = 'node' WHERE (( (node.nid = '26262,21888' ) )AND(( (node.status = '1') )))

So the above query only shows the rendered nodes found in the product group 26262. The product group 21888 is ignored.

UPDATE: after experimenting with the SQL query in phpmyadmin I have found out that the last row in the query should look like this:

> WHERE (( (node.nid IN('26262', '21888', '21877') ) )AND(( (node.status = '1') )))

Now, how can I alter my view to reflect that change?

# Answer
The solution was very simple, and I found it here: Views related nodes with contextual filters multiple-value handling problem

I just had to tick the "Allow multiple values" box under the More section in the contextual filter. A bit embarassing in the end... but that box was very well hidden indeed.
> 1 votes

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


# Question
Title: Returning alternate HTTP codes for unpublished node
I'm trying to return the 404 page instead of 403 response for unpublished nodes in Drupal 8.

I tested kernel response subscriber, but found the code I was using would only change the status code to 404 from 403, not actually display the 404 page. So maybe someone can show me how to generate a 404 page Response object there?

This is the code I was using:

```
class ResponseSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [KernelEvents::RESPONSE => [['alterResponse']]];
  }

  /**
   * Change status code to 404 from 403 if page is an unpublished node.
   *
   * @param FilterResponseEvent $event
   *   The route building event.
   */
  public function alterResponse(FilterResponseEvent $event) {
    if ($event->getResponse()->getStatusCode() == 403) {
      /** @var \Symfony\Component\HttpFoundation\Request $request */
      $request = $event->getRequest();
      $node = $request->attributes->get('node');
      if ($node instanceof Node && !$node->isPublished()) {
        $response = $event->getResponse();
        // This changes the code, but doesn't return a 404 page.
        $response->setStatusCode(404);

        $event->setResponse($response);
      }
    }
  }

}

```

I finally resorted to removing this response subscriber completely and used hook\_node\_access like this:

```
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Access\AccessResult;

function unpublished_404_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {

  if ($op == 'view' && !$node->isPublished()) {
    if (\Drupal::moduleHandler()->moduleExists('workbench_moderation') && $account->hasPermission('view any unpublished content')) {
      return AccessResult::neutral();
    }
    elseif (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical' && \Drupal::routeMatch()->getRawParameter('node') == $node->id()) {
      throw new NotFoundHttpException();
      return AccessResult::neutral();
    }
  }

  return AccessResult::neutral();
}

```

This seems to be in line with several answers on this site for Drupal 7. But I wanted to see if anyone has a better way of doing this either with a KernelEvent subscriber, rather than hook\_node\_access. It seems like what I want to do is test if a node is returning a 403 and then generate a new response with the 404 page and 404 status code. I'm not sure how to do that.

# Answer
You can try to do this earlier in an exception instead of a response subscriber. Extend `HttpExceptionSubscriberBase`, so you need less code to do this. Then replace the 403 with a 404 exception with the method `$event->setException()`

*/src/EventSubscriber/Unpublished404Subscriber.php*

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Unpublished404Subscriber extends HttpExceptionSubscriberBase {

  protected static function getPriority() {
    // set priority higher than 50 if you want to log "page not found"
    return 0;
  }

  protected function getHandledFormats() {
    return ['html'];
  }

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    if ($request->attributes->get('_route') == 'entity.node.canonical') {
      $event->setException(new NotFoundHttpException());
    }
  }

}

```

*mymodule.services.yml:*

```
services:
  mymodule.404:
    class: Drupal\mymodule\EventSubscriber\Unpublished404Subscriber
    arguments: []
    tags:
      - { name: event_subscriber }

```

This replaces all 403 exceptions for canonical node routes. You can get the node object `$request->attributes->get('node')` if you want to check if this is really because the node is unpublished.
> 8 votes

---
Tags: 8, http-request
---


# Question
Title: Commerce Flat Rate Shipping not being added in Paypal Express Checkout
I'm hoping this is straight forward, but I can't seem to find the answer.

I have Drupal Commerce setup and working properly. I have Commerce shipping setup to use a flat rate of $7.00 I have Commerce PayPal Express checkout setup.

Product is $40.00 Flat Rate shipping is $7.00 Once customer adds shipping the total reflects $47.00 When the customer goes to PayPal to pay, PayPal is only showing $40.00

For some reason, the shipping amount is being removed once the customer hits PayPal.

Anyone know what's wrong?

# Answer
> Did you enable shipping service selection in the order confirmation checkout pane provided by the PayPal Express Checkout module? – Ryan Szrama

Thanks again Ryan for pointing out another not so obvious answer!

To "enable shipping service selection in the order confirmation checkout pane provided by the PayPal Express Checkout module"

Go to: admin/commerce/config/checkout/form/pane/paypal\_ec\_review

"Checkout pane configuration These settings are specific to this checkout pane. Checkout panes to include on the Express Checkout review and confirm page"

Check this box! - Shipping service

Ralph Manis - Infinitee Web Design
> 0 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: Where do I edit the HTML surrounding a field's output?
I am working on a site that has an image Field (machine name: `field_resp_media`) that outputs images.

I simply need to add an attribute to the `<img>` tag this field outputs.

I've run keyword searches in modules/contrib and modules/custom, and I came up with nothing.

Would anyone know what file I need to edit and add this attribute?

# Answer
> 2 votes
In Drupal, you don't edit any file belonging to a module/theme you didn't create.

Rather, in your case, you use the hooks Drupal makes available to change the output a module or a theme creates with a theme hook.
In the case of an image field created with the field API, the theme hook that outputs the HTML for the image field when it is rendered on page is `theme_image_formatter()`. What you need to do is overriding that theme hook in a module or in the theme you use for the site.

Since you don't need to totally change the output from that theme hook, you just need to implement `hook_preprocess_image_formatter(&$variables)` and add your attribute to `$variables['item']['attributes']`.

Keep in mind that `hook_preprocess_image_formatter(&$variables)` is invoked for every image field used by Drupal, so you need to be sure you are altering the output of the right image field.

As per implementing `hook_preprocess_image_style()`, this hook is not necessarily called for an image field, since `theme_image_formatter()` contains the following code.

```
  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image);
  }
  else {
    $output = theme('image', $image);
  }

```

It is just invoked when the image field uses an image style. Plus, it would be invoked every time an image style is used, which doesn't necessarily mean when a image field is rendered on a page.

Similar problem there is with `hook_preprocess_field()`, which would invoked every time a field is rendered with `theme('field')`.

# Answer
> 0 votes
It will possible using `THEMENAME_preprocess_image_style` & `THEME_preprocess_field`.

Please check this link. https://www.drupal.org/node/2169157 it will help you.

---
Tags: 7, entities
---


# Question
Title: How can I add a wrapper around my nodes?
How can I wrap my nodes (output in teaser view) in a `<div>` element?

```
<div class="region region-content">
  <h1 class="js-quickedit-page-title page-header">My title</h1>
  // <div class="teasers"> <--- add this
    <article>...</article>
    <article>...</article>
    <article>...</article>
    ...
  // </div> <--- add this
</div>

```

# Answer
Copy the corresponding twig template of your view into your module/theme and name it properly after the view's display, fe. `views--{type, fe. unformatted}--my-view-id--my-block.html.twig`.
> 0 votes

---
Tags: 8
---


# Question
Title: How to load jquery cookie library for anonymous user
It seems with login user jQuery Cookie added and worked correctly but when I visit my website with not login user(anonymous) then I faced with `TypeError: $.cookie is not a function`. Why This happened and **how can I attach jQuery cookie libraries for not logged in users by default?**

Notes: My theme is based on Drupal Bootstrap theme

# Answer
> 9 votes
For available Jquery and Jquery cookie for anonymous user, it should add it on theme libraries dependencies , as example if your theme name is `themename` on `themename.libraries.yml` add

in Drupal 8

```
  dependencies:
    - core/jquery.cookie

```

(Drupal 9 Deprecated core/jquery.cookie and will remove in D10.)

**then in Drupal 9 and 10 use**

```
  dependencies:
    - core/js-cookie

```

Thanks @Mr.Thi to mention this

---
Tags: 8, javascript
---


title: Problem setting a private directory

text:
# Question
Title: Problem setting a private directory
I have problems establishing a private files directory (D7.22)

I started at reading this article: http://drupal.org/documentation/modules/file. I then created a `private` folder above the Drupal root, and entered its path `../private` at `admin/config/media/file-system`. Despite being warned about the performance implications, I chose the Default download method as `Private local files served by Drupal`. Then, in a content type I created a native file field named Attachment, with Upload destination set to `Private files`. Widget: File.

At this stage I imagined that these settings would cause an uploaded file to go inside the `../private` directory. Nope, instead they go into public directory `sites/default/files`. Was my assumption wrong?

I tried the following debugging changes - but to no avail:

* changed `../private` to `sites/default/files/secure`
* changed field widget to Media file selector
* changed default download method to `Public local files served by Drupal`

Is it a site ghost? Am I doing anything wrong? I really see no reason for this not to work. I'm close to filing a bug issue but would appreciate someone confirm that on their installation before I do so.

# Answer
> 6 votes
I'm using private upload on several sites and can confirm that this works. So no need to file a bug issue.

> At this stage I imagined that these settings would cause an uploaded file to go inside the `../private` directory. Nope, instead they go into public directory `sites/default/files`. Was my assumption wrong?

No. This is indeed what should have happened.

So just to make sure, I set up a site to your exact specifications. I.e. with Drupal root in `/demo/drupal` and the private directory in `/demo/private` (where `/` is the Unix *file system* root).

I first tested it using the absolute path (i.e. `/demo/private` as the private upload directory). That worked without a glitch.

I then re-tested it using the relative path to the same directory (i.e. `../private`). That also worked without a glitch.

I also noted that Drupal threw the following error if I tried to input a non-existing directory as the private upload directory:

```
Warning: mkdir(): Permission denied in drupal_mkdir()
 (line 2341 of /demo/drupal/includes/file.inc).
 The directory /demo/bogus does not exist and could not be created.

```

In other words: If Drupal allow you to use `../private` as the private upload directory without throwing this error, your setup *should* work for private upload.

Drupal will automatically place a `.htaccess`-file in the private upload directory to protect it against prying eyes. However, for best security, the private upload directory should be above the web-root.

PS: As for the file being "served merrily to an anonymous user", this will happen if the anonymous user is *granted* access to the *node* the privatly uploaded file it attached to.

All that the "private download method" does, is to extend Drupal's access control system so that files attached to nodes are made inaccesible to those who happen to know their URL. It does so by pretending that the attachement is stored in the fictitious directory (`system/files/`). Since this directory does not exist, bypassing Drupal by converting the path into an URL and requesting it directly from the web server will not work.

This is different from, and more secure than the "public download method". This method let those who know a file attachement URL bypass Drupal's access control.

# Answer
> 0 votes
Thanks a million. Simply putting the private folder under the sites/default/files folder did it for me, because really the private system of drupal put in an .htaccess file, that confuses anyone who tried to directly download the file using the url. So for clarity, set up the private folder in media configuration to be : sites/default/files/private Greg

---
Tags: 7, files
---


# Question
Title: Drupal 8: javascript not loading in theme
I would like to add a little javascript to my bootstrap child-theme, but is not loading.

These are the configuration files:

child.info.yml :

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

name: 'child'
description: 'Uses the jsDelivr CDN for all CSS and JavaScript. No source files or compiling is necessary and is recommended for simple sites or beginners.'
package: 'Bootstrap'

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:
  - 'child/global-styling'

```

child.libraries.yml:

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

  js:
  js/main.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

main.js

```
$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

```

# Answer
> 2 votes
Change

```
$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

```

to

```
Drupal.behaviors.basic = {
   attach: function (context, settings) {
   (function($) {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
   })(jQuery);
  }

```

};

# Answer
> 1 votes
Two things.

One, YAML has to be properly formatted. In another question, I recommended using YAML Lint to ensure you have the right structure.

Should be:

```
global-styling:
  css:
    theme:
      css/basic-page.css: {}
      css/masonry.css: {}
      css/style.css: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
  js:
    js/main.js: {}

```

Also, it is best to split your style and Javascript into two definitions but I suppose thats up to you.

Two, your Javascript has to be compatible with Drupal per the docs.

Instead of:

```
$(document).ready(function() {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})();

```

What you want is:

```
(function($) {
    Drupal.behaviors.windowScroll = {
      attach: function (context, settings) {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
      });
    }
})(jQuery);

```

> Note: Since Drupal uses jQuery.noConflict() and only loads JavaScript files when required, to use jQuery and the $ shortcode for jQuery you must include jQuery and Drupal as dependencies in the library definition in your MODULE.libraries.yml and add a wrapper around your function.

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
     $(context).find('input.myCustomBehavior').once('myCustomBehavior').each(function () {
      // Apply the myCustomBehaviour effect to the elements only once.
    });
    }
  };
})(jQuery, Drupal);

```

# Answer
> 0 votes
**In your-theme.libraries.yml file:**

```
base:

 version: 1.x

js:

 js/main.js: {}

```

**In your-theme.info.yml file:**

```
libraries:

 - 'your-theme/global-styling'

 - 'your-theme/base'

```

Try above method worked on my previous drupal8 website, i think your js file is not loading.

Also place a js folder in your bootstrap subtheme along with your main.js file

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


# Question
Title: Recoverable fatal error when trying to run hook_query_TAG_alter()
I used the approach provided here to reverse comments order in Drupal 8:

```
    /** Implements hook_query_TAG_alter().
 *
 * Alter comments query to order by DESC as well as the default ASC.
 */
function MYMODULENAME_query_comment_filter_alter(QueryAlterableInterface $query) {
  $orderby = &$query->getOrderBy();

  // Sorting for threaded comments.
  if (isset($orderby['torder'])) {
    // Sort by root parent first, then normal threaded.
    $query->addExpression("SUBSTRING_INDEX(c.thread, '.', 1)", 'rparent');
    $orderby = array('rparent' => 'DESC') + $orderby;
  }
  // Sorting for flat comments.
  else if (isset($orderby['c.cid'])) {
    $direction = 'DESC';

    $orderby['c.cid'] = $direction;
    $orderby = array('c.created' => $direction) + $orderby;
  }
}

```

but I receive the followig error when run the module:

> Recoverable fatal error: Argument 1 passed to mymd\_query\_comment\_filter\_alter() must be an instance of QueryAlterableInterface, instance of Drupal\Core\Database\Query\PagerSelectExtender given, called in D:\wamp95\www\drupal83\core\lib\Drupal\Core\Extension\ModuleHandler.php on line 501 and defined in mymd\_query\_comment\_filter\_alter()

what is the problem and how should I solve it?

# Answer
> 1 votes
I used Drupal\Core\Database\Query\AlterableInterface $query as argument.

It solved the problem.

---
Tags: 8, database
---


title: Why can't I run krumo() on a node page?

text:
# Question
Title: Why can't I run krumo() on a node page?
I called `krumo()` inside `hook_node_load()`.

```
function mymodule1_node_load($nodes, $types) {
    krumo($nodes);
}

```

It works on my front page, but not on a node page. I get this error message:

> Fatal error: Call to undefined function krumo() in C:\wamp\vhosts\mydrupal72\sites\all\modules\my\_customs\mymodule1\mymodule1.module on line 126

Why can't I run `krumo()` on a node page?

# Answer
> 0 votes
An option would be using `module_load_include()`. Manually making sure it's loaded

---
Tags: 7, debugging
---


title: Add field to PDF template

text:
# Question
Title: Add field to PDF template
Hello I am working with Views PDF Module, and I am asking how could add a fields to the PDF template file

Thanks.

# Answer
> 0 votes
From the module page:

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

So from within Views, add a PDF page display. Then add the fields you like.

---
Tags: files
---


title: String replace with rules

text:
# Question
Title: String replace with rules
Is there a way to string replace with rules?

I'm trying to find some way to transform values without changing a value entirely.

Is there something I'm missing, or should I just make a custom rule that does string replace?

# Answer
> 0 votes
I used this for my incoming feeds, changing http:// to https://

```
{ "rules_http_to_https" : {
    "LABEL" : "http to https",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "feeds" ],
    "ON" : { "feeds_import_canada_com" : [] },
    "DO" : [
      { "data_set" : {
          "data" : [ "node:body:value" ],
          "value" : "\u003C?php\r\necho str_replace(\u0022http:\/\/\u0022 , \u0022https:\/\/\u0022, \u0022[node:body]\u0022 );\r\n?\u003E"
        }
      },
      { "data_set" : {
          "data" : [ "node:field-contestpageurl" ],
          "value" : "\u003C?php\r\necho str_replace(\u0022http:\/\/\u0022 , \u0022https:\/\/\u0022, \u0022[node:field-contestpageurl]\u0022 );\r\n?\u003E"
        }
      }
    ]
  }
}

```

---
Tags: 7, rules
---


# Question
Title: Drupal 7 sessions wiped after changing settings.php
Yesterday afternoon I had an administrator uncomment and modify the $base\_url variable in our production environment. Any changes made in the repository fires off a redeployment which has never been an issue. Upon the server coming back up, we started receiving complaints that user's who were now logged out.

Does changing settings.php do something behind the scenes that I'm unaware about (session.cookie\_lifetime or session.gc\_max\_life).

I do not have access to the database nor can I retrieve it from our prod environment.

Any help is appreciated so that we don't run into this issue again!

# Answer
> 2 votes
This is likely due to the value changing, which changes the way they are recorded:

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal\_settings\_initialize/7.x

`$base_url` and `$cookie_domain` \- changing these values in settings.php will affect any user who was authenticated before if the values change, and will need to re-authenticate.

---
Tags: 7, database, configuration, cookies
---


# Question
Title: How to create automatically a view of all nodes sharing the same field value?
Working with Drupal 7.54 and Views 3.15

For each content type field, I need to display a link (after the value) which returns a view of all nodes sharing the same field value.

I manage to get my link (field - rewrite results and add a link with tokens) but I need to create a view (with specific contextual filter related to the field) for each field.

Is there a way to build this so I do not need to create x views for x fields? Any token for the field? Any PHP contextual filter using field\_name and field\_value?

Thanks in advance.

Example :

Node 1

* Field A : value x (link)
* Field B : value y (link)

etc.

The link returns a view :

All nodes with value x for Field A

* Node 2
* Node 7
* Node 15

...

Related questions :

Create a view of all nodes that have the same value for a specified field as the current node

# Answer
> 1 votes
# Suggested method

I suggest looking into using the Search API (with Views) for this purpose.

From the Search API module page:

> This module integrates the Search API with the Views module, allowing searches on any index to be created and viewed via Views. All of an entity's properties, as well as those of related entities (e.g. a node's author's name), are available as fields, filters and arguments for all indexed fields are available and sorts (as well as click sorts) can be created on any indexed single-valued field. Also some additional features, like linking the results to the entity, are available.

Drupal.org uses this method to create Issue pages with links like: `https://www.drupal.org/project/issues/search_api?text=&status=13&priorities=All&categories=All&version=All&component=All`. You should be able to craft your links to the view integrated with the Search API using tokens.

# Detailed Instructions

I was able to set this up in my testing with the following steps, which are detailed below.

* Install the Search API and related modules
* Set up a search server
* Set up a search index
* Set up a view of the search index
* Create the links to the view with tokens

## Install the Search API and related modules

Install and enable the Search API module. Also enable the Search views extension module that comes with the Search API.

## Set up a search server

For my testing, I used the Search API Database Search module. This is a separate module in Drupal 7 but it is in the main Search API project for Drupal 8. From the module page:

> This module provides a backend for the Search API that uses a normal database to index data. It is therefore a cheap and simple alternative to backends like Solr, but can also be a great option for larger sites if you know what you're doing.

This search server set up may work for you, or you may need to configure a different service class for your search server. I think specific instructions on other options like Solr are out of the scope of this answer, but I recommend taking a look at the Service classes and features documentation page which lists various options and their features.

To use the Search API Database Search, install and enable the module. Then visit Configuration \> Search and Metadata \> Search API (admin/config/search/search\_api) and click **+Add server**. Name your server, leave the **Enabled** checkbox checked, and choose the Database service as the **Service class**. Click **Create server**.

## Set up an index

Visit Configuration \> Search and Metadata \> Search API (admin/config/search/search\_api) and click **+Add index**. Name your index, choose the **Item type**, and restrict by Bundle (content type) if desired. I restricted to Nodes of type Article in my testing. You can leave the Bundles checkboxes blank if you want to include all content types. Choose the server you set up in the previous step as the **Server**. Click **Create index**.

Now, you will select the fields you want to add to the index. In my testing I added an Integer field to the Article content type, so I added both the integer field and the tags field to the index. Check the fields you want to add and click **Save changes**.

The next part of the configuration is the Filters settings. You can choose to add "Alterations" or "Processors" to the data in the index. Your choices here will depend on what kind of data you're indexing, each option has a description that will help you understand what it does. In my testing I chose to Exclude unpublished nodes under Alterations and I chose Ignore case under Processors. Click **Save configuration**.

At this point, you should click the **View** tab to see the Index status page and add items to your index. The Index status page is located at Configuration \> Search and metadata \> Search API \> Edit (Your Index) (admin/config/search/search\_api/index/INDEX\_MACHINE\_NAME). For testing purposes I suggest indexing in a small batch at first and clicking **Index now**.

## Set up a view of the search index

Now, visit Structure \> Views (admin/structure/views) and click **Add a new view**. Name your view and in the **Show** dropdown field choose Your Index. Click continue and edit.

In the view under **Filter Criteria**, add a filter for your each of your indexed fields (I know that will be a lot of fields in your specific case). I added one for the Integer field and one for the Tags taxonomy field. Make sure you click the "Expose this filter to visitors" checkbox for each filter. (You can also look into the Facet API for the facets option, however I think you would end up with a block for every field you wanted to put a facet on as opposed to one disabled block with a ton of filters you won't use. I think the Facet API method would also be worse for performance but I may be incorrect.)

Now you can visit the view page and adjust the exposed filters to get the URL structures you need to use with your tokens. Or, the pattern is: `https://example.com/[VIEW_NAME]?[FIELD_MACHINE_NAME]=[FIELD_VALUE]`

### Change the Exposed form to a block

For your use case, it sounds like you just want the results from your links and not really a search page with filters or facets. So, once you've got your tokens and URLs working, in your view settings expand the **Advanced** section and change the **Exposed form in block** to Yes. This will put all the filters you've added to a block that must be manually enabled. The filtering in the URL will still work, users just won't see the exposed form with all the possible filters.

## Set up your fields to be links with tokens in your content type

It sounds like you've already got the tokens in links part working on your nodes or your view of nodes. In my testing, I found you can exclude all link arguments except the one you're filtering with, and the view will display everything that matches that field regardless of the other filters.

So, instead of having to make a link this: `https://example.com/test-view?field_integer_field=&other_field=&another_field=&field_tags=[TOKEN_VALUE]`

Your link can just include the one relevant filter: `https://example.com/test-view?field_tags=[FIELD_VALUE_TOKEN]`

---
Tags: 7, views
---


title: How to forward an email to external URL

text:
# Question
Title: How to forward an email to external URL
I would like to create a page that will automatically forward to an external site? Similar to what bitly, tinyurl do. So when people type example.com/page in address bar, site will automatically take them to mysite.com? How can I achieve that?

# Answer
> 1 votes
Sounds like you can just create a URL redirect with Redirect, and send to an external URL. No need to create a node.

---
Tags: theming
---


title: Date formatting: Code or Template?

text:
# Question
Title: Date formatting: Code or Template?
A theory/best practice question as opposed to a technical one. Should it be up to a module's code to format a timestamp into a date string, or the template that displays it?

E.g. the two ways of doing it (both with the same result):

MYMODULE.module

```
$variables['date'] = date('m-d-Y', $timestamp);
return theme_render_template('template.tpl.php', $variables);

```

TEMPLATE\_FILE.tpl.php

```
<span class="date"><?php print $date; ?></span>

```

Or:

MYMODULE.module

```
$variables['date'] = $timestamp;
return theme_render_template('template.tpl.php', $variables);

```

TEMPLATE\_FILE.tpl.php

```
<span class="date"><?php print date('m-d-Y', $date); ?></span>

```

# Answer
Instead of `date()` you should use `format_date()` instead per Drupal.

https://api.drupal.org/api/drupal/includes%21common.inc/function/format\_date/7.x

`format_date` takes various settings and user config into account when formatting the date, whereas just `date` is a php function, and thus, will not. You can also pass it a custom date format name.

While you *can* use `format_date()` at the template level, usually it is best to do it in a preprocess function and pass it along to the template. If you have a module that is supplying variables to a template, supply them upfront.

Variables should be print-ready for the user, with the option of overriding later (extending or preprocessing at the theme level, etc).
> 2 votes

---
Tags: 7, theming
---


# Question
Title: What are the really use of the ancient Project Application issue queue now that you can promote your own sandbox projects?
The Gates are open for Drupal.org Code Contributions, so now you can promote sandbox projects to full projects with releases if you have accepted the git terms of service.

But what is the actual use of the legacy Project Application issue queue (which is now named Drupal.org security advisory coverage applications?

I post this question because I have a module in revision there a some users that says that the code is OK, they made some suggestions and I made the changes until the last comment that says:

> When a node Add is disabled, you should at minimum highlight which content type won't accept new content (in fact providing node edition instead).

This is a UX change that don't affect the security and don't affect the module functionalities. The module works fine without this. And now the module is promoted to full project this is an impediment to approve the module in the new Drupal.org security advisory coverage applications queue?

What are now the procedures to go ahead wit the revisions?

Disclosure: I'm the maintainer of the module Only One. I'm not looking for promotion, I just want to know how to finish the review process.

# Answer
The canonical reference for this is \[Community Initiative Proposal\] Project Applications Process Revamp.

As of 2017/03/14, most of the plan has been implemented on the back-end, but some of the documentation still needs to be updated and there are still a few things that are being fine tuned.

To directly answer your question, the old **Project Application** queue is being repurposed as the **Drupal.org security advisory coverage applications** queue.

There is currently a documentation page about how to apply for permission to opt into security advisory coverage.

In short, you need to go through the application process where your project is reviewed. Instead of being allowed to promote your project (which you can now do on your own), a successful application will result in the applicant being able to opt-into security team coverage (the meaning of the "git vetted" role is being changed).

The process is essentially the same, and the security advisory coverage application checklist has been updated. The review admins will block applications on

* Licensing problems (including third-party code)
* Security problems

An application can be blocked on other items in the checklist at admin discretion.

You can go ahead an work on the issues in your project's issue queue. Make sure you follow best-practices as outlined in (the page I can't find about being a responsible maintainer). If you haven't already, then make sure you have an application in the queue, and reviewers will use the latest -dev version of your code for evaluation.

Just keep in mind that the process changes that were just done were to allow project promotion; there is a still the human factor (and backlog) for the manual reviews for the security opt-in.
> 1 votes

# Answer
Apart from your actual question, you also posted a comment which contains this:

> ... the project is promoted, but now how can I obtain the shield?

Not sure if it will be a complete answer to your question, but your scenario here seems a variation of the question about "Why has my security shield for my new module on Drupal.org been removed?". Your variation now seems to be "Why has my security shield for my new module on Drupal.org not yet been added?" (or why is it not visible yet).

Here is part of my answer in that related question:

> ***`You need to create an official release, for at least 1 version of Drupal core that is supported.`*** In your case, for D7, like a 7.x-1.0 version of your module. Shortly after doing so, your module will have the security shield.

I'm not sure (yet) about how long that ***Shortly*** actually may take, but I also noticed that on the revisions page of OnlyOne the most current timestamp is `13 Mar 2017 at 22:32 CET` (which is less then 24 hours ago). Moreover, on its project page there is also `Last modified: March 14, 2017` (which is today ...). But it could well be that with only a little patience (like until tomorrow?), you will automagically get the shield that you're looking for.

***Update***

Debugging is the art of taking away all possible causes ... about a day later it appears that for your module "a little patience" is not the solution (the shield still doesn't show up). Sorry.
> 1 votes

---
Tags: community-official-site
---


# Question
Title: Sending attachment on webforms with drupal 7
Dears,

I have a webform where quest can send a attachment. For registered users this works bit for guest they send the mail whitout an attachment. The file is uploaded in the webform folder. How can I fix this taht the file is send with the email?

Thanks in advance.

# Answer
This is a problem of Webform ver. 7.x-4.14. Try to use 7.x-4.x-dev version of webform or apply patch #2 from https://www.drupal.org/node/2675170
> 0 votes

---
Tags: webforms, emails
---


title: Finding unused Image Styles

text:
# Question
Title: Finding unused Image Styles
I'm working on a pre-existing Drupal 7 website that has been through several iterations so I'm trying to have a tidy up and remove items which are not required.

I'm currently looking at the Image Styles, of which there are 26 on the site. I'm pretty sure a lot are not used any more, is there any best practise method of making sure they're not used before removing them? My current thinking is either to check every Content Type & View to see if they're used, then do a search in the database & code base to see if they appear in there. Is this the best way? Would it cover all locations they could be being used?

# Answer
You have a couple of tasks,

1. Identify all the image styles
2. Identify where they're used. You can have multiple node displays, views, display suite, panels, etc.
3. Check if they're defined in code (features/custom modules)
4. Remove extra ones that aren't being used

They all apply to images. So your first step if find image fields and where they're used. Drupal has a report for that.

```
admin/reports/fields

```

For Views, you can use,

```
admin/reports/fields/views-fields

```

For each content type, check all displays see which ones are used,

```
admin/structure/types/manage/<CONTENT_TYPE>/display
admin/structure/types/manage/<CONTENT_TYPE>/display/teaser
admin/structure/types/manage/<CONTENT_TYPE>/display/<OTHER_DISPLAYS>

```

Then see if you have Panels or Display Suite. And check those modules to see if they reference other image styles.

After that, you can start looking into your code. This could be tricky. Assuming the contrib modules are in a separate folder,

```
sites/all/modules/contrib

```

It's easy,

```
grep -rn 'image_format_machine_name' sites/all/modules | grep -v 'contrib'

```

But if everything is thrown together into `modules/`, contributed, custom, feature modules, you'll have to exclude contributed modules manually. Probably Excel would be your best bet here.

I think basically that should cover the places where they're used.

Not sure if anyone would have any other ideas.
> 2 votes

---
Tags: media
---


# Question
Title: How to change composer file directory after it has been set?
So, I've been struggling with some problems with composer and drupal 7. I have composer and composer manager installed because of dependencies for the OpenLayers Module. I don't think I use these dependencies since the site works fine without them installed, but I've run into an issue where I need to fix a composer error in my production environment which is on a shared host and I can't install composer. Most recently, I've just been trying to correctly install the dependencies and then move the files to my live server and hope everything works out. The issue is that when I moved the database to the development machine, the composer file directory is still set with the path from the live server. Anytime I try to navigate to Configuration =\> System =\> Composer Manager, or to Status Report, I get the following error:

```
RuntimeException: Error creating directory: /home/phislub9/public_html/sites/default/files/composer in composer_manager_file_dir() (line 299 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).

```

The issue is that this path is now effectively hard-coded, unless I alter it in the database. So, how can I fix this, and what the correct process for installing these dependencies.

# Answer
> 2 votes
> ```
> RuntimeException: Error creating directory: /home/phislub9/public_html/sites/default/files/composer in composer_manager_file_dir() (line 299 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).
>
> ```

Is this location, `sites/default/files/composer` not accessible?. I think you probably need to update some permission or maybe create the file manually. This means that you can't upload files.

---

I think the variable is `composer_manager_vendor_dir`

If so, running this,

```
drush variable-set composer_manager_vendor_dir 'path_here'

```

Would update it.

If that's not the variable, running

```
drush variable-get

```

Should list all the variables and it's just searching which is the right one.

---

> I've run into an issue where I need to fix a composer error in my production environment

You should consider *not* moving your database from Development to Production for this exact reason.

Check the Features module and other ways to move configuration into production, without having to import the database.

Always move your database from Production to Development, and move code from Development to Production.

This way, if you had to change something or apply a fix, it would be on your development environment, not on production.

---
Tags: 7, composer
---


# Question
Title: How do I get Drupal to preference one of a module's .tpls over another?
I have modified a Global module so that it has a 2nd .tpl file. The original .tpl file is for sites using Zurb Foundation 5, the newer one I created is for sites using Zurb Foundation 6. Because this is a global module, these files exist in the same directory.

I've named the newer .tpl inline with what Theme Debug suggests (`image_resp_item--f6.tpl.php`).

Now, I've just got to tell the site that when it's using Foundation 6 to preference the .tpl named `image_resp_item--f6.tpl.php`.

However, I'm completely lost at where to start with this. Is this something I set up on the module's .module file? Or something I set up on each sites template.php file? Is there a hook I can use?

Sorry its kinda vague - been dumped in the deep end here - any advice is appreciated.

# Answer
Update the modules weight in the DB.

This code is for a custom module, when enabled:

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

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Is there another method to call form like drupal_get_form?
I try to get two form in one page from drupal 6 module to drupal 7 module but when i run its just show text "Array". is there any method same like drupal\_get\_form for calling another form at one page ?

Here my code

```
$output = '';
$output = drupal_get_form("filter_cash",$awal,$akhir,$jprog);
$output .= dafcash($awal,$akhir,$jprog);
return $output;

```

Hook\_menu :

```
function cash_menu() {
    $items['cash'] = array(
        'title' => 'Pengajuan Cash',
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'cash_pglistgl',
        'access arguments' => array('cash-new'),
        );
    $items['cash/daftar'] = array(
        'title' => 'Daftar-cash',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'page callback' => 'cash_pglistgl',
        'access arguments' => array('cash-new'),
        );
    $items['cash/init/2'] = array(
        'title' => 'Tambah cash',
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'page_cash_init',
        'access arguments' => array('cash-new'),
        );
    $items['cash/add'] = array(
        'title' => 'cash-tambah',
        'callback arguments' => array('without_'),
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_add',
        'access arguments' => array('cash-new'),
        );
    $items['cash/editinit'] = array(
        'title' => 'EDIT cash',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cashinitedit',
        'access arguments' => array('cash-new'),
        'file' => '',
        );
    $items['cash/editadd'] = array(
        'title' => 'EDIT cash',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_addedit',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/editdelete'] = array(
        'title' => 'EDIT cash',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_deledit',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/batal'] = array(
        'title' => 'cash-batal',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_batal',
        'access arguments' => array('cash-new'),
        );
    $items['cash/delete'] = array(
        'title' => 'cash-hapus',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_acsh_del',
        'access arguments' => array('petty-new'),
        );
    $items['cash/delete_list'] = array(
        'title' => 'cash-hapus',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_del_list',
        'access arguments' => array('cash-new'),
        );
    $items['cash/edit'] = array(
        'title' => 'cash-ubah',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_edit',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/view_detedit'] = array(
        'title' => 'cash-Edit detail',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_view_edit',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/view_detadd'] = array(
        'title' => 'cash-tambah detail',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_view_detadd',
        'access arguments' => array('cash-new'),
        );
    $items['view_detdel'] = array(
        'title' => 'cash-hapus',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_view_detdel',
        'access arguments' => array('cash-new'),
        );
    $items['cash/view'] = array(
        'title' => 'cash-lihat detail',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_view',
        'access arguments' => array('cash-new'),
        'file' => 'cash.view.inc',
        );
    $items['cash/editdetail'] = array(
        'title' => 'Detail cash - Ubah',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_editdetail',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/editalldata'] = array(
        'title' => 'cash-ubah',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_editalldata',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/editall'] = array(
        'title' => 'cash-ubah',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_editall',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/editall2'] = array(
        'title' => 'cash-ubah',
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_editall2',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/view_edit'] = array(
        'title' => 'cash-lihat edit',
        'type' => MENU_CALLBACK,
        'page  callback' => 'page_cash_view_edit',
        'access arguments' => array('cash-new'),
        'file' => 'cash.edit.inc',
        );
    $items['cash/pdf'] = array(
        'type' => MENU_CALLBACK,
        'page callback' => 'page_cash_pdf',
        'access arguments' => array('cash-new'),
        );
    $items['cash/xls'] = array(
        'type' =>MENU_CALLBACK,
        'page callback' => 'page_cash_xls',
        'access arguments' => array('cash-new'),
        );
    $items['autocomplete'] = array(
        'title' => 'autocomplete',
        'type' => MENU_CALLBACK,
        'page callback' => 'find_noreff_auto',
        'access arguments' => array('cash-new'),
        );
    return $items;
}

```

# Answer
> 0 votes
You should render it through drupal\_render() method to get desired result.

```
$output = '';
$output = drupal_render(drupal_get_form("filter_cash",$awal,$akhir,$jprog));
$output .= dafcash($awal,$akhir,$jprog);
return $output;

```

---
Tags: views, theming, hooks
---


# Question
Title: How can I alter variables sent to a paragraph bundle template within a module?
I need to preprocess the field values of a paragraph bundle to "send" additional variables to the template (paragraphs-item--xxxx--full.tpl.php). I want to avoid putting too much php logic into the paragraph template.

I am searching for something similiar to the node\_view hook for a paragraph item. Is there a fitting mechanism or maybee a module providing such an hook?

# Answer
> 12 votes
### Drupal 7

I don't know if this will help you directly, but I found this code snippet on DropBucket and it helped me do something similar:

```
/**
 * Implements hook_preprocess_entity().
 */
function wwvs_slices_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    $edge = field_get_items('paragraphs_item', $variables['paragraphs_item'], 'field_edge');
    if ($edge && $edge[0]['value']) {
      $variables['classes_array'][] = 'slice--edge';
    }
  }
}

```

In my usecase I wanted to augment the paragraph entity with an ID using the url-safe version of the title field used in that paragraph. Here's my implementation:

```
/**
 * Implements hook_preprocess_entity().
 */
function foo_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if(isset($variables['elements']['pp_title']['#items'][0]['value'])){
      $title = $variables['elements']['pp_title']['#items'][0]['value'];
      $title = strtolower(drupal_clean_css_identifier($title));
      $variables['attributes_array']['id'] = $title;
    }
  }
}

```

I hope this is helpful!

# Answer
> 6 votes
### Drupal 8

In Drupal 8 you can use `hook_preprocess_HOOK`:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_paragraph(&$variables) {

}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_paragraph__TYPE(&$variables) {

}

```

---
Tags: theming
---


# Question
Title: What is stopping my theme from using a file that uses a suggested file name?
I needed to modify a module's .tpl file and so copied it, renamed it to something suggested by Theme Debug's file suggestions.

Eg when I run `drush theme_debug` I see:

```
<!-- FILE NAME SUGGESTIONS:
   * image-resp-item--f6.tpl.php
   x image-resp-item.tpl.php
-->

```

So I rename my new file `image-resp-item--f6.tpl.php` and place it in my site's theme.

I clear cache and rebuild the theme registry but to no affect - the site still uses the original .tpl.

To experiment, I change my new .tpl's name to match the old one (remove `--f6`). This works - I see my new code appear on the site.

Why is my site (or theme?) not wanting to use the suggested file name?

# Answer
> 0 votes
Your can either use hook\_preprocess\_page or if you don't want to code use something like context module. You can add a new context to select theme template based on your requirement.

---
Tags: 7, theming
---


# Question
Title: build an admin view of all available rules (rules module), a better rules UI
is there a hook to build an admin view of all available rules (rules module) to build a better rules UI? it may be a table view, so we can apply filters and groups, and order them, like in weight, tag, event, etc. I have sites with 30-40 rules running and sometimes (too many) is difucult to figure out a map of a time-event-order-actions taken on site, seeking a better planification and manteinace. A view with the available elements could help a lot. code is welcome.

# Answer
I am not aware of any hooks but rules\_filter looks promising.
> 1 votes

---
Tags: views, rules
---


# Question
Title: Why I can't use the same code from Drupal 7 in Drupal 8 to generate a button with FAPI?
Following the question Generating \<button type="submit"\> with the form API for Drupal 7 I tried to implement the same thing in Drupal 8.

I need the following output:

```
<button type="submit" class="clearfix"><span>Login</span></button>

```

So I tried to use this code:

```
$form['submit'] = array(
  '#prefix' => "<button type ='submit'>",
  '#suffix' => "</button>",
  '#type' => 'markup',
  '#markup' => "<span>" . t('Login') . "</span>",
);

```

But I obtain this:

```
<span>Login</span>

```

But if I use this code:

```
$form['submit'] = array(
  '#prefix' => "<b>",
  '#suffix' => "</b>",
  '#type' => 'markup',
  '#markup' => "<span>" . t('Login') . "</span>",
);

```

I obtain this:

```
<b><span>Login</span></b>

```

So the `<button>` tag is eliminated but the `<b>` tag not. Very strange for me, the `Button` is not rendered.

Thanks to @Kevin I used the leymannx answer an with this code I solve the problem:

```
$form['submit'] = [
  '#type' => 'inline_template',
  '#template' => '<button type="submit" class="glyphicon glyphicon-search"></button>',
];

```

But, why I can't use the same code in Drupal 7 and Drupal 8 to generate a button with FAPI?

# Answer
The reason why it is not working in Drupal 8 as in Drupal 7 is, that prefix and suffix are passed to xssFilterAdminIfUnsafe() function in doRender() function. Thus preventing all tags except the tags specified in $adminTags.

Excerpt from doRender:

```
  // We store the resulting output in $elements['#markup'], to be consistent
  // with how render cached output gets stored. This ensures that placeholder
  // replacement logic gets the same data to work with, no matter if #cache is
  // disabled, #cache is enabled, there is a cache hit or miss.
  $prefix = isset($elements['#prefix']) ? $this->xssFilterAdminIfUnsafe($elements['#prefix']) : '';
  $suffix = isset($elements['#suffix']) ? $this->xssFilterAdminIfUnsafe($elements['#suffix']) : '';

  $elements['#markup'] = Markup::create($prefix . $elements['#children'] . $suffix);

```

You can use '#allowed\_tags' property to enable specific tags. So this should work:

```
  $form['submit'] = array(
  '#type' => 'markup',
  '#markup' => "<button type ='submit'><span>" . t('Login') . "</span></button>",
  '#allowed_tags' => ['button', 'span'],
  );

```

But '#allowed\_tags' property will not work for '#prefix' and '#suffix'.
> 4 votes

---
Tags: 8, forms
---


# Question
Title: Book page fields inherit content from parent
I created a book with several book pages of a specific content type. I am trying to inherit the values of some fields from the top page of the book to the child pages so that i don't have to fill them manually on each page.

I tried the "Field default token" module with no luck. Actually it doesn't display the value of the token that i select.

Any ideas please?

# Answer
The solution was fairly simple after all. I created two content types and used a field with Entity Reference to pass the values from the first content type to the second one.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Dump-dir specified in aliases.drushrc.php; not seen by drush?
The remote and local directories I've specified in my aliases files exist and are owned by my user (drush is run under my user).

```
$aliases['dev'] = array(
 'parent' => '@parent',
 'site' => 'mysite',
 'env' => 'dev',
 //[user, host, ssh options, etc.]
 'path-aliases' => array(
    '%files' => 'sites/default/disk',
    '%dump-dir' => '/home/joe/drush-backups/mysite_dev',
    ),
);

$aliases['local'] = array(
 'parent' => '@parent',
 'site' => 'mysite',
 //[root]
 'path-aliases' => array(
     '%files' => 'sites/default/files',
     '%dump-dir' => '/Users/joe/Sites/mysite/tmp',
    ),
);

```

Yet I get a warning on sql-sync:

> drush -v sql-sync @dev @local Loaded alias @local from file /Users/joe/.drush/soa.aliases.drushrc.php
> \[notice\] Loaded alias @dev from file /Users/joe/.drush/soa.aliases.drushrc.php
> \[notice\] Local sql cache file does not exist.
> \[notice\] ssh -i "/Users/joe/.ssh/id\_rsa" -p "6421" joe@arch-web-p01.its.utexas.edu 'drush --backend=2 --root=/var/www/html/dev sql-query '\\''SHOW TABLES'\\'' 2\>&1' 2\>&1 \[notice\] WARNING: Using temporary files to store and transfer sql-dump. It is recommended that you specify --source-dump and --target-dump options on the command line, or set '%dump' or '%dump-dir' in the path-aliases section of your site alias records. This facilitates fast file transfer via rsync.
>
> You will destroy data in drupal\_test and replace with data from server/mysite\_dev.
>
> You might want to make a backup first, using the sql-dump command.

And if I continue, I get an error that indicates drush was trying to write to a different directory.

> Do you really want to continue? (y/n): y Calling system(ssh -i "/Users/joe/.ssh/id\_rsa" -p "6421" joe@server 'mysqldump --result-file /private/var/folders/mr/c99kf6c11\_bdsr62m242c59c0000gq/T/mysite\_dev1WyWuk --no-autocommit --single-transaction --opt -Q mysite\_dev --host=myhost --user=mysite\_dev --password='\\''\[pw\]'\\'' --skip-extended-insert --order-by-primary 2\>&1'); mysqldump: Can't create/write to file '/private/var/folders/mr/c99kf6c11\_bdsr62m242c59c0000gq/T/mysite\_dev1WyWuk' (Errcode: 2) Database dump failed
> \[error\] Command dispatch complete
> \[notice\]

I've got all my drush commands working between remote directories run on the site. I am able to rsync between local and remote directories since specifying files path aliases in aliases.drushrc.php.

What am I missing? I have the latest version of drush in both places, so I don't think I need the patch pointed to at How do I set the drush tmp directory?...

# Answer
> 4 votes
FWIW, I finally resolved the error by including the --source-dump option in the command line. I specified the same directory I had listed in my aliases file, and it created the dump file there flawlessly. So perhaps dump-dir is not being read in 6.0-rc2...

# Answer
> 3 votes
I solved the same error. When you specify `%dump-dir`, you also must specify the `%dump` variable, then it works:

```
'path-aliases' => array(
  '%dump-dir' => '/home/tmp',
  '%dump' => '/home/tmp/dump.sql',
),

```

# Answer
> 0 votes
`dump-dir` and `dump` options were remove somewhere in version `7.x` https://github.com/drush-ops/drush/commit/df3980062a89436a26db20097363da69616cbb9c

You can still find it in `6.x` branch but not in `8.x` https://github.com/drush-ops/drush/blob/6.x/examples/example.aliases.drushrc.php

In issue https://github.com/drush-ops/drush/issues/1495 you can read:

> markcarver: What happened to drush\_sql\_dump\_file()?
>
> weitzman: The feature is gone. sql-sync does not keep around transferred dump files any more.

---
Tags: drush
---


# Question
Title: Set default value to an image field form element using form_alter
I am using this code, but the form doesn't get default image value: The image is created and exists in the server:

```
$image = file_get_contents($url);
$destination = 'image.jpg';
$file = file_save_data($image, $destination, FILE_EXISTS_RENAME);

```

And $form is populated this way:

```
$form['field_user_picture']['und'][0]['value']['#default_value']['fid'] = $file->fid;

```

I think I am missing something, could anybody help?

# Answer
> 2 votes
Try it like this:

```
$form['field_user_picture']['und'][0]['#default_value']['fid'] = $file->fid;

```

(Remove `['value']` key.)

---
Tags: 7, entities, media
---


# Question
Title: How do I get rid of a staged configuration import?
I have a staged import that I can't apply and I would like to get rid of it and be clean in my configuration management screen. How do I get rid of the staged import? Can I go to sync folder and delete the .yml files and the export the current configuration again? I am extremely nervous about breaking the site. I know it is saved in the db but I don't want to go in and delete it from there either, unless that is an option. I wont be able to apply any other import because of this staged one sitting here.

# Answer
> 2 votes
If you export the configuration again current configuration files should be deleted and new ones will be created with the configuration hold in your database.

Anyway you should make a backup first, just in case. You can use drush for this. Use drush archive for a complete backup (including files):

```
drush ard

```

Use drush sql-dump to backup only the database:

```
drush sql-dump > /patch/to/new/file/with/db-dump

```

---
Tags: 8, configuration
---


# Question
Title: Strict HTML strips CSS classes in a custom block
I created a custom block using *Strict HTML* (and adding `<div>` and other tags to the allowed HTML). If I look at the frontend, it strips all the CSS classes like `<div class="myclass">`.

What do I have to do to create this block with all the CSS classes, and the custom HTML markup?

# Answer
Default custom blocks in Drupal 8 use the *Basic HTML* text format. Using either *Basic HTML* or *Restricted HTML* will remove any class attributes.

You need to set your format to *Full HTML* to prevent Drupal from stripping out these attributes.
> 1 votes

# Answer
You need to set your format to Full HTML to prevent Drupal from stripping out these attributes. I think it does not working when you backup data and deployed website .
> 0 votes

---
Tags: 8, blocks, theming
---


title: How to delete first user (admin)

text:
# Question
Title: How to delete first user (admin)
For security reason, I want to delete the first user (which has all rights, event without the admin role) and login only with the `drush uli` command. How can I do that? From the backoffice it say I can't remove that user

# Answer
> 4 votes
I doubt that's possible, or at least not without messing with a lot of core code.

User 1 is synonymous with the root user in linux. It can be disabled, hardened, made virtually impossible to access, but not removed.

See Securing user #1 for more information.

---
Tags: 8, users, security
---


title: Why my hook_block_view doesn't work?

text:
# Question
Title: Why my hook_block_view doesn't work?
I installed "Form block" and it creates blocks. I want change block title via my module, but it doesn't work.

I create module and set function with hook\_block\_view:

```
function zzz_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'user_register':
      global $user;
      // Don't display the form to logged in users or if registration is disabled
      if (!$user->uid && variable_get('user_register', 1)) {
        $block['content']['form'] = drupal_get_form('user_register_form');
        $block['subject'] = t('MY TITLE IS HERE');
      }
      return $block;
  }
}

```

What did I do wrong?

# Answer
> 3 votes
`hook_block_view()` is only invoked for the module that defines the block via `hook_block_info()`.

To alter the content of a block provided by another module, use `hook_block_view_alter()` instead.

---
Tags: 7, blocks, hooks
---


# Question
Title: Webform/YAML Form component email mapping
In Drupal 7, Webform module have the ability to map different emails against webform component's options so that the webform notification could be sent to different emails depending on a user selection.

In Drupal 8, Webform was ported and its email submission settings pretty basic so I decided to use YAML Form. However, YAML Form email handler have the ability to either have a custom emails separated by comma or a value from the component.

Is there a way to have component email mapping functionality?

# Answer
> 1 votes
The feature has been added to the latest dev release of Webform-8.x-5.x.

@see Issue #2854021 by jrockowitz: Send email based on element options selection

# Answer
> 0 votes
Currently the functionality is not inbuilt to web forms UI but it can still be done with a custom module.

Following the webform recpie on handlers you can create a custom email handler like so:

Folder/File structure:

* ModuleName
    + src
        - Plugin
        - WebformHandler
            * MODULENAMEWebformHandler.php
    + MODULENAME.info.yml

Content example for MODULENAMEWebformHandler.php

```
namespace Drupal\MODULENAME\Plugin\WebformHandler;
use Drupal\Core\Url;
use Drupal\webform\Plugin\WebformHandler\EmailWebformHandler;

/**
* Emails a webform submission.
*
* @WebformHandler(
*   id = "test_email",
*   label = @Translation("New Email"),
*   category = @Translation("Notification"),
*   description = @Translation("Send email depending on dropdown value"),
*   cardinality = \Drupal\webform\WebformHandlerInterface::CARDINALITY_UNLIMITED,
*   results = \Drupal\webform\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/
class MODULENAMEWebformHandler extends EmailWebformHandler {

  public function sendMessage(array $message) {

    $form_data = $message['webform_submission']->getData('dropdown_id');

    switch($form_data) {

     case 'APAC':
       $recipient = 'apac@example.nl';
     break;

     case 'US':
       $recipient = 'us@example.ru';
     break;

     default:
       $recipient = 'default@example.com';
     break;

    }
    $message['to_mail'] = $recipient;

    parent::sendMessage($message);
  }
}

```

---
Tags: 8, webforms
---


# Question
Title: Media Wysiwyg + CKeditor. Replace inline images with custom images programmatically
I am trying to replace individual images in old node body with a default image using media + ckeditor programatically so as to save disk space as there are lot of images in server.

I was successful in replacing image for an image field programmatically. However, I am not able to determine how do I replace those images embedded within a body along with body text while loading a node using node\_load.

I intend to replace these images using hook\_cron and run replacement operations on older nodes images.

# Answer
The purpose of this question was to replace old node images with a default image so as to reduce disk space usage, as old nodes are not frequently visited by users.

To achieve this first you load the node using node\_load function, and grab the body field:

```
$node = node_load($nodeID);
$body = isset($node->body[$node->language][0]) ?$node->body[$node->language][0] : array();

$text = isset($body['value']) ?  $body['value'] : $body['safe_value'];

```

After this you create DOMDocument object:

```
$doc = new DOMDocument(null, 'UTF-8');

```

Here, UTF-8 is for languages that are not Latin/Plain English.

```
$doc->loadHTML(mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8'));

```

Convert your text to HTML entities following UTF-8 format.

```
$tags = $doc->getElementsByTagName('img');

```

You grab all your image tag from body.

Next, Loop through those tags:

```
foreach ($tags as $tag) {
// Get default Image.
$file_temp = file_get_contents($urlToDefaultImage);
// Get Image information.
$info = pathinfo($urlToDefaultImage);
// Replace if it exists.
$file = file_save_data($file_temp, 'public://' . $info['basename'], FILE_EXISTS_REPLACE);
// Get old image fid.
$oldImage = $tag->getAttribute('data-fid');
// Remove the file info from db and server if not used by any.
$status = file_delete(file_load($oldImage)),
$tag->setAttribute('src', file_create_url($file->uri));
$tag->setAttribute('data-fid', $file->fid);
}

```

After looping through each img tags save the newly generated HTML.

```
$replacedBody = $doc->saveHTML();

```

Remove extra html, body and Doctype from the new body using str\_replace:

```
$replacedBody = str_replace('<html><body>', '', $replacedBody);
$replacedBody = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">', '', $replacedBody);
$replacedBody = str_replace('</body></html>', '', $replacedBody);

```

Next update the newly formated body to node object:

```
$node->body[$node->language][0]['value'] = html_entity_decode($replacedBody);
$node->body[$node->language][0]['safe_value'] = html_entity_decode($replacedBody);

```

Save the node

```
node_save($node);

```

**Bonus:** Updating images in node image field.

Grab the field data.

```
$field = !empty($node->field_{machine_name}[$node->language]) ?  $node->field_{machine_name}[$node->language] : array();

```

Here, {machine\_name} represents the name for image field you created using Content UI.

```
// Loop through old images.
foreach($field as $key => $row) {

    // Check if the image
    if($row['type'] == 'image') {

        // Get default Image.
        $file_temp = file_get_contents($urlToDefaultImage);

        // Get Image information.
        $info = pathinfo($urlToDefaultImage);

        // Replace if it exists.
        $file = file_save_data($file_temp, 'public://' . $info['basename'], FILE_EXISTS_REPLACE);

        // Change the current image with default.
        $node->field_{machine_name}[$node->language][$key] = array(
        'fid' => $file->fid,
        'filename' => $file->filename,
        'filemime' => $file->filemime,
        'uid' => $file->uid,
        'uri' => $file->uri,
        'status' => $file->status,
        'display' => 1,
        );
    }
}

```

Performing these operation will remove default image from your db and server and will save disk space. While we need to use file\_delete function when removing files from body, it is not needed when when perform this operation while we replace on an image/media field. file\_delete function will safely delete the files from server if that file is not used by any other nodes in website, if second parameter is not set to TRUE. While file\_manage\_delete does the same thing, though it will not lookup for database and check for its existing usage, it will simply release your disk space from that file, result in 404 not found image on other reused nodes.
> 0 votes

---
Tags: 7, media, wysiwyg
---


# Question
Title: Keep something in cache even after flushing the cache from the Drupal back-end (not drush)
I have a particular use case where we use a cache warmer to keep a custom resource in cache (/api/the-url/xxx). The cache warming is done with a bash script that is added to the crontab and runs at night.

For this particular use case I want /api/the-url/xxx to stay in cache even if admins flush the cache in the Drupal back-end.

For now I wrote 2 queries:

One query that moves all the /api/the-url/xxx from cached\_data to cached\_data\_temp on flush cache.

```
/**
 * Copies xxx cache from "cache_data" to "cache_data_temp".
 * @param $cid
 */
public function copyCacheDataToTempDataCache($cid) {
    $select = $this->connection->select('cache_data', 'c');
    $select->fields('c');
    $select->condition('cid', $cid . '%', 'LIKE');
    $query = $this->connection->insert('cache_data_temp')->from($select);
    $query->execute();
}

```

One query to move all the /api/the-url/xxx from the cached\_data\_temp after the flush cache.

```
/**
 * Copies xxx cache from "cache_data_temp" to "cache_data".
 */
public function copyTempCacheToCacheData() {
    // Select query to fetch all rows.
    $select = $this->connection->select('cache_data_temp', 'c');
    $select->fields('c');
    // Insert rows into "cache_data".
    $query = $this->connection->insert('cache_data')->from($select);
    $query->execute();
    // Empty table.
    $this->connection->truncate('cache_data_temp')->execute();
 }

```

I've implemented hook\_cache\_flush which implements the following:

```
/**
 * Implements hook_cache_flush.
 */
function MY_MODULE_cache_flush() {
    // Before cache is cleared, get all CID's that start with route:api/the-url/%
    // And store it in "cache_data_temp" table.
    $manager = Drupal::service('xxx.manager');
    $manager->copyCacheDataToTempDataCache('route:api/the-url/');
}

```

And to rebuild the cache:

```
/**
 * Implements hook_rebuild.
 */
function MY_MODULE_rebuild() {
    // On info rebuild, put back all data stored in "cache_data_temp" in cache_data.
    $manager = Drupal::service('xxx.manager');
    $manager->copyTempCacheToCacheData();
}

```

Technically everything works fine. The data is kept in cache\_data on flush (after moving it to the temp table) but it seems the cache is invalidated. What am I missing here?

# Answer
For this use case, you might need to consider another storage instead of cache.

warmer -\> cache

warmer -\> storage -\> cache

storage could be either key value or entity or any other storage you prefer.Check here if you are not sure which one to pick.

This way, your warmed data always persistent in the system and can be purged only by warmer (crontab).

When cache clear happen, you can always fallback to storage.
> 2 votes

---
Tags: 8, caching
---


title: How to clear form cache automatically?

text:
# Question
Title: How to clear form cache automatically?
I am working on a Drupal 7 site. When I check the `cache_form` table it reaches 4 GB daily so I have to manually `truncate` the `cache_form` table. Is there any way to clear `cache_form` table automatically 4 times in a day?

# Answer
> 4 votes
There are several method to clear the cache\_form automatically.

Use optimizedb module

> There is well-known issue with fast-growing table cache\_form. This table stores Drupal form cache and it isn’t cleared when you flush all cache or run cron. Also you can struggle with problem of fragmentation with InnoDB tables on active delete/insert operations. This module provide functionality to solve this problem. Also its provide additional tools for maintenance database.
>
> Module OptimizeDB provide such features:
>
> ```
> Ability to clean **cache_from** in administrative page or do it by cron.
> Ability to optimize all database’s tables and display its sizes.
> Configuration of notification about necessity to perform maintenance tasks.
> Perform check and repair operation with tables.
> Prevent crashing tables when perform all maintained actions.
>
> ```

**If you have drush access** Safe cache\_form Clear module

> Safely remove a limited number of items from the cache\_form table.
>
> This module provides a drush command drush safe-cache-form-clear that can be run at a high frequency, keeping the table at a reasonable size. It requires that you use the database cache back-end for the cache\_form table.
>
> Drupal's core cron can have problems clearing out the cache\_form table when it grows extremely large. This module works around this by limiting the number of items expired from the cache in a single run, dealing with a manageable chunk each time.
>
> You can configure the number of items deleted in a single run by setting the $conf\['safe\_cache\_form\_clear\_limit'\] persistent variable.

for automatically clear the Drupal cache use Cleaner module (it's not clear the cache\_form table).

> The Cleaner module allows the admin to set a schedule for clearing caches, watchdog, and old sessions.

**and another solution is create a custom route in your module** something that not predictable by others (some hash url), on call back function truncate 'cache\_form' table (or equivalent Drupal ) then on your server or your Cpanel create a crontab,schedule it to run the code periodically.

---
Tags: 7, caching, cron
---


# Question
Title: how to open desktop node link shared on facebook onto mobile device (mobile website version)
I have a desktop link: mysite.com/node/22

When I share this link onto facebook, and try to open it on desktop prowser it's work good.

But when I try to open it (from facebook) onto mobile it's back me to webiste (mobile version) home. mobi.mysite.com

how can i make it on mobile go to mobi.mysite.com/node/22

I use (mobile switch) and (mobile tools) modules, and they are works good

thanks

# Answer
> 0 votes
the solution is very simple, I just don't see it.

its in advanced sitting for mobile switch module, Multisite shared content must be checked.

---
Tags: 7, mobile-tools
---


# Question
Title: Get entity reference node object from within rendered entity reference
My specific problem is similar to the one here but I am needing for it to work when the file field is within a node that is rendered within another as an entity reference.

If I use:

```
$node = \Drupal::request()->attributes->get('node');
$variables['node_title'] = $node->getTitle();

```

I get the title of the main node currently being displayed and not the node of the rendered entity reference. Is there a way I can get this instead?

# Answer
You're setting `$node` to the current request. On any node/\* route that will be the node in question, not other nodes included on the page.

Since it is an entity reference field, you can access it like (for example, in a preprocess):

```
$foo_id = $node->field_reference_name->value;
$referenced_node = Node::load($foo_id);

// or
$referenced_file = File::load($foo_id);

```

If `$node->field_name->value` returns the id (node id).

However it isn't really clear if you are talking about a file, or, a node.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to redirect to frontpage from a controller
Right now I'm doing this ugly thing to get the url of the my set frontpage (skipping validations and making sure it exists since I'm not sure if I'll even use this approach)

```
$url = $this->config('system.site')->get('page')['front'];
return new RedirectResponse($url);

```

This **works** but seems ugly, bloated and wrong.

Update:

As pointed out in the comments, this may be a matter of personal taste, therefore the question would be deemed subjective and it can be closed. It surely isn't a duplicate, I'm not asking **how to redirect** in general, it's a specific redirection, perhaps I could've worded it differently.

# Answer
> 16 votes
Use the route `<front>` and when you are in a controller use the injected method redirect():

```
return $this->redirect('<front>');

```

---
Tags: 8, redirection
---


# Question
Title: Language switcher does not have current page query parameters
I have a custom block that shows a schedule. It also show arrows to allow the user to see next or previous days. For this I simply add ?date=DATE to the arrow link. Once landed on one of those pages that have a GET query parameter it is impossible to switch language without loosing your current date selection.

I searched and found many similar issues but all for Drupal 7.

Switching language loses the line item URL parameter

Language switcher (locale\_block) doesn't keep query parameters

Since this part of Drupal have been completely rewritten, I need a solution for Drupal 8.

IMO I think it should be a bug in Drupal 8 core. I think the language switcher should know there is existing GET query parameter that need to be passed along the language links. I don't see any reason you wouldn't want to keep the GET params.

anyone has a solution to this problem?

# Answer
> 0 votes
It seems that when I upgrade from 8.1.x (8.1.10) to 8.2.x (8.2.6) it fixes the problem. So it was a core bug.

---
Tags: 8, i18n-l10n, navigation
---


# Question
Title: How to include a custom menu in page.tpl
I want to code a custom menu straight into page.tpl.php. The default theme uses

```
<?php if ($main_menu): ?>
  <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->
<?php endif; ?>

```

In Drupal 7 I've created a new menu called 'Footer menu'. How do I code that into my theme in the same way as the $main\_menu is coded in the default theme?

# Answer
> 5 votes
Try this

```
<?php
 $menu = menu_navigation_links('menu-your-custom-menu-name');
 print theme('links__menu_your_custom_menu_name', array('links' => $menu));
?>

```

You can also add to template.php

```
function THEME_preprocess_page(&$vars) {

$menu = menu_navigation_links('menu-your-custom-menu-name');

$vars['custom_menu'] = theme('links__menu_your_custom_menu_name', array('links' => $menu));

}

```

the variable $custom\_menu is available in the page tpl

# Answer
> 0 votes
you can override your menu with `hook_theme_tree()` in `template.php`:

```
function THEME_menu_tree__MENUNAME($variables) {
  $menuTree = menu_build_tree('MENUNAME');

  foreach ($menuTree as $item) {

  }
}

```

and then create MENU BLOCK Or just print your menu directly in your `page.tpl`

# Answer
> 0 votes
Well, Nothing from above worked for me with Drupal 7 but below code,

```
    $search_menu_name = "menu-search-box-menu";

   print theme('links', array('links' => menu_navigation_links($search_menu_name), 'attributes' => array('id' => $search_menu_name, 'class'=> array('links', 'inline'))));

```

The above code is like this, "menu-search-box-menu" is my custom menu name/ID. You can find it in that particular menu edit link.

Enjoy. :)

# Answer
> 0 votes
I am using bellow code,It's working for me.

$main\_menu = menu\_navigation\_links('menu-main-page'); print($main\_menu);

# Answer
> 0 votes
This has been driving me mad.

The easiest way by far is this...

In page.tpl.php where your custom menu name is "Custom Menu"

```
<?php

print drupal_render(menu_tree('menu-custom-menu'));

?>

```

---
Tags: routes, theming
---


# Question
Title: Path issues using composer for Commerce install on shared hosting
On a shared server with Composer installed the template for installing Drupal 8 or Drupal commerce creates a project directory and puts the site in a web directory within the project.

On a shared host with a structure like:

/var/www/example.com

with home private tmp ssl web

How do you use composer to install 3 or more Dupal sites like this?

example.com example.com/mystore example.com/dev

If you run the composer install from the web directory /var/www/example.com/web the install paths are:

example.com/projectname/web example.com/mystore/web example.com/dev/web

and projectname, mystore and dev are not a protected directory.

Running composer from /var/www/example.com does not work

# Answer
Went back and installed the drupal 8 tar.gz (without composer or drush) for the 3 directories I wanted and ran composer from each directory to update and then installed commerce.

After installing the tar.gz

ran: composer config repositories.drupal composer https://packages.drupal.org/8

then: composer require "drupal/commerce 2.x-dev"
> 0 votes

---
Tags: installation, composer
---


# Question
Title: How to invoke a custom callback function in Javascript
I am trying to just invoke callback in my AJAX response.

Currently I have the following response.

```
   private function responseWithSuccess($message, $status_code = 200)
    {
        $ajax_response = new AjaxResponse();
        $ajax_response->setStatusCode($status_code);
        $response =
            [
                'status' => 'success',
                'message' => $message
            ];

        $ajax_response->setContent(\GuzzleHttp\json_encode($response));
        return $ajax_response;
    }

```

It returns a response of the specified format, but is it possible to listen for the response text in this case ?

I've found that I have to use the Drupal Command class that is used for communication.

So I created the custom Command, here is code

```
class CustomCallbackCommand implements CommandInterface, CommandWithAttachedAssetsInterface
{
    use CommandWithAttachedAssetsTrait;
    /**
     * The content for the dialog.
     */
    protected $message;

    /**
     * Constructs a \Drupal\mymodule\Ajax\BootstrapModalCommand object.
     */
    public function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        return array(
            'command' => 'onCustomCallback',
            'message' => $this->message,
        );
    }
}

```

And add it to response like that

```
private function responseWithSuccess($message, $status_code = 200)
{
    $ajax_response = new AjaxResponse();
    $ajax_response->setStatusCode($status_code);
    $response =
        [
            'status' => 'success',
            'message' => $message
        ];
    $ajax_response->addCommand(new CustomCallbackCommand($response));
    //$ajax_response->setContent(\GuzzleHttp\json_encode($response));
    return $ajax_response;
}

```

But when I try to send the request, an error appears.

> Fatal error: Call to a member function getLibraries() on null in /public\_html/core/lib/Drupal/Core/Ajax/AjaxResponse.php on line 48

What is wrong with my code ?

So basically the main question is how to call specific callback when a response comes back.

P.S.

I know that I could just override default handlers of the Drupal JS module, but I am looking for a better way.

# Answer
For very basic Commands, you likely do not need to implement `CommandWithAttachedAssetsInterface` or `CommandWithAttachedAssetsTrait`.

Here is a good blog post tutorial for a custom Command: https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8

Here is another example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

Here are a couple modules that implement Commands for an example:

You are not going to want to override core Drupal JS, as it is easy to add your own and communicate to your plugins or third party plugins as demonstrated above.
> 6 votes

---
Tags: theming, 8, forms, hooks, ajax
---


# Question
Title: Filter view by taxonomy terms of current user
I've done lots of work with Drupal 6, but currently have no more ideas how to approach this problem in D8. Please help me :)

I have added taxonomy term field to user profile and would like to filter a view allowing only content having terms listed in user profile.

For example: User has terms "manager" and "south" is presented with content having either of this term without having to select exposed filters etc.

The point is not to restrict content (like with taxonomy access control), just to provide more relevant content.

# Answer
> 1 votes
It's the same process as D7 (see related thread)

But all you need to do is add a relationship to the taxonomy term and then add a contextual filter with the Term ID set as the fixed value.

---
Tags: views, 8
---


title: Solr indexing on custom tables

text:
# Question
Title: Solr indexing on custom tables
We are implementing apache solr search in drupal 7.. after installing the module if you run the index, the apache solr is returning results from the drupal tables (nodes,users,taxonomy,content type). But we have created custom tables (example: product table) where apache solr is not able to index those table data.. how to make it index the custom created tables

# Answer
> -1 votes
There is a patch available for this. Please refer the below link

https://www.drupal.org/node/2201309

---
Tags: search
---


# Question
Title: Is there a way to temporarily disable multilanguage selector links when a page doesn't have a translation?
Currently when a basic page doesn't have a translation and you click on a different language in the multilanguage switcher it shows you the page in the same language. This causes a lot of duplicate content on the website which is bad for SEO.

How can I make sure the multilanguage switcher link to a different language shows up when the article is actually translated and disable the link when it isn't? Is there a way to configure this?

# Answer
> 2 votes
You could implement hook\_preprocess\_block in your theme. Hope this helps you.

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {

  if ($variables['plugin_id'] == 'language_block:language_interface') {
    // Gets current node object from the current path.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Gets all the translation languages, returns an array.
    $languages = $node->getTranslationLanguages();
    // Gets the number of languages.
    $number_of_languages = count($languages);

    if ($number_of_languages == 1) {
      // Basically, clears out the content render array.
     $variables['content'] = array();
    }
  }
}

```

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


# Question
Title: How to disable picture button after click?
I'm new at Drupal CMS and programming at all, but I'm trying to find my way to solve this problem.Unfortunately unsuccesful for now. I've installed Drupal 7.5 and Multipurpose theme which has social icons to redirect to facebook,twitter and etc.In theme settings there is an option to paste link with profile.I wanted to tweak their function a bit but I'm stuck with the code int the page.tpl.php file. What I'm trying to do is basicly to check if the user is logged in, and if he is and a link was given in the setting of the theme to redirect to the social profile.The problem occurs when the user presses the button twice or more because the link copies over and over instead of refresh...for example: 1 click: https://www.facebook.com/user and on the 2 click becomes: https://www.facebook.com/user/user and so on. The code:

```
 <?php if (!$logged_in) : ?>
      <?php if ($twitter_url): ?><li>
        <a title="<?php print $site_name; ?> in Twitter" href="<?php print $twitter_url; ?>"><img alt="Twitter" src="<?php print base_path() . drupal_get_path('theme', 'multipurpose') . '/images/social/twitter.png'; ?>"> </a> <?php endif; ?>
      </li><?php endif; ?>

```

So the question is how can I disable the button(become inactive not hidden) after one click or is there any other approach to solve this problem? Thank you!

# Answer
> 1 votes
The link needs a slash in front of it:

`/user/login`

instead of:

`user/login`

Logout would be:

`/user/logout`

You need to use relative paths or you will continue encountering this behavior. A better way would be to send the variables to your template(s) via the appropriate preprocess function, and use the l() function to create links.

---
Tags: 7
---


# Question
Title: Views PHP Field - Comparing two date fields
I'm trying to compare two date fields in a php field inside a view

I already have this working so far so good...

The php field looks like this:

```
$nid = $data->nid;
$node = node_load($nid);

$start_value = $node->field_tria['und'][0]['value'];
$end_value = $node->field_data_de_resoluci_['und'][0]['value'];
$timezone = $node->field_tria['und'][0]['timezone'];

$start_date = new DateObject($start_value, $timezone);
$end_date = new DateObject($end_value, $timezone);

$difference = $start_date->difference($end_date, 'days');
return $difference;

```

This returns me the day difference value, but always in positive. The desired result should be something like this:

Day difference:

Example 1 (negative value):

2 days ago (or -2)

Example 2 (positive value):

2 days

It also looks like loading every node first doesn't seems to be the most efficient way to do this... but it works.

Thanks a lot

Here is my final code:

```
$nid = $data->nid;
$node = node_load($nid);
$timezone = $node->field_tria['und'][0]['timezone'];

$start_value = $node->field_tria['und'][0]['value'];
$day = substr($start_value,8,2);
$month = substr($start_value,5,2);
$year = substr($start_value,0,4);
$date = "$year-$month-$day";
$value1 = new DateObject($date, $timezone);

$end_value = $node->field_data_de_resoluci_['und'][0]['value'];
$day2 = substr($end_value,8,2);
$month2 = substr($end_value,5,2);
$year2 = substr($end_value,0,4);
$date2 = "$year2-$month2-$day2";
$value2 = new DateObject($date2, $timezone);

$difference = $value1->difference($value2, 'days', FALSE);
return $difference+1;

```

# Answer
You might need to add the `$absolute` parameter in your call to `DateObject::difference()`, in order to be able to get the sign:

```
$difference = $start_date->difference($end_date, 'days', FALSE);

```

According to the DateObject::difference documentation, the `$absolute` parameter:

> Indicate whether the absolute value of the difference should be returned or if the sign should be retained. Defaults to TRUE.
> 1 votes

# Answer
If both fields are on the same entity (the same node in this case) I'd recommend using the Calculated Field module over Views PHP.

The ability to quickly spin up functions in code for computed fields makes these easier to manage (using version control systems) than using Views PHP and also reduces the attack surface of the site (allowing direct input of PHP into the Drupal UI and thus having PHP living in your DB is never a good thing)

Using computed fields - the approach would be largely the same as that being used now - including the advice in the other answer by @dinopmi.
> 0 votes

---
Tags: views, entities, datetime
---


# Question
Title: How can I search for a specific user on the People administration page?
I can filter by Role, Permission and status on the people page, is there an easy way to search for one specific user?

# Answer
That's all you can do with core Drupal - it is a little frustrating for sure. :-)

However, there are lots of contrib modules that let you do more, such as

Of course, you can also opt to make yourself a user-based view and create an admin page yourself by using relationships and filters. :-)

Hope one of these helps!
> 7 votes

# Answer
Assuming this question is about D7, only using Drupal core wont be sufficient. However, you could create a view (using the Views module) of all your users, and use the views style provided by the dataTables module. Here is a quote from the dataTables project page:

> The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:
>
> * Variable length pagination
> * On-the-fly filtering
> * Sorting with data type detection
> * Smart handling of column widths
> * Themeable by CSS
> * And more ...

You'd be especially interested in the ***On-the-fly filtering***. For way more details about this module, refer to "What are my options to visualise a views table with many fields grouped in columns?".
> 2 votes

# Answer
I want to also vouch for https://www.drupal.org/project/usersearchtoadmin in Drupal 7. I used such and had great success for specific people keyword searches "as shown" in the real life example below:
> 0 votes

---
Tags: users, search
---