title: Clear managed_file field on submit

text:
# Question
Title: Clear managed_file field on submit
I'd like to clear the managed file field each time the contents are sent off for further processing on submit.

The callbacks work fine, but I have repeatedly come unstuck in my goal of having a "fresh" form everytime I need to submit a new image.

The form is defined thus:

```
function mymodule_form($form, &$form_state) {

$form['Input type'] = array(
    '#type'=>'fieldset',
    '#title'=>'Upload your image'
);

$form['Input type']['file'] = array(
    //file left in non-permanent state for testing purposes
    '#type' => 'managed_file',
    '#title'=> t('Upload image'),
    '#description' => t('Choose an image to upload. Format must be gif, png, jpg, and may not exceed 2MB in size. Press Submit to confirm your selection.'),
    '#upload_validators' => array(
        'file_validate_extensions' > array('gif png jpg jpeg'),
        'file_validate_size'=>array(512*512*512),
    ),
    '#upload_location'=>'public://mymodule_uploads',
);

$form['Input type']['submit'] = array(
    '#type'=>'submit',
    '#value' =>t('Submit'),
    '#submit'=>array('mymodule_clear_image_submit'),
    '#ajax' => array(
            'callback'=> 'mymodule_update_image_callback',
            'wrapper'=>'somediv'
        ),
);
return $form;
}
function mymodule_update_image_callback($form,&$form_state) {
$picture_settings = array(
        'image' => file_create_url($form['Input type']['file']['#file']->uri)
        );
    drupal_add_js(array('mymodule' => $picture_settings),'setting');

    return;
}

function mymodule_clear_image_submit($form,&$form_state) {
$form_state['complete form']['Input type']['file']['#file'] = NULL;
$form_state['rebuild']=TRUE;
return;
}

```

Neither the submit nor the callback functions seems to be refreshing my form. Setting the file value to NULL has not had an effect either.

I don't know what else to try. Cheers!

# Answer
I found a solution to this problem here: https://www.drupal.org/node/1578656

The idea is to add the following keys to the 'file\_managed' field at the time you want to clear it:

```
$form[FORMKEY]['#file'] = FALSE;
$form[FORMKEY]['filename'] = array();
$form[FORMKEY]['#value']['fid'] = 0;

```

In your case it should be something like this in the form builder function:

```
if ( isset($form_state['storage']['reset-file-field'])
  && $form_state['storage']['reset-file-field'] === true
) {
  $form['Input type']['file']['#file'] = FALSE;
  $form['Input type']['file']['filename'] = array();
  $form['Input type']['file']['#value']['fid'] = 0;

  $form_state['storage']['reset-file-field'] = false;
}

```

And then in your submit handler:

```
$form_state['storage']['reset-file-field'] = true;

```

The if-block is necessary to prevent the upload field being reset when you press 'upload', thus making it useless.
> 1 votes

---
Tags: 7, forms, files
---


title: controller function use with ajax

text:
# Question
Title: controller function use with ajax
I have one controller like as below .

```
<?php
namespace Drupal\users\Controller;

use Drupal\Core\Controller\ControllerBase;

class UsersController extends ControllerBase {

  public function getList() {
    $time = time();
    $data = array();
    $response = $data = $result = null;

      // add all the data in one multiple dim. array
      $data['title'] = 'Example to consume REST API of User List';
      $data['users'] = $result->list;
      $data['form_data'] = $result->form_data;

      // display the content in the middle section of the page
      $build = array(
        '#theme' => 'users_list', // assign the theme [users-list.html.twig]
        '#title' => 'Example to consume REST API',
        '#pagehtml' => 'API URL : api/users/list ',
        '#data' => $data
      );
    }

    return $build;
  }
}

```

this above function is called and render the HTML in the middle of the page in HTML format where page URL is call as per defined in routing file (http://siteurl.com/user-list). I want to use this HTML output in ajax request which will call the same function through ajax instead of page url.

```
<?php
namespace Drupal\ajax\Controller;

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

class AjaxController extends ControllerBase {

  public function call_ajax(){

      //  my target is like as below
       $op = Drupal\Core\Controller\UsersController()->getList();
       return $op;
  }
}

```

Q) Is there any way to get the output of getList() in HTML format in ajax callback?

# Answer
> **WARNING: The following code contains serious security vulnerabilities, and should not be used in a production site without modification.**

After lots of searching finally, I got the solution. I would like to share this.

AjaxController.php

```
namespace Drupal\ajax\Controller;

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

class AjaxController extends ControllerBase {

  public function call_ajax($controller,$function){
    $args = func_get_args();
    $r = array();
    $r['html'] = null;

    $class = "\\Drupal\\".$controller."\\Controller\\".ucfirst($controller)."Controller";

    $obj = new $class();

    if(method_exists($obj,$function)){
      $r['html'] = render($obj->$function());
    }
    return new JsonResponse($r);
  }

}

```

ajax.routing.yml

```
ajax.call:
  path: '/call/ajax/{controller}/{function}'
  defaults:
    _controller: '\Drupal\ajax\Controller\AjaxController::call_ajax'
    _title: 'Get List'
  methods:  [GET]
  requirements:
    _permission: 'access content'

```

ajax.js

```
jQuery(document).ready(function($a){
    $a.ajax({
        url: "call/ajax/users/getList",
        method :'GET',
        dataType: "json",
        success: function(result){
          $a(".region-content").html(result.html);
        }
    });
})

```

Now I have to just pass the controller and function name to call the function using ajax.

The main purpose to use this way is reusability of controller functions.
> 8 votes

---
Tags: ajax
---


# Question
Title: Search module is not working with all content types
In my drupal, i have a search module. This module is not working with all content. For example i have a view. This view's show us announcement. When i was trying to search this content type, there is no result.

I'd tried reindex (/admin/config/search/settings)

So can someone give me an idea?

# Answer
> 0 votes
Default behavior of search module is, it search all the content type contents. If you tried to search with content type name then it is not working, because it is not the search module functionality.

---
Tags: search
---


# Question
Title: Problem with character encoding ( danish æ ø å ) when using page handler include files in hook_menu().
When I use an .inc file to handle my page output, all the danish special characters (Æ, Ø and Å) shows up as question marks, i.e. they are rendered with the wrong character encoding.

This following module works as expected.

## stack\_exchange\_minimal.module

```
<?php
/**
* Implements hook_menu().
*/
function stack_exchange_minimal_menu() {
  $items['mypage'] = array(
    'title' => 'Minimal example',
    'page callback' => 'mypage',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mypage() {
 return 'ÆØÅ - æøå'; //outputs 'ÆØÅ - æøå'
}

```

When I split the code up in two files, however, it doesn't.

## stack\_exchange\_minimal.module

```
<?php
/**
* Implements hook_menu().
*/
function stack_exchange_minimal_menu() {
  $items['mypage'] = array(
    'title' => 'Minimal example',
    'page callback' => 'mypage',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'stack_exchange_minimal.pages.inc',
  );
  return $items;
}

```

## stack\_exchange\_minimal.pages.inc

```
<?php
function mypage() {
 return 'ÆØÅ - æøå'; //outputs '��� - ���'
}

```

I have tried passing the text through a render array instead of just dumping a string as the return value, but whith the same results.

I'm using drupal core version 7.31

What can I do to work around this issue?

# Answer
The problem was, as Andy pointed out, that the file wasn't encoded in UTF-8.

The .inc file was created from the context menu in Windows: 'New' -\> 'Text Document', which defaults to the ANSI encoding.

The solution is simply to convert the file to UTF-8, that can be done for example in Sublime Text by choosing 'File' -\> 'Reopen with Encoding'. Other text editors have similar commands.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How to force Panels to render a node field even when field is empty
I have a field that I want to display via the Views Hybrid formatter in a panel pane as a node element. It renders just fine when there is at least one user-selected item in the field, but when there is none, it is treated as an empty field and so none of the view results show either. The whole thing is not displayed just because the field is empty.

How can I force panels to render a node element even when the field contains zero values?

# Answer
The reason i wanted to render an empty field in a panel was because the views hybrid formatter shows a view when the field is empty. Instead, i ended up showing the view via a views pane and making that pane conditional on the value of the field being empty.
> 0 votes

---
Tags: 7, views, entities, panels
---


# Question
Title: Make Facebook comments on Facebook page show up on my Drupal site
Using Drupal 7. I post some stories on Facebook and receive a lot of comments. I want these comments to also show up on the article page on my drupal site, not just on the Facebook page inside facebook. That is, when users comment on the post inside Facebook, i want the comment to show on the article page on my drupal website. Any ideas in getting this to work?

# Answer
You can have a look at this Facebook Comments Social Plugin Module

> Implement Facebook commenting with settings on the level of both content type and node. This module comes with a Facebook Comments block so you can have comments anywhere on your site.

There are another modules which support your functionalities -\> FB Comments Box

> This module gives your site the ability of using Facebook's Comments Box social plugin, i.e. comments on your site powered by Facebook. It provides an easy way to configure Facebook Comments parameters (like theme, administrators, number of posts, node types to attach to) and then exposes the generated code as a block for you to insert into a region of your choice. This module is intended for anyone who wants to put Facebook Comments on their Drupal site in addition to or instead of Drupal comments from core.
> 1 votes

---
Tags: 7
---


# Question
Title: Views filter out nodes based on taxonomy field
I have multiple node types on my website and a special View listing all the nodes on the site.

I have a taxonomy field which I have applied to some node types but not others. The trouble is any user with editor permissions can add the taxonomy field to any node type which previously did not have it.

**My Views needs to list content only of node types which have the taxomony field included.** In other words, if a node type does not have *field\_taxonomy\_example* included, my View should list *NO* nodes of that type.

My problem is I can't find a way to dynamically exclude node types - statically setting them is not an option because new types can be added any time.

Please help :-)

# Answer
I found a programmatic solution after visiting the Views API page.

Using the following code:

```
function mymodule_views_query_alter(&$view, &$query){
$types = db_select('field_config_instance', 'fci')
        ->fields('fci', array('bundle'))
        ->condition('field_name', 'field_taxonomy_example', 'like')
        ->execute()
        ->fetchCol();

$query->add_where(0, $query->fields['node_type']['field'], $types);

```

}

I was able to insert a dynamic list of node types to test my Views again.

Works like a charm.
> 0 votes

