title: Services and translated nodes

text:
# Question
Title: Services and translated nodes
I have a website where three languages are present. I am requesting nodes through the Services API endpoint and that part is working well.

When requesting a node via JSON, how does the API let me know the requested node ID is associated to translated nodes?

I know the translated nodes do contain a "tnid" record of the original node, but the original node doesn't have anything to indicate that there are translated nodes.

# Answer
To know if there are translations available for particular node, You need to call the below function to get the available translation nodes.

```
$translations = translation_node_get_translations($node->tnid);

```

Ref : Function translation\_node\_get\_translations

So what you can do is, You can call this function when you are returning node from service API along with translated nodes.

Hope this will help.

Thanks
> 0 votes

---
Tags: nodes, i18n-l10n
---


# Question
Title: Adding a background image for Omega subtheme
I've created a custom sub-theme for Omega and I want to change the background of the body to a specific image. I've edited the global.css file in the css folder of my subtheme.

```
body {
    background-image:url("images/starbkg.png") repeat;
     }

```

I've also made sure that global.css was enabled. If I add `background-color:black` to the code the background does change color but I haven't been able to change the background image. I figured just by editing the global.css file I should be able to change the background image. No matter how many times I've flushed the cache and reloaded the page, the background image still won't show up. I've even tried creating a preprocess file. In the preprocess folder of my theme.

```
<?php
/**
* Preprocess HTML.
*
* Implements hook_alpha_preprocess_html().
*/
function myth_preprocess_html(&$variables) {

  $variables['classes_array'][] = 'body';
}
?>

```

(myth is the name of my theme)

I don't need the background to re-size or change, I just want something that sits behind all the other areas on the page and is persistent across all the content. When I inspect the page I find that

```
<body class="html front not-logged-in page-node omega-mediaqueries-processed alpha-  debug-processed responsive-layout-wide">

```

hasn't changed to indicate a background. I've looked into various modules that I would like to avoid and I was hoping to find something relatively simple. I have managed to change the background on non-Omega based themes so I suspect there is something that Omega does that I'm missing.

Thanks in advance for your assistance.

# Answer
> 0 votes
You shouldn't need to do any of the preprocess stuff. We recently had some problems getting things to apply via the global.css file - but we figured them out.

Here is the trick of it. Even though you apply X in the global.css file, if Y is applied in one of the stock css files, and you don't turn off Y (via css in your global.css) - and Y in some way impacts X - X won't be active.

I recommend either Firefox and Firebug - or Chrome and "right click -\> inspect" - and really scrutinize the DOM.

Also - regarding your image file - you might **try specifying a full path**. We have had issues with relative paths.

I hope this helps.

# Answer
> 0 votes
It's likely as simple as fixing your css declaration, and doesn't have anything to do with your Drupal theme:

```
body {
  background-image: url('images/starbkg.png');
  background-repeat: repeat; /* not necessary as it's the default */
}

```

You can only specify the image with `background-image` See here

Are you using any dev tools such as Firebug for Firefox or Chrome Developer Tools? Chrome DevTools will actually warn you in the CSS panel when your declarations are invalid.

As others have pointed out, you need to verify your path. If you have not changed anything from the default Omega sub-theme structure, your images folder will not be in the same directory as your css, it's likely you'll need something like `url(../images/stargbkg.png)`

# Answer
> 0 votes
I'm using Omega 3 subtheme and here is the code that worked for me.

```
background-image: url('your site/sites/default/files/wallpaper.png');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: 100%;

```

# Answer
> -1 votes
Try this:

```
body {
  background-image:url("images/starbkg.png") !important;
}

```

---
Tags: media, theming
---


# Question
Title: Duplicates when creating view with entity reference
I have a content type called Conference and there are various sections of data attached to each conference such as guest speakers, agenda, and local amenities. These sections of data are entity bundles. These attach to the content type with an entity reference field on the bundle, so each bundle has a list of conferences in a select list and you attach the bundle to conference by selecting it in this list.

The problem has come when creating a view to display the conference content type with it's corresponding entity bundle information, I am getting a views-row for every bundle, so the basic information from the content type is being duplicated 8-9 times and the bundle data is showing once, and each bundle shows on a views-row where all other bundle info is missing apart from its own.

I have tried to turn on DISTINCT in query settings but not working and if I turn on aggregation I get this error

```
SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near the keyword 'AS'.

```

My View uses a contextual filter for nid and an entity reference relationship to pull the values through.

Any help is welcome, thanks as I am completely stuck with this. Maybe there is a work around, or maybe I need to set up my views differently?

# Answer
> 0 votes
You can give a try to Views Distinct module.

Also, if there the results the logically different you can think of showing them in way that they look more of information rather than repeated results For example if you group by conference, you can show aggregated speakers for a given conferenece

---
Tags: views, entities
---


# Question
Title: How can I give Ajax access to currently set fields on my form?
I'm working on a block form that needs to update certain elements in the form based on what the user selects with certain elements. I've defined the internal class method and it's getting called correctly; however, it can't access the values stored in the form from the `$form_state`.

For example, when I call `$form_state->getValue('filter_field')`, it returns an empty value, even though it has been set on the page. I suspect that this may be due to the fact that I'm setting the callback like so: `'callback' => [get_class($this), 'updateWidgetAjax']`, and in the final comment in the API, it says to do it like this: `'callback' => '::updateWidgetAjax'`. However, when I try this, I get the `The specified #ajax callback is empty or not callable.` error. I tried following the tutorial on the API page as well as here, yet neither of them worked properly, spouting out the same error as before. I also went through this checklist, but most of the items don't apply.

Additionally, and this is just something annoying but related, if I don't mark `updateWidgetAjax` as static I get the following message in my log: `Deprecated function: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\global_filter\Plugin\Block\FilterBlock::updateWidgetAjax() should not be called statically`, which I suspect will be resolved with fixing the above issue.

**In short,** how do I get the form values in my Ajax callback?

---

The element calling the Ajax:

```
$form['filter_field'] = [
  '#type' => 'select',
  '#name' => 'filter_field',
  '#title' => t('Select field to get the filter value from.'),
  '#options' => self::getAvailableFields(),
  '#empty_option' => t('Select a field'),
  '#ajax' => [
    'callback' => [get_class($this), 'updateWidgetAjax'],
    'event' => 'change',
    'wrapper' => 'default-value-ajax-wrapper',
    //The wrapper is elsewhere on the form
  ]
  '#required' => TRUE,
];

```

The Ajax callback function:

```
public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
  $widget = '';
  $multichoice = FALSE;

  switch ($form_state->getValue('widget_type')) {
    //code that sets $widget
  }
  //Return a render array
  $render = [
    '#type' => $widget,
    '#name' => 'default_value',
    '#title' => t('Default value'),
    '#description' => t('Select the default value for this filter. Leave blank for none.'),
    '#options' => self::getOptions($widget, $form_state->getValue('filter_field')),
    '#required' => TRUE,
  ];
  return $render;
}

```

**EDIT:** I forgot to mention that the form is defined with a `blockForm`, since I'm trying to create new blocks with this. I'm following the Drupal documentation found here. I think this might be a big part of the issue.

# Answer
> -1 votes
I have tried this on my local it works . So you can achieve the form values by using this . Please try this

```
    $form['filter_field'] = [
      '#title' => $this->t('Filter'),
      '#type' => 'select',
      '#options' => ['drupal7' => 'Drupal7', 'drupal8' => 'Drupal8'],
      '#empty_option' => $this->t('-select'),
      '#ajax' => [
        'callback' => '::updateWidgetAjax',
        'wrapper' => 'default-value-ajax-wrapper',
      ],
    ];
    $form['widget_type'] = [
      '#title' => $this->t('Widget Type'),
      '#type' => 'select',
      '#options' => ['pdf' => 'Pdf', 'ppt' => 'PPT'],
      '#empty_option' => $this->t('-select'),
    ];

    $form['wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'default-value-ajax-wrapper'],
    ];

    return $form;

//Ajax callback
  public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
   $widget = $form_state->getValue('widget_type');
    print_r($widget); //Print the value of the field
  }

```

---
Tags: forms, 8, ajax
---


# Question
Title: force image style generation on save node
I've got still my problem described here Image style, reuse image in field collection item but i gave up to get a solution.

A workaround which came up in my mind is to force the generation of imagestyles on nodesave. are there any possibilites to do so?

# Answer
> 12 votes
Yes - you can implement `hook_node_insert()` and `hook_node_update()` in a custom module and create the images there using image API functions. For example

```
function MYMODULE_node_insert($node) {
  // Get some field items from a field called 'field_photo.
  if ($image_items = field_get_items('node', $node, 'field_photo')) {
    $image_item = array_shift($image_items);

    // Load the associated file.
    $file = file_load($image_item['fid']);

    // An array of image styles to create.
    $image_styles = array('style_1', 'style_2');

    foreach ($image_styles as $style_name) {
      // Get the location of the new image.
      $derivative_uri = image_style_path($style_name, $file->uri);

      // Create the image.
      image_style_create_derivative($style_name, $file->uri, $derivative_uri);
    }
  }
}

```

# Answer
> 9 votes
The two answers with blocks of code are mostly correct except they are overlooking one major thing:

The first argument of image\_style\_create\_derivative is expected to be an image style array.

What they're passing is just the name of the style. In the foreach if you add:

`$style = image_style_load($style_name);`

then change $style\_name to $style in the image\_style\_create\_derivative function it should work as expected and generate the styled image.

`image_style_create_derivative($style, $file->uri, $derivative_uri);`

Hope that helps anyone else having this issue.

# Answer
> 4 votes
Thanks for your help Clive, my whole function for the field collection items: (another helpful post from you: Accessing a field collection)

