# Question
Title: How to check for entity access when displaying views fields?
I have a custom entity. There is an access callback defined in `hook_entity_info()` and it is called when I access the entity. Also in views when I select to display rendered entities, the entity is only shown when the user is allowed to see the entity.

However when I change the view to show 'fields' instead of 'rendered entities', the access callback is no longer called and users can see all fields (and properties) of the entity, regardless of any permissions. Looking at the executed query this makes sense, the field values are joined in and the entity is never really loaded.

So, how should one implement entity access for views when displaying fields (in Drupal 7)?

I've found How to check for entity type in Views when using hook\_field\_access?, but I assume that only works for joined fields and not for base entity properties, so that would be only a part of a solution.

# Answer
> 1 votes
In the end I've managed to find a working method which works in a similar way as the views does with nodes.

In `hook_views_data()` (or `hook_views_data_alter()`), make sure to add the `access query tag` table key. You can see Views does this for nodes as well in `node_views_data()`.

```
$data['example_table']['table']['base'] = array(
  'field' => 'nid', // This is the identifier field for the view.
  'title' => t('Example table'),
  'help' => t('Example table contains example content and can be related to nodes.'),
  'weight' => -10,

  'access query tag' => 'my_entity_access' // <- Add this.
);

```

Then add your own implementation of `hook_query_TAG_alter`. This will alter every query where this tag is added. Because of our above alteration this will be automatically applied to all Views data listings, but the tag can also be added manually.

There are some great tricks in `_node_query_node_access_alter()` called from node\_query\_node\_access\_alter() (node modules implementation of hook\_query\_TAG\_alter).

```
function mymodule_query_my_entity_access_alter(QueryAlterableInterface $query) {
  global $user;

  // Read meta-data from query, if provided.
  if (!$account = $query->getMetaData('account')) {
    $account = $user;
  }
  if (!$op = $query->getMetaData('op')) {
    $op = 'view';
  }

  // From here every query will be different depending on your own needs.
  // Since my entity has a privacy parameter that is either public or private,
  // I chose to implement this as follows:

  // Prepare a database OR.
  $or = db_or();

  // If the user has public view permissions, add it to the OR.
  if (user_access('view public my_entities', $account)) {
    $or->condition('example_table.privacy', 'public');
  }

  // If the user has non-public view permissions, add it to the OR.
  if (user_access('view private my_entities', $account)) {
    $or->condition('example_table.privacy', 'public', '<>');
  }

  // Add the compiled set of rules to the query.
  $query->condition($or);
}

```

# Answer
> 7 votes
Presuming your entity providing module has Views integration already setup, and **you're not worried about pagination**, you can invoke `hook_views_pre_render()` to iterate over the results and invoke your access callback for each entity in your base table and filter out entries that the user doesn't have access to:

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  global $user;

  // Iterate over View results for our custom entity
  if ($view->base_table == 'my_entity_base_table') {
    foreach ($view->result as $index => $row) {

      // Presuming eid is the entity PK
      $results = entity_load('my_entity_machine_name', array($row->eid));
      if (!empty($results)) {
        $entity = $results[$row->eid];

        // If the custom access callback returns FALSE, remove from results.
        if (!MYMODULE_my_entity_access_callback('view', $entity, $user)) {
          unset($view->result[$index]);
        }
      }
    }
  }
}

```

**If pagination is a concern**, it's a tougher problem; adjusting the view results break consistent offsetting (e.g. page 1 might return 4 results, page 2 might return 10 results). Plus, the results of SQL query can't adjust for information that is only known by executing PHP.

In those instances, you'll have to adjust your method (e.g. `hook_views_query_alter()` if the access callback is DB query based, altering your View pager options, etc.) to accommodate for the access callback manipulating the view.

---
Tags: 7, views, entities, users
---


title: URL alias in page.tpl.php

text:
# Question
Title: URL alias in page.tpl.php
I try to make link 'Mobile version' on site page site.com/page. This link leads to this page but on subdomain m.site.com/page. I use page.tpl.php. I try to write this.

```
<a href="http://m.site.com/<?php print drupal_get_path_alias();?>">Mobile version</a>

```

`<?php print drupal_get_path_alias();?>` prints nothing. What's wrong? Maybe there is some more elegant and right way to solve this?

# Answer
Your code only work for Drupal 7. As you are using Drupal 6, please pass the current url as argument.

```
print drupal_get_path_alias($_GET['q']);

```
> 2 votes

---
Tags: 6, path-aliases
---


title: Building a Custom Search block

text:
# Question
Title: Building a Custom Search block
I have to search the entered text in a drupal table and if there is a match for the keyword get all the fields corresponding to that keyword. I have executed the query and I have the fields to be printed in a array called $column\_name.

How can I display these fields to the user in the form of a table?

```
function module_form_submit($form, &$form_state) {
$text = $form_state['values']['text_field'];
$query = db_select('table_name', 'n');
$query->fields('n', array('field_1','field_2','field_3'));
$query->condition('n.field_0', $text, '=');
$column_name = $query->execute();

```

# Answer
I created two forms and called the second one only after the first form is submitted. To create a table i used table theme.

```
if (!empty($form_state['values']['text'])) {

 //db_query here to search the key word
 $text = $form_state['values']['text'];
$header=array(t('patient id'), t('patient name'));
$row = array(
    array(
t('one'),t('two')
    ),
);

 $form['table']=array(
 '#theme'=>'table',
 '#header'=>$header,
 '#rows'=>$row,
 );
 }
 else {

 $form['text'] = array(
'#type' => 'textfield',
'#title' => t('patient_id'
));

 $form['buttons']['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit Button'),
//'#ajax'=> array('callback'=>'anonymous_page'),

);
}
return $form;
}

```

in the form submit add

```
$form_state['rebuild']=true;

```
> 0 votes

---
Tags: forms, database, blocks, search
---


# Question
Title: Is it possible to have all content types as dropdown field in one content type in drupal 7?
I have one requirement, where I need to create one content type having field 'Type' and it should have Dropdown list of content type present in that Drupal project. Is it possible to do it? Can anybody suggest me how can I achieve this?

# Answer
I can suggest four different solutions:

1. Using Bundle Name Reference module , of course I haven't used this module and I'm not sure if it presents the same functionality as you desire.
2. Easy but not always working , Create a taxonomy vocabulary and add terms having same name as your content type does , then you can add a taxonomy reference to your content type targeting that vocab.
3. The problem in solution 2 is that when a new content type is added you manually must add a term for that in your vocab , to overcome that problem you can write a simple module then implement hook\_node\_type\_insert and there you can add term to your targeting vocab programmatically so you wont need to manually add new terms any more.
4. The last and the most complicated solution , maybe you can write it as a module so others can use it in future. You will need to write a module to implement a new field type , you will need to implement hook\_field\_schema to add new table for your field type (there you can store bundle ID of selected content type) , a field widget which must be Select type and its options can be filled using this function : node\_type\_get\_types.
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: What is the parameter $instance_id in the function Block::setVisibilityConfig?
I need to programatically set the visibility of a block. I've loaded the block, and I know I need to use the `Block::setVisibilityConfig` method, but I don't know what the `$instance_id` variable is.

Does anyone know what to pass here to the function?

# Answer
I got it. Example:

```
use Drupal\block\Entity\Block;

function mytheme_preprocess_html(&$variables)
{
    $block = Block::load('sitebranding');
    $block->setRegion('content');

    $visibility = $block->getVisibility();

    if (isset($visibility['request_path']['pages']))
    {
       unset($visibility['request_path']['pages']);
       $visibility['request_path']['negate'] = 0;
       // $visibility['request_path']['pages'] = '/node/2';
       $visibility['request_path']['pages'] = \Drupal::config('mymodule.settings')->get('services_block_path_visibility');
       $block->setVisibilityConfig('request_path', $visibility['request_path']);
       $block->save();
    }
}

```
> 4 votes

---
Tags: 8, blocks
---


# Question
Title: How do I make several displays of one image field in a node?
I'm trying to implement a JS image gallery to my project. I've created three image styles:

* thumbnails 135x105
* gallery 690x430
* full 1600x900 (responsive)

Thumbnails are used as a pager for the gallery. By clicking the zoom button, the full image should be loaded and opened in a modal.

**The question is, how to use all three image styles with one image field and display them in one node?**

On Drupal 7 I've used Gallery Formatter module, but on Drupal 8 it's not working properly.

The task seems to be quite trivial, but i didn't find any answer. May be there is some module or i can set image style to the field in twig template? Thanks in advance!

# Answer
The right solution would be an image formatter, which is configurable to have multiple instances of the same image with different display options.

If you can't find this in a module, you can improvise in preprocess of the node template:

**mytheme.theme:**

```
function mytheme_preprocess_node(&$variables) {
   if (isset($variables['content']['field_image'])) {
    $image = $variables['content']['field_image'];
    $image['0']['#image_style'] = 'gallery';
    $variables['content']['field_image_gallery'] = $image;
    $image['0']['#image_style'] = 'full';
    $variables['content']['field_image_full'] = $image;
}

```

This code makes a copy of the image field and puts it in two additional fields, each with a different image style. This is for a single value field. I suppose your gallery is a view of multiple nodes with a single image. If there are multiple images in one node you would have to process the images in a loop (a bit more improvisation needed).

If it is a responsive image use this line to change the image style:

```
$image['0']['#responsive_image_style_id'] = 'gallery';

```

All three images should be of the same kind (standard or responsive), otherwise there would be some more work to do.
> 1 votes

---
Tags: entities, 8, media
---


# Question
Title: How to access values from earlier steps in multi-page Webform?
I'm using Webform 4. It uses Drupal's tokens, not it's own % tokens like it used to in version 3, and pretty much all what I found was about webform 3.

Say I want to make multi-page subscription form. On first page there is only an email field. On second one, I want a markup that will say something like:

> Detailed subscription configuration for molot@example.com

Similarly, I'd like to be able to use them as default values for future fields, like asking user for billing address, and then for delivery address.

Are there any tokens for that? What I did for now is:

```
function mymodule_token_info() {
  $type = array(
    'name' => t('Webform submitted values'),
    'description' => t('Tokens related to $_POST[\'submitted\'].'),
  );
  $tokens = array();
  if(isset($_POST['submitted'])) {
    foreach($_POST['submitted'] as $key => $val) { //discard $val now
      $tokens[$key] = array(
        'name' => $key,
        'description' => "\$_POST['submitted']['$key']",
      );
    }
  }
  return array(
    'types' => array('webform_submitted' => $type),
    'tokens' => array('webform_submitted' => $tokens),
  );
}

function mymodule_tokens($type, $tokens, $data, $options) {
  if($type == 'webform_submitted') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
      //Hide errors below. We don't care if it really exists yet. If empty, so be it.
      @$replacements[$original] = (string)$_POST['submitted'][$name];
    }
    return $replacements;
  }
}