---
Tags: 7, views
---


# Question
Title: CKEditor + IMCE file uploader. What am I missing?
I've got CKEditor and IMCE modules installed and enabled. I've got an "Insert image" link at the bottom of the "body" text area. However, I can't seem to get the wysiwyg editor to display.

What am I missing?

In admin/config/content/formats I only have Plain text format.

Should I add Fitered HTML, full HTML and php manually?

Or shoud have they been created automatically with one of the modules?

# Answer
Depending on what version of Drupal you're using, my first inclination is to say the Media module is what you're missing.

That aside, there are a number of steps to take to configure the WYSIWYG image experience.

* How did you install CKEditor? Did you install the WYSIWYG module and the CKEditor library properly?
* Did you install the correct version of CKEditor? I think you might need the 3.6 version.
* Have you set up the correct input format? Does your user have permissions to use it?
* Have you set up a CKEditor profile with the correct image insert buttons that integrate with IMCE?

Those are the main things that come to mind, though knowing more about what happens (i.e., when you disable rich text, does anything display in the editing window?) and what steps you've already taken would help narrow it down.
> 5 votes

# Answer
In my case there was some error on javascript side. When I started debuging using Firebug, then I got exact the line number with error and commented out the line. This solve my issue and all button appear in IMCE File browser.

I am using Wyswing. module , IMCE and Wysysing IMCE Bridge module in Drupal 7

ANOTHER POSSIABLE REASON IS : YOU MAY HAVE NOT ASSIGNED THE USER PROFILE OF IMCE TO ROLE. 1) GO TO admin/config/media/imce 2) ASSIGN EACH ROLE A USER PROFILE USER-1 3) AND SAVE.
> 2 votes

# Answer
I found that the sharebar module conflicts with the imce / ckeditor

https://drupal.org/project/sharebar

there is even a open issue for this. https://drupal.org/node/2058939

once I turn off sharebar module, imce image upload buttons reappear.
> 0 votes

# Answer
An old problem, but still relevant ;-) In my case it was a jquery incompatability issue with bootstrap. Enabling Jquery update module was the solution.
> 0 votes

---
Tags: wysiwyg, files
---


title: How does caching work for blocks?

text:
# Question
Title: How does caching work for blocks?
Say I have this type of code to build a custom block in Drupal 8.

```
 public function build() {

  //code that does a Guzzle call to retrieve data setting $links to contain that data

  $build['article_links'] = array(
    '#theme' => 'them_stuff',
    '#article_links' => $links,
    '#cache' => array('max-age' => 600),

  );

  return $build;
  }

```

Currently I don't have the *'#cache' =\> array('max-age' =\> 600),* and so every time to page loads the Guzzle call is run. If I add *'#cache' =\> array('max-age' =\> 600),* does that mean that the Guzzle call won't be run until the cache is invalidated?

# Answer
> 3 votes
Blocks are cached by default, so not specifiying anything should mean your guzzle call should only run once.

max-age 600 then means that the cache is not valid indefinitely but only 600s.

Note that anonymous page cache currently doesn't respect that setting. You have to disable that if you need this to update every 600s.

---
Tags: 8, caching
---


# Question
Title: Force a page to be rendered in admin theme
In drupal 7 we could force a page to open in admin page, there are several way to do that in drupal 7

Now I am looking for equivalent solution in Drupal 8, **How can I force drupal to render a specified pages as admin theme?**

# Answer
> 7 votes
You can add the \_admin\_route option to a route:

```
aggregator.feed_add:
  path: '/aggregator/sources/add'
  defaults:
    _controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
    _title: 'Add feed'
  requirements:
    _permission: 'administer news feeds'
  options:
    _admin_route: TRUE

```

You can also implement your own negotiator (See \Drupal\user\Theme\AdminNegotiator) or add that option to routes dynamically in a request subscriber.

---
Tags: theming, 8
---


# Question
Title: drupal_add_js() 'setting' not being set on form submit
I have a form and on that form the #submit action it calls a function that saves some data. Now what I need to do is I need to pass some data back to the website confirm page to be used by JavaScript. To do this I used drupal\_add\_js() 'settings' but this does seem to work? The data never gets set.
From what I've read I think it might be something with the form redirecting during the submission process and the JS is getting lost?

# Answer
> it might be something with the form redirecting during the submission process and the JS is getting lost?

Yes, you are absolutely right! Normaly, after form submitting user is redirected with `drupal_goto()` function. Messages which set with `drupal_set_message()` are stored in $\_SESSION so they are not lost, but `drupal_add_js()` doesn't use session.
You can prevent redirect in your submit function:

```
// In this case your form hanler will be able to see flag $form_state['submitted'] and
// other data from previous form processing to indicate that form was submitted.
$form_state['rebuild'] = TRUE;
// Will work.
drupal_add_js(array('myModule' => array('test' => 'test-value')), 'setting');

```

Or with:

```
$form_state['redirect'] = FALSE;
// Will work, too
drupal_add_js(array('myModule' => array('test' => 'test-value')), 'setting');

```

But I would have used `$_SESSION` as it is more flexible.

```
$_SESSION['js_settings'] = array('myModule' => array('test' => 'test-value'), 'setting');

```

Then you have to process `$_SESSION` yourself in accordance with your site logic.
> 4 votes

# Answer
if you have a form attaching js or css could be more painless with

'#attached' option this can attach css js library and settings documentation here

you may use hidden form element to save some data it will always appear on form\_states. Setting some values to hidden field is easier solution IMHO
> 1 votes

# Answer
You can set a session in form submit:

```
function my_form_submit($form, $&state) {
  $_SESSION['js_value'] = 5;
}

```

Then you can check if this session variable is set in your theme's template.php file and `theme_preprocess_page()` hook. This hook is executed everytime you load a page (and only after form redirect, not before), so you can add the js variable into your html here. But do not forget to unset the session variable after adding js varible, otherwise it will be loaded on every page request, not only after form submit.

```
function theme_preprocess_page($&vars) {
  // check if the session variable exists
  if (isset($_SESSION['js_value']) {
    drupal_add_js(array('myModule' => array('js_value' => $_SESSION['js_value'])), 'setting');
  }
  // optionally you can add a js file that will process the variable (if not added by default)
  drupal_add_js('path/to/js/file.js');

  // do not forget to unset the session variable
  unset($_SESSION['js_value']);
}

```

You can then access the variable in file.js, that will be loaded after form submit:

```
jQuery(document).ready(function () {
  // check if the variable exists and finally do some action
  if(typeof Drupal.settings.myModule.js_value != 'undefined') {
    alert(Drupal.settings.myModule.js_value);
  }
});

```

This way your js variable will be present in any page and only at the page that comes first after the form submit.
> 1 votes

# Answer
In the submit hook you should set a variable ( `variable_set("name", "value")` ) and read it / add it to js settings in the hook\_init() using `variable_get("name", "dafault_value")`;

Please take into consideration that saving variables using variable\_set() will save them to the database. You should delete them if you don't need them anymore. If the value you want to save will be used one time only you might want to use sessions instead.
> 0 votes

---
Tags: forms, javascript
---


title: Scheduler Module unpublish content

text:
# Question
Title: Scheduler Module unpublish content
Trying to schedule a content type to be unpublished on a specific date. Using the scheduler module everything is set up seemingly correct. When I run Cron the update fails,

* Updater Content - Publishing status complete. Results: No updates were performed. 1 updates were invalid
* When i go to Scheduled Updates Overview and run scheduled updates manually it works just fine.

Why is Cron Failing?

# Answer
I have created a drush command to run only the scheduled\_updates\_cron() function from the command line and also from crontab. I didn't know why all of my updates were invalid till I saw your post, so I made some research and I managed to make my drush command work like the "Run Updates" button from Scheduled Updates Overview page, by specifying the user who should run the update.

Example (Wrong results): `drush command-name`

Example (Good results): `drush --user=1 command-name`

If you are using the `drush cron`command, you should modified it to `drush --user=1 cron`

I hope this helps !
> 0 votes

---
Tags: 8, cron
---


# Question
Title: Can i specify an image style in my custom module
I search everywhere in the web but i dont find any solution.

I make an entity query for get some nodes. I pass the nodes to my template. In there nodes, i have an image field. So my questions is, can i specify an image style in this case ?

*Controllers.php*

```
$query = $this->entity_query->get('node');
$query->condition('type', 'foo');
$nids = $query->execute();
$foos = $this->entity_manager->getStorage('node')->loadMultiple($nids);
return array(
        '#theme' => 'foo',
        '#foos' => $foos
    );

```

template.html.twig

```
{% for foo in foos %}
    <img src='{{ file_url(foo.field_picture.entity.uri.value) }}'>
{% endfor %}

```

# Answer
> 0 votes
There are several options:

1. Use a view
2. Use Twig Tweak with a display mode, where you configure the image style
3. Use this code How to find image style URL from within twig template?

If you don't need more than what is in your question, I would start with 1, because don't reinvent code for things that are in core.

---
Tags: theming, 8, media
---


title: Authentication to LDAP Server

text:
# Question
Title: Authentication to LDAP Server
I'm using LDAP module to allow user login through a LDAP Server. This is server configuration:

**Server Properties**

* sid = eng\_ldap\_server
* numeric\_sid = 1
* name = Eng LDAP Server
* status = 1
* ldap\_type = ad
* address = 10.10.72.202
* port = 389
* tls = 0
* followrefs = 0
* bind\_method = 2
* basedn = Array ( \[0\] =\> dc=BMS,dc=ORVIETO )
* binddn = admin
* user\_dn\_expression = cn=%username,%basedn
* user\_attr =
* account\_name\_attr =
* mail\_attr =
* mail\_template =
* picture\_attr =
* unique\_persistent\_attr =
* unique\_persistent\_attr\_binary = 0
* ldap\_to\_drupal\_user =
* testing\_drupal\_username =
* testing\_drupal\_user\_dn =
* grp\_unused = 0
* grp\_object\_cat =
* grp\_nested = 0
* grp\_user\_memb\_attr\_exists = 0
* grp\_user\_memb\_attr =
* grp\_memb\_attr =
* grp\_memb\_attr\_match\_user\_attr =
* grp\_derive\_from\_dn = 0
* grp\_derive\_from\_dn\_attr =
* grp\_test\_grp\_dn =
* grp\_test\_grp\_dn\_writeable =
* search\_pagination = 0
* search\_page\_size = 1000