```
function channelportal_gallery_node_update($node) {

  //get all the id's from the field collection values
  $galleryimages = field_get_items('node', $node, 'field_gallery_and_caption');
  $fieldcollectionids = array();

  foreach ($galleryimages as $key => $value) {
    $fieldcollectionids[] = $value['value'];
  }

  // Load up the field collection items
  $items = field_collection_item_load_multiple($fieldcollectionids);

  foreach ($items as $item) {

    $image_item = field_get_items('field_collection_item', $item, 'field_gallery_image');

    // Load the associated file.
    $file = file_load($image_item[0]['fid']);

    // An array of image styles to create.
    $image_styles = array('gallery_big', 'gallery_thumbnail');

    foreach ($image_styles as $style_name) {
        // Get the location of the new image.
        $derivative_uri = image_style_path($style_name, $file->uri);

        // Create the image.
        image_style_create_derivative($style_name, $file->uri, $derivative_uri);
    }
  }
}

```

# Answer
> 2 votes
There seems to be a module for that problem: https://www.drupal.org/project/imageinfo\_cache

Have a look at the "Related Modules"-Section on the page, too.

# Answer
> 0 votes
It's recommended to use both hook\_node\_insert() and hook\_node\_update() and to check if the needed image derivatives are not generated, then generate them, otherwise, do nothing.

```
/**
 * Implements hook_node_insert to generate derivative images for the new inserted node in
 * case they are not generated
 * @param object $node
 */
function YOUR_MODULE_node_insert($node) {
  //REPLACE field_YOUR_IMAGE_FIELD WITH YOUR FIELD IMAGE NAME
  if(isset($node->field_YOUR_IMAGE_FIELD['und'][0]['uri'])) {
    _generate_image_style($node->field_YOUR_IMAGE_FIELD['und'][0]['uri']);
  }
}

/**
 * Implements hook_node_update to generate derivative images for the new updated node in
 * case they are not generated
 * @param object $node
 */
function YOUR_MODULE_node_update($node) {
  //REPLACE field_YOUR_IMAGE_FIELD WITH YOUR FIELD IMAGE NAME
  if(isset($node->field_YOUR_IMAGE_FIELD['und'][0]['uri'])) {
    _generate_image_style($node->field_YOUR_IMAGE_FIELD['und'][0]['uri']);
  }
}

/**
 * Generates the needed image styles by the image uri if they are not already generated
 * @param string $image_uri
 */
function _generate_image_style($image_uri) {
  //This should be changed to your image styles names.
  $image_styles = array('image_style_name1', 'large_image', 'promo_image');
  foreach ($image_styles as $style) {
    $derivative_uri = image_style_path($style, $image_uri);
    file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $image_uri, $derivative_uri);
  }
}

```

Note: If your image field take multiple images then you should loop through them like that:

```
if(isset($node->field_main_image['und']) && is_array($node->field_main_image['und'])) {
  foreach($node->field_main_image['und'] as $delta => $image_field) {
    _generate_image_style($node->field_YOUR_IMAGE_FIELD['und'][$delta]['uri']);
  }
}

```

The image styles generation is taken from here

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


title: Making a form by having a view

text:
# Question
Title: Making a form by having a view
I am trying to convert a view to a form as follows:

*I need to have a table of articles (which can be produces easily by views) and inserting a checkbox next to each row (article), and a button next to this table as Submit button. The created form out of the articles\` view should be able to initialize the value of the checkboxes before showing them (which can be done somehow by form\_alter).*

So, the problem is that I really don't know how to create this form.

I used VBO, but VBO does the operation for the selected rows! I need a method which can help me to set the values of checkboxes by code, before views render, and when the submit button is clicked, whole rows should be checked!

can you please suggest a tested & working solution?

thanks

# Answer
> 0 votes
`view_form_submit` is not working in D7, you have to use the `hook_form_alter` and then you have to change the `#submit`:

```
$form['actions']['submit']['#submit'][] = 'custom_form_submit';

```

---
Tags: views, forms
---


# Question
Title: An AJAX HTTP error occurred. HTTP Result Code: 200
I'm trying to Run the Test from Administrative User, and it bring me below Error message:

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /drupal7.50/batch?render=overlay&id=18&op=do StatusText: OK ResponseText: Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\drupal7.50\includes\database\database.inc on line 2204

How can I fix that?

# Answer
Increase your PHP max\_execution time in php.ini
> 1 votes

# Answer
If you check the message after **ResponseText**, it says:

> ResponseText: Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\drupal7.50\includes\database\database.inc on line 2204

Which means the process has taken more than default execution time set for PHP which is 30 seconds. You can increase the execution time by editing **php.ini** file located at "**C:\xampp\php\php.ini**" and setting value of `max_execution_time` variable to more than 30. And then **restart Apache**.

The above change will be applicable to all site running from your local. To make it specific to particular site you can use one of the following method:

By editing **settings.php** located at "sites/default/settings.php" and adding following line:

```
ini_set('max_execution_time', 120);

```

Or you can also modify **.htaccess** file located in your Drupal root and add following line:

```
php_value max_execution_time 120

```
> 1 votes

# Answer
You can try to change the value for max\_execution\_time in php.ini file to be bigger than 60. for example: max\_execution\_time = 300

Do not forget to restart your server.
> 0 votes

---
Tags: 7, ajax
---


title: CKeditor doesn't format the body value

text:
# Question
Title: CKeditor doesn't format the body value
I am building a website in Hindi language. I was given a Database containing rows of title and body. I created a node for each row using this code :

```
$query = db_select('hindi', 'n')
      ->fields('n', array('title','body'))
      ->execute();

foreach($query as $item) {
    $title = $item->title;
    $body = $item->body_value;
    $values = array(
        'type' => 'article',
        'uid' => 1,
        'status' => 1,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'hi'
    );
    $entity = entity_create ('node', $values);
    $ewrapper = entity_metadata_wrapper('node', $entity);
    $ewrapper->title->set($title);
    $ewrapper->field_body->set(array('value' => $body,'format'=>'full_html'));
    $ewrapper->save();
}

```

The nodes are display very well in the node view page, like this

But Ckeditor doesn't perform the text formats (line breaks and ...). Like this

What is the problem?

---

# More information

This is the result of Firebug when inspecting the Body value of the CKEditor

# Answer
> 3 votes
According to my experience `<br>` causes this problem ,my solution for this is to replace all `<br>` with `<br />` before saving in `body field`

**So** try

```
$body =   str_replace("<br\s*>", "<br />",nl2br($item->body_value));

```

---
Tags: 7, wysiwyg
---


title: How to delete Unused Images?

text:
# Question
Title: How to delete Unused Images?
I am using Drupal 7. When I test my page speed in Google PageSpeed Tools, it says to compress the images. After that I compress the image and uploaded it. The uploaded image placed in files folder like (test\_0.png) and the old name is test.png. I have lot of images like that. How to remove images which are not in use.

# Answer
> 0 votes
Try audit Files module

> Audit files is designed to perform audits of your upload directory and the corresponding database records. It will cross check that all files in the database have a corresponding physical file, or it will check that all files in the upload directory have a corresponding entry in the database.
>
> This module can be helpful in identifying orphan files that have not been deleted when their corresponding node was removed.
>
> The module has configurable options to ignore specified files and/or directories.
>
> The reports allow you to permanently remove files or database entries that represent orphans.

# Answer
> 0 votes
All files uploaded via Drupal UI is managed in `file_managed` database table and the file usage is maintained in a separate table as `file_usage`.

There are couple of modules you can give a try for.

1. Audit Files
2. Fancy File Delete

Also you can write a query and delete all such which are no more in use. You can setup a cron job which periodically does that for you.

Sample Code: source

```
//db_query to find all files not attached to a node:
$result = db_query("SELECT fid FROM file_managed WHERE NOT EXISTS (SELECT * FROM file_usage WHERE file_managed.fid = file_usage.fid) ");

//Delete file & database entry
for ($i = 1; $i <= $result->rowCount(); $i++) {
  $record = $result->fetchObject();
  $file = file_load($record->fid);
  if ($file != NULL) {
    file_delete($file);
  } }

```

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


# Question
Title: Hide tab for user page for specific roles
I am trying to hide tab for user page. This is good script but work only for node type. How can I make it work for user pages? Thanks to all!

```
function bartik_preprocess_page(&$variables, $hook) {
    if (!empty($variables['node']) && $variables['node']->type == 'article' && in_array('editor', $variables['user']->  roles)) {
        $to_be_removed = array('node/%/edit', 'node/%/view');
        foreach ($variables['tabs'] as $group_key =>$tab_group) {
            if (is_array($tab_group)) {
                foreach ($tab_group as $key =>$tab) {
                    if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $to_be_removed)) {
                        unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

```

/-------- Update --------/

Now I tryed this:

```
function my_theme_preprocess_page(&$variables, $hook) {
    /* Hide Tabs in users page */
    global $user;
    $arg = arg();
    if (($arg == 'user') && in_array('gestore', $variables['user']->roles)) {
        foreach ($variables['tabs'] as $group_key =>$tab_group) {
            if (is_array($tab_group)) {
                foreach ($tab_group as $key =>$tab) {
                    if (isset($tab['#link']['path'])) {
                        unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

```

But not work.

/----- Last Update -------/

This works. Thx @Yogesh.

```
global $user;
if ((arg(0) == 'user') && in_array('editor', $variables['user']->roles)) {
    foreach ($variables['tabs'] as $group_key =>$tab_group) {
        if (is_array($tab_group)) {
            foreach ($tab_group as $key =>$tab) {
                if (isset($tab['#link']['path'])) {
                    unset($variables['tabs'][$group_key][$key]);
                }
            }
        }
    }
}

```

# Answer
You can use arg() function. The function returns a component of the current Drupal path. i.e. if you're on edit user page, the values returned by arg() function will be arg(0) as 'user', arg(1) as user ID, arg(2) as 'edit'.

```
function bartik_preprocess_page(&$variables, $hook) {
  $arg = arg();
  if (('user' == $arg) && (!empty($arg[1]) && is_numeric($arg[1])) && in_array('editor', $variables['user']->roles)) {
    // Your code goes here..
  }
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to set a session variable when a link is clicked?
I have created a search block. It outputs multiple results (names) as links. User can follow the link. How can I pass the user name into $\_SESSION variable?

I tried doing this, the result shows a *page not found* error.

```
'name' => l(t($n['name']), 'edit_details' ,array('query' => array('uid' => $n['uid'])))