```

It works, but it only shows values from one step earlier, so requires some dirty tricks with hidden fields to carry email value across multiple steps. I admit - it was just quick and dirty. Is there any **built-in** way to do it, or properly **maintained contributed** module for this? Or a way to make this code work independently of `$_POST['submitted']`, to make it carry values across many steps and to make it's tokens (from available Webform elements) visible on token list in edit windows?

# Answer
This does not answer the question in your title, but reading your use case it sounds like the scenario that Profile2 was written for. Related stackoverflow post

Webform is great for surveys and such, but when you want "to be able to use them as default values for future fields" they need to be connected to the user. So you would then need more custom code to fetch the user's historic webform submission to pull these values in a form alter for your billing address. Profile(2) is written precisely to make this easier.

Also, the less last-minute custom coding you are doing before handing this off to some one else, the less that some one else will curse you in their heart when they are trying to make updates.
> 1 votes

# Answer
Decalre the variables as global and pass from\_state\[values\]\[\] into them. This worked for me, in multi stage forms with ctools modal popup.
> 0 votes

---
Tags: webforms, tokens
---


# Question
Title: How to find which content types have comments enabled?
I just want, quickly, to know which content types have comments enabled, without having to go from content type to content type and view the configuration page of each, especially if there are more than fifteen.

# Answer
I searched but I found nothing relative, so I take the initiative to answer my own question.

MySQL seems to be the answer:

```
mysql> select type from comment c, node n where c.nid = n.nid group by type;
+------------------+
| type             |
+------------------+
| my_content_x     |
| my_content_y     |
| my_content_z     |
+------------------+

```

This can be equally used:

```
mysql> select entity_type, bundle from  field_data_comment_body group by entity_type, bundle;
+-------------+-------------------------------+
| entity_type | bundle                        |
+-------------+-------------------------------+
| comment     | comment_node_my_content_x     |
| comment     | comment_node_my_content_y     |
| comment     | comment_node_my_content_z     |
+-------------+-------------------------------+

```

All nodes which at least have one comment:

```
mysql> select type, n.nid from comment c, node n where c.nid = n.nid group by n.nid  order by type;
+--------------+------+
| type         | nid  |
+--------------+------+
| my_content_x |  115 |
| my_content_x |  90  |
| my_content_y |  521 |
| my_content_y |  295 |
| my_content_z |  127 |
| my_content_z |  11  |
+--------------+------+

```
> 3 votes

---
Tags: 7, comments
---


title: Looking for database insert example

text:
# Question
Title: Looking for database insert example
According to `db_insert` manual page this function is deprecated and it is better to use Drupal 8 database connection to perform insert.

> Deprecated
>
> as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call insert() on it. For example, $injected\_database-\>insert($table, $options);

Now how can I get a database connection and call `insert()` method?

# Answer
> 22 votes
To inject the database service add/alter the following methods in your controller class:

```
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PetmdController extends ControllerBase {

  protected $database;

  public function __construct(Connection $database) {
    $this->database = $database;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }

  public function foo() {
    $this->database->insert(...)->fields(...)->execute();
  }
}

```

# Answer
> 3 votes
To add to Berdir answer here is how you can inject your database service in your controller

```
$db = \Drupal::database();
$query = $db->select('location','loc');
$query->fields('loc', array('id', 'name', 'bond_goal','deposit_goal','date_created','date_updated'));
$query->addField('loc','name','location_title');
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);

```

You can study `core/lib/Drupal/Core/Database/Query` classes for more information

# Answer
> 2 votes
First, as your quote says, it is deprecated for *Drupal 9*. Which means it will stay around for years and will not be removed from Drupal 8 ever.

But yes, its a good idea to avoid deprecated functions. Like any other deprecated function, you can always simply look at its implementation to see how the new way of doing it is. Although instead of calling out to \Drupal, you want to inject the database or whatever other service you need when that is possible (when you are in a service, controller, form, plugin, ...)

# Answer
> 1 votes
**Option 1:**

```
$db = \Drupal::database();
$query = $db->select('k_product', 'p');
$query->fields('p', ['idpr', 'name', 'type']);
$data = $query->execute()->fetchAllAssoc('idpr', 'name', 'type');

```

**Option 2**

```
$db = \Drupal::database();
$data = $db->query('SELECT idpr, name, code, detail FROM k_product')->fetchAllAssoc('idpr', 'name');

```

---
Tags: database, 8
---


# Question
Title: How to programmaticaly serve a 404 in template.php
I have the previous logic to feed a View in `MY_TEMPLATE_preprocess_page`. When the URL, where I have some paremeters passed in a user friendly way, does not exist (the parameters are not correct), I am serving a "Product not found message". However, I think it is more correct, for SEO purposes, to serve a 404-Not Found page, with the correct HTTP Headers. I am trying to achive this with `drupal_not_found` but the page takes a minute to load and finally shows a blank screen.

Where should I put the logic and the `drupal_not_found` call? Must I move it to my custom module, in MY\_MODULE\_init() or something? I need to access `$node->nid`.

Example:

Correct : http://www.example.com/products/shoes

Wrong (404) : http://www.example.com/products/dsfsdfswerweipwr

# Answer
My personal advice is to return the "No results found" message from Views instead of issue a 404. Why? Because if you ever wind up adding products or changing the name of a product, what used to be a 404 is not anymore. I feel like from an SEO perspective you would have an uphill battle. Anyway.

One way to do this would be from a custom module. Do not do it in template.php.

```
/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(&$view) {
   if ($view->name == 'myview' && some_other_conditions) {
     if (empty($view->result)) {
       drupal_add_http_header('Status', '404 Not Found');
       drupal_not_found();
       drupal_exit();
     }
  }
}

```

Bonus, Drupal 8:

```
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(ViewExecutable $view) {
   if ($view->id() == 'myview' && some_other_conditions) {
     if (empty($view->result)) {
       throw new NotFoundHttpException();
     }
  }
}

```

Is the view generating the page at products/%? Why do you need to know the `$node->nid`?
> 4 votes

# Answer
I think the theme layer is a little bit too late to set your headers. It might break your caching.

That said, if you are sure you need your code to live in the hook\_preprocess\_HOOK, then you can rely on the fact that page not found is a HTTP header you can set by calling `drupal_add_http_header('Status', '404 Not Found');`

I would recommend instead of doing it in the preprocess hook using one of the following places

1. if /product is a menu item you wrote yourself in a custom module, then in the callback function of your menu item do `return MENU_NOT_FOUND;`
2. use hook\_page\_alter, you can get the node object at this hook by

`function THEMENAME_page_alter(&$page) {
 if ($node = menu_get_object()) {
 // Stuff.
 }
}`
3. hook\_init() is also a good bid, you can get the node object in the same manner as in step 2
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Add rel="nofollow" to menu displayed by menu_block module
I am trying to add rel="nofollow" attribute to menu links output by the menu\_block module.

My core menu is called Main Menu, which I do not want to modify as it is used for main navigation. However the product level of this menu is output in the footer by Menu Block module, and it is these links I want to add an attribute to.

Thanks.

# Answer
If you use different menus then:

There's a module for that(tm) Menu Attributes

If it's the same menu then things get farm more complicated as you'll have to implement some hook. Take a look at hook\_menu\_block\_tree\_alter in menu\_block.api.php.
> 1 votes

# Answer
Something like this for Navigation Menu (`navigation`):

```
function THEMENAME_preprocess_menu_link(&$variables) {
    //for Navigation Menu ('navigation')
    if ($variables['element']['#theme'] == 'menu_link__navigation') {
        $variables['element']['#localized_options']['attributes']['rel'][] = 'nofollow';
    }
}

```

Something like this for Footer Menu (`menu-footer`):

```
function THEMENAME_preprocess_menu_link(&$variables) {
    //for Footer Menu ('menu-footer')
    if ($variables['element']['#theme'] == 'menu_link__menu_footer') {
        $variables['element']['#localized_options']['attributes']['rel'][] = 'nofollow';
    }
}

```

Something like this for speficit paths:

```
function THEMENAME_preprocess_menu_link(&$variables) {
    $system_paths = array(
        'node/56',
        'taxonomy/term/56',
        //more-your-paths
    );

    if (in_array($variables['element']['#href'], $system_paths)) {
        $variables['element']['#localized_options']['attributes']['rel'][] = 'nofollow';
    }
}

```
> 0 votes

---
Tags: blocks
---


# Question
Title: Page title block hidden on custom route, panel or view pages when content type is chosen in block visibility settings
I defined a custom route in a custom module:

```
mymodule.overviewpage:
  path: '/mymodule-overview'
  defaults:
    _controller: '\Drupal\mymodule\Controller\PageOverviewController::content'
    _title: 'Overview'
  requirements:
    _permission: 'access content'