Anything wrong?

# Answer
> 0 votes
I was having a lot of problems with the connection and authentication with the server until I change the bind dn format.

Maybe try something like this:

binddn = webwasher88@hnbwyo.com

---
Tags: users, authentication-authorization
---


title: Save node via ajax continuously

text:
# Question
Title: Save node via ajax continuously
I'm trying to save a node (with the normal node form) via an ajax callback. The first save works. But after that I want to return the same node form again so that the user can update the values and save the node again. But this second save attempt fails. I always get a message like "this form has already been submitted". Are any solutions for this problem? Or shall I write a custom JS menu hook which saves the node programmatically?

Here are the relevant parts of my module

```
function MYMODULE_form_finding_node_form_alter (&$form, &$form_state){
  $form['#prefix'] = '<div id="wrapper">';
  $form['#suffix'] = '</div>';
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'MYMODULE_finding_node_form_submit_ajax',
    'wrapper' => 'finding-form-wrapper'
  );
}

function MYMODULE_finding_node_form_submit_ajax($form, &$form_state){
  $form_id = '#' . str_replace('_','-',$form['#form_id']);
  $commands = array();
  $commands[] = ajax_command_remove('.l-messages');
  if(form_get_errors()){
    $commands[] = ajax_command_replace($form_id, '<div id="finding-form-wrapper"></div>');
    $commands[] = ajax_command_replace('#finding-form-wrapper', drupal_render($form));
  }
  else{
    $node = $form_state['node'];
    $form_state = array();
    $form_state['rebuild'] = TRUE;
    $form_state['build_info']['args'] = array($node);
    $form = drupal_build_form('finding_node_form', $form_state);
    $form['#id'] = str_replace("_", "-", $form_id);

    $commands[] = ajax_command_replace($form['#id'], drupal_render($form));
  }
  $commands[] = ajax_command_prepend('.page', '<section class="l-messages row"><div class="columns">' . theme('status_messages') . '</div></section>');
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
So I managed to figure it out myself. It just seems that you need to build up the whole new form state manually and then rebuild the form with that state again. Here's my modified code for the ajax submit handler. But if anyone still has a better solution please post your answer here.

```
function MYMODULE_finding_node_form_submit_ajax($form, &$form_state){
  $commands = array();
  $commands[] = ajax_command_remove('.l-messages');
  if(form_get_errors()){
    $commands[] = ajax_command_replace(NULL, drupal_render($form));
  }
  else{
    $node = $form_state['node'];
    $new_form_state = array();
    $new_form_state['build_info']['args'][] = $node;
    $new_form_state['no_redirect'] = TRUE;
    $new_form_state['input'] = array();
    $new_form_state['values'] = array();
    $new_form_state['method'] = $form_state['method'];
    $new_form = drupal_rebuild_form('finding_node_form', $new_form_state);

    $commands[] = ajax_command_replace(NULL, drupal_render($new_form));
  }
  $commands[] = ajax_command_prepend('.page', '<section class="l-messages row"><div class="columns">' . theme('status_messages') . '</div></section>');

  return array('#type' => 'ajax', '#commands' => $commands);
}

```
> 0 votes

---
Tags: nodes, ajax
---


title: Add metatags import to migration

text:
# Question
Title: Add metatags import to migration
I have made a migration module to import the full content from a legacy Drupal 6 site to my new Drupal 7 site, using the migrate d2d module. Everything works fine, but I have just discovered that there are many custom meta tags added manually for both nodes and taxonomy in the legacy site (using the Metatags module). The taxonomy meta tags I can deal with manually, but I really would need to figure out how to add the mapping for metatags in my node migration classes. Do I add code in my general migration class in `node.inc` (that extends DrupalNode6Migration)?

Do I use prepareRow() to fetch info from the database and add this to a mapping with a default value in the new site? As far as I can see there are no fields in the legacy site that holds the metatags (I need title, keywords and description).

If anyone knows how to do this, please help.

# Answer
Finally I came up with a solution and I post it here in case anyone else has the same problem. There are two tables in the legacy site named `metatags` and `metapages`, in which you can find everything needed for importing the metatags.

So in `my prepareRow()` in each node migration class I added these rows, and now the metatags from the legacy Drual 6 site has been imported to my Drupal 7 site :-)

```
$metapages_path = !empty($row->nid) ? 'node/'.$row->nid : false;
if($metapages_path){
    $meta_title_pid = Database::getConnection($target='default', $key='legacy')->query('SELECT f.title, f.pid FROM {metapages} f WHERE f.path = :path',array(':path' => $metapages_path))->fetchAssoc();
}
$meta_title = !empty($meta_title_pid['title']) ? $meta_title_pid['title'] . ' | [site:name]' : '';
$this->addFieldMapping('metatag_title')->defaultValue($meta_title);
$meta_pid = !empty($meta_title_pid['pid']) ? $meta_title_pid['pid'] : false;
if($meta_pid){
    $meta_keywords = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'keywords'))->fetchAssoc();
    $meta_description = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'description'))->fetchAssoc();
}
$keywords = !empty($meta_keywords['value']) ? $meta_keywords['value'] : '';
$this->addFieldMapping('metatag_keywords')->defaultValue($keywords);
$description = !empty($meta_description['value']) ? $meta_description['value'] : '';
$this->addFieldMapping('metatag_description')->defaultValue($description);

```
> 0 votes

---
Tags: meta-tags, migrations
---


# Question
Title: How can I get my RSS feed to be Auto Discovered?
Created an RSS feed in Drupal 8 using Views. The feed is fine, but yet I don't have the discoverability icon show up in browsers. Looking at the HTML source I don't see anything like this at all

I found this answer for Drupal 7 but doing *"Feed Settings \> Attach To \> Master"* had no affect.

# Answer
Attach the Feed display to a valid Page display. The "Master" display may not be a valid page display.

An example of this can be seen in the default "Front Page" view. In this view, the feed display is attached to page\_1, which is the page at the URL `/node`.

See the YAML export snippet from views.view.frontpage.yml below:

```
  feed_1:
    display_plugin: feed
    id: feed_1
    display_title: Feed
    position: 2
    display_options:
      sitename_title: true
      path: rss.xml
      displays:
        page_1: page_1
        default: ''

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: Is it possible to create a table from Paragraph fields in Views?
I'm trying to create a table in Views with the information from a node that is using Paragraphs. Somehow I can't find a way to display the values from the paragraph fields in a proper table, is this even possible? All I can manage to do is the table as shown in the picture below:

If possible, how can I create a table where each field has its own column instead? And if that's not possible – what other approach should I use?

# Answer
> 4 votes
You need to enhance your view with Relationships.

Let's say you have a content type *Client* with a paragraphs field *Mail*, which allows embedding instances of the paragraphs bundle *Client\_Mail*. When you create a view on all Client nodes, you should find a Relationship to the field (Mail) which contains your paragraph bundle (Client\_Mail). After adding this relationship, the fields making up the paragraphs bundle will show up in the field list. You can add and arrange them like regular node fields, but make sure that the paragraphs relation is chosen in the field settings.

---
Tags: views, entities
---


# Question
Title: How can I debug Simpletests for a custom module?
I am struggling to debug PHPUnit Tests (with xdebug) in a custom D8 Module from PHPStorm or via the command line. Is it possible to do this?

I'm running an Acquia Bolt generated site on a Drupal-VM Virtual Machine running PHP7 w/ XDebug Enabled. The site is using composer.json as the dependency manager for drupal core as well as all contrib modules. This is just a project for me to test some things, so here's the github repo.

Here is my Test Class

# **Here's what I have tried**

## *Command Line*

I can run my tests from within an ssh session on the VM with the following command:

$ `php core/scripts/run-tests.sh --url http://data.vm --color --verbose --module data_logger`

I have tried to initiate the debug session from the command line with the following:

$ `export XDEBUG_CONFIG="idekey=PHPSTORM remote_enable=1 remote_connect_back=0 remote_mode=req remote_port=9000";
sudo php core/scripts/run-tests.sh --url http://data.vm --color --verbose --module data_logger`

$ `sudo php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=192.168.88.1
-dxdebug.remote_connect_back=0 core/scripts/run-tests.sh --url http://data.vm --color --verbose --module data_logger`

Note, I don't think I shouldn't have to specify any of the xdebug variables on the command line because they are already set but I as grasping at straws...

The tests execute, but the debugger session never seems to start within PHPStorm.

## *PHP Storm*

PHPStorm **Miserably Fails** running my custom module PHPUnit Test.

PHPStorm **SUCCEEDS** running and debugging the Bolt included PHPUnit tests in the `tests/phpunit` folder.

After setting the PHPUnit settings screen to use a remote interpreter and specifying a custom autoloader to the root vendor folder `/var/www/data/vendor/autoload.php`

I right click and choose run/debug on one of the files, and everything works as expected. The debugger starts and we're good to go.

The command that is displayed in the console is:

`sftp://vagrant@192.168.88.88:22/usr/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=192.168.88.1 /home/vagrant/.phpstorm_helpers/phpunit.php --no-configuration Drupal\\Tests\\PHPUnit\\BuildTest /var/www/data/tests/phpunit/BuildTest.php`

The main difference that I see is that these tests extent `TestBase` where as my Test extends `WebTestBase` and the PHPUnit tests at the root level include a phpunit.xml file which I have tried to copy and update to point to the vendor/autoload.php as well but this didn't have any effect.

What I'm confused about is why PHPStorm seems to inherently understand that the `tests/phpunit/*` are PHPUnit tests when I right click on those files but when I right click on my Test class file, I get the option to debug with Javascript or as a PHP Script. Why does PHPStorm not recognize my test class as a PHPUnit test?

Bottom line, how can I debug a custom module test in PHPStorm?

## Additional Context:

I can verify that xdebug is running on the VM as expected:

```
$ php -i | grep xdebug
/etc/php5/cli/conf.d/20-xdebug.ini,
xdebug
xdebug support => enabled
xdebug.auto_trace => Off => Off
xdebug.cli_color => 0 => 0
xdebug.collect_assignments => Off => Off
xdebug.collect_includes => On => On
xdebug.collect_params => 0 => 0
xdebug.collect_return => Off => Off
xdebug.collect_vars => Off => Off
xdebug.coverage_enable => On => On
xdebug.default_enable => On => On
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.extended_info => On => On
xdebug.file_link_format => no value => no value
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.halt_level => 0 => 0
xdebug.idekey => PHPSTORM => PHPSTORM
xdebug.max_nesting_level => 256 => 256
xdebug.max_stack_frames => -1 => -1
xdebug.overload_var_dump => On => On
xdebug.profiler_aggregate => Off => Off
xdebug.profiler_append => Off => Off
xdebug.profiler_enable => Off => Off
xdebug.profiler_enable_trigger => Off => Off
xdebug.profiler_enable_trigger_value => no value => no value
xdebug.profiler_output_dir => /tmp => /tmp
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.remote_addr_header => no value => no value
xdebug.remote_autostart => Off => Off
xdebug.remote_connect_back => On => On
xdebug.remote_cookie_expire_time => 3600 => 3600
xdebug.remote_enable => On => On
xdebug.remote_handler => dbgp => dbgp
xdebug.remote_host => localhost => localhost
xdebug.remote_log => /tmp/xdebug.log => /tmp/xdebug.log
xdebug.remote_mode => req => req
xdebug.remote_port => 9000 => 9000
xdebug.scream => Off => Off
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.show_mem_delta => Off => Off
xdebug.trace_enable_trigger => Off => Off
xdebug.trace_enable_trigger_value => no value => no value
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.trace_output_dir => /tmp => /tmp
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.var_display_max_children => 128 => 128
xdebug.var_display_max_data => 512 => 512
xdebug.var_display_max_depth => 3 => 3

```

I can verify that my test displays and runs as expected at `admin/config/development/testing`.

Note: I can pause the test if I initiate the test through Drupal at `/admin/config/development/testing`. This is not an ideal workflow as it's slow and I'd rather not switch out of the IDE. I would rather initiate the test from within PHPStorm or from the command line.

Here are my PHP, Debug, and PBGp Proxy Settings as well:

# Answer
This plugin for PHPStorm solves the problem perfectly. https://www.previousnext.com.au/blog/native-phpstorm-drupal-test-runner#comment-1588

https://github.com/mglaman/intellij-drupal-run-tests

Alternatively, this plugin led me to the realization that you can also do the same thing with a PHP Script Run/Debug configuration.

Essentially just adding the following in the arguments field: `--php /usr/bin/php --url http://webny.dev --dburl mysql://drupal:drupal@127.0.0.1/drupal --concurrency 1 --module simpletest_example`

obvously changing out for your db settings and module/class/file
> 1 votes

---
Tags: 8, debugging, testing
---


# Question
Title: Is it possible to alter the cacheability of a specific entity either programatically or via configuration
I am writing a custom breadcrumb builder and discovered that the breakpoint I had set in it was not firing due to cache of the breadcrumb entity. When I inspect it after creation, I can see that it is created as permanently cacheable. Ideally, I'd be able to set something in the services.yml file to tell it to ignore that specific entity. Alternatively, if there were a setter that paralleled the getMaxCacheAge() method, that would work.

As it is, it seems like my only good option here to globally switch to the null cache provider.

FWIW, here's my current little snippet of test code:

```
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('TESTING'), '<front>'));
    return $breadcrumb;
  }

```

# Answer
I just came up with a solution, but I'm not sure it's the "right" way to do it.

Anything entity that implements RefinableCacheableDependencyTrait will allow you to introduce additional dependencies with a call to addCacheableDependency(). I sort of hoped there might be a predefined dependency that was hardcoded to no cache. I didn't find such a thing. What I did find is that if the argument to that method is not an object that implements CacheableDependencyInterface, then it makes it uncacheable. So, here's what I ended up with:

```
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('TESTING'), '<front>'));
    $breadcrumb->addCacheableDependency(null);
    return $breadcrumb;
  }

```
> 1 votes

---
Tags: caching
---


# Question
Title: How to create custom forms to filter views results in Drupalgap
I want to build a views page where user searches for a text (without auto-complete) by entering query in a text box and clicking a button on drupalgap, and I want to have flag links on the results On the documentation page of drupalgap views exposed filters, http://docs.drupalgap.org/7/Views/Views\_Exposed\_Filters "building your own forms and constructing own URL parameters" is mentioned but there is no example of that. Is there any example/tutorial of usage like that? Thanks in advance,

Update: This is the function that I define my form:

```
function form_custom_form(form, form_state) {
      try {
        form.elements['name'] = {
          type: 'textfield',
          title: 'Kart No',
          required: true
        };
        form.elements['submit'] = {
          type: 'submit',
          value: 'Ara'
        };
        form.elements['my_markup'] = {
          markup: '<ul id="arac_getir2_view" data-role="listview" class="ui-listview ui-listview-inset ui-corner-all ui-shadow"></ul>'
        };
        return form;
      }
      catch (error) { console.log('my_module_custom_form - ' + error); }
    }

```

This is the code which works:

```
function form_custom_form_submit(form, form_state) {
  form_value = form_state.values['name'];
  form.elements['my_markup'] = {
    markup: '<ul id="arac_getir2_view" data-role="listview" class="ui-listview ui-listview-inset ui-corner-all ui-shadow"></ul>'
  };
  arac_getir2_pageshow();
}
/*catch (error) { console.log('form_custom_form_submit - ' + error); }*/

function arac_getir2_pageshow() {
  var path_to_view = 'arac_getir';
  views_datasource_get_view_result(path_to_view, {
    success: function (data) {
      if (data.nodes.length > 0) {
        var items = [];

        $.each(data.nodes, function(index, object){
          var node = object.node;
          items.push(
            l(node.title, '#') +
            flag_quick_link(
                    'ara_getir', // The flag's machine name.
                    'node', // The entity type.
                    node.nid, // The entity id.
                    parseInt(node.flagged) ? true : false // The current flag status.
                    )
            );
        });
        console.log(items);
        drupalgap_item_list_populate('#arac_getir2_view', items);

      }
    }
  });
}

```

This is the one which does not:

```
  function form_custom_form_submit(form, form_state) {
    form_value = form_state.values['name'];
    arac_getir_page();
  }

  function arac_getir_page() {
    try {
      var content = {};
      content['arac_list'] = {
        theme: 'view',
        format: 'ul',
        format_attributes: {
          /*'data-inset': 'true',*/
          'data-split-icon': 'star' /*the icon to use for the flag button */
        },
        path: 'arac_getir', /* the path to the view in Drupal */
        row_callback: 'arac_getir_list_row',
        empty_callback: 'arac_getir_list_empty',
        attributes: {
          id: 'arac_getir_view',
          'data-filter': 'true',
        }
      };
      return content;
    }
    catch (error) { console.log('arac_getir_page - ' + error); }
  }

  /**
   * The row callback to render a single row.
   */
   function arac_getir_list_row(view, row) {
    try {
      return l(row.title, 'node/' + row.nid) + row.field_kart_no +
      flag_quick_link(
        'ara_getir',
        'node',
        row.nid,
        parseInt(row.flagged) ? true : false
        );
    }
    catch (error) { console.log('arac_getir_list_row - ' + error); }
  }

  /**
   *
   */
   function arac_getir_list_empty(view) {
    try {
      return t('Kart bulunamadı');
    }
    catch (error) { console.log('arac_getir_list_empty - ' + error); }
  }

```

# Answer
> 0 votes
You could first create a custom form: http://docs.drupalgap.org/7/Forms/Creating\_a\_Custom\_Form

Then in its submit handler build a Views Render Array and inject it into a waiting div placeholder element (markup widget) on the form:

http://docs.drupalgap.org/7/Views/Displaying\_a\_View/Views\_Render\_Array http://docs.drupalgap.org/7/Forms/Form\_Elements/Element\_Markup

Or have the submit handler go to a page with arguments: http://docs.drupalgap.org/7/Pages/Page\_Arguments

Then that's page's `page_callback` could build a Views Render Array and use the search string as a contextual filter to the View.

---
Tags: views, javascript
---


# Question
Title: Multiple sites and performance in Drupal 7
I help manage a cluster of sites related to course curriculum. Each site is a separate Drupal 7 install with its own theming, modules, user list, content types, entity structure, and codebase - all of them identical (not shared, but replicated across all the sites). They all run on the **same server** as different Drupal instances. I'm not a huge fan of managing each individual site and its modules, libraries and theming, but this is the setup as I inherited it.

Now we are looking at adding a few sites to the cluster. This is an opportunity to organize differently, and I haven't found any adequate data on which method is better. These are my three choices as I see them.

1. **Multiple Drupal instances** (the way we have it now).
    * Advantages:
        + If code for one instance gets broken, the others will continue to run.
        + Opportunity for separate userlists, taxonomies, etc. (Right now we are not leveraging this, but I suppose we might in the future.)
    * Disadvantages:
        + Every upgrade has to be tested and implemented on all sites individually.
        + Performance hit from running all those instances (cron runs, session variables, caches, etc.)
2. **One Drupal instance running Multisite.**
    * Advantages:
        + One codebase means one set of modules to maintain.
        + One Drupal instance would smooth out the performance issues (maybe?)
    * Disadvantages:
        + Each site still has its own database, requiring separate userlists, taxonomies, etc.
3. **One Drupal instance** with all the content in one place. (This is the way I'd really like to go.)
    * Advantages:
        + Much, much easier to maintain.
        + Performance savings? (**This is what I really want to quantify somehow**)
        + Only one site to upgrade when we finally go to D8...
    * Disadvantages:
        + Lose flexibility among sites' user lists and access levels. (I can get some of this back using taxonomy terms, but for now it's immaterial.)
        + Lose flexibility with content types and structure. (The sites are very nearly identical as it is, and the differences can be smoothed out in development.)
        + If one site gets broken, they're all broken. (Already true to an extent because all the sites are on one server.)
        + Performance hit from all that content being in one database?

What I'm wondering is, what are the performance savings for each option over #1 (the status quo)? Quantitative data is great, but even an explanation of where the savings come from would go a long way.

# Answer
> 2 votes
My recommendation is to go with a multisite.

Multiple Drupal instances and multisite are about the same in terms of performance (multiple databases). One Drupal instance will not scale as well and thus will not perform as well. The database layer is a bottleneck of Drupal that is hard to work around.

You can create custom code for taxonomies to make them shared across all multisites; users can use something like https://www.drupal.org/project/bakery. Doing this for multiple Drupal instances is a little harder to pull off in comparison to a multisite.