```

In `hook_menu()` I set `$items['edit_details/%']` to `array()`. I passed the value into the session with `$_SESSION['id'] = $_GET['uid'];`.

# Answer
You can do like this.

Link URL :

```
 'name' => l(t($n['name']),'edit_details/@uid', array('@uid' => $n['uid']))

```

In hook\_menu() :

```
$items['edit_details/%user'] = array(
    'title'          => 'Lets start',
    'page callback'   => '_get_user',
    'page arguments'  => array(1),
    'access callback' => TRUE,
    'type'            => MENU_CALLBACK,
  );

```

In callback : In callback function you will get complete user object, as this wild card used for user core module.

```
function _get_user($user) {
  $_SESSION['user_name'] = $user->name;
  //Redirect to any other page you want.
}

```

Thanks!
> 0 votes

---
Tags: 7, uri, sessions
---


# Question
Title: How to configure drush with Acquia DevDesktop on Windows to access through proxy?
There are some answers to similar questions using WAMP, but now drush is not recommended under Windows (unless using DevDesktop, which I am). And this is seriously frustrating. I followed the instructions here and created a `wgetrc` file with the proxy addresses and `use_proxy=on` on `d:\`, then set up a `wgetrc` environment variable to point to `d:\`. Stopped and started DevDesktop to verify that the wgetrc variable is taken into account. But when i try to download a module (eg `drush dl admin_toolbar`), I get an error message:

> simple\_xml\_loadfile(): I/O warning : failed to load external entity Project.php:74 Failed to get available update data from https://updates.drupal.org/release-history/admin\_toolbar/8.x

Following the comments below I tried again (twice). Once, with the env variable WGETRC set to d:\wgetrc, next with the file renamed to \_wgetrc as suggested and the env variable set to d:. Neither worked, here is what seems to be the relevant wget output (obtained by redirecting the output to a file):

First attempt:

```
Wgetrc:
  d:\wgetrc (env)
  /etc/wgetrc (system)
Locale: /usr/share/locale
Compile: gcc -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/etc/wgetrc"
  -DLOCALEDIR="/usr/share/locale" -I. -I/usr/src/wget/wget-1.12/src
  -I../lib -I/usr/src/wget/wget-1.12/lib -D__CYGWIN__ -DEILSEQ=138
  -O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686
Link: gcc -O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686
  -Wl,--enable-auto-import /usr/lib/libssl.dll.a
  /usr/lib/libcrypto.dll.a /usr/lib/libiconv.dll.a
  /usr/lib/libintl.dll.a /usr/lib/libiconv.dll.a -lregex ftp-opie.o
  openssl.o http-ntlm.o gen-md5.o ../lib/libgnu.a

```

Second attempt:

```
Wgetrc:
  d:\ (env)
  /etc/wgetrc (system)
Locale: /usr/share/locale
Compile: gcc -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/etc/wgetrc"
  -DLOCALEDIR="/usr/share/locale" -I. -I/usr/src/wget/wget-1.12/src
  -I../lib -I/usr/src/wget/wget-1.12/lib -D__CYGWIN__ -DEILSEQ=138
  -O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686

```

As far as I can see it is looking in /etc/wgetrc no matter what I do, which is not much use on Windows. In all cases I get this error still:

```
https://updates.drupal.org/release-history/file_entity/8.x [3.81 sec,16.55 MB]
Executing: wget --version
Executing: wget -q --timeout=30 -O "C:\\Users\\mknapp\\AppData\\Local\\Temp\\dow6C08.tmp" https://updates.drupal.org/release-history/file_entity/8.x
simplexml_load_file(): I/O warning : failed to load external entity    [warning]

```

I've even tried putting the wgetrc file in c:\windows\system32\drivers\etc but to no avail

# Answer
You can follow this tutorial to install drush on windows. http://www.drupal8.ovh/en/tutoriels/95/install-drush-on-widows

For the proxy you can try:

Controle panel -\> System -\> Advance settings -\> variable -\> variable system

PROTOCOLE\_proxy NAME:PASSWORD:HOST:IP

http\_proxy http://192.168.100.100:3128

https\_proxy http://192.168.100.100:3128

Example from : http://www.drupal8.ovh/en/tutoriels/208/internet-access-via-proxy
> 0 votes

---
Tags: drush, acquia-dev-desktop, proxies
---


title: List text field dependent of text field

text:
# Question
Title: List text field dependent of text field
In my user edit form I want to add a text field where it asks name of class and I want to add other field List text type and it will display the grade for example:

Math Grade 7 Now the issue is that teacher can add more than 1 class so and the option field I set unlimited elemts but it doesn't work properly because also I need to add element in List text.

I want to achive this:

Math Grade 7 Bio Grade 5

Add class

Issue:

Math Bio Grade 7 Grade 5

one is not depending of other, please Help!!

# Answer
You can use Field Collection module to achieve this.

Using this module you can create group of field, such as class and grade in one collection. Also you can set 'Number of values' to unlimited for field.

Thanks!
> 0 votes

---
Tags: entities
---


# Question
Title: List field: translated values are not translated
In my Drupal 8 project I have some list fields. For example maybe a field "project type" with the following key|values, coming from the original language German:

```
1 -> öffentliches Projekt
2 -> privates Projekt

```

Which I translated in the field's settings:

```
1 -> public project
2 -> private project

```

The field is NOT set to be translatable because the value should not be changed in a translation: the project type is in all languages the same! But now when I go to the node edit page, when I view the node or when I add this field as exposed filter to views I always see the German values of the field no matter what is set as the current language of the page. When I change the field to be translatable the value of the list field can be changed in English translation -\> so it can come that a project is "public" in German and "private" in English what is not the desired result.

How do I get the translated values of a list field to be used in form element and node view when the list field itself should not be translatable?

# Answer
Ok, it seems that it was just a weird cache thing. I cleared the cache several times after changing these translations. Now the translated values of the select list appear without setting the field to be translatable.
> 0 votes

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


# Question
Title: How to empty the cart automatically before adding a new item to the cart?
How to empty the cart automatically before adding a new item to the cart in ubercart ver 6?

Is it possible adding `uc_cart_empty($cart_id) ;` in uc\_cart module?

# Answer
> 1 votes
You can clear the cart using the following function

```
uc_cart_empty(uc_cart_get_id());

```

Use the above function in your module when you want clear cart. To empty the cart automatically before adding a new item to the cart call the function in hook\_add\_to\_cart().

eg:

```
function MODULE_NAME__add_to_cart($nid, $qty, $data) {
  uc_cart_empty(uc_cart_get_id());
  drupal_set_message("Previous item cleared");
}

```

# Answer
> 0 votes
This is correct answer:

function MODULE\_NAME\_uc\_add\_to\_cart($nid, $qty, $data) { uc\_cart\_empty(uc\_cart\_get\_id()); drupal\_set\_message("Previous item cleared"); }

---
Tags: 6, ubercart
---


title: Hide sid in webform confirmation page

text:
# Question
Title: Hide sid in webform confirmation page
I am using webform for contact us page.

Once form is successfully submitted, I have redirected it to a thank you page.

But the URL of thank you page keeps adding webform sid, like given below:

http://localhost/test/thank-you?sid=1234

I want to hide the sid from URL.

I am using custom redirect URL in form settings.

# Answer
> 1 votes
No you can not ignore the "sid" from submission confirmation page.

## Yes you can create a separate thank you page and redirect to that page.

You can install this modules:

-\> rules

-\> webform rules

Now add a rule that redirects the user to your URL after a webform submission.

---

Using hook\_form\_alter(), and set the override there.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
     $form['#submit'][] = 'my_submit_handler';
  }
}

function my_submit_handler(&$form, &$form_state) {
  $form_state['redirect'] = 'home';
}

```

---

Refer Redirect Drupal Webform Submissions

# Answer
> 1 votes
If you Use any of the two then it wont show SID in URL.

```
node/<yournodeid>/webform/configure

```

---
Tags: 7, webforms
---


title: How to add item into a paragraphs

text:
# Question
Title: How to add item into a paragraphs
I'm trying to create Paragraphs programatically, to store an Indesign File with the images linked to it, so I have my paragraph type with some fields

* field\_indesign\_file : (limited to one value)
* field\_indesign\_image : (illimited number of images)

Currently the creation is OK :

```
$paragraph = Paragraph::create([
  'type' => 'indesign',
  'field_indesign_file' => [
    'target_id' => $indesign->id(),
  ],
  'field_indesign_image' => [
    'target_id' => ${'image'.'3'}->id(),
  ],
]);

```

but I don't know in advance how many pictures I'll have attached to the indesign file, so Id' like to be able to add other values to the `field_indesign_image`.

I tried using

`$paragraph->field_indesign_image[LANGUAGE_NONE][1]['value'] = [
 'target_id' => ${'image'.'1'}->id()
 ];`

and

`$paragraph->field_indesign_image->appendItem(
 [
 'target_id', ${'image'.'3'}->id()
 ]
 );`

but none of this method worked, I didn't find a lot of documentation and sometimes answers to other topic are a bit too complicated for me to understand since I'm a beginner at drupal 8.

# Answer
> 0 votes
Finally I used a dynamic array

`$tabImage[]["target_id"]`

and inserted it

```
'field_indesign_rendition' => $tabImage,

```

---
Tags: entities
---


# Question
Title: How to get notifications for unpublished content?
I want to achieve that user can view the unpublished content once they have logged in .

Unpublished content should be displayed as a notification like Topic(1).

How to achieve this ? Is there solution to achieve this?

# Answer
# Part 1 - Notifications

Have a look at the Menu Badges module to add such notifications to any **menu item** and/or **menu tab** of your choice.

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

### Video tutorials:

# Part 2 - View unpublished content

You may want/have to combine this also with using the view\_unpublished module. Some details from its project page:

> This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.
> 2 votes

# Answer
You can set the Permissions to allow/deny unpublished content access.

> user can view the unpublished content once they have logged in

