# Question
Title: How do I attach an existing file to a node?
Here's my problem. I have a D6 site which has been in production for a number of years, and in consequence has used various methods (and modules) for displaying images within body text of book pages. The latest of these modules is IMCE. Up to now (unless I've missed something), none of these mechanisms had any management of the links to images incorporated in the body text. As a result, I have a lot of links pointing to various places in my files directory,

With the arrival of Drupal 8, I've discovered "managed files" and the possibility of using "Inline Images" with CKEditor, such that files in the body text are properly managed, and you get a display in the Files listing of where the images are used.

Since this suits my use case fine, I think I don't need any alternative modules any more. However, here comes the problem: having migrated the site from D6 to D8, the physical directory where the files are kept has changed and since all the files have been copied over, all the body text links are broken.

What to do? Well, I decided to write a drush command which would look through all the body texts that contain `<img>` tags, extract the image file references, find the real file, create a managed file entity, attach that entity to the node, change the `<img src="my file ref">` and save it back to the body.

Thanks to Berdir's friendly advice, I abandoned the original idea of using SQL to go directly through the table, and decided to have a go at Entity Queries instead (first time ever!). So we have this:

```
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'book');
$entity_ids = $query->execute();
foreach($entity_ids as $nid) {
  $node = Node::load($nid);
  $body = $node->get('body')->getValue();
  $body_text = $body['value'];
  $summary = $body['summary'];
  $format = $body['format'];
  }

```

So far so good. I won't bore you with the details of how I extract the file name and directory, but I can do this. So now I want to create and save a file entity, and then attach it to the node. This code creates the file entity (but see Berdir's answer below, not everything is necessary here):

```
    $file_name = end(explode("/", $src));
    $file = entity_create('file');
    $file->setFilename($file_name);
    $file->setFileUri('public://images/'.$file_name);
    $file->setSize($size);
    $file->language('en');
    $file->isNew();
    $file->setTemporary();
    $file->save();

```

(I confess that I'm really struggling to get my head round the Drupal 8 API and object programming...).

This actually works, it does create a temporary file entity which shows up properly in the Content list (except the MIME type is missing, that needs adding).

However, this is probably not the way to go because there surely must be some mechanism for creating the file entity and attaching it to the node without going through all this - just as CKEditor does when you add an inline image.

I've tried getting a list of all the methods proposed by the Node class, and thought maybe `$mynode->referencedEntities()` would show me the way - but this doesn't include inline images (I tried with a new test node that does contain an inline image, and it doesn't show here). Should it perhaps appear via a link to the body text as a field entity? And if so, where to go to get this information, and manipulate it?

I have found this in the Editor core module, perhaps this is the way to go?

```
function _editor_record_file_usage(array $uuids, EntityInterface $entity) {
   foreach ($uuids as $uuid) {
    if ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid)) {
    if ($file->status !== FILE_STATUS_PERMANENT) {
      $file->status = FILE_STATUS_PERMANENT;
      $file->save();
    }
  \Drupal::service('file.usage')->add($file, 'editor', $entity->getEntityTypeId(), $entity->id());
    }
  }
}

```

# Answer
> 1 votes
A few things..

You should avoid raw sql queries against entity tables, they are managed and it is not guaranteed that the structure will always break. Use entity queries and then load the entities using Node::loadMultiple() for example, or $storage-\>loadMultiple().

A few lines of your existing code are not necessary. the size is calculated, language() is a getter that has no arguments, it is automatically new.

To set the uid, you can use setOwner($user) or setOwnerId($uid), and there are corresponding getter methods on the node objects, so once you load them, you can just set it from the node with $file-\>setOwner($node-\>getOwner())

However, that seems to be a completely different question than what you have in the title. That just syncs the owner (which is not that important, not for public files at least). It doesn't do anything to connect them to the node. To get the usage tracking, you can rely on what Drupal does by default if you include the UUID as an data attribute. I don't remember the exact name right now, just manually add an image with CKEditor and you'll see it in the source code. If that's there then Drupal does it for you automatically.

---
Tags: 8, nodes, files
---


# Question
Title: How to achieve the use exposure filter of views, head Title Update？
I use the exposed filter on a Drupal 7 website. I want to achieve that when the user clicks on the filter, the head of the title will also output the filtering term.

Any suggestions?

# Answer
1) Add `Taxonomy term: Name` as a field

* Check `Exclude from display`
* Uncheck `Link this field to its taxonomy term page`

2) Click on *Title:* and put `[name]`
> 3 votes

---
Tags: 7, views
---


# Question
Title: How/where do I add $('#fullpage').fullpage() code?
I want use the fullpage library. In my theme.libraries.yml file, I added theses lines.

```
fullPage:
  header: true
  js:
    js/fullPage.js/jquery.fullPage.js: {}
  dependencies:
    - core/jquery

```