To do a shared taxonomy you'll need a new database connection in your settings.php pointing to a new db. This will hold all of your taxonomy\_\* tables; or you can designate one already existing db to be the master record. Then using hook\_taxonomy\_term\_presave() and hook\_taxonomy\_vocabulary\_presave() write the master taxonomy info into the correct db or if it already exists have it use that tid/vid. Then in hook\_taxonomy\_vocabulary\_insert()/hook\_taxonomy\_vocabulary\_update() and hook\_taxonomy\_term\_insert()/hook\_taxonomy\_term\_update() write the taxonomy info to the rest of the databases in your multisite. See taxonomy\_term\_save() and taxonomy\_vocabulary\_save() and use the drupal\_write\_record code to write. Use db\_set\_active() to change database connections. Have all multisites use the same settings.php file (symlink or include), and in there have a big array containing all your database connection info; create a path lookup function that uses conf\_path() and readlink() if needed for knowing what db to connect to. You'll need to migrate all taxonomies before so they all match. This took a little while to code, about 2 weeks. The code I have is for D6 so it wont work for D7.

We used the shared taxonomy on around 80 databases using https://www.drupal.org/project/domain to give us 1300+ domains. It scaled very well.

---
Tags: performance, multi-sites
---


# Question
Title: How can I show parents after child term inside a Views exposed filter?
I have a vocabulary with states and cities, where city are children of state:

I have an exposed filter with depth. How can I show parent term after child? For example, like this:

I'm confused because the array has no relation between parent and child. For example, this is the form array select box:

```
{
#type: "select",
#options: {
0: {
option: {
17: "Aragon"
}
},
1: {
option: {
21: "-Barbastro"
}
},
2: {
option: {
20: "-Calatayud"
}
},
3: {
option: {
19: "-Zaragoza"
}
},
4: {
option: {
16: "Cataluña"
}
},
5: {
option: {
22: "-Barcelona"
}
},
6: {
option: {
24: "-Girona"
}
},
7: {
option: {
23: "-Tarragona"
}
},
8: {
option: {
18: "Valencia"
}
},
9: {
option: {
26: "-Alicante"
}
},
10: {
option: {
27: "-Elche"
}
},
11: {
option: {
25: "-Valencia"
}
},
All: "- Any -"
},
#size: "",
#default_value: "All"
},
```

# Answer
> 2 votes
The exposed taxonomy filter select box form doesn't have any hierarchy built into the select form array (e.g. using subarray to present `optgroup` elements). Rather, its labels are indented to present the hierarchy on each select option.

To alter the labels, you can utilize `hook_form_views_exposed_form_alter()` to alter the selectbox array structure with some string manipulate logic. For example:

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $parent = '';
  $options = $form['tid']['#options'];
  foreach ($options as $index => $option) {
    if (is_object($option)) {
      $label = reset($option->option);
      $key = key($option->option);
      if (substr($label, 0, 1) != '-') {
        $parent = $label;
      }
      else {
        $options[$index]->option[$key] = $options[$index]->option[$key] . " ($parent)";
      }
    }
  }
}

```

---
Tags: 7, views
---


# Question
Title: Add Emoticon at my Simplenews Newsletter's subject
I send newsletters from my Drupal 7 website using Simplenews. What I want is to add emoticons at the subject of the newsletter, like a Smiley or something like this.
Is it possible?

# Answer
> 2 votes
If you're talking text-based emoticon (e.g. ":)", ":D") then the answer is yes. If you're talking Unicode emoji-character based emoticons (e.g. ) then the answer is *maybe*. While Drupal sends out UTF-8 encoded emails, support for *display* of the emoticons depends totally on recepient's email client so your results will vary.

---
Tags: 7, emails
---


# Question
Title: How to avoid showing duplicate content in Views?
I have a View block that displays all of the nodes written by an author on their profile. However, I'm having trouble with Views spitting out duplicate content.

For styling and functionality purposes, all of the fields are being outputted through an extra title field. I simply rewrote the output of the added title field, including tokens for all of my fields. I then set all of the fields (except for the rewritten title field) to "Display None", so that the fields were not duplicated.

Below is a screenshot of my current Views setup.

>

Here is a screenshot of the Views grid on the user profile. Ignore the missing images. I don't have all of the websites images synced to my local environment.

>

I tried using the "Distinct" option in the query settings, which eliminated most of the duplicates. However, Views continues to duplicate random content. Some content will have no duplicates, some content has multiple duplicates.

I've also tried using aggregation, but Views will not output anything when I turn aggregation on. I'd love for aggregation to be the solution, but I can't figure out how to get it to work.

# Answer
Using @CodeNext's advice, I rebuilt my view while monitoring the output on the user profile page. I discovered that the `File: Name` field was causing the duplicates. It never crossed my mind that it would have caused the duplicates. I was using that field to generate a image path for the Pinterest button. To avoid using this field, I downloaded the Image URL Formatter module. It was easy to generate an image path by adding another image field and selecting the URL formatter option.
> 2 votes

# Answer
I have came across this question in past looks like it is same as your Question: Filtered View gives duplicates

Referring that, I came to know you can use Views Distinct.

And you can follow this video tutorial: How To Remove Views Duplicates (Drupal Tutorial).
> 3 votes

# Answer
I see you have 2 content author relationships. You should only need 1 of them. Remove the 1st one, highlighted in blue in your pic.

Now click on `user: content authored`, make sure you have checkmarked ☑ require relationship.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Allow multiple taxonomy term values on term listing page
Is it possible to return results of multiple taxonomy terms on the `taxonomy/term/%tid` page?

For example, `taxonomy/term/203+221` or `taxonomy/term/203/221` should display all nodes with either one of those two terms.

# Answer
I've found the path `taxonomy/term/203+221` (which will yield the nodes tagged with either 203 OR 221) is possible by making a slight change to the Contextual Filter of the taxonomy/term/%tid view (which you should have enabled in Structure \> Views \> Taxonomy Term.

Expand the Advanced section of the view configuration, click on the first Contextual filter "Content: Has taxonomy term ID (with depth)".

You will see a checkbox that allows multiple values, which is checked by default.

However, to get this working I had to scroll further down to the "Specify validation criteria" section and change the "Filter value type" to "Terms separated by a , or +".

Now you should be able to use multiple term IDs in your URL, combined with a "+", to see all nodes tagged with any of the IDs in the list. You can test out various URL arguments using the Views Auto preview:
> 3 votes

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


# Question
Title: Is it possible to post video on Facebook user timeline using Facebook Autopost module?
I need to upload videos to Facebook and I'm using Facebook Autopost and **Rules** module.

I've followed the video tutorials from:

They teach how to post images and text but none mention videos. How can I upload videos with this module?

# Answer
No. Not without building upon it. While the version of the FB PHP SDK (3.2.3) that the module relies on supports uploading video, there is no support for it in the module.

Looking at the current module, it looks possible to build in support. For example, take the scenario where the module supports uploading an image to the user timeline:

Presumably, one could extend another class (e.g. `FBAutopostEntityVideo`) from `FBAutoPostEntity` that would add the various details for base classes that would allow it to plug in to the underlying SDK.

To sum it up, the existing module doesn't support however there's some support at lower levels in the code. That comes with the caveat that there might be more overhead to add (e.g. is there more to defining a Video entity than just extending the `FBAutoPostEntity` class) than what I mentioned here.
> 2 votes

---
Tags: 7, social-network
---


# Question
Title: How to conditionally not load js for anonymous users?
We have a situation where our contrib modules are being loaded for the anonymous user, but they are not needed. As a result, we are seeing higher page load times. We tried using `hook_js_alter` in a custom module with the code below. What is the proper way to not load the js files we don't need for the anonymous user?

```
mymodule_js_alter($javascript) {

  $javascript['somefile']['weight']=50;
  $javascript['somefile']['scope']=bottom; //region for bottom of the page

}

```

Current code:

```
function mymodule_js_alter(&$javascript) {

    if(user_is_anonymous()){
       unset($javascript['sites/all/modules/contrib/autocomplete/autocomplete.js']);
     }
 }

```

# Answer
If you don't want to load your JS in anonymous user, check the user if its logged in then load the JS file if its true. use user\_is\_logged\_in() to check if user is logged in, place it inside your hook\_preprocess\_page().

Example:

```
  $theme_path = drupal_get_path('theme', 'zen');
  // This will load only in authenticated user.
  if(user_is_logged_in()) {
    drupal_add_js($theme_path . '/plugins/jQuery/jquery-2.2.3.min.js');
  }

```
> 2 votes

# Answer
You can use it like:

```
/**
 * Implements hook_js_alter().
*/
function hook_js_alter(&$javascript) {
// Removes the js for anonymous users.
  if(user_is_anonymous()) {
    unset($javascript['sites/all/theme/js/file.js']);
  }
}

```
> 1 votes

---
Tags: 7, theming, hooks
---


# Question
Title: Migrate content types and contents from old drupal version to drupal 8
I'm working on a new drupal 8 website.
I have already a drupal 7 installation with severals content type (custom field image, date etc ...) and i dont know what is the best pratice to migrate thoses contents types to my new drupal 8 installation..
**Does someone know how to do that properly ?**
Regards.

# Answer
Take a look at this one, it pretty simple to migrate content types, fields, terms, users using below module: https://drupalize.me/blog/201511/simple-drupal-7-drupal-8-migration

And this module does all the work: https://www.drupal.org/project/migrate\_upgrade
> 2 votes

---
Tags: migrations
---


# Question
Title: How to use linkit package after uplaoding file with filedepot package?
I am using File Depot to upload files.

What I want to do is to upload some images into the filedepot folders and then make a link to that files in my posts/pages/book pages/etc. Is it possible ?

What would be even better is to be able to find the files using LinkIt. Is that possible ?

# Answer
this is an older thread, but maybe Linkit Upload is a nice solution for this problem. With that module enabled you can upload files directly from the Linkit popup.
> 0 votes

---
Tags: navigation, files
---


# Question
Title: Configure page title block for contact form pages only
I want the page title block to display on the contact form pages, because the nodes have their titles in their display.

It seems for a form you can't add the title to the form display, thus leaving me with the option to display it via the page title core block.

What I've tried as configuration for the block under **visibility**:

* *Contact form bundle*: none selected (= for me, assuming: **all**)

* *Custom menu link bundle*: Negate the condition (= for me, assuming: **none**)
* *Content type*: Negate the condition (= for me, assuming: **none**)
* *Redirect type*: Negate the condition (= for me, assuming: **none**)
* All other configurations -\> untouched (= for me, assuming: **all**)

But, **the page title is never being displayed.** Only when I deselect *everything* I see my page title... but I only need it on some pages.

*Summarized, I want to **only display** the page title on specific pages, in a structural way (which means: no CSS hack)*

# Answer
You only need to select the Contact form bundles you want to display the page title on. Leave anything else untouched.
> 1 votes

# Answer
What about doing it in hook\_from\_alter()? Something like this should work, but I think this will screw with the login block as well, something to watch out for:

```
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_form';
    case 'user_register_form';
    case 'user_pass';
      $request = \Drupal::request();
      $route_match = \Drupal::routeMatch();
      $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
      $form['title'] = array(
        '#theme' => 'page_title',
        '#title' => $title,
        '#weight' => -1000,
      );
    break;
  }
}