May be the module Notify (https://www.drupal.org/project/notify) can do this job ?
> 0 votes

# Answer
Well it depends on the kind of notification system you are looking to have in place.

1. Is it goign to be real time? So soon a node is created with status 0(unpublish) it triggers system wide notification which can visible real time to all allowed users.
2. Or is it ok to update the count on page load?

For 1:

* For realtime notification it could be polling based(not recommened). You can try for message module
* If you want push notification you will need a combination of a queue where you can send your notification, nodejs process which can read the queue and socket.io to emit to browser.

For 2:

* (Custom Way)If its ok to update the count on page load, its relatively much easy to implement. All you need to do is query the database and theme the output in form of custom block,

You can call this function inside a custom block and place the block in any region you want to show count of unpublished content. Every time the block will load it will query and get the count but it wouldn't be real time.

```
function _get_node_count_by_status($status = 0) {
      $query = db_select('node', 'n');
      $query->fields('n', array('nid'));
      $query->condition('n.status', $status);
      $node_count = $query->execute()->rowCount();
      return $node_count;
}

```
> 0 votes

---
Tags: 7, notifications
---


# Question
Title: What might cause the unexpected workflow state changes after executing a rule?
I want to change the workflow state to draft from publish and unpublished the node on edit. I used rules for this:

* For Unpublish:
* For publish:

When I edit a node and save it, workflow state changes to draft through Rules and again changed to published state.

I have not set any trigger settings.

Please suggest what could cause this.

# Answer
> 2 votes
# Option 1

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are typically 2 ways of debugging, as further detailed below.

### Rules Evaluation Log

Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

### Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

### More info

For way more details about these 2 variations, move on to Rules **debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".

# Option 2

Try to consolidate your 2 rules in a single rule, by using the Conditional Rules module. This module allows you to use Rules Conditions within Rules Actions. So in your case if you can think of an appropriate Rules Event that fits both cases, you simply use the Rules Conditions and Rules Actions within such consolidated single rule, whereas you use Conditional Rules to trigger either (not both!) of your Rules Actions.

# Answer
> 0 votes
Not sure if I got your problem, but here are few pointers based on my understanding

* Ensure the order in which your rules are getting invoked if the rule with publishing action is invoked in the last it will anyway publish the node.
* Event for your rule for unpublishing the node is 'before saving content of type Document', can you changing it to update updating existing content of type Document' to make sure there is nothing in place which triggers during and after presave hook.

---
Tags: 7, rules, debugging, workflows
---


# Question
Title: How to convert a menu tabs in menu links block?
It would be very useful to be able to change the "tabs menu" in "menu links" to specific pages and users roles. In order to customize the UI.

I have not found any module for this.

# Answer
One of the ways is to simply change the menu type from MENU\_LOCAL\_TASK to MENU CALLBACK, and then simply create a menu item with the path.

Sample Code: Cherry pick menu tabs and convert:

```
function MYMODULE_NAME_menu_alter(&$items) {
  $items['node/%node/view']['type'] = MENU_CALLBACK;
  $items['node/%node/edit']['type'] = MENU_CALLBACK;
}

```

Convert all at once

```
function MYMODULE_NAME_menu_alter(&$items) {
  foreach ($items as $key => $value) {
    if ($items[$key]['type'] == MENU_LOCAL_TASK) {
      $items[$key]['type'] = MENU_CALLBACK;
    }
  }
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to Override OG Group Owner Permissions for view/edit group content?
So I have a group content type called student portfolio, which is managed by the student. Then I have a group content node type called endorsement that can be written by professors that are group members.

**Question 1:** How do I prevent students from editing endorsements? There is no checkbox anywhere in my configuration that says the student role can edit endorsement. Also, on my group permissions, for Members, only "Edit own Endorsement content" is checked, but the student can still edit, which seems like a bug if you ask me.

I'm thinking I'll need some sort of `hook_menu_local_tasks_alter()` code, but just wanted to verify.

**Question 2**: How do I prevent the student from even viewing a group content page type? (This is a different project.) On the group page, I think this is just a simple matter of setting the permission on the pane, but I also don't want students to be able to view the stand-alone page.

# Answer
> 0 votes
Because group owners are considered the equivalent of "Super administrator" (user 1) of their group AND group content, which I happen to totally disagree with, this wound up being solved using `hook_node_access()` as follows for Question 1:

```
/**
 * Implements hook_node_access().
 *
 * Runs every time a user tries to edit an endorsement
 */
function icme_admin_node_access($node, $op, $account) {
  if ($node->type == 'endoresment' && $op == 'update') {

    // Does the user explicitly have create/edit endorsement content access?
    // By default, the OG module provides group owners add/edit/delete access
    // to all group content
    $ua_create = user_access('create endoresment content');
    $ua_edit = user_access('edit own endoresment content');
    if (!$ua_create && !$ua_edit) {
      // Show access denied message, and, interestingly enough,
      // also sets the permission for the edit link.
      return NODE_ACCESS_DENY;
    }
  }
}

```

Question 2 is similar, but just need to change `$op == 'update'` to `$op == 'view'`.

I'm curious to see if anyone posts a better solution (other than fixing the OG module).

# Answer
> 0 votes
As @Webdrips said

> 'group owners are considered the equivalent of "Super administrator" (user 1) of their group AND group content'

However, this behavior may be controlled via an OG setting. Navigate to *'admin/config/group/settings'* and **UN**-check option *'Group manager full permissions'*.

On a side note, in my opinion this is a poor literal selection for the setting, as 'group manager' can be confused with the 'administrator member' role that manages the group. I've spent a few hours on a similar bug, and I had to dive into the code before I understood that this setting actually refers to the group author/creator.

---
Tags: 7, users, organic-groups
---


title: What does this Apache SOLR error mean?

text:
# Question
Title: What does this Apache SOLR error mean?
From the log (set as "error"):

SearchApiException while optimizing Solr server local solr server: "0" Status: Request failed: request timed out in SearchApiSolrConnection-\>checkResponse() (line 541 of /var/www/domainname/sites/all/modules/contrib/search\_api\_solr/includes/solr\_connection.inc).

What does this error message mean?

# Answer
The error means exactly what it says:

> Request failed: request timed out

The connection between your Drupal server and Solr server timed out.

If the servers are geographically far from one another, you might consider moving them closer together to reduce latency. Your Solr or Drupal server may also need more resources.

Both are things you'll need to incrementally test (preferably in an identical staging environment) until you've worked out where the bottleneck is and how you can overcome it
> 1 votes

---
Tags: search
---


# Question
Title: How to migrate an admin.inc file which creates a configuration form for settings?
I am trying to migrate a module from drupal 7 to drupal 8, but sadly I cannot find any proper documentation on how to do this. I already re-wrote `.info` file to `.info.yml` but at this point its just a dead-end. For example I have a `admin.inc` file which creates a configuration form for settings. It looks like this:

```
function commerce_shipping_gls_settings() {
  $form = array();
  $form['rates'] = array(
    '#type' => 'fieldset',
    '#title' => t('Shipping costs'),
  );
  $form['rates']['commerce_shipping_gls_shipping_rate_amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Shipping service rate amount'),
    '#default_value' => variable_get('commerce_shipping_gls_shipping_rate_amount', 3900),
    '#required' => TRUE,
    '#element_validate' => array('element_validate_integer_positive'),
  );
  return system_settings_form($form);
}

```

I was trying to find how to convert a config file to drupal 8, but sadly I didn't get much. Could someone please give me some guidance on how can I achieve this?

# Answer
> 3 votes
`system_settings_form()` is replaced by `\Drupal\Core\Form\ConfigFormBase` in D8.

you can see
https://www.drupal.org/node/1910694
Working with Configuration Forms

Example:

```
namespace Drupal\example_module\Forms;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class StudentConfigForm extends ConfigFormBase {
  // The Form ID that is used in alter hooks.
  public function getFormId() {
    return 'student_config_form';
  }
  // Configuration names that will be editable
  public function getEditableConfigNames() {
    return ['example_module.student'];
  }

  public function buildForm(array $form, FormStateInterface $form_state, $args = '' ){
    $config = $this->config('example_module.student');
    $values = $config->get();
    $form['student'] = array(
      '#type' => 'details',
      '#title' => $this->t('Student'),
      '#open' => TRUE,
      '#tree' => TRUE,
    );
    $form['student']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('First name'),
      '#default_value' => $values['student']['first_name']
    );
    $form['student']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Job title'),
      '#default_value' => $values['student']['last_name']
    );
    $form['student']['age'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Age'),
      '#default_value' => $values['student']['age']
    );
    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $state) {
    $values = $state->getValues();
    $config = $this->config('example_module.student')
      ->set('student', $values['student'])
      ->save();
  }
}

```

---
Tags: forms, 8, migrations
---


title: Node listing on taxonomy term pages

text:
# Question
Title: Node listing on taxonomy term pages
I've created two taxonomy vocabularies e.g. "One" and "Two" and I've added 5 terms by these vocabularies.

Then I created two taxonomy category template files, but I have one big problem.

Example: term named "Apples" from vocabulary "One" list all nodes that have this term.

I'm trying to get url and node name, trimmed body text and pager so this term page it shows 10 nodes and there is a pager at the bottom.

I created view block, but it's huge job to create blocks for each terms etc..

So how I can list all nodes on these term pages?

# Answer
> 0 votes
You are not supposed to create view block for each term, your view can take dynamic argument for taxonomy and will return results accordingly, All you need is to have contextual filter setup for your views.

# Answer
> 0 votes
If you're looking to build Views for different presentations of term pages or just giving Views control over the page output (and not the core taxonomy module) you might want to give Taxonomy Views Integrator a try.

You would be able to create Views with a term id contextual filter, and then control what the output is. It is fine to have one, or in some cases, you could have a couple depending on use case.

---
Tags: 7, nodes, taxonomy-terms
---


# Question
Title: Are $form_state values cleaned of malicious code even if #limit_validation_errors is set?
I'm building a multi step form with a bunch of required fields on each step. The user has to be able to save the current step of the form, even if they haven't filled out all the required fields.

I will then save it to a custom entity I've created.

I'm using code like this:

```
#limit_validation_errors => array(),
#submit => array()

```

to disable validation. So will Drupal's internal code still clean these values of malicious code when I trigger a submit/save them to the entity? Or do I have to do it myself?

I'm using $this-\>set('key', $value); to save the data.

# Answer
> 1 votes
If you set #limit\_validation\_errors, only elements passed into the value are validated. Everything else is not validated. So for example with this:

```
#limit_validation_errors = array()