```

Here is the controller:

```
class PageOverviewController  extends ControllerBase {
  public function content() {
    return array(
      '#markup' => 'hello'
    );
  }

}

```

This route is working fine, I see the "hello" text when entering this path in my project but I do not see the page title. The page title "Overview" is used in the title tag in head of the HTML page but there is no page title block - it is not even rendered. Changing to Bartik theme I see the page title "Overview".

I know found out that the visibility of this block was set: there was a checkbox checked which defined the block to be hidden when on a node page of a special content type/ node bundle:

My question: why is the page title block not visible on panel or view generated pages or on custom routes? What should I add to avoid such a behavior? Is there a way to hide the block for special contenty types without hiding it elsewhere?

# Answer
> 5 votes
Because they are not a page of that node type. This filter doesn't just apply to node/\*, it applies to all pages. And if there is no node object, the condition will always be false.

If you need something that is true on all non-node pages but for node pages only for a specific ype, you need to define your own condition plugin or use hook\_block\_access().

---
Tags: 8, blocks
---


# Question
Title: How to manage by cron a long-running queue of very many items
I'm creating a File Checker module that verifies files managed by Drupal actually exist at the uri where Drupal believes they are.

It places an item in a queue for each file entity. As there could be large amounts of files on a site, so there can be large amounts of queue items (10000, 100000 ...). Each item (file entity) can take a few seconds to process if the files are stored remotely e.g. on Amazon S3 or Dropbox. So the queue could take hours to process.

File checking can be scheduled to happen at regular intervals, i.e. by cron, so queue processing needs to happen by cron queueWorkers.

What is the best way to handle the duration of these cron queueWorkers? Their plugin annotation has a cron time option (default 15 seconds) that controls how long they run for when awoken by cron. I could either:

1) set their time option to something very long like 86400, so they can process queue items for a whole 24 hours if they need to; or

2) set their time short like 60 seconds, and use something like the Ultimate Cron module to specify that just this queueWorker is woken up every 60 seconds (and not other cron tasks).

# Answer
> 3 votes
The problem with using queue for an operation like this is that you have to fill up the queue frequently.

Queue makes sense if you have something that is e.g. user or somehow else triggered one by one (or a few at a time), added to the queue and then processed in background. For something like your use case, you want to process tens of thousands of entries, it is a lot of overhead to add them to the queue first and then process them again.

Instead, a simple approach would be to keep track of the file ID. process the first 100 files, sorted by fid, ascending. store the last file ID in state, then on the next run get the next 100 files, where fid is bigger then the last processed fid. If you reach the end (identified based on having processed less than 100 files, you reset the fid back to 0 (possibly combined with some kind of timestamp, so you only start again after N seconds passed since you started the last time). 100 could be configurable, so users can process fewer or more files per run, depending on whether they have them local or not.

Keep in mind that by default, there is only one cron process, if you're running for a long time, it will block everything else. Ultimate Cron could help there, also with running your cron job more frequently than others. It supports multiple threads, but I honestly don't know how well that works already in 8.x (And I am the 8.x maintainer of that module ;)).

You could also always expose it as a drush command, then it would be easy to do it as a completely separate, standalone cron process.

---
Tags: 8, cron, queue
---


title: Functional tests performance

text:
# Question
Title: Functional tests performance
In Drupal 8, I am creating functional tests extending the `BrowserTestBase` class.

Launching a test though (even an empty one) requires about 2-3 minutes.

Is this normal, is it there a way to speed up the functional tests?

# Answer
> 4 votes
Do *not* use standard (as you said in a comment).

Use testing and then create only what you need in the test. That's the main thing to speed up your tests.

They are still rather slow, but that should help.

Another thing to consider is to avoid having many test methods. Each runs in a completely new, isolated environment. A trick that is often used is to have a single testAll() method and many doTestSomething() methods, then they are faster by almost factor count(test methods), since set up is usually by far the slowest part.

You can also run tests in parallel with `--concurrency 8` (nummber of cpus is a pretty good value for concurrency)

# Answer
> 2 votes
Which one are you using? Do note that there are two BrowserTestBase classes, one is marked as deprecated:

https://api.drupal.org/api/drupal/core%21tests%21Drupal%21Tests%21BrowserTestBase.php/class/BrowserTestBase/8.2.x

Here is what I wrote for Taxonomy Views Integrator:

http://cgit.drupalcode.org/tvi/tree/tests/src/Functional

I can run that test and (if I recall) it is done in less than 60 seconds. Note that the more test methods you define, more modules you require, the longer it will take to set up the testing instance of Drupal.

On a VM I have dedicated 2GB of RAM, 256M for PHP 5.6 (or 7, depending on which VM) on DrupalVM.com instance.

Also, I am running them from the command line, not the UI test runner.

---
Tags: 8, performance, testing
---


# Question
Title: Is there a group of modules that would allow to assign new permissions to users basing on the votes they receive for their comments, or posts?
If I would implement something similar to the reputation system implemented in the Stack Exchange sites, which modules should I install on my Drupal site?

# Answer
You can use Userpoints to allow users to collect points for things they do. See Userpoints Nodes and Comments for granting points when users post comments or nodes.

Then, Userpoints Contrib contains both modules to integrate with Voting (not all modules which are part of the 7.x-1.x-dev release have been ported to Drupal 7 yet) and the ability to assign roles to a user when he has a certain amount of points. Note that Userpoints Contrib 6.x is in a rather bad shape, most modules in there are really buggy. However, we worked hard on the first round of module upgrades to 7.x in this issue: http://drupal.org/node/869770 and have released the first few modules which are well tested and should be quite stable.
> 5 votes

# Answer
The Rules module would be your best bet, but it would need integrating with a voting system.

Although still in development, the Voting Rules module seems to be what you are looking for. Here is an issue for it to be integrated with the Voting API.
> 2 votes

# Answer
Yes it's perfectly possible to do what you're asking for. Here is a summary of how to do so (and only using popular modules with stable releases ...):

* Use User Points to implement a reputation system.
* Transform votes in User points.
* Assign a new role if sufficient User Points.
* Remove role if insufficient User Points.

Read on for more details about each of these steps.

### Step 1 - Use User Points to implement a reputation system

The typical solution to implement a reputation system in a Drupal site, is to use the User Points module, combined with using Rules to grant some amount of points, e.g. based on received votes.

### Step 2 - Transform votes in User points

Anything about voting in Drupal boils down to (= depends on) using the Voting API module. And using Rules, it is possible to transform votes (up or down) towards User Points, as detailed in my answer to "How to use Rules to transform upvotes and downvotes towards User Points?".

### Step 3 - Assign a new role if sufficient User Points

You can use Rules also to assign a new role (grant permissions) to a user as soon as they have accumulated a predefined number of User Points. As an example, have a look at this Rules example (in Rules export format):

```
{ "rules_grant_new_role" : {
    "LABEL" : "Grant a new role",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "11" } },
            "DO" : [
              { "user_add_role" : {
                  "account" : [ "site:current-user" ],
                  "roles" : { "value" : { "5" : "5" } }
                }
              },
              { "drupal_message" : { "message" : "You have at least 11 points (actually you have [total-points:value] points ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

```

The above rule does retrieve, as the very first Rules Action (not Rules Condition) the current amount of User Points of a user. If the amount is at least 11, it will show an appropriate message about that and it will grant the role with role id = `5` (adapt this role id and/or amount of user points needed to fit your needs).

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing a Rules Component (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

Just in case you don't realize: the clue to make this rule work is the very first Rules Action "***Load user points of a user***". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".

### Step 4 - Remove role if insufficient User Points

Using a variation of the rule shown in step 3, you can also remove such role again if something happens so that the amount of user points is no longer sufficient. I assume anybody can tweak the rule in step 3 for this case also (if not click here).

### Note: Use the Answers module as an example

To actually implement such reputation system, the number and types of Rules you'll need is not just "a couple of them". You'll need to take into consideration upvoting, downvoting, un-upvoting, un-dowvoting, disallow votes from the author, etc. To avoid re-inventing the wheel, have a look at the various rules included with the Answers module (disclosure: I'm a co-maintainer) for a lot of inspiration about this.
> 1 votes

---
Tags: 7
---


# Question
Title: Minimizing cache clearing during development
I'm suffering from very long (several second) load times when developing locally with Drupal 8 when developing/debugging twig templates or in general having ALL caching disabled. Rebuilding cache makes my admin pages needlessly require a rebuild for example. When I'm not actually working on them I'd like them to remain cached.

I'd like to be more specific in my cache clearing so that I can clear only the parts I'm actively working on - ex a view or block - instead of constantly invalidating the entire site cache which is rather expensive.

I've found that cache tags may work, but I can't find documentation or the location where I might find a listing of available cache tags or really much else on clearing specific caches. So if tags are effective, where can I find all registered cache tags on my site?

Is there more information I'm missing on how targeted caching is implemented in Drupal 8? Are there alternatives to tags that might work better?

Edit: I should mention my environment, in case there is an alternative solution.

I'm running Drupal using docker, with Nginx/PHP-FPM and MySQL containers , on Docker for Mac which has known issues with file mounts so I'm only mounting my custom modules as volumes into any containers. I profiled the difference between mounting everything and am now spending negligible time doing file operations whereas previously it was very expensive.

Now it appears that my bottleneck is calling the Database many times per pageload, I imagine this is because I'm rebuilding the entire cache meaning I'm adding/removing it from the DB over and over. I may try memcached or redis and see if that helps.

My ideal solution here is to just invalidate portions of the cache I actually want to invalidate instead of the entire thing though. Cached pages are ofc incredibly fast in this environment. My staging environment which is using native Docker does not have the FS issues but still suffers when caches are turned entirely off.

# Answer
> 2 votes
Define *all caches disabled*, how do you do that?

The recommended approach is to only disable the render cache (as per the example local settings.php), but if you have a complex site and a slow, especially virtualized environmment, that can still take some seconds on every request.

Make sure you don't have xdebug or so constantly enabled. Use PHP7 if possible, that's basically 50% faster. It doesn't make mysql faster obviously, but unless you have very slow/bad queries, that is likely a smaller part of the whole response than you think. And if you have slow queries, then you need to find ways to optimize them, since it will get much morse when you have more parallel page requests.

If you clear cache manually, make sure you use `drush cc render` and not `drush cr` unless you actually change something that requires a full cache clear.

Cache tag invalidation doesn't really help that much, you could of course find out the cache tag of your specific block/view and invalidate just that, but there is no drush command for that yet). You could write your own cache backend that extends from the default and allows to ignore cache writes of cache IDs that match a certain pattern. But invalidation will require you to figure out the cache id of the thing, unless you work on the same thing for quite some time, that won't be worth the effort.

For more specific things, you'd need to profile the site to find out what is actually slow.

---
Tags: 8, caching, performance, debugging
---


# Question
Title: How to get count in views when group by some field?
I have view which display results based on taxonomy field grouping:

And results look like below :

I am trying to display count of each group in brackets next to Topic field, Is that possible to achieve with this kind of view. Please suggest.

Thanks!

# Answer
> 0 votes
You can try using this module

Term Node Count

---
Tags: 7, views
---


title: Rewriting output of View

text:
# Question
Title: Rewriting output of View
I have a View of taxonomies. I want to rewrite the output of each field (name) as this:

```
<a href="javascript: void(0);" onClick="alert('[name]');">[name]</a>

```

so when I click on the taxonomy, it will prompt an alert with the term name.

I try to rewrite through the Views GUI to no avail. I even tried with `views_pre_render`but because there is no #markup property, the rewriting is not HTML but plain text. I did the trick with views\_pre\_render and other kind of content, but not in taxonomy. And is it really impossible to achieve that in the GUI ? Surely I am missing something very very basic here.

# Answer
> 1 votes
You can do this through theming.

For that you can create a new **views-view-field--VIEW\_NAME--FIELD\_NAME.tpl.php** file and write the HTML output for the field.

Dont't forget to clear your cache after adding the file or you can do 'Rescan template files' inside your view.

---
Tags: 7, views, javascript
---


# Question
Title: Combination of AJAX Views and infinite pager
In Drupal 7, I load an AJAX View (in response to user clicking a link) with the following code (source: How to load and display a view with Ajax in Drupal 7?)

```
 jQuery.ajax({
    url: Drupal.settings.basePath + "/views/ajax",
    type: "post",
    data: {
    view_name: "books",
    view_display_id: "page", //your display id
    view_args: identifier, // your views arguments
  },
    dataType: "json",
    success: function (response) {
    if (response[1] !== undefined) {
      jQuery("#bloque-" + identifier).html(response[1].data);
    }
   }
 });

```

However, I cannot combine AJAX Views with Infinite scroll module, and even a basic pagination does not work, as it does not override the pager link code.

# Answer
You can try this -

On your page template where you want to load this view use following sample code (with your view specific values such as arguments etc.) which will add all the required JS to your page -

```
$view = views_get_view('books');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
    'views' => array(
        'ajax_path' => url('views/ajax'),
        'ajaxViews' => array(
            array(
                'view_name' => $view->name,
                'view_display_id' => $view->current_display,
                'view_args' => check_plain(implode('/', $view->args)),
                'view_path' => check_plain($_GET['q']),
                'view_base_path' => $view->get_path(),
                'view_dom_id' => 1,
                'pager_element' => $view->pager['element'],
            ),
        ),
    ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

```

In your JavaScript code use Drupal.attachBehaviors() which will attach Infinite Scroll to your View's HTML -

```
jQuery.ajax({
    url: Drupal.settings.basePath + "/views/ajax",
    type: "post",
    data: {
        view_name: "books",
        view_display_id: "page", //your display id
        view_args: identifier, // your views arguments
    },
    dataType: "json",
    success: function (response) {
        if (response[1] !== undefined) {
            jQuery("#bloque-" + identifier).html(response[1].data);
        }
        Drupal.attachBehaviors();
    }
});

```
> 1 votes

---
Tags: 7, views, ajax, paging
---


# Question
Title: Add cardinality_unlimited taxonomy reference to custom entity
Okay, so I'm getting an error that I think may be a Views bug, but I don't have enough knowledge about Views & SQL right now to be sure about that.

Here's the hook I'm using to install the new field into the poll entity, using `drush entity-updates`:

```
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'poll') {
    $fields['cat'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Category'))
      ->setDescription(t('Category of poll'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => -10,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ),
      ))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

```

Then, I make a view that would like to use this taxonomy term as a Contextual Filter. I want to use the taxonomy term name rather than the ID, so I need to add a relationship. I add relationship in the view and look for the Taxonomy Term relationship that has my description, "Category of poll" and select it. The view complains about a SQL error:

`SQLSTATE[42S22]: Column not found: 1054 Unknown column 'poll__cat.cat' in 'on clause': SELECT poll_field_data.id AS id, taxonomy_term_field_data_poll__cat.tid AS taxonomy_term_field_data_poll__cat_tid FROM {poll_field_data} poll_field_data LEFT JOIN {poll__cat} poll__cat ON poll_field_data.id = poll__cat.entity_id AND poll__cat.deleted = :views_join_condition_0 LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data_poll__cat ON poll__cat.cat = taxonomy_term_field_data_poll__cat.tid LIMIT 5 OFFSET 0; Array ( [:views_join_condition_0] => 0 )`

The reason for the error in the above query is that the `poll__cat.cat` column does not exist, but it rather SHOULD be `poll__cat.cat_target_id`.

My question is: is this a views bug or a bug with the way I'm adding the field to the poll entity, and if it is a views bug:

1. How do I debug it? Where does views set the column name it's looking for?
2. Is there a hook I can use to change it, and/or should I submit this odd case to the views project?

**EDIT**: I'm trying to use `hook_views_query_alter` and `hook_views_pre_execute` to try and modify the broken query to do what I want it to do, but it is incredibly frustrating, because all of the things are protected, and it is very inconvenient to access anything, considering the purpose of these hooks is to modify data. I'm trying to look through the functions for ViewExecutable and the views Sql class, but I don't see anything that will help me change the column to what it should be! Anyone who can help in any way, I will be so grateful.

**Edit 2:** It seems like this guy: Views doesn't like multiple entity references in my entity has had a similar problem. I feel like this is a bug somewhere, or at the very least an issue with CARDINALITY\_UNLIMITED being confusing to implement with entity references.

# Answer
This is the best solution I have been able to come up with so far. Answers are still welcome, because I still don't know:

1. Why this is happening, is it a views bug?
2. Could I have created the field in a way that using a hook to alter the query is not necessary?

What I ended up doing was using `hook_views_pre_execute(Drupal\views\ViewExecutable $view)` to get the query out of `$view->build_info['query']->getTables()` and then manually change the condition on my join table to use the correct column, which was not `poll__cat.cat` but rather `poll__cat.cat_target_id`.
> 0 votes

---
Tags: 8, views
---


# Question
Title: Are there any naming conventions for helper functions in modules?
I'm writing a module and I need to create an auxiliary (helper) function, but I don't know which is the best name to my function.

Should I name my function like:

```
function _MODULE_my_function

```

or:

```
function MODULE_my_function()

```

I usually use `_MODULE_my_function()` but there is a standard for this?

There is not reference about this in the Drupal Coding Standards or in the Naming your modules, functions, and variables article.

# Answer
How to name a function is described in Naming Conventions which says:

> Functions should be named using lowercase, and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.

That is valid for hooks and other functions implemented from the module.

For functions that are not hooks, you could also prefix them with an underscore, right before the grouping/module name. If you do it, you are saying to the developers of other modules that the function is not supposed to be called from other modules, but it is *private* for the module defining it.
This is a practice followed from PHP which is also followed from Drupal. For example, `theme()` had been renamed `_theme()`, before being removed, to make clear it was a private functions modules should not call. It's described in `theme()` renamed to `_theme()` and should not be called directly.

> The direct callability of `theme()` was removed in favor of building render arrays consistently. It has been renamed to `_theme()` and is for internal use only. Build render arrays instead of using `_theme()` in your code for the following reasons.
>
> Calling the `_theme()` function directly raises several issues:
>
> * It circumvents caching.
> * It circumvents defaults of types defined in `hook_element_info()`, including attached assets
> * It circumvents the `pre_render` and `post_render` stages.
> * It circumvents Javascript states information.
> 4 votes

# Answer
I believe I have seen it on a few places that helper functions should be prefixed with an underscore. This is how you distinguish between them and other callbacks / main functions, plus you make it impossible to accidentally name something after a hook.

I've been using this system for years and is in my custom module boilerplate as well.

Hope this helps.
> 2 votes

---
Tags: coding-standards
---


# Question
Title: I want to override results of an autocomplete field (Entity reference in a content)
I have a content type Intertainment and i made a reference of a view(entity referene).

I used inline entity form complex widget in manage form display the entity reference and i checked "Allow users to add existing jeux".

When i add/edit the entity reference field of type Intertainment , when i click "ajouter une jeu existant - or add jeu existant."

=\> Results of autocomplete are when i taped something its give all titles of references entities like this : test taxo 1

My need is to override the array results of autocomplete of inline entity form module and i don't want to add a new widget.

Example add type of content in the key of result array of autocomplete.

=\> What i want to make :

# Answer
It's pretty much the same as Show node IDs along with titles in Entity reference Autocomplete list except you use content type name instead of node id.

Currently there is a bug in Drupal 8 where this does not work properly. Here is the issue: Views Filter by an entity reference view not working as expected you could try the patch in comment #26 or the module in comment #13. I have not tried them yet.
> 1 votes

---
Tags: views, 8, ajax
---


# Question
Title: Create a term reference with a select list selecting one at a time
I have a couple term reference fields, one of which allows unlimited values, and one of which allows 4 values. I'm using Simple Hierarchichal Select as the widget for the unlimited one, and it lets the user select a first value, and then click 'add another item' if they need more.

If I set the other value to a simple hierarchical select widget, it shows 4 rows with no Add another button. This makes sense, but encourages the wrong behavior for this case -- I'd prefer the user select only one value, but if they need to they can add up to 4. Having 4 rows from the beginning encourages them to add 4.

I would slightly prefer to use a select list widget for this limited field, but I don't feel confident that users are comfortable with the ctrl-click to select multiple items operation, so I'd prefer a dropdown allowing them to select one at a time, with an add more button. SHS would be fine too, if I could get it to show the 'add another another item' instead of showing 4 rows from the beginning.

Is either of those operations possible? Basically I want some kind fo dropdown widget, that allows users to select one value, and require them to click add another item, to add more, up to 4.

# Answer
> 0 votes
You can do it using Field Collection module

Once enabled, go to your content type and add a new field of `Type: Field Collection` and set to 4 values.

Then go to `/admin/structure/field-collections` and click on manage fields and add your select list field here and set value to 1.

Result:

If you don't want to allow users to set the same value, then you will need to use jQuery to hide value "X" in the 2nd drop down if the 1st drop down is set to value "X"

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


# Question
Title: How to create a Views relationship using the Address Field module?
I am trying to create a view to filter content types assigned to a specific country (set using Address Field module), determined by the current node's title.

My address field is not being listed under relationships in views.

How am I able to set contextual filters by a nodes country? Is this currently possible, or am I just missing something?

# Answer
> The country should be filtered by the current node's title

The better approach is to create Taxonomy Terms, so you can tag your nodes.

In `admin/structure/taxonomy` Add a vocabulary called Countries.

Then add a term reference field to your content type and select countries as your vocabulary, and use auto complete widget.

So all you have to is type the country name here and it will tag your node with that name.

In views, for contextual filter add Has taxonomy term ID

**PS:** You could use the Rules module to auto tag your nodes based on the Country field value.
> 1 votes

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


# Question
Title: How do I create a collaborative webform using Webforms?
How can I create a webform that allows users to collaboratively fill out a webform built using the Webform module in Drupal 7?

The users are building their own webforms, which works great to populate text and content. Some forms should allow several users to collaborate on filling them out. Basically, they will be to-do checklists where each user will mark tasks complete. This is a single submission edited by multiple users.

I could write these checklist type forms using the Forms API, allowing the users to maintain the forms themselves has proven much more efficient for getting forms published.

I am open to modules that extend Webforms or even other modules that fit the requirements better. However, I would like to stay with Webforms because my users are already comfortable with it.

# Answer
> 0 votes
I have been able to share a single submission with a role.

First, enable the 'save draft' option in webform Advanced Settings The 'Save Draft' option is here: webform/configure -\> Advanced Settings -\> Show "Save draft" button

Then, create a role with

* 'Access all webform results'
* 'Edit all webform submissions'

permissions. Any user assigned to this role can edit a submission started by another user.

The edit submission link (node/%/submission/%/edit) will be shared with the appropriate team members.

---
Tags: webforms
---


# Question
Title: How can I move the location of the advanced search form?
This has been giving me troubles for some time now. I am in the process of changing my search results page on my drupal 7 site. I have modified both the search-result and search-results template files to change how my results are displayed on the page.

However I can't figure out how to move the **placement** of the advanced search form. It is driving me crazy. I have created my own "advanced search" button, and want to give it the dropdown functionality that the default "advanced search" link has.

I know that I can change the "node\_form\_search\_form\_alter" function from node.module to alter the guts of this form, but thats not what I want. I just want to place it on the screen somewhere else.

I can't for the life of me figure out how to do this. I have gone through every template file, and the advanced search form just seems to magically appear. Any help would be GREATLY appreciated.

In the image below, you can see the default advanced search link, but I want to move it to my button that I have added, on the right of the page.

# Answer
> 1 votes
One option is the Advanced search block module which makes the advanced search form available as a configurable block.

> Provides the advanced search form (normally displayed above search results) as a block. The block includes default values for the advanced search fields making it easy to refine searches.

From a brief glance at this module's code, it looks like it hides the default form and re-creates the advanced search form in a block.

---
Tags: theming, search
---


# Question
Title: Drush commands report "hostname: Name or service not known"
Many Drush commands are reporting this error once or more:

> hostname: Name or service not known

The commands seem to run fine, though.

This is Drupal 7 running on a local development environment on OpenSUSE 13.1. The status reported by Drush is the following one. (I have edited out username and password.)

> Drupal version: 7.34
> Site URI: http://default
> Database driver: mysql
> Database username:
> Database name:
> Database: Connected
> Drupal bootstrap: Successful
> Drupal user: Anonymous
> Default theme: zen
> Administration theme: seven
> PHP executable: /usr/bin/php
> PHP configuration: /etc/php5/cli/php.ini
> PHP OS: Linux
> Drush version: 6.2.0
> Drush configuration:
> Drush alias files:
> Drupal root: /srv/www/htdocs
> Site path: sites/default
> File directory path: sites/default/files
> Private file directory path: ../files/private
> Temporary file directory path: /tmp

Running "drush up --debug" shows the error message:

> Cache MISS cid: 6.2.0-alias-path--c4cc2b4982c6401ca3d49ce3d0e075b4
> hostname: Name or service not known

How can I fix this error message?

# Answer
Drush calls the `hostname` program to determine if a given fqdn for a remote site alias is actually the localhost. There appear be other incidental uses for this program, since it is called when you run `drush status`.

If your system is saying 'name or service unknown', it means that you networking is not completely configured on the host server. This isn't a Drupal/Drush issue, but see:

http://www.linuxquestions.org/questions/linux-networking-3/ssh-name-or-service-not-known-479307/

If that does not solve your problems, try asking in a SuSe forum.
> 4 votes

# Answer
I fixed this issue by updating both /etc/hosts and /etc/hostname. In other words, I ensured that the content of /etc/hosts matched what returned by /etc/hostname.
> 2 votes

---
Tags: drush
---


# Question
Title: Trigger a function after saving content type
I've created my own *search engine* with a custom module and some XML. I would like to add content to the XML file with a custom function in my module.

The content that needs to be added will be coming from some content types. Is there a way to trigger a function after a content type is saved (node saved)?

I know the Rules module can do this, but I need to do it from my custom module (i.e. I need to write a function to achieve this).

Is this even possible?

# Answer
> 1 votes
There are some hooks you can use to do this, but they are all fired before the data is recorded in the database.

Have a look at `hook_node_insert()`, `hook_node_update()` and `hook_node_presave()`. The two first ones are fired only on insert or update, the last one every time.

After, another way to do so, is to add your own submit method on node\_form, using the `hook_form_FORM_ID_alter()` (`hook_form_node_form_alter()`), which will be fired after the node is properly saved in the database.

If I were you, I would use a setting page for my module to set the content types to use.

---
Tags: 7
---


# Question
Title: Formatting Field Collection data with Views Data Export (CSV)
I've got a Field Collection on use in a basic page content type on my Drupal 7 site. I've built a view with the Data Export module that is outputting the data from nodes of this content type as a CSV. The view is configured to dump all of the Field Collection data for each parent node into one cell... not ideal, but I'll live with it.

The problem is that there is no separator between the fields in the Field Collection. So, the contents of the Field Collection cell in the CSV looks like this:

```
Fruit_1: AppleFruit_2: OrangeFruit_3: Banana

```

It makes reading through the data in that cell unbearable (*the separator should be after Apple and Orange... oh and fruit is just for this example, not actual data*).

How do I get some kind of separator in there? Doesn't have to be anything fancy; something as simple as a comma and a space would be lovely! Ex:

```
Fruit_1: Apple, Fruit_2: Orange, Fruit_3: Banana

```

I've experimented with Field Collection Views, but no luck.

# Answer
> 2 votes
The solution is to implement a `views_pre_render` hook in a custom module.

```
function mymodule_views_pre_render(&$view) {
    if ($view->name == 'myview') {
        foreach ($view->result as $key => $row) {
            $line = array();
            foreach ($view->result[$key]->field_field_fruit_collection as $n => $collection) {
                $item = current($collection['rendered']['entity']['field_collection_item']);
                $line[] = $item['field_fruit'][0]['#markup'] .  ' (' . $item['field_color'][0]['#markup'] . ')';
                unset($view->result[$key]->field_field_fruit_collection[$n]);
            }
            $view->result[$key]->field_field_fruit_collection[0]['rendered']['#markup'] = implode(', ', $line);
        }
    }
}

```

In this example, the collection field is `field_fruit_collection` which is made up of two fields: `field_fruit` and `field_color`. The contents of the exported collection field will look like :

```
"Apple (red), Banana (yellow), Kiwi (green)"

```

# Answer
> 1 votes
Try using the view's `Relationships` settings, set your field collection as relationship and you should be able to select its fields and proceed from there just as if they were your node's (or whatever entity's) native fields.

---
Tags: views, entities, importing-exporting
---


title: how to link a menu item to a block?

text:
# Question
Title: how to link a menu item to a block?
i have a site with menu items and i want to make the item link to any block i want for example :

i have "About me" item in the menu and i want this item to link to a block that user can find it at the bottom of the page if he click on it will directly takes him down to the block. any suggestion please to do that ?

i add an ID for the block by **block\_attributes module**

# Answer
> 3 votes
You can use the Void Menu module to achieve this.

> Void menu allows you to configure special values to tags for use in the Drupal 7 menu system. You can customize up to 10 different void tags with any value you wish and use them freely inside the Drupal menu system.

For example, to link to a block with an id of #about, go to the Void Menu configuration page (admin/config/user-interface/void\_menu), and set one of the "tags" to your block id (including the #).

Then set your menu link path to the tag name.

For smooth scrolling you can use the Scroll to destination anchors module.

> This module modifies the default behavior of destination anchor links...so that users will be smoothly scrolled to the destination instead of immediately being jumped.

You will need jQuery to use the Scroll to destination anchors module.

---
Tags: blocks, taxonomy-terms
---


# Question
Title: wget or curl executables not found. Curl activated but not working
As I know so far Drush has some limitation on Windows. I need however, to get it working, and I have activated the curl module in php.ini. All you need is to uncomment the line:

```
extension=php_curl.dll

```

Now, I run phpinfo.php and it seems curl is activated, but I still get the console error:

> wget or curl executables not found.

I have restarted the Apache server several times but still no way out.

Is anyone able to help me up?

# Answer
> 2 votes
The problem was with the php.exe path in drush.bat

The solution is to properly edit it. In my case ( I use xampp ) here is the path:

```
@echo off
REM See http://drupal.org/node/506448 for more information.
@c:\xampp\php\php.exe "%~dp0drush.php" %*

```

# Answer
> 1 votes
Are you sure you're editing the correct php.ini file? Drush is a command line tool, and when PHP runs on the command line, it usually uses a different php.ini file than the PHP running under Apache (or any other web server).

To test if curl is enabled in command line PHP, run this command:

```
$ php -i | grep -A 3 'curl'

```

In my case (Ubuntu 11.04), the output was:

```
/etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/gd.ini,
/etc/php5/cli/conf.d/mcrypt.ini,
/etc/php5/cli/conf.d/mysql.ini,
--
curl

cURL support => enabled
cURL Information => 7.21.3

```

which means that curl is enabled.

To check which php.ini file your command line php uses, run:

```
$ php -i |grep php\.ini

```

In my case, the output was:

```
Configuration File (php.ini) Path => /etc/php5/cli
Loaded Configuration File => /etc/php5/cli/php.ini

```

On Windows, the values will be different but the idea is the same.

# Answer
> 0 votes
I know this has already been answered, but in case it helps somebody: I came here searching for a solution to the same error (`wget nor curl executables found.`), but the accepted answer did not work for me.

After a little more digging and testing, what turned out to be the cause of the problem is that the cygwin binaries folder had not been added to my windows environment path variable (System Properties \> Advanced \> Environment Variables \> System variable \> Path).

In my case, the path to add was `C:\cygwin64\bin`. And now it works. :)

# Answer
> -1 votes
Turn "allow\_url\_fopen" off in your php.ini file

---
Tags: drush
---


title: Avoid control-B is "eaten"

text:
# Question
Title: Avoid control-B is "eaten"
I am a heavy EMACS user. On the Mac I get EMACS keybindings in most text fields, and on most websites. However, if I am on a drupal website editing an HTML field, control-b toggles bold. Command-B should toggle bold; control-b should move me back a character.

Is it possible to fix this, on either my client or on the Drupal server?

# Answer
> 2 votes
This has to do with the CKeditor's javascript library rather than drupal. There are several sites and questions around on how to do this, for example this. I haven't tried this, but my guess is that you need to modify the config.js file that lives in your /sites/all/library/ckeditor folder of your drupal installation.

---
Tags: wysiwyg
---


# Question
Title: How to remove a URL from my XML sitemap?
I have installed the XML sitemap module and included all my articles in the sitemap. By default, also the URL **node/add/article** is added, but I do not want that since anonymous users cannot visit this page. Google's Search Console tells me that the URL is blocked by **robots.txt** \- which is great - but I want to get rid of the warning messages that show up due to the blocking.

How can I delete the URL **node/add/article** from my sitemap?

# Answer
This could either happen because it's node/add/article is included within a menu that's indexed by XML Sitemap or a custom path that was added.

In either case, a drush command can update the path flag for exclusion & rebuild the sitemap so that it's no longer there.

```
drush sqlq "UPDATE xmlsitemap SET status = 0 WHERE loc = 'node/add/article'"
drush xmlsitemap-rebuild

```

If you need to do this through the UI, you'll need to check either **/admin/config/search/xmlsitemap/custom** for a custom link or edit the menu item that contains it (**/admin/structure/menu**).
> 6 votes

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


# Question
Title: Custom block template PHP page, possible to make content editable in UI?
I have custom PHP files for a few blocks, e.g., */sites/all/themes/at-commerce/templates/block--block-10.tpl.php*

Is it possible to make this content editable using the block editing UI mechanism in Drupal administration, so the customer can make changes him/herself?

For example, customer visits URL *admin/structure/block/manage/block/10/configure* and can edit the content.

# Answer
> 0 votes
What you're describing is already in Drupal 7 core. It's called the **Contextual Links** module. When enabled, modules can define menu paths that enable a set of links that is contextually relevant to the content.

In your case, a user with *Use contextual links* & *Administer block* permissions will see a gear icon that produces a dropdown link from where they can configure & edit content of any custom block.

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


# Question
Title: How to make a menu link on a subdomain use the main domain as base_url
I have a site example.com with a subdomain sub.example.com. In my apache config both domain and subdomain point to the same directory, containing the Drupal installation. That is as far as i went to set up a the subdomain.

The issue is, the main menu on sub.example.com uses the same menu and template as the main site. The links link to sub.example.com/node/1 instead of example.com/node/1, effectively creating a clone of the whole site on the subdomain.

How do i show the same menu, but have the links all link back to example.com/node/1

# Answer
> 1 votes
It will depend on your theme, but typically the menu array (e.g. `$mail_menu` in **page.tpl.php**) can be altered such that each menu item have the array element `'absolute'` set to `TRUE` so that `l()` will generate the link with an absolute path.

For example, in a `MYTHEME_preprocess_page()` function:

```
/**
 * Override or variables into the page template.
 */
function MYTHEME_process_page(&$vars) {
  foreach ($vars['main_menu'] as $id => $menu_item) {
    $vars['main_menu'][$id]['absolute'] = TRUE;
  }
}

```

As long as `$base_url` is set to `http://example.com`, it should render the menu links to your original domain.

---
Tags: 7, navigation, subsites
---


# Question
Title: Problem attaching files to nodes with Services
I'm trying to attach files (images) to nodes via Services 3 from an external app using JavaScript.

From what I understand (and doing) is:

1) Create a node posting JSON to my endpoint domain.com/api/node.json

```
{
  "type":"foo",
  "title":"Hello World",
  "language":"und",
  "body":{"und":{"0":{"value":"Body Text"}}},
}

```

2) Create file posting JSON to my endpoint domain.com/api/file.json

```
{
  "filename":"image.jpg",
  "target_uri":"public://image.jpg",
  "filemime":"image/jpeg",
  "file":"myBase64String"
}

```

No problem at all at this point.

Then when trying to attach the files created to the node, is where I have trouble, not http errors, simply nothing happens.

First I have tried posting JSON to my endpoint domain.com/api/node/\*nid/attach\_file after successfully creating a new file, and getting back the fid

```
{
  "field_name":"foo",
  "filename":"image.jpg",
  "fid":"*fid"
}

```

Returning Status 200 OK empty text, but when viewing the node remains the same without the file attached.

I have also tried to create the files first and then when posting for node creation adding the fid, the node is created but no file attached.

```
{
  "type":"foo",
  "title":"Hello World",
  "language":"und",
  "body":{"und":{"0":{"value":"Body Text"}}},
  "field_foo":{"und":{"0":{"fid":"*fid"}}}
}

```

My field is a field type Image, widget Image. I have also tried in another field type file, with same results.

If someone can give me a heads up, what am I doing wrong or what is missing. I can't find any explanatory documentation on line.

Thank you.

# Answer
try adding more data to the attached file (it might be that fid and filename is not enough I can't find the example I used a long time ago, which had a similar problem):

* alt (might be required in general or only if marked as required in bundle)
* title (might be required in general or only if marked as required in bundle)
* uid
* filemime
* uri
* status = 1
* display = 1

Some references I could find quickly:
> 0 votes

# Answer
It looks like this is related to the issue I raised on the Services module issue queue File is created but can't view it in the browser.

I tried a few times to save a file by attaching the base64 encoded data, returned by Javascript whenever I load a file from my application.

I could only make it work by removing the base64 identifier at the beginning of the string which seems too much of a hack... So I modified Services' file resource, using *file\_get\_contents()* in order to retrieve the image content.

You can find a patch on the issue page. Word of caution, although , I simply replace a function, this patch hasn't yet been tested!
> 0 votes

---
Tags: 7, services
---


# Question
Title: Add css to nodes of certain content type
I've been trying to add css to a content type for a while, but I can't seem to find any help on this for drupal 8.

How do you add a library to only the nodes of a content type?

Thanks in advance!

# Answer
> 7 votes
The generic answer:

```
if (some condition) {
  $something['#attached']['library'][] = 'yourmodule/yourlibrary';
}

```

If you're in a module, do it in `hook_node_view()` and add it to $build. If you're in a theme, do it in `hook_preprocess_node()` and add it to $variables.

some\_condition for your case would be `$node->getType() == 'your_type'`, in case of preprocess, the node object is in `$variables['node']`

You can even do it directly within a template with `attach_library()`, see https://www.drupal.org/node/2456753.

---
Tags: 8, theming
---


title: How to use sdpm() or dpm()?

text:
# Question
Title: How to use sdpm() or dpm()?
Almost everywhere I search I find the following example for using `dpm()` or `sdpm()` with the Devel and the Search Krumo modules:

> Paste the following code in your theme's template.php file, save, and clear cache.
>
> ```
> function foo_form_alter(&$form, $form_state, $form_id) {
>   if ($form_id == 'search_block_form') {
>     sdpm($form);
>   }
> }
>
> ```

This is working fine.

But how can I see the other components, like Menu and its components or any block?

I tried following for menu but it is not working.

```
function mymodule_menu_link_alter(&$item, $menu) {
   sdpm($menu);
}

```

# Answer
> 2 votes
`hook_menu_link_alter()` accepts only one argument in Drupal 7. That's why your code isn't working.

Try the following:

```
function YOURMODULE_menu_link_alter(&$item) {
  if ($item['menu_name'] == 'YOUR_MENU') {
    dpm($item);
  }
}

```

I have wrapped it in an if check, since otherwise it would run `dpm` for all menu links on a page and depending on the amount of links it may cause memory overflow or timeout.

---
Tags: 7, debugging
---


# Question
Title: Is it possible to redirect anonymous users from /admin to /user?
Say I have a site called drupal.local, the user login page would be `drupal.local/user`. And the admin 'homepage' would be `drupal.local/admin`.

The problem is that lots of people seem to expect `drupal.local/admin` to lead them to the login page if they are not already logged in. Unfortunately instead of doing that, they just get:

> You are not authorized to access this page.

I guess (thinking about it) a decent solution would be to put a link to the login page in the 403 error template text - but it would be more elegant to redirect the user to /user if they weren't already logged in.

Is it possible to do such a thing?

# Answer
Sure, you can install a module like Redirect 403 to User Login:

> Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:
>
> > "Access denied! You must login to view this page."
>
> Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.
> 5 votes

# Answer
You can also go for LoginToboggan

```
Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

```
> 3 votes

# Answer
You could use the Rules module for this. Here is the rule you'd need for it (in Rules export format, just use copy/paste to import it in your own setup):

```
{ "rules_redirect_admin_path_to_user_path" : {
    "LABEL" : "Redirect admin path to user path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "admin",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "To access this path (= /admin) you need to login first, you will be redirected automatically to  path (= /user)." } },
      { "redirect" : { "url" : user" } }
    ]
  }
}

```

This rule uses 2 Rules Conditions:

* Is this an anonymous user?
* Does the current path start with `/admin`?

Whenever such redirect actually happens (that is: both Rules Conditions are satisfied), the user will also receive an informational message like so:

> *To access this path (= `/admin`) you need to login first, you will be redirected automatically to path (= `/user`).*

If you don't want such message to appear, then just delete the line containing `drupal_message` in the exported rule above.

Similar to the previous answers, it might require you to enable an extra contributed module (Rules). But, as indicated by its growing popularity also, that module is probably already enabled in mostly any site (similar to the Views module), because there are dozens of use-cases for this module).

**Note**: IMO it makes sense to perform such redirect for any path that *starts with* `/admin`. But should you rather prefer to perform such redirect only for an exact match for path `/admin` (instead of starting with such path), then simply replace the 2nd Rules Condition with this one (that is: omit the "operation" which is "starts"):

```
  { "text_matches" : {
      "text" : [ "site:current-page:path" ],
      "match" : "admin"
    }
  }

```
> 1 votes

---
Tags: 7, users, redirection
---


# Question
Title: How do I let users unpublish and publish their own content?
I want to let users unpublish and publish their own content. By default, you have to give "administer nodes" permission for users to be able to unpublish or publish content. That is way to broad though. I want to let users unpublish or publish a node if and only if they created it. This also means they should be able to view unpublished nodes if and only if they created it.

# Answer
> 22 votes
A UI approach which I have used on some sites is the Override Node Options module, adds permissions similar to those that my other answer provides, plus a bunch extra.

# Answer
> 21 votes
We always use the Publish Content module for that. It adds a number of fine-grained permissions and a publish/unpublish tab on nodes.

> This module
>
> * enables granular publish and unpublish permissions:
>     + global (un/publish any content)
>     + per "node type" (un/publish any \[nodetype\] content)
>     + per user (un/publish own \[nodetype\] content
> * adds a "Publish/Unpublish" tab to the node page for one-click un/publishing.
> * exposes publish/unpublish links to your views, making it easy to streamline workflows for reviewers, editors and publishers.
> * is lightweight and always will be.

# Answer
> 10 votes
I'd recommend using the Revisioning Module which gives you a few benefits over the above methods. One of course is that it is a fully maintained module and thus there will be a lot of eyes on the code and plenty of bug fixes. Two, you will get more features to fit this into your overall workflow.

For your use case, gives your users both the "creator" permissions and the "moderator" permissions, so they can basically moderate their own content, but as says in the module description, they are *not* given god-like powers such as giving 'administer nodes' would give.

# Answer
> 6 votes
There is a module that does this, but I can't quite remember the name. I actually felt that the approach the module took was too cumbersome, it had a lot of code when the actual important code was only really one line wrapped with some permission logic.

This is my version of the code:

```
function MYMODULE_perm() {
  $perms[] = 'administer status of any content';

  foreach (node_get_types() as $type) {
    if (isset($type->type)) {
      $perms[] = 'administer status of any '. check_plain($type->type) .' content';
      $perms[] = 'administer status of own '. check_plain($type->type) .' content';
    }
  }

  return $perms;
}

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'node-form' && $form_id == "{$form['#node']->type}_node_form" && _MYMODULE_access($form['#node']->type)) {
    if ($form['options']['#access'] == FALSE) {
      $form['options']['#access'] = TRUE;
    }
  }
}

function _MYMODULE_access($type) {
  return user_access('administer status of any content')
      || user_access('administer status of any ' . check_plain($type) . ' content')
      || user_access('administer status of own ' . check_plain($type) . ' content');
}

```

That adds a few extra permissions that allow you to allow users to publish/unpublish their own or all of a content type, and all content types, set how you wish.

# Answer
> 3 votes
I just want to update Decipher answer, witch seams to me the best approach if you do not want to add another module, to fit for Drupal 7 :

```
/**
 * Implements hook_permission().
 */
function MYMODULE_permission() {
  $perms = array(
    'administer status of any content' => array(
      'title' => t('Administer status for all content type'),
      'description' => t(''),
      'restrict access' => true
    ),
  );

  foreach (node_type_get_types() as $type) {
    if (isset($type->type)) {
      $perm_types = array(
        'administer status of any '. check_plain($type->type) .' content' => array(
          'title' => t('Administer status of any '. check_plain($type->type) .' content'),
          'description' => t(''),
        ),

        'administer status of own '. check_plain($type->type) .' content' => array(
          'title' => t('Administer status of own '. check_plain($type->type) .' content'),
          'description' => t(''),
        ),
      );
      $perms = array_merge($perms,$perm_types);
    }
  }

  return $perms;
}

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (preg_match('/_node_form$/', $form_id) && _MYMODULE_access($form['#node']->type)) {
    if ($form['options']['#access'] == FALSE) {
      $form['options']['#access'] = TRUE;
    }
  }
}

function _MYMODULE_access($type) {
  return user_access('administer status of any content')
      || user_access('administer status of any ' . check_plain($type) . ' content')
      || user_access('administer status of own ' . check_plain($type) . ' content');
}

```

# Answer
> 1 votes
You can achieve this by combining the power of the Flag and Rules modules.

1. Create a new Flag *Publish* and give users permission to only flag their own content.
2. Next, add a new Rule that triggers when a node is flagged and that publishes the flagged node. Similarly, create a second Rule that unpublishes nodes which are unflagged under *Publish*.
3. Finally, give users permission to see their own unpublished nodes and add a *Publish* link to the node's pages.

# Answer
> -1 votes
The content access module should cover what you want.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

---
Tags: users, nodes
---


# Question
Title: theming form of block subscription newsletter module
someone could tell me how to form theming block newsletter subscription module, I use the bootstrap theme and I want to change the markup and add some classes css

# Answer
There are many ways. One is this way to theme the blocks.

There is simpler way to add a class to a block then add css in the theme info file.
> 0 votes

---
Tags: theming
---


# Question
Title: AJAx HTTP ERROR, can't add views to Drupal 7 site, same behavior on 2 different sites
I get these errors when creating views at every step, in Chrome errors says 200 in Firefox says 500...

I can get as far as having the view created, by ignoring the error, but then I can't add any fields, so it renders my Drupal site useless basically.

I have played around with Jquery versions and no solution seems to work.

Additionally, this behavior can be seen on 2 different website, identical...

Sites are both up to date Drupal 7, on status report everything is immaculate, they both run Boostrap theme but the admin Theme is Bartik

# Answer
> 0 votes
It was a problem with the hosting company....but they were great and changed to PHP 5.4(native) right away, fixed it.

Great job namecheap.com hosting, as usual, they are actually really good

---
Tags: ajax, javascript
---


# Question
Title: ajax on button throw exception The specified #ajax callback is empty or not callable
I have made a form for my module with a button using AJAX callback to fill in values in multiple select form another multiple select but when pressing the button the AJAX not triggered at all and when checking the logs an exception shows with the message:

> Symfony\Component\HttpKernel\Exception\HttpException: The specified #ajax callback is empty or not callable. in Drupal\Core\Form\FormAjaxResponseBuilder-\>buildResponse() (line 67

Here is my code:

```
public function getFormId() {
    return 'ads_admin_form';
}

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

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['cats-wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'cats-wrapper', 'class' => ['shownselect']],
    ];
    $form['bind-wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'bind-wrapper', 'class' => ['shownselect']],
    ];
    $form['cats-wrapper']['cats'] = array(
        '#type' => 'select',
        '#title' => t('Category'),
        '#options' => Place_AdsController::getClassifiedContentTypes(),
        '#ajax' => array(
            'callback' => '::catSelectedCallback',
            'wrapper' => 'bind-wrapper',
            'effect' => 'fade',
            'event' => 'change',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        ),
    );
    $form['bind-wrapper']['terms-wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'terms-wrapper', 'class' => ['shownselect']],
    ];
    $form['bind-wrapper']['fields-wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'fields-wrapper', 'class' => ['shownselect']],
    ];
    $form['bind-wrapper']['terms-wrapper']['terms'] = array(
        '#type' => 'select',
        '#title' => t('Available Terms'),
        '#multiple' => TRUE,
        '#options' => NULL,
        '#size' => 7,
    );
    $form['bind-wrapper']['terms-wrapper']['addTermsBtn'] = array(
        '#type' => 'button',
        '#value' => t('>>'),
        '#ajax' => array(
            'callback' => '::termsSelectedCallback',
            'wrapper' => 'selectedterms',
            'effect' => 'fade',
            'event' => 'click',
            'prevent' => 'submit',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        ),
        '#attributes' => ['class' => ['bindBtn']],
    );
    $form['bind-wrapper']['terms-wrapper']['selectedterms'] = array(
        '#type' => 'select',
        '#title' => t('Selected Terms'),
        '#multiple' => TRUE,
        '#options' => NULL,
        '#size' => 7,
    );
    $form['bind-wrapper']['fields-wrapper']['fields'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#title' => t('Available Fields'),
        '#options' => NULL,
        '#size' => 7,
    );
    $form['bind-wrapper']['fields-wrapper']['addFieldsBtn'] = array(
        '#type' => 'button',
        '#value' => t('>>'),
        //'#executes_submit_callback' => FALSE,
        //'#limit_validation_errors' => FALSE,
        '#attributes' => ['class' => ['bindBtn'], 'onclick' => 'return (false);'],
    );
    $form['bind-wrapper']['fields-wrapper']['selectedfields'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#title' => t('Selected Fields'),
        '#options' => NULL,
        '#size' => 7,
    );

    $form['bindFields'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
        '#attributes' => ['id' => 'bindFieldsBtn'],
        '#submit' => ['::submitForm'],
    );
    return $form;
}

public function catSelectedCallback(array &$form, FormStateInterface $form_state) {
    $val = $form_state->getValue('cats');
    $terms = Place_AdsController::getsubCategory($val, 10);
    $currFields = Place_AdsController::contentTypeFields($val);
    unset($terms[current(array_keys($terms))]);
    $form['bind-wrapper']['terms-wrapper']['terms']['#options'] = $terms;
    //$form['bind-wrapper']['terms-wrapper']['#attributes']['class'] = ['shownselect'];
    $form['bind-wrapper']['fields-wrapper']['fields']['#options'] = $currFields;
    //$form['bind-wrapper']['fields-wrapper']['#attributes']['class'] = ['shownselect'];

    return $form['bind-wrapper'];
}

public function termsSelectedCallback(array &$form, FormStateInterface &$form_state) {
    $selected_index = $form_state['values']['terms']['und'];
    $val = $form_state->getValue('terms');
    $form['bind-wrapper']['terms-wrapper']['selectedterms']['#options'] = $val;
    return $form['bind-wrapper']['terms-wrapper']['selectedterms'];
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message('Nothing Submitted. Just an Example.');
    $new_node = array();
    foreach ($form_state->getValues() as $key => $value) {
        $new_node[$key] = $value;
    }
}

```

# Answer
Not totally sure but I think that the problem is that both buttons (`addTermsBtn` and `addFieldsBtn`) have the same `#value`. Try to use different `#value` for the buttons or use #name attribute for differentiate them.
> 5 votes

# Answer
Change your callbacks to be like this:

```
'callback' => [$this, 'catSelectedCallback'],

```
> 2 votes

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


# Question
Title: Filter a view on field on a user referenced entity
Given:

* A view with some field
* A field with referenced entity on user entity, named: `assigner`
* A filter on the field `assigner`

How i can filter by a list of user? if i apply the same filter on `Authored by` it works.

The only option view edit form shows me is a filter on text base input.

# Answer
> 0 votes
Before adding a filter on the user name you need a relationship for your field `assigner`. This in the advanced section of views. After you have set up the relationship:

**User referenced from field\_assigner**

You can add a filter:

**Name (autocomplete)**

and choose the relationship:

**field\_assigner: User**

---
Tags: 8, views
---


# Question
Title: how to display entity references as numbered list?
I'm selling music albums in Commerce. The product type has an entity reference field with unlimited values for the content type 'tracks' which I'm using to display the tracklist of an album. I'd like to output this field as a numbered list so the track I reference are displayed like this:

1. track title
2. track title etc.

I also need to be able to export the track number from a View via Views Data Export.

Any ideas as to how achieve this?

# Answer
Its pretty simple, in this example **I will use title instead of an entity reference field**, but it's the same process.

**Step 1)** add `Global: View result counter` as a field.

**Step 2)** Uncheck create label, and checkmark hide from display.

**Step 3)** Re-arrange so your counter is above your entity reference field.