```

Problem is of course the title is below the tabs.
> 0 votes

---
Tags: 8, blocks, emails
---


# Question
Title: How to specify PHP block visibility settings for content types AND loads of urls?
I wrote lately some instruction to display a block in two different cases:

* when the content type is \[my-content-1\] or \[my-content-2\]
* when the url is /my\_page1 or /my\_page2

I found how to do it in Block visible for Specific Content Type AND Specific URL.

```
<?php
$match = FALSE;
$types = array('content-petites_annonces' => 1);
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type])) {
    $match = TRUE;
  }
}

if (substr($_SERVER["REQUEST_URI"], 0, 10) == '/petitesan')
{ $match = TRUE;}

if (substr($_SERVER["REQUEST_URI"], 0) == "/node/add/content-petites_annonces
")
{ $match = TRUE;}

return $match;
?>

```

It works fine, I could declare several content types in the first array (I've got 6).
But as for the urls, it only works if I repeat the same line every time (and there are loads of them).

```
if (substr($_SERVER["REQUEST_URI"], 0) == "/my_page1
        ")
    { $match = TRUE;}
if (substr($_SERVER["REQUEST_URI"], 0) == "/my_page2
    ")
    { $match = TRUE;}
...

```

I am certain there is a more mutualized way to do it.
Is there also a mean to get it working regardless of the pagination, i.e. whithout having to notify every time

```
 if (substr($_SERVER["REQUEST_URI"], 0) == "/my_page?page=X
            ")
            { $match = TRUE;}

```

Is the answer hidden in the 0, 10 in the precision about the request URI? I didn't even used that line.

# Answer
> 3 votes
This sounds like the perfect use case for something like the Context module. Contexts are triggered and become active, and would save you from writing tons of PHP to get the matching to work in an unlimited number of use cases and edge cases.

> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

Related modules

# Answer
> 1 votes
There is another way to answer your question, ***without PHP in the block settings***: you can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the appropriate menu block is shown on the appropriate pages). And combine this with a check in such rule for your specific content types.

For an illustration of how to use this module, refer to my answer to "How to show blocks by url, when nodes have multiple paths?". It includes some Rules Components (in Rules export format), which you should replace by your variations to make it match your specific question.

To actually "*determine the path structure in rules*" (as in your extra comment below this answer), you might want to use a Rules Condition using a regular expression. Similar to the Rules Condition in the rule I included in my answer to "How to automatically skip intermediate redirects?".

Using regular expressions opens up many more situations (on top of the Rules block visibility module) where this solution can work. If you're not familiar with Regular Expressions (not obvious ...), then maybe you also want to look at my answer to "How to suppress a core Drupal warning or error message set with drupal\_set\_message for site users?".

### Bonus:

This approach ***does NOT require the PHP filter to be enabled*** either (which you should try to avoid whenever possible) ...

---
Tags: 7, blocks
---


title: Display additional fields in the Inbox?

text:
# Question
Title: Display additional fields in the Inbox?
I have added two new fields (a Viewfield and a simple text field), and I would like to display these fields in the Inbox (`/messages`) along with the existing Subject, Participants, and Last Updated data. How can I add those fields to that page ? Is there a tpl format I could use ?

# Answer
```
/**
 * Implements hook_form_alter().
 */
function modulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_list') {
    $form['updated']['list']['#header']['bar_column_field']['data'] = 'Bar Column';
    $form['updated']['list']['#header']['bar_column_field']['field'] = 'bar_column_field';
    $form['updated']['list']['#header']['bar_column_field']['class'][] = 'privatemsg-header-bar-column';
    $form['updated']['list']['#pre_render'][] = '_pre_render_bar_column';
  }

/**
 * Custom #pre_render function.
 */
function _pre_render_bar_column($tableselect) {
  $i = 0;
  foreach ($tableselect['#options'] as $id => $options) {
    $data = 'Bar data in the table ' . $i++ . '';
    $tableselect['#options'][$id]['bar_column_field'] = array('data' => $data, 'class' => array('privatemsg-list-bar'));
  }
  return $tableselect;
}

```

You can change the `$data` variable with any field's value, after performing a query or something, and placing your actual data to the new column. A field could be attached to messaging (`admin/config/messaging/privatemsg/fields`) or to any other available entity.
> 1 votes

---
Tags: privatemsg
---


# Question
Title: How can I use drupal_static() to save an element in an associative array?
I'm making repeated calls to a few related object instances, and I need to cache them in memory.

If I have an array of objects, like:

```
array('object_a' => $obj_a, 'object_b' => $obj_b);

```

I want to do something like:

```
$obj_a = getmyobj('object_a');

```

Where the object is created if it doesn't exist in memory already.

# Answer
You can use drupal\_static to store an array of object.

You can then define a method, lets call it 'getmyobj', to get your data like this :

```
function getmyobj($obj_name) {
  $objects = &drupal_static(__FUNCTION__);

  if (! isset ($objects[$obj_name])) {
    // Here you load your obejct
    $objects[$obj_name] = method_to_load_your_object($obj_name);
  }
  return $objects[$obj_name];
}

```

Then you will be able to get you object with the above code :

```
$obj_a = getmyobj('object_a');

```
> 1 votes

---
Tags: 7
---


# Question
Title: Regions not showing in block region demonstration
My regions are not showing anymore in my block regions demonstration. However they are showing in my block layout.

The regions also not display on the pages. I don't know what I did wrong. I checked the .info.yml, libraries.yml and .theme but nothing helped. I cleared the cache and still it wouldn't display.

What I did:

* Cleared the cache
* Checked info.yml
* Checked .theme
* Checked .libraries.yml
* Added blocks to the regions in question

# Answer
> 1 votes
1. Check in the drupal backend and with devel or kint if your regions / blocks exist.
2. Remove the blocks in the drupal backend.
3. Add the blocks again.
4. Clear the cache.

# Answer
> 1 votes
It's pretty hard to troubleshoot, but I would really recommend looking at the .theme file again. It sounds like the region is not configured/configured incorrectly there. Maybe post that here?

---
Tags: theming, 8
---


# Question
Title: How to create twig files content type specific in Drupal8?
I have created a content type in Drupal 8. How should I write content type specific twig file?

# Answer
you can use this file for specific content type "node--{content type machine name}.html.twig". Please check this url for Twig Template naming conventions.
> 5 votes

---
Tags: theming, 8
---


title: sharethis module in drupal

text:
# Question
Title: sharethis module in drupal
I am using Share this module in Drupal . In that when we click on Facebook, Linkedin the image is also inserted and linked to that social site but when we click on twitter,no image is pulled in.Kindly help me with this

# Answer
> 0 votes
Check out Twitter validator tool for possible reason. The Twitter specification may help you as well.

---
Tags: social-network
---


# Question
Title: How to create multiple slideshows on my front page?
I am new to Drupal and I don't know how can I create multiple slideshows on my front page.

I am developing an image sharing website where users will upload their images. I want that when a user adds a gallery a slideshow is made on the front page. Like if I have four users means I will give four different slideshows on the front page.

Any help?

# Answer
> 2 votes
I would recommend using Views Slideshow as it is a very easy to install and configurable module if you are used to using Views in Drupal.

All you would have to do then is intwine your logic, looping through users and their associated uploaded images and place the block on your front page.

Here is a tutorial for drupal 8 and drupal 7 using views slideshow:

I hope this helps.

# Answer
> 1 votes
There are two possibilities from here, you can either

1. Use a jquery pluggin for beautiful sliders and add back-end functionality to it (use display suite module). I'd suggest Owl Carousel, Google it, Learn it, Use it. It's very simple.
2. Use the Colorbox module. It's not as beautiful as #1, but it's extremely simple, easy to use, clean and to the point. It can automatic create slider of gallery of pictures your users will upload on your site.

Plus: Best thing about these options is that, they are very light-weight and there is almost no performance loss. I use them in half dozens of my site. However the only negative factor might be: they don't require any coding, however you can use them the way you want.

Update: If you use bootstrap (which you probably do, I mean who doesn't use BS), then there is nothing easier and simpler than Bootstrap Carousel.

# Answer
> 0 votes
This sounds like a bad idea. Slideshows add quite an amount of javascript to a page and having a lot of them on the page will mean that your page will be slower to load than you might like.

If you want to do this, what you'll need to do is create an image field (probably on a content type called "Gallery" or something) that allows people to upload multiple images.

After this, install the flexslider module (or some other slideshow module - flexslider is very popular and fairly easy to use). Then on the "Manage Display" page for this content type, set the field formatter to flexslider. You can configure the flexslider settings on the flexslider configuration page under `/admin/config/media/flexslider`

You will then need to use Views to list the nodes that have this image field and place that view on the front page (as a block or by making a views page and setting that to the front page).

Without knowing more about your exact requirements, I can't give you an exact solution, but the above should will get you started.

In short, you need: \- An multivalue image field \- Flexslider module (and library) \- Views

# Answer
> 0 votes
Maybe this module could be useful for you : Field Slideshow

It will provide a new Field formatter for an Image field (display) and you will have your slideshow each time someone enters values for that Image field.

Another module that could be useful for users : Multiupload Imagefield Widget

It will provide a new Field Widget for an Image field (form) and you will be able to upload multiple images at once, selecting them directly on your computer. It saves time but watch yout maximum upload size settings.

Finally, you will need Views to create a Users view displaying the Image field. To avoid the 1000 users as it was noticed, I suggest you display only the last 4 or 5 users. This view could thus be displayed on your frontpage, directly (replace the default front) or through Panels if you need to add someting else around this View. CSS to design everything and you're good.

Hope this helps.

---
Tags: views
---


title: Change link within block

text:
# Question
Title: Change link within block
http://www.ascoworld.com/services

On the above page, there is a block with three icons that links to the wrong pages. I want to change where they link to but can't seem to find out how. Apologies, but I am as new as can be at this. I didn't create the website and have never used Drupal before, I just got passed it and told to fix these issues.

Thanks!

# Answer
The page layout is broken but I assume that you are talking about **Services** menu block. Based on the HTML source it is a menu block and a main menu to be specific. So to the change the link go to `Structure > Menus > Main Menu` and change the link path there.

**UPDATE:**

Since the page is broken in my end my above answer is wrong. As @iamroald comment it is created via Views. Go to `Structure > Views > Services`. It seems like there is a `Token` substitution in there.
> 0 votes

# Answer
**Updated Answer**:

The views block content is created in node, node type `service group`. so if you wanted to change the link you can update the alias pattern here `/admin/config/search/path/patterns`.

or manually update it here `admin/config/search/path`
> 0 votes

# Answer
The Link is coming from the content path field that means node link. If you need to add custom link. you need to create a field in service group content type. Then edit all the contents of type "service group" and add your link there. After that add that field in your view and delete content path field from view.
> 0 votes

---
Tags: navigation
---


# Question
Title: Get a notification if a new version (tag) is created
Before there was a RSS fead that got update if a new release of drush is available, see question: Getting an email notification when a new Drush version is available.

But after drush is moved to github it seems that the RSS feed does not get updated anymore.

Is there a possibility to get an email notification if a new release tag is created on the github site?

# Answer
Not directly through Github, but check https://sibbell.com

It's notifies you of new Github releases.
> 0 votes

# Answer
Doesn't the standard release feed work for Drush?

https://github.com/drush-ops/drush/releases.atom

Anyway, this questions isn't really about Drush, but about Github and the feeds they provide. I suspect somebody will close this question ;-)

Added: Looking closely at the question, I see that what is requested is an email notification. Then probably the other answer is better. My bad.
> 0 votes

---
Tags: drush, updating, notifications
---


# Question
Title: How to perform a Database API Inner query
I have this Database API code, and I'm trying to add a sub-query to it:

```
$query = db_select('' . $base_table . '', 'n')
      ->extend('PagerDefault');
      ->extend('TableSort');

```

to turn this:

```
SELECT
FROM
taxonomy_term_data n
ORDER BY n.tid ASC

```

Into this:

```
SELECT
FROM
(SELECT * taxonomy_term_data LIMIT 10) n
ORDER BY n.tid ASC

```

I've tried passing a db\_select statement into another db\_select statement. I've tried query-\>addExpression() and db\_query() to no avail.

# Answer
You Can refer to this link

However you can try like below

```
$query->condition('<condition>', $subquery);

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Adding a jQuery interaction with Views Accordion
I have a Views Accordion displaying some books under their categories. I want to add some jQuery interaction, so when the user clicks the triangle of each category, the content will be loaded via jQuery AJAX. How can I include this functionality? Something like this, though I cannot see any ID identifier associated with the href which opens / closes each of the accordion bellows.

```
 function mymodule_views_pre_render(&$view) {
     if($view->name == "categorias"){
         drupal_add_js('jQuery(function() {
             jQuery("#categorias-page-0").click(function(e) {
              // ... AJAX stuff
              });
         });', 'inline');
     } // if
 } // function

```

Show image below, what I have, and when clicking on each category I would like to perform whatever jQuery actions I'd like.

# Answer
You have to use `$(this)` with out working on id/class.

Refer to this link jQuery $(this) Selector with Examples.
> 2 votes

# Answer
Using suggestions by #Nagarjuna , I have updated the code so I can retrieve the internal ID of the accordion bellow. The only problem is that the numbers 0, 1, etc., are just a numbering, but using the same SORTING than the Views Query, they should match perfectly when accesing the content via AJAX.

```
 function mymodule_views_pre_render(&$view) {
   if($view->name == "categorias"){
     drupal_add_js('jQuery(document).ready(function () { jQuery(function () {
       jQuery(\'a[href ^= "\' + "#categorias-page-" + \'"]\').each(function() {
            jQuery(this).click(function(){
              var clickado = (this + "");
              var categoria = clickado.split("-");
              alert(categoria[categoria.length - 1]);
            });
        });
    }); }(jQuery));', 'inline');
 } // if
} // function

```
> 2 votes

---
Tags: 7, views, javascript, ajax, navigation
---


# Question
Title: When to use a preprocess function instead of changing the template
I am using drupal 7.

I have one query that when to use a preprocess function instead of changing the template files?

# Answer
From the docs

> The main role of the preprocessors is to set up variables to be placed within the template (.tpl.php) files.

And building on that:

> There can be numerous preprocessors for each theming hook. Every layer from core, modules, engines and themes can have one, each progressively building upon the variables before being rendered through template files. This keeps the markup clean and easy to work with inside templates by placing most of the logic inside these preprocessors.

So if you're setting up a variable that you want to be rendered in a template, your code will go in a preprocess function.

When it's time to render the variables that have been set up, wrap them in specific markup and so on, you'll be editing template files.
> 6 votes

---
Tags: theming
---


# Question
Title: How to create an Atom RSS feed with site's content type?
I have a content type named "blog" of drupal 7 website. How to create Atom RSS feed with site's blog?

# Answer
You can use Views \+ Views Atom to create XML feeds.
> 1 votes

---
Tags: 7, feeds
---


# Question
Title: How to add a "Remove Taxonomy term" option to VBO instead of only "Add taxonomy term"?
In Drupal 6 VBO I had an option to check if I want to add, remove term for example

In drupal 7 view I can just add it (check the box) and not remove it for some reason, what am I missing

I am attaching a screenshot from Drupal 6 where I could add, remove, even replace terms, how to do it in D7 is the question

# Answer
You could try to perform a bulk operation using logic expressed in a Rules Component. More details below ...

VBO comes, out of the box, with some predefined (hardcoded) operations that is to be applied to each row selected in the view. The available operations are shown within "Selected bulk operations" when configuring the VBO field. In your case "Add the selected terms" seems to be one of those. While something like "Remove the selected terms" (as per your question) is not included.

However using Rules (Conditions and/or Actions) you might probably get it to work, i.e. by execute a VBO operation which you define using a Rules Component. To get the idea, have a look at the video about Using Rules components with VBO" uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video. This video actually shows how to (also) add a term to a node, so it should be pretty forward to use a similar technique, and perform a *remove* instead of an *add* of a term.

Note: to process 100.000 nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to put the widget to rate nodes in a view next to title?
I have a view with the list of nodes, how can I put the widget to rate the nodes next to title?

**Note**: I'm already using the Rate module. But it returns me only the results.

# Answer
> 5 votes
Since you're using the Rate module, you should configure Views as shown in this image:

So what you need to do, is to configure the field "`Votes:Value`". As you can see in my image above, within the ***Appearance*** Dropdown I selected `Rate Widget (compact)`. if you only have "*Rate Widget option or Default*" (as in your comment, it's probably because you have not yet added the required *Relationships* to your view.

Relationships is a way to join tables from another module. To get you going with this also, have a look at the next image:

Some more details about the 3 (numbered) annotations I added in this image:

1. That's where you add the Relationship, in this case you need to select `Content:Votes`.
2. After you added that relationship, within ***Fields*** you can now add a new field `Votes:Value` (that is: because of the relationship that was added, you'll be able to select this specific field from the list of available fields when you try to add an extra field).
3. After you completed the previous step, automagically in the preview area you'll see a preview of the views results you'll get (don't bother too much about the theming of that preview at this time, what counts is that the result is correct).

---
Tags: views, rating
---


# Question
Title: Is it possible to insert a value in field using Rules?
How can I insert data in database using Rules?

I created entity type ***Job*** and added some fields. I want to insert values inside those fields when the flag button is clicked. I tried "`set a data value`" but I think it will work if I already have an existing field and value.

I also tried to use "`add variable`" in my Rules Action and set value on it. My question is how can I validate if it's working?

PS: I tried to look the data inside my database but I can't see it.

# Answer
Before you will be able to create a Rules Action like "Set a data value" for your field, you have to make sure to add a Rules condition `Entity has field` (related to the field for which you want to set a value). And make sure to add that `Entity has field` condition BEFORE other Rules Conditions in which you might want to refer to this field (if you have any such conditions in your rule).

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

And to validate if your rule is working, just add a "Set a message" (within System) as your very first Rules Action, to display the actual value (using an appropriate token for your field), after your executed your rule (and re-execute it). If that doesn't work (or help), use Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".
> 1 votes

---
Tags: 7, entities, rules
---


title: Problem with installing a module

text:
# Question
Title: Problem with installing a module
I need to import a new config without some files because when I try to install the profile module it says that `profile.type.main`, `system.action.profile_delete_action`, `system.action.profile_publish_action`, `system.action.profile_unpublish_action` already exists in the current config and this doesn't allow me to install that module

# Answer
> 2 votes
You can use Drupal console commands to delete the existings configs. New install will only be possible when the existing configs are deleted. use Drupal config:delete active profile.type.main

If you dont have drupal console installed then deleting the configs from db is other work around for this issue.

Go to the config db table and delete the configs which are existing.

Thank you

---
Tags: drush
---


title: Add an imagestyle to a template twig

text:
# Question
Title: Add an imagestyle to a template twig
Im using the Aegan theme, and it uses it's own slideshow. Now I'd like it to use a specific image style, that formats the images according to my presets.

The code in the page.html.twig looks like this

```
{# Include a slider. #}
  {% if slider %}
    <div class="flexslider">
      <ul class="slides">
        {% for slide in slider %}
          <li>
            <a href="{{ slide.url }}"><img src="{{ slide.src }}" alt="{{ slide.name }}"></a>
            {% if slide.description %}
              <p class="flex-caption">{{ slide.description | raw }}</p>
            {% endif %}
          </li>
        {% endfor %}
  </ul>
</div>{% endif %}

```

The style is called aegan\_slide (don't really know where I can find it. But how do I apply my custom style to this code?

# Answer
If you don't use sub themes of Aegan, you need edit file **aegan.theme**

Add more use class at top:

```
use Drupal\image\Entity\ImageStyle;

```

Replace code line 53-\>73

```
if ($slideshow_path && $show_slideshow) {
    $vars['slider'] = array();
    for ($i = 1; $i <= theme_get_setting('slideshow_count', 'aegan'); $i++) {
      $fid = theme_get_setting("slide_image_{$i}", "aegan");
      if (!empty($fid)) {
        $file = \Drupal\file\Entity\File::load($fid[0]);
        $uri = $file->getFileUri();
        $image_path = file_create_url($uri);
      }
      else {
        $image_path = THEME_PATH . "/images/slide-{$i}.jpg";
      }
      $vars['slider'][] = array(
        'name' => !empty($fid) ? $file->getFilename() : "slider-{$i}",
        'url' => theme_get_setting("slide_url_{$i}", "aegan"),
        'src' => $image_path,
        'description' => theme_get_setting("slide_description_{$i}", "aegan"),
      );
    }
  }

```

with

```
if ($slideshow_path && $show_slideshow) {
    $vars['slider'] = array();
    //replace large with image style you want
    $image_style = 'large';
    $image = ImageStyle::load($image_style);
    for ($i = 1; $i <= theme_get_setting('slideshow_count', 'aegan'); $i++) {
      $fid = theme_get_setting("slide_image_{$i}", "aegan");
      if (!empty($fid)) {
        $file = \Drupal\file\Entity\File::load($fid[0]);
        $uri = $file->getFileUri();
        $image_path = $image->buildUrl($uri);
      }
      else {
        $image_path = THEME_PATH . "/images/slide-{$i}.jpg";
      }
      $vars['slider'][] = array(
        'name' => !empty($fid) ? $file->getFilename() : "slider-{$i}",
        'url' => theme_get_setting("slide_url_{$i}", "aegan"),
        'src' => $image_path,
        'description' => theme_get_setting("slide_description_{$i}", "aegan"),
      );
    }
  }

```
> 0 votes

---
Tags: 8, media
---


# Question
Title: How can I create a custom landing page for a specific taxonomy term?
How would I be able to have a customisable page where in it will be a landing page for special taxonomy terms and will display the related articles of a specific taxonomy term.

For instance, `mywebsite.com/myspecialtaxonomyterm` will display a PAGE, wherein a list of articles related to the tag **myspecialtaxonomyterm** is displayed, beside it is a custom widget as the sidebar and on top of it is a custom block which may contain videos or banner image. Can this be done by the Views module alone or should I create a module for this to be done?

NOTE: This page will be set to be the landing page of a specific tag, based on my example above. I am really confused on how to approach this.

# Answer
> 0 votes
To display only node content with a specific taxonomy term checked, add `Content: Has taxonomy term` to the Filter Criteria of your view. Once you add the filter, you will be prompted to select your taxonomy term vocabulary as well as the term you wish to filter your view by. Once completed, you will only see content associated with the desired term.

If you're using Panels, as your post's tags indicate, you can create your landing page using Pages (comes with panels). Make sure the view you create is a block, not a page, and it will be easy to plug into any panel.

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


title: Entity field value

text:
# Question
Title: Entity field value
I have been creating some custom entities to Drupal 8 and they pretty much work as expected but a small thing of getting any value of a field.

Lets say I have basefielddefinition like this:

```
$fields['level'] = BaseFieldDefinition::create('integer')->setLabel(t('Level'))
      ->setDescription(t('Level of the event.'))
      ->setSettings(array(
        'max_length' => 10,
        'text_processing' => 0,
      ))
      ->setDefaultValue(1);

```

It works as expected and the field I have in SQL looks pretty much like this:

`level` int(11) DEFAULT NULL,

But I seem to be unable to get the value of the field itself with any logical operation.

If I try this (in member method) `$this->get('level')->value` I get a String no matter what is the type of the field. Is there an actual way to get the data in correct type or do I need to start creating a huge typecast device somewhere here?

I tried going a lot deeper with the `TypedDataInterface` but could not find a correct way to get the typed data from there. Also if it is somehow doable there I would really like to point out that, for me at least coming from strongly typed languages, it would seem to logically be the first thing one wants to do, not something that needs to be accessed trough a huge load of different methods. Also isn't that what PDO is for, getting rightly typed data from the SQL in the first place?

# Answer
```
$this->get('level')->get('value')->getCastedValue();

```

This works for integer, float and other numeric typed data. I think the majority use case is going to get output as a string anyway, which is why `$this->get('level')->get('value')->getValue()` is generically a string.

Content entity storage does not do any type casting to strings when it maps from the result set, and Typed Data should not be doing this either. The PDO MySQL driver (using mysqlnd) should set the type in PHP (and so should the PostgreSQL driver). You may need to check how PDO is behaving with respect to your database system.

**Update**

Note that that the default TypedDataNormalizer does not normalize into a casted value, but uses `PrimitiveBase::getValue` instead. It would probably be possible to target IntegerInterface in a custom normalizer to call getCastedValue, but I haven't tried that.

**Update 2**

`$this->get('level')->getValue()` would return the array of the field item. I should be \`$this-\>get('level')-\>get('value'), and that should be IntegerData.
> 0 votes

---
Tags: entities, 8
---


# Question
Title: Contextual filters not allowing multiple values
I'm using Drupal 7 and Views 7.x-3.8. I have a taxonomy term "A" which is related with another taxonomy term "B". I want to retrieve a list of "A", but filtered by those "B" that are present in the URL as query parameters. There can be more than one "B" in the URL.

So I've created a contextual filter with PHP code that finds all "B" IDs in the URL and ends up with something like: "return $B1+$B2+$B3...;". Of course, I've checked the *Allow multiple values* option.

If I pass only one value (e.g. `return "15";`), the query runs OK and it brings me all "A" related with the B with ID 15, but if I pass two or more values (e.g. `return "15+20";`), I get a *No query was run* message, and nothing in the view.

Is this bug for the Views module? I've also tried to replace the PHP code with a simple `return "15+20";` in order to simplify the test case, but I get the same error.

# Answer
> 3 votes
I don't know if this would answer your questions, but I just noticed that, not only you need to check "**Allow multiple values**", you also need to specify "**Term IDs separated by , or +**" in the "Filter value type" select list.

(using Views 7.x-3.14 at the moment)

# Answer
> 1 votes
This has been here for quite a while but since it is unanswered here is what I've done for similar cases.

First of all, let it be clear that you cannot return more than one value with PHP contextual filter in views. I haven't seen any module or method that allows this. If anyone has please provide it!

You can however supply the values you get with that PHP code to a views block setup with contextual filter. This way you can use those values as a contextual filter considering that your drupal installation has the PHP filter module enabled.

With that and having your contextual filter setup allowing multiple values you would be good to go. If you use validation criteria remember to setup filter value type properly.

The values must be included as a string in the form of "a,b,c,d" for AND or "a+b+c+d" for OR where a, b, c and d are values obtained through that PHP code.

So lets say you have declared $values to contain your values. You would call your views block within a page or block and, using PHP filter to write your output, input the following:

```
<?php $values = ''; ?>
<?php /** code to get your values in the form of 'a,b,c,d' or 'a+b+c+d' **/ ?>
<?php print views_embed_view('my_view_machine_name', 'my_block_machine_name', $values); ?>

```

I've successfully used this with over 800 ID's in the string. If by any chance you get errors it could be your server's setup as it currently happens on my dev machine.

---
Tags: views
---


# Question
Title: Views: Aggregations Do Not Group by a Date Field
So, I am using Drupal 7.19 and Views 3.5. For some reason, I can not group by a date field no matter what!

I created a simple view that displays the number of nodes that have been published per month. As such, I selected the `Nid` and `Post date` fields, enable aggregation, count on `Nid` and group on `Post date`.

No grouping. There is a record being pulled for every single node in the database, as if the grouping is being completely ignored.

If you run the SQL statement Views generates on the database, you also get a complete result set but that is obviously because the UNIX time stamps themselves are different, if even my a second. That's expected. How can I get Views to group by a formatted value, such as a Month, Year, etc, to avoid this problem?

I tried everything suggested here and elsewhere - I already had the `RDF` module disabled, emptied cache, added a new date format, strip white space from the date field ,I even disabled the `Date` module for fear it was conflicting with it.

This is driving me absolutely crazy! Would appreciate any suggestions. Thanks.

# Answer
You cannot group on fields which are not equal. The post date is a datetime field in unix time format (number of seconds since 1/1/1970). Unless you have several nodes created at exactly the same moment in time, you will not be able to group on this field.

You are going to have to group on a derivative. Look at the way the standard Archive view does it. The query is

```
SELECT DATE_FORMAT((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL -14400 SECOND), '%Y%m') AS created_year_month, COUNT(node.nid) AS num_records
FROM
{node} node
WHERE (( (node.status = '1') ))
GROUP BY created_year_month
ORDER BY created_year_month DESC
LIMIT 30 OFFSET 0

```

This puts the created date in the form YYYYMM. You are going to have to rewrite the field and group on the rewritten results. That way you are only dealing with the year and month portions of the date.

The archive view does this with a pre-defined 'bogus field' called created\_year\_month. This field is available as an argument (only) because it is defined as such in the default views handlers.

To achieve a similar result in your own view, you can either clone the Archive view and try to alter it for your purposes, or you are going to have to write your own 'field' handlers to expose the field in its desired format for your view. Another option is to use the Views Date Format SQL module, which does exactly this.
> 2 votes

# Answer
To group on a date field just copy the contextual filter from the default archive view. No need for aggregation to be turned on. Settings shown in pic:
> 3 votes

# Answer
I've just stumbled across this problem myself: not being able to group on the 'Posted Date' field. I simply created another date field, used granularity of day then this automatically collects the published date as nodes are created without touching it. Everything working fine now..
> 0 votes

# Answer
If you are using aggregation and want to sort in order of when a node was created, just sort by node id. Each time a new node in drupal is created it alway increments up using the last node created. It does not matter if a previous node was deleted, whatever the last node id... drupal will add 1.
> 0 votes

---
Tags: 7, views
---