```

Nothing in the form is validated. And with this:

```
#limit_validation_errors = array('field_1', 'field_2')

```

Only field\_1 and field\_2 will be validated.

To continue on with this, only fields that are validated become part of $form\_state\['values'\], and are then passed on to any submit functions. These values will be as safe as any values in a FAPI form submission, as they will be both sanitized and validated.

Any fields not included in the array passed to #limit\_validation\_errors will not be part of $form\_state\['values'\], and therefore there is nothing to sanitize, nor any malicious code to validate. The element will simply be missing (or maybe empty, I can't remember off the top of my head) from $form\_state\['values'\] in the submit functions.

For myself, the only use case I've ever found for #limit\_validation\_errors, is one I stopped using. I would use it on a back button for ajax forms, so that the user could step back a step, without getting errors for any fields on that step of the form. The problem however is that any partially filled fields are then lost on that step of the form when going back, since the submitted values are entirely ignored.

What I do instead, is in my validation function, I check to see if the 'next' button has been clicked before validating.

Example form definition (imagine this is step 2 of a multi-step form)

```
function some_form_step_2($form, &$form_state)
{
  $form['some_field'] = array
  (
    '#type' => 'textarea',
    // See comments after code about why I did this:
    '#title' => t('Enter a value') . '<span title="' . t('This field is required.') . '" class="form-required">*</span>',
    '#default_value' => isset($form_state['values']['some_field']) ? $form_state['values']['some_field'] : '',
  );

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

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

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

  return $form;
}

function some_form_step_2_validate($form, &$form_state)
{
  // check to see if the clicked button was the 'next' button
  if($form_state['op'] == $form_state['next'])
  {
    // Ensure a value has been entered into some_field
    if(!strlen($form_state['values']['some_field']))
    {
      form_set_error('some_field', t('Please enter a value'));
    }
  }
}

function some_form_step_2_submit($form, &$form_state)
{
  // Here, if the 'next' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized
  // and validated

  // However, if the 'back' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized,
  // but not validated, as the validation only needs to happen
  // when advancing to the next step, not stepping back to the
  // previous step
}

```

As you can see from the code, the validation only happens when the 'next' button is clicked. The field some\_field is actually required, however, if #required is set on the field, it will always be validated when the back button is clicked. This can be prevented with:

```
$form['#limit_validation_errors'] = array();

```

However, if the user has entered a partial value into this field, #default\_value will be empty if the user goes back to the first step, and then returns to this step, since the value will not be made part of $form\_state\['values'\]. The way I've built it, the 'required' asterisk (\*) is included with the form field title to show the user it is required, but the validation of the required field only happens when advancing to the following step, not when going back to the previous step. This way the user can go back whether a value has been entered into the field or not.

Another added advantage of this method is that a custom error message can be shown for required fields. If #required = TRUE was set on the field above, instead of using the method I did, the error message would be 'Please enter a value? is required' (or something close), which is not very clean English. With the code above, the message is instead 'Please enter a value', with the field highlighted.

---
Tags: forms, 8
---


title: Link to Views page with token?

text:
# Question
Title: Link to Views page with token?
I've got a Views (machine readable name: e.g 'views-events-page') page that I gave a URL (in the path field, e.g. 'events').

I want to link to this Views page from Link field. Of course, I can paste the path 'events' into the link field. But supposing I would change the path of the Views page the link will be broken. Is there any chance of using a token to get the path of this Views page, like `[views:view-events-page:path]`.

I was not lucky asking the search engine of choice the right question. I did not find any useful

# Answer
you can create a custom token , another helper link

or use Custom Token module then get views url with

```
$view = views_get_view('viewname');
$view->set_display('display_name');
view->get_url(); // if not work try this  $view->get_path()

```

Learn how to create custom token according to below example

```
 /**
 * Implements hook_token_info().
 */
function my_module_token_info() {

  // Add tokens.
  $site['city_name'] = array(
    'name' => t('Token Name'),
    'description' => t('Token Description'),
  );

  return array(
    'tokens' => array(
      'site' => $site,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function my_module_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

 if ($type == 'site') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'city_name':
          $city_name = variable_get('city_name');
          $replacements[$original] = $sanitize ? check_plain($city_name) : $city_name;
          break;
      }
    }
  }

  // Return the replacements.
  return $replacements;
}

```
> 0 votes

---
Tags: 7, views, tokens
---


# Question
Title: Is there an easy way to have an image in a radio button label?
I have a dynamic list of images, that I want to have a user select via associated radio button in a form. Is there an a way I can do this with the base form api, or is this the kind of thing I'd need to create a custom theme for?

# Answer
Okay, the approach that worked with my dynamic list of images

```
$end_options = [];

foreach ($dynamic_list_of_items as $item)
{
  $end_options[$item['option_key']] = $item['title'].'<br/><img src="/'.$item['image_path'].'"/>';
}

$form['items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Select Item'),
  '#description' => $this->t('Choose which item you'd like to use.'),
  '#options' => $end_options,
];

```

IE, you can put rendered html into the '#options' property of a radio button and it will work. Simpler than I thought.
> 1 votes

# Answer
You can do this using CSS.

Add appropriated class from $form then use CSS to add images as background-image.

For example:

```
$form['example'] = array(
  '#type' => 'radios',
  '#title' => t('example'),
  '#default_value' => 1,
  '#options' => array(0 => ('Value 0'), 1 => ('Value 1')),
);

```

CSS

```
.form-item-example > labela[for=edit-example-0]{
      background-image: url('/path/to/image-0.png');
}

```
> 1 votes

---
Tags: theming, forms, 8
---


# Question
Title: How to fix Bootstrap theme overlapping on views administration pages
Using bootstrap as an administration theme. Required rather than seven because of the way we are getting people to contribute to the site.

Under views contextual filters, they layout falls apart. Anybody solved this? See under "Path component".

I have tried debugging the page and setting clear:both everywhere etc.

# Answer
> 1 votes
It is possible to set the admin theme just for views in the views settings page: admin/structure/views/settings. "Custom admin theme for the Views UI".

This does not fix the bootstrap theme problem, but it does solve my problem where I want to use the bootstrap theme for content administration actions.

Secondly, to solve my problem where I want a consistent user interface when viewing and editing content under admin/appearance there is a setting

```
Use the administration theme when editing or creating content.

```

This enables me to provide people submitting content with the same experience as viewing.

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


# Question
Title: Menu list links of different languages of a Localized Menu are shown in all languages?
I have a menu which is set to **Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.**

The in the menu I have several links in english and spanish languages.

In the frontend regardless the language I select all links of the menu are shown. ie: if I select english the spanish links are also shown.

What am I missing here?

# Answer
I'm assuming you already have the **i18n Menu Translation** sub-module is enabled (it is one of the Internationalization sub-modules).

Edit the menu to be translated, by navigating to admin/structure/menu/manage/main-menu/edit (for the "main menu"). From there you can select the **translation mode** you want, e.g. *Translate and Localize* (from your question it seems you also did that already).

With what's above you should be in pretty good shape to complete the finishing touch: when editing a menu link, there should be a new link **Translate** to actually translate the menu entry. After you entered a translation for the "original" (eg English) menu item in another language (eg Spanish), Drupal will ensure that whenever you switch to another language, the corresponding menu item will be switched also (to the matching language).

Should you have some other menu item in your original menu in that "other" language, you can safely delete that menu item. After you delete such item, that'll be 1 menu item less that is shown "in both languages" (as in your question). Repeat the above (= translate menu item and delete original duplicate item) for each of your duplicate (in both languages) menu items.

Refer to the Multilingual Guide for (way) more details.

Miltilingual sites are really fun in D7 (way better then it was in D6, and D8 promises to become more easy to configure). Typical variations (with similar solutions) of this "menu" topic are:

* **translations of blocks**, which requires the Block Languages (i18n\_block) submodule to be enabled.
* **translations of taxonomies**, which requires the Taxonomy Translation (i18n\_taxonomy) submodule to be enabled.
> 0 votes

---
Tags: 7, routes, i18n-l10n
---


title: Why isn't my service found?

text:
# Question
Title: Why isn't my service found?
I'm trying to load a service into my Drupal module, but even after checking twice whether I did something wrong, I can't seem to find any error in my code as I did everything as the documentation said and Drupal still gives me a non-existent service error.

Here's the my services.yml file:

```
services:
  rb_weather.wunderground:
    class: Drupal\rb_weather\WundergroundWeather