**Step 4)** Re-write results and **use replacement patterns** to format your title field.
> 0 votes

---
Tags: views, entities, commerce
---


# Question
Title: Add a CSS class to a certain text field for node display
How can I add a CSS class to a certain text field? I have a content type, "Board Member", displaying thusly, see my screen shot below if it comes through... This is the node, not a view. The text for "BIO" is typical paragraph style and size. I want it slightly bigger. The field in the content type is a "Long Text with summary". The widget used is "Text Area with a summary". I don't see any way to assign a unique CSS style to it in Drupal. Investigating CSS here, Firebug only shows this:

```
<div class="field field-name-body field-type-text-with-summary field-label-hidden">
<div class="field-items">
<div class="field-item even">
<p>Lorem.....</p>

```

Why is it skipping showing that this field is the "bio". The other lines of text above it "Name" and "Board Member Role" were presenting **unique** classes and thusly I was able to format with css class rules to make them green and large.

I don't want to depend on the user to type in text with WYSIWYG exactly the same style with each of the board members, although that can be done since I've enabled that for FULL and Filtered HTML for that field. I just seems that I should be able to assign a CSS class to this field. I'll be using this field for TEACHERS and STAFF later on as well.

Thanks for the help.

Dave N

# Answer
Another option would be to use Display Suite if you didn't want to use hooks in `template.php`.