jquery.js and jquery.fullPage.js are now present in the `<head>` tag, but to run fullpage.js, I must execute \[this additional script.

```
$(document).ready(function() {
    $('#fullpage').fullpage();
});

```

How and where do I add this little script?

# Answer
> 0 votes
You need to create a javascript file in your theme and attach it to pages as shown in the documentation. https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

Make sure you theme library has a dependency on fullPage.

---
Tags: 8, javascript
---


# Question
Title: Composer error installing Address module
I had a previous error with the Address module, here. Unfortunately the solution is no longer helping.

I'm installing the Address module as follows:

```
composer config repositories.drupal composer https://packages.drupal.org/8
composer require "drupal/address ~1.0"

```

Unfortunately I get the following error:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package commerceguys/addressing (locked at v0.8.4, required as ~1.0) is satisfiable by commerceguys/addressing[v0.8.4] but these conflict with your requirements or minimum-stability.
  Problem 2
    - The requested package commerceguys/zone (locked at v0.7.1, required as ~1.0) is satisfiable by commerceguys/zone[v0.7.1] but these conflict with your requirements or minimum-stability.

```

I've tried the solution linked above, but it doesn't help. I've also checked I'm running the latest version of Composer (1.2.1).

Any ideas?

James

# Answer
> 0 votes
The problem seems to be that I had installed a previous version of the Address module in the `sites/all/modules` directory, which seems to have been confusing Composer. Composer installs into the `modules` directory, and after deleting the older copy, I was able to run the `composer require` command without problems.

---
Tags: 8, composer
---


# Question
Title: How to show Wordpress blog posts in Drupal's Search Api?
We have a blog site on Wordpress that we want displayed in our search without having to create Drupal nodes for each blog post. We using the following below and were interested in seeing how we can do this as the Wordpress Migrate and Migrate has not provided a way to do this.

All we want to do is display the blog post on our search (which using Apache Solr Search Index) in such a way that we pull the blog post title, description and a direct link to the post.

# Answer
There are 2 ways you can achive this :

1. \[simple\] Import the posts from wordpress rss with Feeds https://www.drupal.org/project/feeds
2. \[more difficult\] Crawl the Wordpress content and populate the Apache Solr index directly. You can use an open source crawler like Apache Nutch The difficult part is that the external content is not managed by Drupal, only through Solr so you don't have many options to play with the indexed content in the Drupal site.
> 0 votes

---
Tags: 7, views, search
---


# Question
Title: Redirect node/id to node/path-auto-alias
**Using Drupal 8**

I need to set various links between my content types and so far I'm setting the link using their **path-auto-generated-alias**, but that's terrible practice because if I change the pattern one day I will have to change every single existance of the out of date url alias.

I've seen plenty of answers for **Drupal 7** with module Global Redirect but it states that it's *deprecated* for Drupal 8 and to use Redirect instead. I installed the module and I'm presented with this:

I have no idea what's amitted in there, tokens? If someone could direct me to a documentation where I can learn to use the module I'd really appreciate it since I'm at a loss.

The reason why I'm in that part is because I have the following Global Settings and it's not redirecting `/node/id` to expected Path Auto URL alias.

# Answer
> 4 votes
Found my mistake, you can't have `Check access to the redirected page` enabled in the global REDIRECTS.

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


# Question
Title: Duplicate Results Using Views, loosing results using (File) File: Content using Thumbnail image
I’ve got a “views” question. I have a view that is using `File Usage: File` under advanced \> relationships and `(File) File: Content using Thumbnail image`. In that later relationship, `(File) File: Content using Thumbnail image` , when `require the relationship` is checked, I loose nodes that don’t have thumbnail images, when it’s not checked, I get duplicates (the content type holds a thumbnail and a header image and for some reason it returns a result with the thumbnail and a duplicate result with the header image instead of the thumbnail) - Anyone got any idea how I can get both the ones with the images and without, and not have duplicates?

I tried Other \> Use aggregation and Query Settings \> Distinct (and pure distinct) and didn’t have any luck either

# Answer
> 0 votes
Why you don't get in the view the field that has the image and display it as thumb("image style"). That "Content using Thumbnail image" i guess it load every image with an "preview" from the respective node.

---
Tags: database, views
---


# Question
Title: Send custom user fields to twig template
I'm writing my first Drupal 8 theme.

Now for a block I need all some custom fields of the user. So that I can use it in my theme.

I create a theme file with collectionmanager\_preprocess\_html method.

```
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function collectionmanager_preprocess_html(&$variables) {
// Load the current user.
$user = User::load(\Drupal::currentUser()->id());

// get field data from that user
$firstname = $user->field_first_name->value;
$lastname = $user->field_last_name->value;

$variables['custom_firstname'] = $user->field_first_name->value;
$variables['custom_lastname'] = $user->field_last_name->value;
}

```

If I'm correct I can access the variables in twig with {{custom\_firstname}}. But it show always a null value. Can someone help me with this? I can't find my issue on this. The variable $firstname and $lastname contains the correct values.

# Answer
collectionmanager\_preprocess\_**html**() prepares variables for **html**.html.twig template. For **page**.html.twig the of the function name should be collectionmanager\_preprocess**\_page**(). The same pattern should be used for other theme hooks (view, block, field etc).
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Why does my Rules Condition about registration code seem to fail?
I'm using the Rules module and the Registration code module and I've tried configuring a rule like so:

* Rules Event: upon saving a new user account(event).
* Rules Condition: if the registration code used is "123456"(condition).
* Rules Action: add a role for a user.

The rules export is as shown below:

```
{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "regcode" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [ { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

```

However, the Rules Action is not working (nothing works).

Any idea how to get this to work?

**Note**: The Rules Action works with the event "User has used a registration code" without any Rules Condition (if I temporarily remove that Rules Condition). But I'm badly in need of the condition as we want to check if a user has used a specific code. If yes, that user should be assigned a role.

# Answer
I have thought of and implemented a different way out as explained below.

`**Event**: User has used a registration code
**Conditions**: User has used a registration code, Data comparison (regcode:tags) = 14, user has field access = "a user field"
Then,
**Action**: set a data value. i was able to view the registration code used (through token), and set it in a user field automatically.` Note: I have already tagged the particular code with a taxonomy term from the registration code settings interface. This method was adopted because i realized the regcode:tag is readily available almost all the time in the rules config. Also, 14 above is the taxonomy term id of the term tagged with the code in question.
> 1 votes

# Answer
### The typical Rules Condition doesn't seem to work here

Typically when using Rules, you can always give it a try to see if you can add, as a FIRST Rules Condition, a condition like "Entity has field". Or any other variation of a condition that informs the Rules module that you want to test the value of that field in a subsequent rules condition. Without that, Rules has no clue about which data to make available for subsequent processing ...

But, that doesn't seem to work/help for this particular case. For more details on that (if you really want to know why it doesn't work), you may want to look at the active ***Major task*** (not bug!) about Make better use of the Entity system ... (from *Fago*, who has quite a Rules "reputation" ...).

### Rules debugging

If that doesn't help, I typically add a (temporary) Rules Action to just "Show a message on the site" (eg to show the value of a field ...). That might result in other unexpected results, to help you further debug it ...

But that doesn't seem to help either (grrrr), so time to move on to Rules **debugging**, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

### Try to find (and read) the documentation

Too bad, this module doesn't seem to have a lot of documentation, and the README.txt is not of much help either.

### If anything else fails, read the sources

OK, the advantage of open source ... lets go read the sources ...

Aha, I see the regcode.rules.inc (`regcode` in this filename is the machine name of the Registration code module), so let's see what this module's Rules integration has to offer:

* A Rules Event with machine name "**regcode\_used**" and label "**User has used a registration code**". Fine, that's also what's used in the rule in the question here (nothing new).
* A Rules Condition with (a loooong) machine name "**regcode\_rules\_condition\_regcode\_available**" and label "**User has used a registration code**". *Huh???* That's the same label as in the Rules Event, confusing!!! But that Rules Condition is what intrigues me. Time to fabricate a variation of the rule in the question.

### Rule prototype (1st attempt)

Have a look at this variation of the Rule in the question (also in Rules export format, use the Rules UI to import it in your own site):

```
{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } },
      { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

```

The only difference in this rule (as compared to the original rule in the question) is the very first (confusing labeled) Rules Condition with machine name `regcode_rules_condition_regcode_available`.

That additional Rules Condition seems pretty close to the typical Rules Condition as I mentioned in the beginning of my answer (and Fago's issue I mentioned before makes a lot of sense to me now). And since the question states "*... badly in need of the condition ...*", I thought I'd leave the QA-testing of this variation of the rule in the question to the OPer of the question ...

Too bad, but that 2nd Rules Condition can never work, since the "`[regcode]`" token is not the token we're looking for (ie something that is a string, and which we want to check if it yes or no matches the registration code we're interested in to assign that special role). Read on for a new (2nd) attempt ...

### Rule prototype (2nd attempt)

With some additional eyeballing and experiments, I noticed that within "Rules Actions" (not Rules Conditions!) there is the token `[regcode:code]`, apart from all sorts of other regcode related tokens. So that opens another opportunity to get it to work anyway: let's just grab that `[regcode:code]` string and pass it on to a (new) Rules Component, in which we're going to do our thing (ie verify the registration code and grant the role if the code is what we want it to be. Below is the adapted rule from the previous attempt, and the (new) Rules Component:

**a) Adapted Rule**:

```
{ "rules_grant_a_role_after_using_a_registration_code" : {
    "LABEL" : "Grant a role after using a registration code",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value of token \u0022regcode:code\u0022 is: [regcode:code] and will be used as parm for the subsequent Rules Action, which invokes a Rule Component." } },
      { "component_rules_grant_role_for_specific_regcode" : { "actual_regcode" : "[regcode:code]" } }
    ]
  }
}

```

**b) Rules Component**:

```
{ "rules_grant_role_for_specific_regcode" : {
    "LABEL" : "Grant role for specific regcode",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "actual_regcode" : { "label" : "Actual Regcode", "type" : "text" } },
    "IF" : [ { "data_is" : { "data" : [ "actual-regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "10" : "10" } }
        }
      },
      { "drupal_message" : { "message" : "Since you used registration code \u0022[actual-regcode:value]\u0022, you have been granted a special role that corresponds to it." } }
    ]
  }
}

```

Note the 2 extra "Show a message" actions I added (to simplify QA testing).

Curious to hear if with this 2nd attempt it does work, or if you can MAKE it work from here on ...
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How can I redirect users on login based on their chosen language?
I'm looking to redirect users after they login.

The site is multilingual, using English and French.

I've tried using the Login Destination module and using Rules, but it has no options for accessing the language the user has chosen.

On the user edit page, the user can select 'English' or 'French' as their language.

I'm looking, ideally, for a simple rule condition to add, or some PHP.

None of the answers I've found so far have mentioned multilingual sites.

Thanks.

# Answer
> 0 votes
May be this can help you.

```
function custom_module_user_login(&$edit, $account){
  $base_url;
  if($account->language) {
          $redirection = $base_url.'/'.$account->language;
  } else{
      $redirection = $base_url;
  }

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.

  if (!is_null($redirection) && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
    $GLOBALS['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }

```

# Answer
> 0 votes
If you go to `/admin/config/regional/language/configure`, you will see an option `Follow the user's language preference.`. Enable that (and optionally drag it to be at the top) and you're good to go.

# Answer
> 0 votes
The more elegant and Drupal way is to modify the `$form_state['redirect']` variable.

From Drupal core code comments (in includes/form.inc):

> `$form_state['redirect']` determines where to redirect the user. This can be set either to a string (the path to redirect to), or an array of arguments for `drupal_goto()`.

The key part of the solution is to pass a language argument for `drupal_goto()`. First add an additional form submit handler for the login form, and modify the redirect variable in this handler. Example:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_user_login_alter(&$form, $form_state, $form_id) {
  $form['#submit'][] = 'mymodule_user_login_form_submit';
}

/**
 * Switches language according to user profile.
 */
function mymodule_user_login_form_submit($form, &$form_state) {
  global $user;
  global $language;

  // Exit quickly if UI is already in correct language.
  if (!(isset($user->language) && isset($language->language) &&
    $user->language != $language->language)) {
    return;
  }

  // Verify user language exists and is enabled.
  $languages = language_list();
  if (!isset($languages[$user->language]) ||
    !$languages[$user->language]->enabled) {
    return;
  }

  // Change destination to translated equivalent, if applicable.
  if (isset($_GET['destination'])) {
    $translations = translation_path_get_translations($_GET['destination']);
    if (array_key_exists($user->language, $translations)) {
      $_GET['destination'] = $translations[$user->language];
    }
  }

  if (isset($form_state['redirect'])) {
    if (is_array($form_state['redirect'])) {
      $form_state['redirect'][1]['language'] = $languages[$user->language];
    } else {
      $form_state['redirect'] = [$form_state['redirect'], [
        'language' => $languages[$user->language],
      ]];
    }
  } else {
    $form_state['redirect'] = [sprintf('user/%d', $user->uid), [
      'language' => $languages[$user->language],
    ]];
  }
}

```

For further reading, there is a fair amount of information about this topic on this community documentation page from Drupal: How to redirect users after login in drupal?

---
Tags: 7, users, i18n-l10n
---


# Question
Title: How to get multifield(subfields value) in rules Drupal 7
i use the multifield module with multifield table display in my entityform.

So, in my entityform i have one multifield type with 5 subfields.

How can i get subfield value in Rules?

Thanks

# Answer
> 0 votes
First, you can try to "drill down" your entity and find the subfields. This is a great tutorial on how to drill down your data in rules. If it's not available, you can "Fetch an entity by id" into rules (under actions) and then it will be available.

---
Tags: 7, rules
---


# Question
Title: How to let the users input the filters in views
I have enabled Exposed Group Filters in views. When I set the option to "input required" no results are shown, also does not give me an option to input any filter from the selected option. All I get is an Apply button.

My Query is:

How do I let the users see all results in the view first, let the user input their filter criteria from the allowed list & then show them the results basis of the filters?

I have tried Better Exposed Filters, its still not giving me an option to input my query.

Please advice.

Thanks

# Answer
The exposed filters are not displaying because the view is empty and therefore not rendering. As per this issue, if you give your view something to display when it is empty (i.e. a `no results behaviour` setting), it will show your filters.

Then, if you really don't want to show 'no results' (which is what most people put in there) you *could* hide it wish CSS.
> 0 votes

---
Tags: views
---


# Question
Title: How to redirect a cancel button to destination on each form?
I'm using the following code to add a cancel button on every form I have for add / edit of every content type. The target should be the destination adress in the url

In some content types it is working and some not:

```
$link = l(t('Annuleren'), drupal_get_destination());

      // add the actual button to the form
      $form['actions']['cancel'] = array(
        '#type'   => 'submit',
        '#value' => "Annuleren",
        '#access' => TRUE,
        '#weight' => 55,
        '#submit' => $link,
        '#limit_validation_errors' => array(),
        );

      dpm ($form);

```

It has something todo with #value. If I replace it to #markup like below example then it is working but I do not get a label in the button.

```
  '#markup' => "Annuleren",

```

How to solve this?

# Answer
> 7 votes
In your code above, you're using wrong value for `#submit`. `#submit` accepts an array of submit callback function names, check e.g. here.

You can either add a link in form, which will take user to destination and style the link to look like a button. Check example below:

```
function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'markup',
    '#markup' => '<div class="form-cancel-button-wrapper">' . l(t("Cancel"), 'URL', array('attributes' => array('class' => array('form-cancel-button')))) . '</div>',
  );

  return $form;
}

```

**OR** you can create a normal submit button and add a custom submit handler which will take user to destination. Check example below:

```
function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value' => "Cancel",
    '#weight' => 55,
    '#submit' => array('_custom_form_cancel')
    '#limit_validation_errors' => array(),
  );

  return $form;
}

function _custom_form_cancel($form, &$form_state) {
  drupal_goto('URL');
}

```

**Note:** When you define a custom form element, you don't need to give `#access` property specifically, it is `TRUE` by default.

---
Tags: 7, forms
---


# Question
Title: How can I filter the taxonomy terms by language?
I have searched a way to filter the taxonomy terms by language (as done for nodes), but I didn't find any way to do it.

Does the Views module support that filter in taxonomies too, or just in nodes?
How can I filter the taxonomy terms by language?

# Answer
> 11 votes
By enabling the module Internationalization Views, the option to filter the taxonomy term by the language is available. Note that the version is currently in dev but it works like a charm.

# Answer
> 3 votes
You can use the Internationalization Views module in combination with the Taxonomy Translation module (which is part of Internationalization) to get a language filter for taxonomy terms.

> Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet. **Requires Internationalization 6.x-1.5 or newer**.

# Answer
> 2 votes
Here is another solution:

```
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'yourviewmachinename') {
    $query->where[] = array(
      'conditions' => array(array(
        'field' => 'taxonomy_term_data.language',
        'value' => array('***CURRENT_LANGUAGE***'),
        'operator' => 'in',
      )),
      'args' => array(),
      'type' => 'AND',
    );
  }
}

```

Source here.

# Answer
> 1 votes
The Views module doesn't allow to filter the taxonomy terms by the language associated with it, as Drupal only associate a language with nodes.

You can set the view to show only nodes with a predefined language, though.

* Under "Filter criteria," select "Add"
* in the next form, select "Content translation: Language"
* the next form will allow you to select which language to use to filter the view content between "Select all," "Current user's language," "Default site language," "No language," and one of the languages enabled in the site.

I added this filter on the taxonomy term view that comes with the Views module, selecting English as language to filter the content, and I created two nodes: one in English, and one in Latin. I assigned to both the nodes the same taxonomy term, the one with ID equal to 22.
When I visited http://example.com/taxonomy/term/22, the view effectively shown just the content in English.

# Answer
> 0 votes
**Language filtering for entity translation.** A language filter in the view's "Filter Criteria" section is only needed if you use the node translation system. If instead you use the more modern Entity Translation system available for Drupal 7, just adapt the "Field Language" setting in the view's "Other" section.

**How to do it for taxonomy terms.** I tried this for taxonomy terms and it works. Just make sure you add the correct one of the two field instances for every translatable field, namely the one with a description of "Appears in: taxonomy-term:your-vocab-name". For details, see on issue #1841434.

# Answer
> 0 votes
Add to your YOUR\_MODULE.module

```
function YOUR_MODULE_views_data_alter(&$data) {
  $opts['title'] = 'Language';
  $opts['table'] = 'taxonomy_term_data';
  $opts['help'] = 'Taxonomy term language.';
  $opts['filter']['handler'] = 'YOUR_MODULE_handler_filter_language';
  $data['taxonomy_term_data']['language'] = $opts;
}

```

Add to your YOUR\_MODULE.info

```
files[] = views/handlers/filter/YOUR_MODULE_handler_filter_language.inc

```

Create File "views/handlers/filter/YOUR\_MODULE\_handler\_filter\_language.inc" within your module directory and place next content:

```
/**
 * @file
 * Views handler to filter language by term.
 */

/**
 * Filter by submission status
 */
class YOUR_MODULE_handler_filter_language extends views_handler_filter_in_operator {
  function get_value_options() {
    $languages = array(
      '***CURRENT_LANGUAGE***' => t("Current user's language"),
      '***DEFAULT_LANGUAGE***' => t("Default site language"),
      LANGUAGE_NONE            => t('Language neutral'),
    );
    $this->value_title = t('Language');
    $options = array_merge($languages, locale_language_list());
    $this->value_options = $options;
  }

  // '0' won't work as a key for checkboxes.
  function value_form(&$form, &$form_state) {
    parent::value_form($form, $form_state);
    $form['value']['#type'] = 'select';
  }
}

```

Clear All caches and New criterion will appear.

Or use my module Akuma Taxonomy

# Answer
> 0 votes
As I'm having some other issues with Internationalization Views module, namely that it seems to alter allready translated UI from views (pager directions, header / footer text etc.), I liftet the relevant code for creating the language filters out in a separate module. Replace MYMODULE below with the name of your module. Works as a charm for me!

```
/**
 * Code below is lifted from the i18nviews module. Gives the possibility to filter for
 * language on term views
 *
 * Implementation of hook_views_data_alter().
 *
 * Registers views handlers with dependency to i18n_taxonomy.
 */
function MYMODULE_views_data_alter(&$data) {

  // Add i18n language field to taxonomy_term_data. No clash.
  $data['taxonomy_term_data']['language'] = array(
    'group' => t('Taxonomy term'),
    'title' => t('Language'),
    'help' => t('The language the term is in.'),
    'field' => array(
      'handler' => 'MYMODULE_handler_field_taxonomy_term_language',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'MYMODULE_handler_filter_taxonomy_term_language',
    ),
    'argument' => array(
      'handler' => 'MYMODULE_handler_argument_taxonomy_term_language',
    ),
  );
}

/**
 * Field handler to provide simple renderer that shows term language.
 */
class MYMODULE_handler_field_taxonomy_term_language extends views_handler_field_taxonomy {
  function render($values) {
    $languages = locale_language_list();
    $value = isset($languages[$values->{$this->field_alias}]) ? $languages[$values->{$this->field_alias}] : '';
    $value = $this->get_value($values);
    return $this->render_link($this->sanitize_value($value), $values);
  }
}

/**
 * Filter by language
 */
class MYMODULE_handler_filter_taxonomy_term_language extends views_handler_filter_in_operator {
  function get_value_options() {
    if (!isset($this->value_options)) {
      $this->value_title = t('Language');
      $languages = array(
        '***CURRENT_LANGUAGE***' => t("Current user's language"),
        '***DEFAULT_LANGUAGE***' => t("Default site language"),
        LANGUAGE_NONE => t('No language')
      );
      $languages = array_merge($languages, locale_language_list());
      $this->value_options = $languages;
    }
  }
}

/**
 * Argument handler to accept a language.
 */
class MYMODULE_handler_argument_taxonomy_term_language extends views_handler_argument {
  function construct() {
    parent::construct('language');
  }

  /**
   * Override the behavior of summary_name(). Get the user friendly version
   * of the language.
   */
  function summary_name($data) {
    return $this->term_language($data->{$this->name_alias});
  }

  /**
   * Override the behavior of title(). Get the user friendly version of the
   * node type.
   */
  function title() {
    return $this->term_language($this->argument);
  }

  function term_language($langcode) {
    $languages = locale_language_list();
    return isset($languages[$langcode]) ? $languages[$langcode] : t('Unknown language');
  }
}

```

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


# Question
Title: Which alias do I use to run it with another PHP version?
The Server available for our new Drupal project uses an old PHP CLI Version by default. But I have setup an alias in `.bash_profile` like so:

```
alias php7=/path/to/php7

```

and that is working fine. I would like to use Drush, so I cloned the repository, such that I can use Drush with the PHP version from the alias with `php7 ./path/to/drush`.

Doing so just prints the content of Drush to the terminal.

How can I setup an alias for PHP 7 that allows me to run Drush with that PHP version?

I have added these lines to the .bash\_profile file.

```
alias php7=/path/to/php7
export DRUSH_PHP=/path/to/php7
alias drush="php7 $HOME/path/to/drush.phar"

```

When I run `drush pm-update drupal`, I get the following errors.

> The external command could not be executed due to an application error.
> The command could not be executed successfully
> Returned: PHP Parse error: syntax error, unexpected '\[' in phar:///path/to/drush.phar/includes/startup.inc on line 63, code: 255)
> pm-updatestatus failed.

Why? How can I fix that?

Running `drush pm-updatestatus` or `drush cr` works, and `drush status` shows no errors.

Is there a bug in a specific version?

# Answer
This is possible by setting the environment variable DRUSH\_PHP as described in the documentation. https://www.drupal.org/node/1302418

Also you can make use of "php" global otpion which allows to specify the absolute path to PHP interpreter.
> 1 votes

---
Tags: drush
---


# Question
Title: How to resist anonymous user to access module internal files? eg. path starts from \Drupal\module\mymodule\files
I have one file placed in my module. I want that only authenticated users or admin can access the content of this file. For anonymous users, it should be shown 'You don't have permission to access...'

Link is like `<a href = "' . $base_url . '/' . drupal_get_path('module', 'my_module') . '/files/myfile.xml" target="_blank">Sample File</a>'`

Right now issue is, even if i logged out, I am able to see the content of this link.

I tried this:

```
if(isset($user->roles[1])) {
        global $base_url;
        return $mylink;
      }

```

but above code is not working for me.

What is the best possible way to achieve this?

# Answer
> 3 votes
If I've understood your requirement correctly, you've some files other than normal Drupal files, like csv, txt which should not be accessible to Anonymous user.

This should be done at .htaccess level or you can give a try to private file system in Drupal Core. Check the ans given to "how to restrict file access to specific user roles" for more details on Private File system. The question is related to Drupal 7 because of which contributed modules will not be available for Drupal 8. But you can check configuration options mentioned for Drupal 8 Core.

---
Tags: 8, users, navigation
---


# Question
Title: AJAX form blocks getting internal server error
I am trying to add a subscribe button as a block.

I added a form as

```
class SubscribeTag extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['ajaxsubmit'] = [
      '#type' => 'submit',
      '#value' => 'Subsscribe',
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'wrapper' => 'message-wrapper',
      ],
    ];

    $form['messages'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'message-wrapper'],
    ];

    return $form;
  }

  public function getFormId() {
    return 'skb_subscription';
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message('Thank you for subscribing');
  }

}

```

It works correctly when a route is defined. When i go to the page /skb\_subscribe\_form the callback works correctly.

```
skb_subscription.subscribe:
  path: 'skb_subscribe_form'
  defaults:
    _form:  '\Drupal\skb_subscription\Form\SubscribeTag'
    _title: 'SKB Subscription'
  requirements:
    _permission: 'access content'

```

But when i try add the form to a block using the code

```
class SubscribeBlock extends BlockBase {
  public function build() {
    return \Drupal::formBuilder()->getForm("\Drupal\skb_subscription\Form\SubscribeTag");
  }
}

```

i get the following error "A fatal error occurred: The specified #ajax callback is empty or not callable."

I tried changing the callback with

```
$form['actions']['ajaxsubmit'] = [
      '#type' => 'submit',
      '#value' => 'Subsscribe',
      '#ajax' => [
        'callback' => '\Drupal\skb_subscription\Form\SubscribeTag::ajaxSubmit ',
        'wrapper' => 'message-wrapper',
      ],
    ];

```

but still getting the same error.

# Answer
> 2 votes
Try this

```
$build['form'] = \Drupal::formBuilder()->getForm('\Drupal\skb_subscription\Form\SubscribeTag');
 return $build;

```

---
Tags: 8, blocks, ajax
---


title: How do I customize Display Suite?

text:
# Question
Title: How do I customize Display Suite?
I know that Display Suite change its features due to limitation of PHP script within DS in Drupal 8.

What I want is customize the uploaded file which display something like this:

Code File: sample\_file.zip

Into:

Download Code

In which, Download Code is a link the same with the original output as sample\_file.zip.

I created a token field in Display Suite and put the following code to no avail:

```
<a href="[node:field_code_file]">Download Code</a>

```

The output of this is a plain text:

```
<a href="/drupal8/sites/default/files/2016-11/sample_file.zip">Download Code</a>

```

Instead of Download Code.

So, how can I link the downloadable File as shown in the image below into something like `Download Code` with the original link of the file?

# Answer
The File output (**Generic File**) is rendered from "`file-link.html.twig`" template file. To update the Link Text, you can override template\_preprocess\_file\_link() in your theme's `themename.theme` file. So suppose if my theme name is `bartik` then function name will be `bartik_preprocess_file_link()`. Check example below:

```
use Drupal\Core\Template\Attribute;
use Drupal\file\Entity\File;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_HOOK() for file-link.html.twig.
 */
function [THEME_NAME]_preprocess_file_link(&$variables) {
  $file = $variables['file'];
  $options = array();

  $file_entity = ($file instanceof File) ? $file : File::load($file->fid);
  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $url = file_create_url($file_entity->getFileUri());
  $variables['#cache']['contexts'][] = 'url.site';

  $mime_type = $file->getMimeType();
  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    // Add new Link text here.
    $link_text = 'Download Code';
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity->getFilename();
  }

  // Classes to add to the file field for icons.
  $classes = array(
    'file',
    // Add a specific class for each and every mime type.
    'file--mime-' . strtr($mime_type, array('/' => '-', '.' => '-')),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  );

  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']->addClass($classes);

  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
}

```

Or, you can create a custom field formatter which can be selected on **Managed Display** Page. as per example provided here, Create a custom field formatter.
> 0 votes

---
Tags: 8
---


# Question
Title: How to create bootstrap subtheme using sass?
I am using latest bootstrap version(7.x-3.8) . I want create a subtheme by using SASS but i don't know how to proceed.

# Answer
> 4 votes
# Create a New Sub-theme

1. Copy `bootstrap/starterkits/sass` folder into `sites/all/themes` or a respective `sites/*/themes` folder.
2. Rename the folder to a unique machine readable name. This will be your sub-theme's "name". For this example and future examples we'll use **subtheme**.
3. Rename `subtheme/sass.starterkit` to match the folder name and append .info (e.g. `subtheme/subtheme.info`).
4. Open `subtheme/subtheme.info` and change the name, description and any other properties to suite your needs.
5. Download and extract the latest 3.x.x version of Bootstrap Framework Source Files into the root of your new sub-theme. After it has been extracted, the directory should be renamed (if needed) so it reads `subtheme/bootstrap`.

# Compile Sass

1. Override default bootstrap variables in `subtheme/sass/_default-variables.scss`.
2. Edit `subtheme/sass/overrides.scss` as your fit to properly integrate with Drupal
3. Compile `subtheme/scss/style.scss` to `subtheme/css/styles.css`.

---

More Information : Read Drupal-Bootstrap Documentation

---
Tags: 7, theming
---


# Question
Title: Alter views exposed filter using any hook function
I want to alter an exposed filter of a view to add a new field to the existing filter. I tried the same with hook\_views\_pre\_view() and the new filter field added successfully. But after typing something to that autocomplete field, that field disappears. Means on the first page load, field displaying correctly but when AJAX starts it disappears. Also I tried with other hook functions like hook\_views\_pre\_build and hook\_views\_pre\_execute(). Can any one help me on this? Thanks.

```
function modulename_views_pre_view(&$view) {
  if ($view->name == 'my_view_name') {
      $view_filters = $view->display_handler->get_option('filters');
      //Add new field
      $view_filters['new_field'] = array(
        'id' => 'new_field',
        ..
        ..
      );

     $view->display_handler->override_option('filters', $view_filters);

  }
}

```

# Answer
> 0 votes
This will be work by using hook\_views\_default\_views\_alter function. This function should be defined in MODULE\_NAME/views/MODULE\_NAME.views.inc file. Need to include this file on .info file as files\[\] = views/MODULE\_NAME.views.inc.

```
function MODULE_NAME_views_default_views_alter(&$views) {
        if (array_key_exists('MY_VIEW_NAME', $views)) {
          $options = array(
          0 => 'Blocked',
          1 => 'Active',
          );
          $display = $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'];
          $display->display_options['filters']['field_status']['id'] = 'field_status';
          $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
          $display->display_options['filters']['field_status']['field'] = 'field_status';
          $display->display_options['filters']['field_status']['value'] = $options;
          $display->display_options['filters']['field_status']['exposed'] = TRUE;
          $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
          $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
          $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'] = $display;
          }
    }

```

Hope this may helpful for anyone who are facing same issue.

---
Tags: views
---


title: Multiple payment targets

text:
# Question
Title: Multiple payment targets
I have a scenario where payments should be made to different targets based on some conditions. I was considering multi-store approach but I felt it might be a overkill considering that we only need payment targets and not complete store management.

Is there any simpler way of achieving this?

# Answer
> 0 votes
Which payment gateway are you planning to use? If it is Paypal, then there is this system called Adaptive payment which helps you split payments.

---
Tags: commerce
---


title: Using Search Api Solr indexed search?

text:
# Question
Title: Using Search Api Solr indexed search?
I Installed \[search api solr module\]\[1\] and solr-5.5.2 server. When I tried to add server in drupal backend(/admin/config/search/search-api/add-server) , I'm getting warning message as shown in attached image and I'm not able save the settings.Can anybody help me in this? http://192.168.88.89:8983/solr/#/drupal8 is my solr server which is running

Though i added the configuration, why i'm not able to save.Is there any other settings? I have moved solr-conf/5.x files to server/solr/drupal8/conf.

# Answer
For the solr core name, try using just "drupal8" instead of "/index/drupal8"

Here are the settings I'm using locally:
> 1 votes

---
Tags: 8, search
---


# Question
Title: Batch update XML Sitemap for content type using VBO - D7
I am trying to update a portion of my Basic Pages' XML Sitemap setting. By default my Basic Pages are Excluded in the XML Sitemap (what I want), but I want to bulk update only **some** of them (long story). I can manually go to each of the pages and update them to be Included, but that will be a pain.

I tried to use VBO and I created the filters I want, but there isn't a XML Sitemap update Operation. I can create a Rules Action, but again, I couldn't find integration with the XML Sitemap setting.

Is there a setting for bulk updating the XML Sitemap setting that I'm missing? Or some module that does this already?

Other ideas I have if this functionality doesn't exist:

* VBO: Execute arbitrary PHP script & run a Database update
* Rules Action: Create a custom action to run a Database update
* ???

Drupal 7.34, Rules 7.x-2.7, VBO 7.x-3.2, XML Sitemap 7.x-2.2

Thanks.

# Answer
> 0 votes
Try XML sitemap VBO https://www.drupal.org/project/xmlsitemap\_vbo It create xml-operations in Bulk operations of views.

# Answer
> 0 votes
Looks like there isn't really a rules integration yet. The *best* outcome here would be to write that integration and contribute it to the project.

Failing that, a custom action using PHP would do the trick. Obviously you should take a backup before executing anything like that.

---
Tags: 7, views, xml-sitemap
---


# Question
Title: How to stop all the processes except by entering Linux via SSH?
I have been deleting some Feeds through the Feeds GUI, but somehow Drupal 7 has been stuck. The site is in maintenance mode. I have no Drush access, and I cannot enter with Admin 0 user.

How can I stop all the processes except by entering Linux via SSH?

# Answer
If you can log into your hosting account control panel, you may have access to PHPMyAdmin to change the password. Also you might be able to reboot your server from there.
> 1 votes

---
Tags: 7
---


title: Problem with admin_menu and Varnish

text:
# Question
Title: Problem with admin_menu and Varnish
I'm a beginner with configuring varnish, so my apologies if this is a stupid question. I am trying to make things work on my ubuntu VM (12.04) with Varnish 3.

I am facing a problem, where after I log in, the admin menu (created by admin\_menu) just disappears. Looking at the ajax request, it seems that varnish sends the request to drupal, receives a valid answer and then just refuses to serve it. It just outputs a 503 error instead.

I have captured the varnish logs, but I'm not sure what to make of them. Anyone has any ideas?

```
    11 ReqStart     c 192.168.1.20 50807 2144510792
   11 RxRequest    c GET
   11 RxURL        c /js/admin_menu/cache/a4270b058219f623d092552467a5cde0
   11 RxProtocol   c HTTP/1.1
   11 RxHeader     c Host: www.giftmonkey.ubuntu
   11 RxHeader     c User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:24.0) Gecko/20100101 Firefox/24.0
   11 RxHeader     c Accept: text/plain, */*; q=0.01
   11 RxHeader     c Accept-Language: en-US,en;q=0.5
   11 RxHeader     c Accept-Encoding: gzip, deflate
   11 RxHeader     c X-Requested-With: XMLHttpRequest
   11 RxHeader     c Referer: http://www.giftmonkey.ubuntu/
   11 RxHeader     c Cookie: __utma=94903434.1646672653.1383344251.1383344251.1383390432.2; __utmz=94903434.1383344251.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); has_js=1; pmcwidth=1920; __utmc=94903434; SESS9433506a0f068ea0ad220f58b963eef8=6FfRyBpNYYBlufL7y6AoBa5eqBP
   11 RxHeader     c Connection: keep-alive
   11 VCL_call     c recv pass
   11 VCL_call     c hash
   11 Hash         c /js/admin_menu/cache/a4270b058219f623d092552467a5cde0
   11 Hash         c www.giftmonkey.ubuntu
   11 VCL_return   c hash
   11 VCL_call     c pass pass
   11 Backend      c 17 default default
   11 TTL          c 2144510792 RFC 31536000 -1 -1 1383409657 0 1383409657 0 31536000
   11 VCL_call     c fetch
   11 TTL          c 2144510792 VCL 120 -1 -1 1383409657 -0
   11 VCL_return   c hit_for_pass
   11 ObjProtocol  c HTTP/1.1
   11 ObjResponse  c OK
   11 ObjHeader    c Date: Sat, 02 Nov 2013 16:27:37 GMT
   11 ObjHeader    c Server: Apache/2.2.22 (Ubuntu)
   11 ObjHeader    c X-Powered-By: PHP/5.3.10-1ubuntu3.8
   11 ObjHeader    c Expires: Sun, 02 Nov 2014 11:17:03 +0000
   11 ObjHeader    c Last-Modified: Sat, 02 Nov 2013 11:17:04 +0000
   11 ObjHeader    c Cache-Control: private, max-age=31536000
   11 ObjHeader    c ETag: "1383391024-1"
   11 ObjHeader    c X-Drupal-Cache: HIT
   11 ObjHeader    c Content-Language: ro
   11 ObjHeader    c Vary: Cookie,Accept-Encoding
   11 ObjHeader    c Content-Encoding: gzip
   11 ObjHeader    c Content-Length: 6705
   11 ObjHeader    c Content-Type: text/html; charset=utf-8
   11 FetchError   c Junk after gzip data
   11 Gzip         c u F - 6611 59085 80 80 52818
   11 VCL_call     c error deliver
   11 VCL_call     c deliver deliver
   11 TxProtocol   c HTTP/1.1
   11 TxStatus     c 503
   11 TxResponse   c Service Unavailable
   11 TxHeader     c Server: Varnish
   11 TxHeader     c Content-Type: text/html; charset=utf-8
   11 TxHeader     c Retry-After: 5
   11 TxHeader     c Content-Length: 436
   11 TxHeader     c Accept-Ranges: bytes
   11 TxHeader     c Date: Sat, 02 Nov 2013 16:27:37 GMT
   11 TxHeader     c X-Varnish: 2144510792
   11 TxHeader     c Age: 0
   11 TxHeader     c Via: 1.1 varnish
   11 TxHeader     c Connection: close
   11 TxHeader     c X-Cache: MISS
   11 Length       c 436
   11 ReqEnd       c 2144510792 1383409657.339800358 1383409657.400331020 0.511597395 0.060457230 0.000073433
   11 SessionClose c error
   11 StatSess     c 192.168.1.20 50807 2 1 5 0 5 4 1760 6926

```

# Answer
The error see to be on some cache file of drupal's admin\_menu. The js aggregated file browser is requesting is being refused by Drupal by 503. You may get some pointers to this issue here https://groups.drupal.org/node/28604

Try clearing all the Drupal caches using "drush cc all" command. Are you using any js aggregation on Drupal side? Try changing to https://drupal.org/project/advagg?
> 1 votes

# Answer
I seem to have resolved this on our system by doing the following:

Navigate to admin/config/administration/admin\_menu

Under "Performance" field group - uncheck "Cache menu in client-side browser"

Save

Note: I only have this enabled as such in my dev/stage environments, since that's where 99% of everything 'work' related happens. I suppose it could be 'disabled' in production as well, providing it is only used by admins, and that no 'normal' role, anon, has perms for said item. The caching benefit isn't realized in this type production usage, so it wouldn't matter.
> 0 votes

---
Tags: proxies
---


title: Commenting gallery items

text:
# Question
Title: Commenting gallery items
i want to create a gallery where users can comment on each image. I've seen approaches for Drupal 7, for example:

* Node gallery Module
This is currently not supported in Drupal 8.
* Gallery / Image Content Type with references
Is this a suitable approach for more than 1000 pictures?

Is there a better way to make this work in Drupal 8? Am I missing improvements on Drupal 7/8?

# Answer
I built 2 gallery type sites with album-image and category-product relations last week - my first 2 Drupal 8 sites! If direct modules are not available, you can try using views to solve your problem by creating your own gallery setup (if acceptable).

**Step 1: Create provision for gallery categories**

Create a taxonomy vocabulary named `gallery_category` and add relevant fields to it. These would serve as albums:

* **image**: album cover
* **body**: album description

**Step 2: Create provision for gallery items**

Create a content-type named `gallery_item` and add relevant fields to it:

* **image**: the image
* **body**: image description
* **category**: reference to the `gallery_category` vocabulary - you can have single or multiple values depending on whether your images would belong to one or more categories (as per requirement).

**Step 3: Set up views**

* Create one view to display a list of all categories
* Create another view or modify the default taxonomy term view to fine-tune the list of gallery items inside a category.
* For the views, if you have too many categories or items, make sure you enable paging or some other relevant solution to make sure all items don't load in a page.

**Note:** This is a general answer to try and help you. Modify the steps and details as necessary to achieve the output you desire. Good luck!
> 0 votes

---
Tags: 8, comments, media
---


# Question
Title: Render a node as plain text for sending by mail
I like to use a node as mail body in Drupal 8. I have written a simple module which works fine except for output formatting:

```
function foo_notification_node_insert($node) {
  $type = $node->getType();
  if ($type === 'foo') {
    $to = 'test@examples.com';

    // passed to hook_mail
    $params = array(
      "node" => $node
    );

    \Drupal::service('plugin.manager.mail')->mail(
      'foo_notification',
      'notice',
      $to,
      'de',
      $params
    );
  }

function foo_notification_mail($key, &$message, $params) {
    $node = $params["node"];

    // subject
    $message['subject'] = "New node: " . $node->getTitle();

    // render body
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($node->getEntityTypeId());
    $view = $view_builder->view($node, 'default', 'de');
    $message['body'][] = render($view);
}

```

If I understood correct `$view_builder->view($node, 'default', 'de');` returns a render array. This one is rendered to HTML by `render($view);`. Drupal mail service converts HTML in message body to plain text. And that looks ugly.

Rendered mail body looks like:

```
---------------- My node title -------------------------------------
first field label
               first field value

      second field label
                second field value

      third field label
                third field value contains a longer text which break
at some point and is continued like this. Just for demonstration a
few more lines.
This ist how it looks like if it contains a line break. It's ugly.

```

The node has multiple fields and I like to use same view for representation on page (HTML) and in mail (plain text) - especially the order and formatting of node fields.

So what's the correct solution?

# Answer
To render your node in plain text, you can try one of the following approaches as per your needs:

**Approach 1: Remove the tags!**

Add new-lines characters where appropriate and remove all tags from the Drupal rendered output (output might be ugly).

**Approach 2: Use custom template**

Create a custom view mode for your node (may be name it `plain`) and override node template to generate plain text for the specific view mode.

**Approach 3: Send HTML mail**

I read your question well and saw that you need to send plain text, but if a cute kitten doesn't die because of it, you can send your mail in HTML if acceptable.
> 1 votes

# Answer
The render engine of Drupal cannot render Node as plain text (at least natively).

I think you have to choice between send the mail in HTML format with is very easy by changing the *$message\['header'\]* of your mail or installing Mail system with Swift Mailer (very easy too). Or you have to parse the field value yourself by escaping HTML markups (bad way IMO).

I strongly recommend you to send your mail in HTML format if you want to enjoy the benefits of the drupal render engine, which is made for generate HTML output.
> 2 votes

---
Tags: theming, nodes, emails
---


# Question
Title: How to fix AJAX HTTP request which was terminated abnormally?
I keep getting this AJAX error message every time when I add taxonomy terms or open view pages with AJAX, to name a few.

```
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /system/ajax
StatusText: error
ResponseText:
ReadyState: 4

```

Any suggestions to how I can resolve the problem? I'm using the dev desktop.

# Answer
> 5 votes
This issue sounds like yours: Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors

# Answer
> 1 votes
For Drupal 7 you may try to apply the following core patch: D7-fix\_autocomplete\_terminated\_error-1232416-179-do-not-test.patch which goes like:

```
--- a/misc/ajax.js
+++ b/misc/ajax.js
@@ -448,7 +448,10 @@ Drupal.ajax.prototype.getEffect = function (response) {
  * Handler for the form redirection error.
  */
 Drupal.ajax.prototype.error = function (response, uri) {
-  alert(Drupal.ajaxError(response, uri));
+  // Fix for autocomplete terminated error.
+  if (response.status != 0) {
+    alert(Drupal.ajaxError(response, uri));
+  }
   // Remove the progress element.
   if (this.progress.element) {
     $(this.progress.element).remove();
diff --git a/misc/autocomplete.js b/misc/autocomplete.js
index 8f7ac60..980c1ca 100644
--- a/misc/autocomplete.js
+++ b/misc/autocomplete.js
@@ -306,7 +306,10 @@ Drupal.ACDB.prototype.search = function (searchString) {
         }
       },
       error: function (xmlhttp) {
-        alert(Drupal.ajaxError(xmlhttp, db.uri));
+        // Fix for autocomplete terminated error.
+        if (xmlhttp.status != 0) {
+          alert(Drupal.ajaxError(xmlhttp, db.uri));
+        }
       }
     });
   }, this.delay);

```

# Answer
> 0 votes
I have also been seeing this lately. Mine popped up immediately and did not have the turning indicator at all.

I have come to a post at Required autocomplete reference field gives "ReadyState: 0" ajax error #5 @jenlampton gave ma a Clue as to my problem. Although I did use http and not https, I used a link without the www as referenced in my settings.php configuration.

Adding www in my browser made the error disappear.

In conclusion, check your settings.php configuration where $base\_url = 'http://www.example.com" if you have https use https, if you have www.example.com do not go to example.com.

---
Tags: 7, ajax
---


# Question
Title: Importing Webform Submission List (Text) with Feeds Tamper
I am exporting Webform Submissions from one Drupal site and attempting to import them onto another site with Feeds.

Unfortunately, the "Select Options" Webform field (that allows for multiple options to be selected) looks like the following in the exported file.

I am attempting to import these results directly into Drupal with feeds. I wish for these to go into one List (Text) field called "Status Desired".

As you can see, these all have different headers and I want them all to go into the same field.

I tried to use the "Find replace" in Feeds Tamper to change the "X" to the correct value but I had no success.

For example, if the user selects all 4 of the options, only the last one is imported.

Is there any way for me to use Feeds Tamper to import this as is into Drupal?

Or will I have no choice but to modify the data in Excel?

# Answer
> 0 votes
I managed to find a solution on thejibe.

The Feeds Tamper setting I was looking for was "Rewrite".

In the last field, I added "Rewrite" and added tokens for each of the values separated by commas.

Following that, I added Explode.

I did a test import and had great success.

I hope this helps someone.

---
Tags: webforms, feeds
---


# Question
Title: Add a twig variable to a certain href url menu item when it is being created
I have a Drupal 8 install that I am trying to add a variable to a href URL when it equals #blog but I can't get it to work. Can anyone see what I am doing wrong?

This is my menu template file:

```
{{item.url}}
{% if item.url == '#blog'  %}
    <a href="{{ item.url }}" class="dropdown-toggle" style="color:red;" data-target="#" data-toggle="dropdown">{{ item.title }} <span class="caret"></span> /Tksksks iss</a>
{% else %}
    {{ link(item.title, item.url) }}
{% endif %}

```

# Answer
> 2 votes
I just ran into this and have a late answer for you. Your twig template's if statement does not work because your string comparison is against the Drupal Core URL object. You can, however, create a variable in twig and use that for your comparison.

```
{% set menuUri %}{{ item.url }}{% endset %}
{% if menuUri == '#blog'  %}
    <a href="{{ item.url }}" class="dropdown-toggle" style="color:red;" data-target="#" data-toggle="dropdown">{{ item.title }} <span class="caret"></span> /Tksksks iss</a>
{% else %}
    {{ link(item.title, item.url) }}
{% endif %}

```

This will let your comparison to the URL "#blog" work just fine.

---
Tags: theming, 8
---


# Question
Title: Image preview not showing on add/edit page
Preview of the uploaded images are not showing on the node add/edit page but images are uploaded correctly. We're using Lightning Acquia distribution and using Entity browser for the image field.

What could be the possible issue?

# Answer
This is a known issue in the current version of entity\_browser that ships with Lightning. Upgrade the entity\_browser module to 8.x-1.0-alpha10 or later to resolve the issue.

If you have used composer to install, simply update the drupal/entity\_browser module via composer.
> 2 votes

---
Tags: 8, media
---


# Question
Title: Notice: Undefined index: theme_settings in theme-settings.php
I'm creating a custom theme settings and got error this two errors

* Notice: Undefined index: theme\_settings in cocoa\_form\_system\_theme\_settings\_alter() (line 411 of F:\DEV\SITES\DEV\cocoa\sites\all\themes\cocoa\theme-settings.php).
* Notice: Undefined index: favicon in
cocoa\_form\_system\_theme\_settings\_alter() (line 413 of
F:\DEV\SITES\DEV\cocoa\sites\all\themes\cocoa\theme-settings.php).

Here is my theme-settings.php

What am i missing. Please Help

# Answer
> 0 votes
The message you're seeing on site are notices. And those are coming because the index '`theme_settings`' and '`favicon`' doesn't exists in `$form` array. To fix this notice you can update the code as below:

```
  $form['cocoa_options']['drupal_settings']['theme_settings'] = $form['theme_settings'];
  // Change above line to below line.
  $form['cocoa_options']['drupal_settings']['theme_settings'] = (!empty($form['theme_settings']) ? $form['theme_settings'] : '');

  $form['cocoa_options']['drupal_settings']['favicon'] = $form['favicon'];
  // Change above line to below line.
  $form['cocoa_options']['drupal_settings']['favicon'] = (!empty($form['favicon']) ? $form['favicon'] : '[DEFAULT_FAVICON_URL]');

```

More information on how to fix this can be found on PHP: “Notice: Undefined variable” and “Notice: Undefined index”

---
Tags: 7
---


# Question
Title: How do I solve this memory usage limited problem?
I have more than 100,000 articles to move from Drupal 6 to Drupal 7.

How do I solve this memory usage limited problem?

module: migrate d2d

# Answer
Currently migrate module does not support batch query for to get value of nodes. You need to apply one patch which work for you.
> 1 votes

---
Tags: migrations
---