```

Here's the config form code (the part loading the service):

```
class RBWeatherSettingsForm extends ConfigFormBase
{
/**
 * @var WeatherInterface
 */
private $wunderground;

public function __construct(ConfigFactoryInterface $config_factory,    WeatherInterface $wunderground)
{
    parent::__construct($config_factory);

    $this->wunderground = $wunderground;
}

public static function create(ContainerInterface $container)
{
    return new static(
        $container->get('config.factory'),
        $container->get('rb_weather.wunderground')
    );
}

```

I have included the classes using the "use" command as PhpStorm doesn't complain about that, however, Drupal does not want to recognize it.

My service classes as well as the services.yml file are placed under rb\_weather/services folder.

Thanks a lot.

# Answer
Not certain, but it sounds like your files may not be in the correct places based on your description.

The services.yml should be in the root of your module, not in a sub folder.

Also, your service classes should be in a /src/ folder. It would be okay to have them in a /src/services folder if you want, but module namespaces in drupal start in the module's /src/ folder, not in the root; the reason for this is because drupal uses the PSR-4 naming conventions, which specify that structure. You can find more info about how drupal modules should be structured here: https://www.drupal.org/node/2156625
> 5 votes

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: Problem installing in local "The translation server is offline"
I'm trying to install Drupal 8 on my laptop (localhost on a WAMP server), and I always get the following error in the first steps:

> Requirements problem
>
> The translation server is offline.
>
> The installer requires to contact the translation server to download a translation file. Check your internet connection and verify that your website can reach the translation server at http://ftp.drupal.org. Check the messages and try again.

That step is mandatory, and I can't continue the installation process. Opening http://ftp.drupal.org, I can see the website with no problem.

I've disabled anti-virus and firewall, and I have tried the process from different locations (different Internet access) on the same computer, with the same result. I'm using EasyPHP WAMP on Windows 8.1, with versions that meet the requirements of PHP, MySQL.

What can be blocking the access to the translation server? Is there any way to omit this step?

# Answer
> 19 votes
I think you didn't select English in the first step, and probably your Internet connection is behind a proxy and I guess Drupal doesn't support it.

You can select English and continue or:

1. Go to Translation server and download the specific language, the Spanish for example

>

>

2. Copy the download file in sites/default/files/translations
3. Continue with installation

# Answer
> 5 votes
Download this file : https://curl.haxx.se/ca/cacert.pem

And add the path to the file in your php.ini :

```
curl.cainfo="D:\wamp64\keys\cacert.pem"

```

# Answer
> 0 votes
This situation can be derived from invisible exception: *Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?*

To solve this problem you need to activate (uncomment) **"php\_openssl" module** in php.ini:

```
extension=C:\xxx\php_openssl.dll

```

Before edit php.ini you can test your situation by small php script:

```
<?php
error_reporting(E_ALL);
$file = file_get_contents('https://www.google.com/');
die($file);
?>

```

If it return **"Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?"**, you should edit php.ini and RESTART Apache windows service.

---
Tags: installation
---


title: filtered_html in theme-settings.php

text:
# Question
Title: filtered_html in theme-settings.php
In my theme-settings.php i want to set text format to `'filtered_html'` and display in `page.tpl.php`.

I used this code to display text area:

```
$form['options']['description'] = array(
'#type'          => 'textarea',
'#title'         => t('Description'),
'#default_value' => theme_get_setting('description'),
);

```

And display it using `<?php print strip_tags(theme_get_setting('description')); ?>` in page.tpl.php

How do i set the textarea to use `'filtered_html'` format

# Answer
Try this:

```
$form['options']['description'] = array(
'#type'          => 'text_format',
'#title'         => t('Description'),
'#default_value' => theme_get_setting('description'),
'#format'        => 'filtered_html',
);

```

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7.x/#text\_format
> 0 votes

---
Tags: 7, forms
---


title: Index isn't crawling paragraph fields

text:
# Question
Title: Index isn't crawling paragraph fields
I have the following index and paragraph fields checked off as my paragraph field is called *field\_content*. However when I do a search for something inside these paragraph fields. I'm not getting any results.

Is there a way to debug if it indeed is crawling my paragraph fields? Or is there another setting that I might be missing since I'm attaching the paragraph entity to the Basic Page content type. Does Search API even go into the sub-entity and crawl that aswell?

# Answer
Aside from just checking off those boxes on the search api page, you have to also mark it in the View exposed filter that your creating as seen below:
> 3 votes

---
Tags: search, paragraphs
---


# Question
Title: How to fix migrate query() that's breaking my migration?
So I have a Drupal 2 Drupal (d2d) migration configured as follows:

```
class RanchoAboutNodeMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    ...

    // This is an entity reference field
    $this->addFieldMapping('field_attached_images', 'iid')
         ->separator(',')
         ->sourceMigration('Image');
    ...
  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('image_attach','ia','n.nid = ia.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->addField('ia', 'iid', 'iid');
    $query->addField('ia', 'nid', 'inid');

    return $query;
  }
}

```

The query causes two problems:

1. I can only import items one at a time through `drush mi` or the UI
2. Most important: I'll eventually run into a PDOexception for duplicate rows and then the error "Could not save to map table due to NULL value for key field nid" with migrate attempting to move totally empty rows.

Both items can be addressed by commenting out the line with `$query->addExpression()`, but then I miss some desired images. When the migration is actually working, everything migrates correctly, including the referenced image(s).

Any thoughts on what's causing this bizarre behavior when things go wrong and how to address it?

Only thing I can think is to create a local query in prepareRow(), but I don't think I've seen anyone else do that before.

# Answer
Adding a query to `prepareRow()` is the way to go:

```
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    $query = Database::getConnection('default', 'd6source')
           ->select('image_attach', 'ia')
           ->fields('ia')
           ->condition('nid',$row->nid);
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->groupBy('ia.nid');
    $result = $query->execute();
    foreach ($result as $r) {
      $iid[] = $r->iid;
    }
    $row->iid = implode (",", $iid);
  }

```

This has the huge added benefit of not messing up the source row count.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Dynamically Caclulated Values with Entity Field Query
Is there any way to query by dynamically calculated values using Entity Field Query? Take the following:

I want to query where the sum of `field_some_number` and a user-provided variable are greater than or equal to 5. Right now I'm only able to do the following:

```
$my_variable = -7;
$query->fieldCondition('field_some_number', 'value', 5, '>=');

```

But obviously this doesn't include my user-provided variable. How can I calculate this on the fly? Could `hook-query-alter` help me with this? I have not been able to figure out how to properly implement it. I'm using this with the Restful-Drupal module.

# Answer
> 0 votes
I don't think Entity Query supports expression.

* In your case, I think you might not even need it as you can workaround.

$value\_to\_compare = 5 - $user\_provided\_value; $query-\>fieldCondition('field\_some\_number', 'value', $value\_to\_compare, '\>=');
* But if you need to compute value based on columns of database table, you can go ahead with db\_select, where you can have addExpression for calculation.

$query-\>addExpression('table\_columns\_1 + table\_columns\_2', 'sum'); $query-\>having('sum', 5,'\>=');

---
Tags: entities, database
---


# Question
Title: How to set or change path to Drupal 8 contact form?
Drupal 8 provides two default contact forms: "Personal contact form" and "Website feedback."

While "Personal contact form" is added to each user's profile by default, to "Website feedback" Drupal automatically provides a link to this form from the footer. The path of this link is "contact" by default. How can I change the path to this contact form, where are those paths generally set and configured?

And by the way, is it possible to change the labels?

# Answer
I also needed a page at `/contact` path. With a simple custom module you can change the default routing for the contact forms.

Let's assume custom module is called: `example` and the new default for the contact forms will be `/contactform` instead of `/contact`:

**example.services.yml**

```
services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

**src/Routing/RouteSubscriber.php**

```
<?php
// Save this file as `src/Routing/RouteSubscriber.php` in your module directory.

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Change the core's default path for `/contact` so that we can use it as an alias.
    if ($route = $collection->get('contact.site_page')) {
      $route->setPath('/contactform');
    }
    if ($route = $collection->get('entity.contact_form.canonical')) {
      $route->setPath('/contactform/{contact_form}');
    }
  }
}

```
> 8 votes

# Answer
Each form is available at contact/{form\_name}. The link on the page that you're looking at points there.

It's not possible to provide a different path, but you can manually create an alias that points to that page.
> 6 votes

---
Tags: 8, emails
---


title: Services Download API

text:
# Question
Title: Services Download API
I am having difficulties setting up an endpoint with the services module to download a file. Ultimately I want the user to hit the services end point with something like `/api/download/file/fid` and it will download the file to the users machine. The reason I want to do it through services and not just get users to hit `/sites/default/files/file.filetype` is because I need to be able to restrict access to the download link with HTTP basic auth. I have tried searching but cannot find how to achieve this? any help is much appreciated.

EDIT: My xml response when I imported arpitr's endpoint configuration and called it.

```
<result>
    <fid>6</fid>
    <uid>1</uid>
    <filename>Transition1.jpeg</filename>
    <uri>public://Transition1.jpeg</uri>
    <filemime>image/jpeg</filemime>
    <filesize>435007</filesize>
    <status>1</status>
    <timestamp>1475199010</timestamp>
    <type>image</type>
    <uuid>4c703ad2-290c-4573-9a29-a7e86e1a874e</uuid>
    <field_file_image_alt_text/>
    <field_file_image_title_text/>
    <rdf_mapping/>
    <metadata>
        <height>2304</height>
        <width>3072</width>
    </metadata>
    <alt/>
    <title/>
    <height>2304</height>
    <width>3072</width>
</result>

```

I am missing `<file>` which is the content of the file base 64 encoded, any idea why this could be?

# Answer
> 2 votes
You can send an image through resources using base64\_encode(), or \_file\_resource\_retrieve().

I don't remember the specifics of it all, but here is how I did it for Services in a project last year. You'll have to dissect the code yourself, but it definitely does work:

```
/**
 * Override of the Services module File resource, retrieve method.
 *
  * The original method does not allow for the retrieval of an image with an image style.
  * This override accepts an additional parameter, $image_style, which if set will return
  * the file data for the image in that image style. This allows for the retrieval of private files.
  *
  * @param $image_style
  *   If this value is set to an image style, the data for the image in that image style will be returned.
  *   Otherwise, the original File resource is invoked.
  *
  * @see _file_resource_retrieve()
  */
 function ba_api_file_retrieve($fid, $include_file_contents, $get_image_style, $image_style)
 {
    if($image_style)
    {
        if ($file = file_load($fid))
        {
            $filepath = $file->uri;

            if($image_style == 'raw')
            {
                $return = base64_encode(file_get_contents(drupal_realpath($filepath)));
            }
            else
            {
                $return = base64_encode(file_get_contents(drupal_realpath(image_style_path($image_style, $filepath))));
            }
        }
        else
        {
            $return = 'file not found';
        }
    }
    else
    {
        module_load_include('inc', 'services', 'resources/file_resource');

        $return = _file_resource_retrieve($fid, $include_file_contents, $get_image_style);
    }

    return $return;
 }

```

# Answer
> 1 votes
You can try importing the following exported working service endpoint which will allow you to download file by accessing /api/download/file/

```
    $endpoint = new stdClass();
    $endpoint->disabled = FALSE; /* Edit this to true to make a default endpoint disabled initially */
    $endpoint->api_version = 3;
    $endpoint->name = 'file_download';
    $endpoint->server = 'rest_server';
    $endpoint->path = 'api/download';
    $endpoint->authentication = array(
      'services' => 'services',
    );
    $endpoint->server_settings = array();
    $endpoint->resources = array(
      'file' => array(
        'operations' => array(
          'retrieve' => array(
            'enabled' => '1',
          ),
        ),
      ),
    );
    $endpoint->debug = 1;

```

**Update:**