This would allow you to add the class directly from the content type edit page, this would probably be a little easier to manage if you started adding more classes to other fields.

1. After downloading Display Suite, you would need to enable: Display Suite, Display Suite UI, Display Suite Extras.
2. Then go to `/admin/structure/ds/list/extras` and check `Enable Field Templates`
3. Go to your content types manage display page and use the "Select A Layout" dropdown, this will enable display suite for that view mode under that content type.
4. Arrange your fields as needed and click the gear button to the right of the field and select Field Template: Expert
5. Check "Field Item" or any of the wrappers and add a class and an element and you're done.

It may seem like a lot to do to complete your specific task but it will make your life much easier in the long run. I haven't built a single site without display suite since I discovered it.
> 6 votes

# Answer
You can implement `hook_preprocess_field()` in your `template.php` file. Here you can check for the field name and add the class you want. Refer here
> 3 votes

# Answer
If I am understanding you, you want the paragraph with the "Lorem....." text wrapped in a class.

You could skip the wrapper and selector the element with:

You could hard code it with the jQuery wrap function:

`$( "SELECTOR" ).wrap( "<div class='bio'></div>" );`

The SELECTOR could again be:

* .wrapperClass:last-child
* .boardMemeberRoleClass + p
> 0 votes

---
Tags: entities, theming
---


# Question
Title: create node with a field and it updates another field in a view, elsewhere on the site
(using D7) I'd like a user to be able to create and save a node of a certain content type and have it so the value or setting of one of the fields called "location" will then update the same field (or another field that tells the user the "location") that's part of a view elsewhere in the site? I'll also want to plot the "locations" of things on a map using openlayers later on. I've looked at rules so far and haven't seen how to do it with rules, but I'm new to rules. And I've seen entity reference, which looks like it takes the place of D6's node reference, but I'm not sure how to use it in this way. So how can I do this?

# Answer
> 1 votes
Sounds like you could create a rule where:

Event = Node-\>After saving new content

Condition = Node-\>Content is of type (your "certain content type")

Action = Set a data value. Use the data selector to drill down to the field that your View elsewhere is displaying for location. Hit Continue. Use the data selector to drill down to the field in the recently created content that your user has entered the location data into. Save.

---
Tags: entities
---


# Question
Title: cannot enable module after DB migration, only in one environment
I have 3 environments: `live`, `stage` & `dev`.

I've taken a database backup from `live` and imported into `stage` & `dev`.

I clear all caches on `stage` & `dev` and navigate to `/admin/modules` to turn on `module_a` but on `stage` it's disabled and i'm unable to enable it.

It seems strange that I am enable it locally but it's `disabled` on `stage`.

How do I go about debugging this?

# Answer
> 0 votes
The system module builds this form in the function `system_modules()`. It disables a module in the UI under 3 conditions:

* The module is required by your Drupal distribution.
* The module is missing a dependency.
* The module (or one of its dependencies) has version incompatibility with Drupal core.

In any of these cases, you can click the Description fieldset which shows the dependencies required and highlights the ones that are missing.

Another direct method is to utilize the Drush command:

```
drush en module_a

```

Drush will attempt to enable the module and alert you if `module_a` doesn't exist or it has unmet dependencies (which should help you track down what is missing).

---
Tags: 7, database, migrations
---