As output you will receive the complete file object as xml and file will be embded to file attribute which is base64 encoded, now when you receive the response you can use the file metadata and to download use file attribute from response, base64 decode and then save it. Response xml from above service endpoint.

```
<?xml version="1.0" encoding="utf-8"?>
    <result>
      <fid>2</fid>
      <uid>1</uid>
      <filename>Screen Shot 2016-09-28 at 1.54.36 PM.png</filename>
      <uri>public://field/image/Screen Shot 2016-09-28 at 1.54.36 PM.png</uri>
      <filemime>image/png</filemime>
      <filesize>61202</filesize>
      <status>1</status>
      <timestamp>1475196925</timestamp>
      <rdf_mapping/>
      <uri_full>http://drupal.services.local/sites/default/files/field/image/Screen%20Shot%202016-09-28%20at%201.54.36%20PM.png</uri_full>
      <target_uri>field/image/Screen Shot 2016-09-28 at 1.54.36 PM.png</target_uri>
 <file>iVBORw0KGgoAAAANSUhEUgAAA1QAAAC1CAYAAABYkb7nAAAYKmlDQ1BJQ0MgUHJvZmlsZQAAWIWVWQk4Vd27X..</file>
      <image_styles/>
    </result>

```

# Answer
> 1 votes
Another option would be to use the "private" file mode for the file field, then implement `hook_file_download` to do your access check when the download URL is requested.

You could also add HTTP authentication protection to a particular folder in the files directory via .htaccess or your webserver config.

---
Tags: services
---


# Question
Title: Boost makes the editing of content/settings impossible
Once the Boost is enabled and I add its code into the .htaccess something weird starts to happen. No changes are being saved when editing the content or settings, after hitting the submit button the page just reloads ignoring the changes, no messages are shown, and sometimes the admin menu disappears. For the not logged in users the Boost works fine, html files are being generated and served. But it makes impossible to administer the site, looks like it affects the Drupal for logged in users as well or something. As soon as I remove Boost's code from the .htaccess – everything starts working again.

Using it on Apache 2.2.29

Tried to set it for the specific pages only, but had no success.

Could you help me and tell what needs to be done?

# Answer
Did you add the Boost section in your .htaccess, which is necessary to make it work? If you already have, you might check that the part about GZIP is present.

I had this same problem, and what I did was to disable and uninstall and remove the Boost module. Then I installed and enabled the previous Boost version where this GZIP section is present. I saved that part in .htaccess and went back to installing the latest Boost version again, but with the added GZIP part in the .htaccess file.

You can also check this thread out: Impossible to edit nodes, log to in etcetera after enabling Boost and editing .htaccess

The most important gzip rules are these (if you want to try this without disabling, uninstalling and the re-installing the module:

```
  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]

  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz -s
  RewriteRule .* cache/%{ENV:boostpath}/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz [L,T=text/html,E=no-gzip:1]

```

Hope this helps.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Display a taxonomy term every number of rows
I have a view with Infinite Scroll Pager giving me the latest products of the website.

Every taxonomy term has an image attatched on it.

I want to display taxonomy terms every 3 rows of products.

# Answer
I think you must alter the view.

1. Create the views normally, add taxo to every rows.
2. Use the Hook hook\_views\_pre\_render(&$view)
3. Delete the term for every rows except 1/3.

For example something like this:

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_myviewname') {
    $result = $view->result;
    $count = 0;
    foreach ($result as $i => $row) {
      if(!$count % 3){
        unset($view->result[$i]->field_MYTEXONOMYFIELD[0]);
      }
      $count++;
    }
  }
}

```

Example from : http://www.drupal8.ovh/en/tutoriels/238/alter-a-view-edit-view-result-programmatically
> 0 votes

---
Tags: views
---


# Question
Title: Theme setting to change block position (region)
i want to create a theme setting to change blocks position(region) for ex.

> option\_1 block\_branding-\> region\_top block\_main\_menu-\> region\_menu
>
> option\_2 block\_branding-\> region\_branding block\_main\_menu-\> region\_header\_first

I think that should do something like:

* Create a file with a function to change the region of the blocks according to option.
* Call this function when the form is submitted.

But I don't how to get block info to change its position.

# Answer
First of all you should change each desired block region for your theme manually at `Administration>Structure>Block layout Tab` and then go to the config export function at:
`Administration>Configuration>Development>Configuration synchronization>Export Tab>Full archive` to export all the block settings for your theme.
Then you should take a look at to the generated YAML files and placed them in a new folder within your theme at `/config/install`. you then uninstalled the theme and then reinstalled it as the default.
> 1 votes

---
Tags: 8
---


# Question
Title: How to assign blocks to particular regions on theme install?
Drupal 8 provides some blocks by default. Eg. `Site Branding`, `Main Navigation`, `Powered by Drupal`, `Search` etc.

I have created a theme that has `Site branding` & `Main Navigation` named regions in which corresponding blocks can be placed.

When I enable my theme, `Site Branding` & `Main Navigation` blocks are placed in `Header` & `First Sidebar` region of my theme by default respectively.

How can I place `Site Branding` & `Main Navigation` blocks to their respective regions by default on theme install?

# Answer
> 8 votes
First of all, you should change each desired block region you want manually at `Administration>Structure>Block layout Tab` and then go to the config export function at:
`Administration>Configuration>Development>Configuration synchronization>Export Tab>Single item` to export each the block settings for your theme.
Then you should take a look at to the generated YAML files and placed that in a new folder within your theme at `/config/install`. you then uninstalled the theme and then reinstalled it as the default.

Summary:
1. Install `MY_THEME`
2. Place the blocks in the desired regions
3. Export config files and remove from them `uuid` and core config hash
for example `Site Branding` block `block.block.MY_THEME_branding.yml` file

```
langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - DEPENDENT_THEME
id: MY_THEME_branding
theme: MY_THEME
region: site_branding
weight: 0
provider: null
plugin: system_branding_block
settings:
  id: system_branding_block
  label: 'Site branding'
  provider: system
  label_display: '0'
  use_site_logo: true
  use_site_name: true
  use_site_slogan: true
visibility: {  }

```
4. Place config files to `MY_THEME/config/optional` or `MY_THEME/config/install` directory (if you're absolutely sure all dependencies are met)
5. Uninstall `MY_THEME` and clear all caches
6. Reinstall `MY_THEME` again

# Answer
> 7 votes
Found the answer:

This can be done by adding a yml file (block instance) for each block in the `theme/config/install` folder.

For eg., To assign the `Site Branding` block (machine name `system_branding_block`) to the `Site Branding` region (machine name `site_branding`) add the following code in the `config/install/block.block.THEME_NAME_branding.yml` file:

```
langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - DEPENDENT_THEME
id: THEME_NAME_branding
theme: THEME_NAME
region: site_branding
weight: 0
provider: null
plugin: system_branding_block
settings:
  id: system_branding_block
  label: 'Site branding'
  provider: system
  label_display: '0'
  use_site_logo: true
  use_site_name: true
  use_site_slogan: true
visibility: {  }

```

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


# Question
Title: Programmatically render HTML in taxonomy term description
I'm facing an issue where I'm attempting to programmatically set the description property for a taxonomy term that includes HTML, but the HTML is being rendered as text, rather than being rendered into HTML elements, unless I manually access the term in a browser and save it.

## Example

```
taxonomy_term_save((object)array(
  'name' => $name,
  'description' => $t('<h5>My description.</h5><p>More info.</p>'),
  'vid' => $vocab->vid,
));

```

When I attempt to render the description, it appears as:

> `<h5>My description.</h5><p>More info.</p>`

However, if I then go to Structure \> Taxonomy \> My\_Vocabulary \> My\_Term and simply save the term (without any edits), it will then render properly as:

> **My description.**
>
> More info.

I've also made a number of attempts to achieve this through an Entity Metadata Wrapper, but no luck (though I am admittedly not well versed on EMWs).

How can I programmatically force the description to correctly render the HTML without having to manually re-save it?

Any help is appreciated!

# Answer
> 2 votes
The `taxonomy_term_data` table, which is the entity table for taxonomy terms, has a `format` column which stores the name of a filter to apply to the `description` when rendered.

It's available as a property on the entity, so you can use:

```
taxonomy_term_save((object)array(
  'name' => $name,
  'description' => $t('<h5>My description.</h5><p>More info.</p>'),
  'vid' => $vocab->vid,
  'format' => 'full_html',
));

```

# Answer
> 1 votes
Use the format property:

```
$term = taxonomy_term_load($tid);
$term->description = t('<pre><strong>Text</strong></pre>');
$term->format = 'full_html';
taxonomy_term_save($term);

```

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


# Question
Title: How to set HTML value for taxonomy description field using entity_metadata_wrapper
I've set my taxonomy description field to taking a filtered text value. Using the UI, I can edit a taxonomy term, write some HTML, save, and when I view it I see the HTML rendered by my browser.

However when doing this:

```
$wrapper = entity_metadata_wrapper('taxonomy_term', 123);
$wrapper->description->set('<p>My html</p>');
$wrapper->save();

```

And viewing the term's page, the description comes out with the html converted to entities, i.e. I see `<p>My html</p>` instead of a paragraph with `My html` as its content.

I notice that

```
$wrapper->description->value(); // <p><p&gtp;My html<p></p>

```

Whereas if I load a term that I have edited with the UI, saving HTML to the description field,

```
$wrapper->description->value(); // <p>Some html</p>

```

I've looked at `$wrapper->description` and `$wrapper->value()->description` and there's no difference between a term with/without the correct/desired behaviour.

Also, I note that with normal fields, when you set a formatted text field you pass/get an array `[ 'format' => 'filtered', 'value' => '<p>the html</p>' ]` whereas here I only ever get a string.

Is this something peculiar to taxonomy terms (and is there a workaround or extra code I need)? Have I misunderstood something?

Thanks.

# Answer
> 1 votes
I just encountered a similar situation myself and it looks like you're choices are either `taxonomy_term_save()` or to update the table directly via `db_update()`. The format property belongs to the term itself, rather than the Description property of the term. If you execute `$term->getPropertyInfo()` you'll see that the format property is not returned. Keep in mind that the Description is a property of the taxonomy entity, rather than a field, but doesn't seem to be accessible via EMW.

## taxonomy\_term\_save()

```
taxonomy_term_save((object)array(
  'tid' => $tid,
  'description' => $t($descriptions[$info['step']]),
  'format' => 'full_html',
  'vid' => $vocab->vid,
));

```

---
Tags: 7, taxonomy-terms, entities
---


# Question
Title: How to list duplicate nodes, with views, based on compared fields with links
I'm trying to create a list with duplicate nodes, so i can delete those. I'm not coder and I have already tried the module "remove duplicates" without success, so i have to use views with vbo module.

The field i have to compare nodes, contains a link. If the same link is in more than one node, i need it to be listed.

I have turned aggreation on. I have one field, displaying a link. I have created a filter, pointing at the above field with link, with "count" and set it to "show only greater than 1" acording to other similar questions on how to list duplicate titles.

Unfortunately this does nothing for me. As soon as i turn on the filter, there is no output.

Can you tell me what I'm missing here ? Sorry for the poor english.

# Answer
Figured it out.

Create content field of the fields i want to aggregate. Create Content NID and set to COUNT. Create filter Content NID with Is greater than 1.

Voila Also the field with the data is to be aggregate, must NOT be a link, then it wont work.
> 0 votes

# Answer
There isn't an easy, non-coder based way to do that with views. You *could* however create a view with the link field visible, and as a sort parameter as well. That way identical field values would show up next to one another. It'd be then the process of selecting the duplicate node (I'd suggest deleting the one with the higher nid) and deleting it.

Let me know if that makes any sense at all, or if you need a 5 minute proof of concept demo.
> 1 votes

# Answer
Create a view that is a table. Add the required fields to that view including the link field. Click settings here: "Format: Table | Settings"

Then group by the field for the link.

Like so:

Here is an example:
> 1 votes

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


# Question
Title: Show 2 content types in a view that share same field value
Hi i have 2 content types:

* **Agent**
* **Organisation**

they both have fields for id:

* **ID** ( agent content type)
* **Org ID** ( Organisation content type)

Now i need to create a view that will list fields from both of the content types, and only relation between them is same value in fields ( **field\_id** and **field\_org\_id** ).

Since content is already there and there are more than 200 nodes in each content type, i need to work with what i have. That means i cant add new fields ( like node reference ).

Is there a way to make a view that will list fields from two content types that share same value in 2 fields with different name? And in each row to have mix of fields from both content type with relation of this ID.

# Answer
> 1 votes
Since **field\_id** and **field\_org\_id** are two separate fields, you'll need some way to tie them together. A custom entity could do that, but you could also cheat a little and use a taxonomy vocabulary that contains these two fields.

You could then build a view that displays all content and add a relation to the vocabulary and restrict the results to only the content that possesses this relationship.

Cheaty, but I think it might be the easiest solution.

Edit:

I wouldn't modify the content or content types, but rather, add the **field\_id** and **field\_org\_id** fields to the taxonomy vocabulary, then iterate through your **Agent** and **Organization** nodes and generate taxonomy terms that associate one field's value to another by populating each term's **field\_id** and **field\_org\_id** fields from their respective **Agent** and **Organization** nodes.

So, some code...

## Create the vocabulary

```
$vocab = new stdClass();
$vocab->name = 'Organization to Agents';
$vocab->machine_name = 'org_to_agents';
taxonomy_vocabulary_save($vocab);

```

## Add the fields

```
$fields = array(
    'field_id',
    'field_org_id',
);

foreach($fields as $field) {
  // Replace my)taxonomy_vocabulary with your chosen vocabulary name.
  if (is_null(field_info_instance('taxonomy_term', $field, 'my_taxonomy_vocabulary'))) {
    field_create_instance(array(
      'label' => $t($field),  // <-- This doesn't need to be pretty.
      'widget' => array(
        'type' => 'textfield',
      ),
      'field_name' => $field,
      'entity_type' => 'taxonomy_term',
      'bundle' => 'my_taxonomy_vocabulary',
    ));
  }
}

```

## Get the list of IDs

```
// Credits to https://www.drupal.org/node/1079616#comment-10864932 for example.
$agents = db_query("SELECT nid FROM {node} WHERE type = :type", array(':type' => 'agent'))
  ->fetchCol();
$orgs = db_query("SELECT nid FROM {node} WHERE type = :type", array(':type' => 'organization'))
  ->fetchCol();

// Should result in a list of unique Node IDs that exist in
// at least one node for both content types.
$nids = array_intersect($agents, $orgs);

```

## Create your taxonomy terms

```
$vocab = taxonomy_vocabulary_machine_name_load('my_taxonomy_vocabulary');
foreach($nids as $key => $nid) {
  $term = (object)array(
    'name' => $key, // Use any unique value that makes sense here.
    'vid' => $vocab->vid,
  );
  $term->field_id[LANGUAGE_NONE][0]['value'] = $nid;
  $term->field_org_id[LANGUAGE_NONE][0]['value'] = $nid;
  taxonomy_term_save($term);
}

```

Again, this is a bit "cheaty", and a custom entity would probably be considered more proper, but I think this should help.

Hope it helps!

---
Tags: views
---


title: Multiple REST endpoints

text:
# Question
Title: Multiple REST endpoints
I have an endpoint, which is active and working for more than a year, and I recently had the need to add a new endpoint, which obviously has a different url ("Path to endpoint").

For both, however, I need to use the login functionality, and other custom actions (each one has its own url, callback and access callback, in two separated custom modules).

But on every call, i can see that both endpoints are being requested, all arguments are being doubled etc. Here's the `$controller` as seen from `hook_services_request_preprocess_alter`:

```
Array
(
    [help] => Array
        (
            [0] => Description from endpoint 1
            [1] => Description from endpoint 2
        )

    [callback] => Array
        (
            [0] => MY_FIRST_MODULE_callback_function
            [1] => MY_SECOND_MODULE_callback_function
        )

    [access callback] => Array
        (
            [0] => MY_FIRST_MODULE_access_callback_function
            [1] => MY_SECOND_MODULE_access_callback_function
        )

    [args] => Array
        (
            [0] => Array
                (
                    [name] => email
                    [type] => string
                    [description] => Email
                    [source] => Array
                        (
                            [data] => email
                        )

                    [optional] => 1
                )

            [1] => Array
                (
                    [name] => email
                    [type] => string
                    [description] => Email
                    [source] => Array
                        (
                            [data] => email
                        )

                    [optional] => 1
                )

        )

    [etc] => ....

)

```

This happens whichever url is requested, it's causing both the iOS and Android apps to crash, and i couldn't find a way around it.

What should / can I do to run both endpoint independently, and why are both getting invoked even if the url ("Path to endpoint") is different?

# Answer
> 2 votes
Use a distinct resource name, or simply enable the same resource on the other services endpoint to use it there.

To debug issues with the controller, you can check in `RESTServer.inc` in particular the functions `getController` and `resolveController`. Adding some debug/logging code there may help to resolve the issue.

---
Tags: services
---


# Question
Title: How to rearrange views PHP sorting criteria?
Usually, it works fine when I rearrange two or more sorting criteria within a Views (simple drag and drop) but in my case (Content fields grouped by taxonomy terms), one of the sorting criteria is a Global:PHP (based on a PHP field) and it seems like it is **always treated first** whatever level I choose? And of course, I need it to be treated secondly.

EDIT1 : Here is the problem in details

I have a list of nodes with pagination (1-15, 16-28, etc.). I also have a taxonomy field to group the nodes (categories). I need to sort the nodes by taxonomy terms (according to the weight) and secondly by first page. I get the first page using a PHP field to extract the data from the pagination. If I use the pagination field directly, the sorting is wrong (page 100 will appear before page 11, "alphabetical order").

Finally, I need :

Term 1

Node 1 pages 1-15

Node 4 pages 78-100

Node 12 pages 167-184

Term 2

Node 2 pages 16-45

Node 10 pages 110-125

Term 3

etc.

Any idea?

Thanks.

Related posts :

Cant get desired results for multiple sort criteria in a view

Sort criteria is ignored in Views

Views: custom field for sort criteria

EDIT2 : As suggested by Smalution, a custom module could help. I am thus working on the little code needed to sort my View using a custom PHP field. I am using hook\_views\_query\_alter and add\_orderby but I can not find the right way to write it since the custom PHP field is not stored in a table like any other standard Drupal fields (the PHP field is computed when the View is calculated). Could anyone help me to complete the code given by Smalution? Thanks for any tip. Tell me if more details are needed.

# Answer
> 1 votes
You can go for hook\_views\_query\_alter.

> Alter the query before executing the query.

```
function module_name_views_query_alter(&$view, &$query) {
  if ($view->name == 'Viewname') {
    //dpm($view->query->orderby[0]);
   // put your modified sorting criteria
  }
}

```

---
Tags: 7, views
---


# Question
Title: Drupal advanced forum - different styles for different forums
With Advanced Forum on Drupal 7, how can I apply different styles to different forum posts, depending upon which forum they are in? Although I can see how to style different forums, there doesn't seem to be any way of using a different style per post depending upon the forum it is in, as there is no CSS class added denoting the posts forum.

# Answer
> 1 votes
On further investigation I believe this can be done with a combination of assigning a path to a post via pathauto, and the Context module, which can add CSS depending on the path.

---
Tags: 7, theming, nodes
---


# Question
Title: Internal Server Error and Machine Readable Names
I have installed a new local site using Drupal 8.1.10 which takes a lot of time whenever I give any command (lets say create a text field) and then sometimes it gives a 'Internal Server Error' after which the 'machine readable name' of the text field which I was creating becomes unusable.

It then gives the error 'The machine-readable name is already in use. It must be unique.' whereas the field was not created and the 'machine readable name' is not actually in use.

This has happened multiple times. How do I resolve this?

# Answer
> -1 votes
Just try this : on **.htaccess**, replace `Options +FollowSymLinks` by `Options +SymLinksIfOwnerMatch`

Example from : http://www.drupal8.ovh/en/tutoriels/9/install-drupal-8-virtualmin-error-500

---
Tags: 8, entities, debugging
---