# Question
Title: Injecting additional content from multiple sources into a block using twig
I have a module which presents a table of contents from a twig template of examples on to how to use the module. This listing is located at /flot-examples. I would like additional modules to be able to add links to this list. The main module, flot\_examples has a block, plugins defined like this:

```
<ul>
{% block plugins %}
{% endblock %}
</ul>

```

This way, any plugin modules can add `<li><a href='flot-examples/[plugin_name]'>plugin example</a>` to the list

If I have only one plugin, I think I could override the route to /flot-examples by the plugin, call `{{ parent() }}` and inject content into `{% block plugins %}` However, if I have multiple plugins, they all can't do that.

I also see that there is a way for the parent to identify child scripts as 'appendable':

```
{% use [child_module].html.twig with appendable as appendableContent %}

```

This would work, but the parent module would have to be given a list of the child modules. If this is the best way to accomplish this, I imagine I would have to:

1)add an array to the parent module, flot\_examples, (where?) so that...

2)the child modules would append their names to (where?) so that ...

3)when this array is passed to the twig template (flot\_examples.module and somewhere else?), it can loop over the array (in the twig temple) to generate the `{% use .... %}` statement.

I guess I can see another strategy would be to move this directory listing out of a twig template, and just use render arrays. Then would the child module use preRender functions to append additional list items to the render array, somehow?

Are any of these on the right track? Which would be "the best" or "the easiest" way?

# Answer
I went with a hook instead. There must not be a way to do this in twig.

This section resides in a controller in the parent module:

```
$plugin_items = [];
// Call modules that implement the hook, and let them add items.
\Drupal::moduleHandler()->alter('flot_examples_toc', $plugin_items);
if (count($plugin_items > 0)) {
  $output['plugins'] = [
    '#title' => 'Plugins',
    '#theme' => 'item_list',
    '#items' => $plugin_items,
  ];
}

```

And this resides in the child \[module\].module file.

```
<?php
use Drupal\Core\Url;
function flot_spider_examples_flot_examples_toc_alter(&$item_list) {
 $options = [
      ':one' => Url::fromRoute('flot_spider_examples.example')->toString(),
    ];
 $item_list[] = t('<a href=":one">Spider Chart</a> (with spider plugin)', $options);

```

}

The parent creates an array and passes it to the children by reference. They can alter the array by adding elements to it. The parent then adds it to the render array.
> 1 votes

---
Tags: theming, 8
---


title: How to disable default site?

text:
# Question
Title: How to disable default site?
I used Drupal multisite approach. When I go to `mydomain.com` the default site is loaded and if I deleted `sites/default/settings.php` file, it is creating again.

How do I disable the default site so that, not even the installation page is shown?

# Answer
> 1 votes
Create a directory under the `sites` directory besides `default` with the exact name as your domain and place the settings.php file in it. You can delete the default/settings.php after this.

# Answer
> 0 votes
You can follw these documents for better understanding of multisite approach in Drupal.
link1 Link2

If possible you can mention in your question, which steps you have followed also.

# Answer
> 0 votes
You can just delete everything in default/settings.php and write whatever logic you like in settings.php (print message, redirect, just exit, etc ....) and don't forget exit() the the script after you finish.

Also you can choose one of the sites you have to act as a default site just replace the default directory with it.

@see conf\_path() for the code implementation of Drupal multi-site.

---
Tags: 7, multi-sites
---


title: Build-in query persist?

text:
# Question
Title: Build-in query persist?
Is there a default Drupal 8 database persist function? Like as for Doctrine.

```
for($i=1;$i<100;$i++) {
    $query->persist();
}

$query->flush();

```

I want to collect first a lot of data and bulk send it to the database.

The code I am using now is the following.

```
$db = \Drupal::database();
foreach($response->customer_products as $itemCode) {
    $productNode = $this->loadObjectProduct($itemCode);
    $db->insert('customer_product')
           ->fields([
              'card_code' => $cardCode,
              'item_code' => $productNode->id()
           ])
       ->execute();
}

```

That requires too much memory, and it fires a lot of queries.

Is there some way to collect the queries and bulk-send it to the database?

# Answer
It's possible to stuff more values into a custom insert (or merge) by using the values method. This isn't comparable to the persist functionality, and can only be used in limited scenarios such as a single table. A more complex storage scenario, such as with entities, would not be possible as a single entity save operation could be writing to multiple tables (unless someone rewrote a custom entity storage layer).

Also, I am not sure what the loadObjectProduct exactly does in your code, but this seems to be loading node entities. It would probably be best to use an Entity Query::condition and fetch back multiple entities.

Finally you need to use an array map/reduce to map the values.

Something like the following pseudo-code:

```
// Using Database static method from \Drupal\Core\Database\Database.
$database = Database::getConnection();
// Assumes loadObjectProduct is refactored.
$nodes = $this->loadObjectProducts($itemCode);
// I tend to think backwards about this sort of thing. :-)
$values = array_reduce($nodes, function (&$result, $productNode) use ($cardCode) {
  $result[] = [
    'card_code' => $cardCode,
    'item_code' => $productNode->id(),
  ];
  return $result;
}, []);

try {
  $database->insert('customer_product')
    ->fields(['card_code', 'item_code'])
    ->values($values)
    ->execute();
}
catch (DatabaseWrapperException $e) {
  // Catch errors
}

```
> 1 votes

---
Tags: 8, database
---


# Question
Title: Garland sub-theme color functionality is not working
I have a subtheme in Drupal 7 for Garland theme. below is my my\_garland.info file for the sub-theme

```
name = My Custom Sub Theme
description = Custom sub-theme of Garland
core = 7.x
base theme = garland
stylesheets[all][] = my_garland.css

```

i have also include some information in the template.php file to help with the color module

```
function my_garland_process_html(&$vars) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($vars);
  }
}

```

I have also copied the color and images file from the garland theme therefore the initial blue works perfectly and i can see the color wheel but the total page layout is not changing. I have also tried to follow this link to see if it will be resolved but all in vain. Thanks in advance for your assistance.

# Answer
> 0 votes
From Example: Creating a Garland Subtheme That Utilizes the Color Module

> That said, even if you do not have a style.css file in your subtheme directory, you still must add it to your .info file with stylesheets\[all\]\[\] = style.css

---
Tags: 7, theming
---


# Question
Title: How do I use variables from config.ini.php?
I have a **config.ini.php** file as follows :

```
;<?php
;die(); // For further security
; // These php lines are used to hide the data from the browser
; // They are both valid php and valid ini files
;/*
; Don't forget to disable and reenable module, after adjusting the values
[folders]
var_1= "value1"
var_2 = "value2"

```

And in **module\_name.install** file, I am using it as follows.

```
/**
 * Implementation of hook_enable().
 */
function module_name_enable() {
  $config_file = 'config.ini.php';
  $parameters = parse_ini_file($config_file);
  foreach ($parameters as $key => $value) {
    \Drupal::state()->set($key, $value);
    \Drupal::config('module_name.settings')
      ->set($key, $value)
      ->save();
  }
}

```

I then try to use a variable with the following code.

```
$getvar = \Drupal::config('module_name.settings')
      ->get('var_1');
\Drupal::state()->get('var_1', '');

```

I am not getting the value. What am I doing wrong?

# Answer
> 4 votes
As far as I know, you shouldn't be using a "config.ini.php" file for configs in your custom module.

You should have a /examplemodule/config/install/examplemodule.settings.yml file like this:

```
var_1: "value1"
var_2: "value2"

```

Then when you reinstall your module, it adds the values. There's no need to run code in hook\_install.

To access the values, use:

```
\Drupal::config('examplemodule.settings')->get('var_1');

```

and to edit:

```
\Drupal::configFactory()
  ->getEditable('examplemodule.settings')
  ->set('var_1', $value)
  ->save();

```

You're using state correctly, I tested this out:

```
\Drupal::state()->set('var_1', $value);

$var_1 = \Drupal::state()->get('var_1');

```

# Answer
> 3 votes
`hook_enable` doesn't exist any more. Your code should be in `hook_install`

Other than that, this will set a value:

```
\Drupal::configFactory()
  ->getEditable('module_name.settings')
  ->set('var_1', $value)
  ->save();

```

And this will retrieve it:

```
\Drupal::config('module_name.settings')
  ->get('var_1');

```

Just tried it, confirmed to be working. If you're still not seeing the value, there's something wrong with your non-Drupal code (the ini file parsing), or the context in which you're trying to retrieve it.

---
Tags: 8
---


# Question
Title: Set view's filter to show nodes of entity refference field of current node
I have nodes of content type "product" and this content type has an entity reference field with multiple values, that contains references to another product nodes.

Is it possible to set the filter of view block to show only products that are in current opended product's reference field?

# Answer
What you want is views' right column.

You need to use a contextual filter of `Content: nid`, choose to provide a default value `Content id from url`. If you want to suppress the current product (eg. for a related products display use the `Exclude` option in the `More` fieldset at the bottom.)

Then add a relationship and select your entity reference field.

Finally you can add the field `Content: rendered node` and at the top choose your newly created relationship. This should give you a list of referenced products.

Update: I guess the exclude option takes no effect in this case, since you'll be only listing the referenced products.
> 1 votes

# Answer
I found solution by adding new filter criteria of Global:PHP(PHP) type, where you can type your own php logic, in my case:

```
$node = node_load(arg(1));

if(isset($node->field_recommended_products['und'][0])) {

  foreach($node->field_recommended_products['und'] as $prod)  {

     if($prod['target_id'] == $data->nid) {
       return true;
     } else { return false; }

  }

} else {
  return false;
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How to overwrite Paragraphs Item on subpages?
I am using a couple of Drupal Paragraphs Items in full-size edge-to-edge view with Bootrap’s container class. It’s working great.

I’ve applied a container class to paragraphs-item--service.tpl.php

However how can I overwrite the paragraph item on a subpage that uses a 2 column layout?

# Answer
Instead of putting it into the template, a better solution would be to use the hook\_entity\_view\_alter to add the classes based on some conditions.
> 0 votes

---
Tags: theming
---


# Question
Title: How to clear unused files from the database and the filesystem?
I would like to have a script that runs on cron, to delete all files that are not currently being used. I noticed that the file\_usage table and the hard drive are getting filed with them.

Is there a way to do so?

# Answer
Drupal should be taking care of this for you. The pattern that modules should be following is:

* When you're adding a new file call file\_save() (or a function that calls calls it) then call file\_usage\_add() to let the system know it's being used.
* When you're done with a file call file\_usage\_delete() to release it then call file\_delete($file, FALSE). The FALSE indicates that it should be deleted only if nothing else is using it.

So unless you've got a buggy module there probably aren't to many unused files sitting around but if you wanted to check it you could run the following query:

```
select fm.* from file_managed fm
left join file_usage fu on fm.fid = fu.fid
where fu.fid is null

```

I ran that on a test site and noticed that the devel\_generate module isn't properly registering usage of the user's pictures when it creates them. You might notice similar things.
> 3 votes

# Answer
I don't think this is a very good idea. What guarantees you that because the file is currently not being used it will not be used in the future? Also, there are many reasonably priced hosts that offer unlimited hard drive space for like $10 dollars a month so hard drive space would be the least of your concerns. You could consider migrating your site to one of those.
> 0 votes

# Answer
Something that may help is to use the File Checker module. Some details about it, from its project page:

> In a perfect Drupal world your server filesystem and its correspoding entries in Drupal's files table are 100% synchronized. But what if parts of your file system have been corrupted due to some disk failure? Or one of your modules messed up your database and files? Or your deploy script went beserk? Well, then this module will help you to monitor and find out which files are out of sync.
>
> Out of the box the files table has two kind of statuses: Temporary (0) and Permanent (1). The file checker introduces an additional status Missing (2). In scope of the verification process which can be triggered in various ways the status column of the files table is updated.
>
> **Features**
>
> * Run verification process: on demand, via cron, via drush (in planning)
> * File list overview page with filters
> * Views integration
> * Drush command for file checking
>
> If you want to export the results of a view it's recommended to use views\_data\_export module.
> 0 votes

---
Tags: 7, files, cron
---


# Question
Title: Views output does not match actual output
I have a view that I finally got to work in the view preview. Then I go to the link that should give me the same result at the preview and I get the no results behaviour. I double-checked that the view is saved and I cleared the cache.

When I visit the url in the preview area, I do not get the result in the preview. Any ideas of what I did wrong?

# Answer
I found the answer. Honestly, I was being a derp and a noob. Maybe I just needed time to think about it before posting a question. I will answer it here in case anyone else runs into the same issue.

**Make sure you do not have any other views using the same url pattern!**

This is a view I have been trying to make work for a while because I needed to reference two different vocabularies that were attached to the content type: location and department. It proved to be slightly more complicated than a typical view because of the two vocabularies and because of Drupal 8 which I am still getting used to. I forgot to delete or disable the previous view I was trying to figure it out in. When I deleted the old view that didn't work (but used the same url pattern), everything was fine.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Constant Contact module puts subscribe checkbox on every user profile page
So, we are using the Constant Contact module to allow users to sign up for newsletters on our website. In the admin pages the module provides a 'Subscribe Method' option that let's you specify how users opt-in to the newsletter feature. We are using 'checkbox'.

This is all fine, except that we are also using user profiles, with multiple categories. When a user goes to edit his or her account details this 'subscribe' checkbox is appearing on every single category page, even when its totally irrelevant.

Is there some way we would be able to hide / remove this field from displaying anywhere other than the user's 'account' page?

# Answer
I found this same issue. It is due to a bug in the module. I have submitted an issue here and have attached a patch which fixes the bug.
> 1 votes

# Answer
If you have the block module enabled - try removing it.

If you like how the block module displays the checkbox information - its for new "newsletter signups" - restrict it's view.

1 - Go to - admin/structure/block/manage/constant\_contact/1/configure 2 - Head all the way to the bottom for visibility settings. 3 - add which nodes/pages you'd like it to be visible in. You can use * as a wildcard. 4 - Save settings. 5 - Save blocks.

Check if that works for you.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How are SQL queries properly handled within a module?
I would appreciate a little guidance on where to begin so I don't waste a ton of time looking in the wrong places.

I have a content type that has a number of associated entities appended to it; these all have date ranges on them. I need to create a module that upon `hook_node_save()` and `hook_node_insert()` checks other associated entities for various date conditions (do dates completely overlap, or partially overlap) and either adjusts the dates on those entities, or deletes the entity.

I know how I'd do this if it was purely SQL, but I want to do it the *Drupal way*.

How are SQL queries properly handled within a module?

# Answer
Drupal essentially has three groups of functions to query the database:

* Functions to make static queries
* Functions to make dynamic queries
* Functions to make queries about entity fields

`db_query()` and `db_query_range()` are part of the first group, while `db_select()` is part of the second group; finally the `EntityFieldQuery` class is what you use for queries involving the values of entity fields.

To make clear which functions you should use, keep in mind that dynamic queries are those queries that are dynamically built at run-time, such as in the following code.

```
$table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);

$query = db_select($table, 't')
  ->fields('t')
  ->condition('entity_type', $entity_type)
  ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
  ->condition('language', field_available_languages($entity_type, $field), 'IN')
  ->orderBy('delta');

```

Since the table name changes at runtime, using that code is preferable to concatenate strings to build the query.

Dynamic queries are also those that needs to be altered by other modules, such as the following one.

```
if ($nids) {
  $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
  $query->join('node', 'n', 'b.nid = n.nid');
  $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
  $query->addField('n', 'type', 'type');
  $query->addField('n', 'title', 'title');
  $query->fields('b');
  $query->fields('ml');
  $query->condition('n.nid', $nids, 'IN');
  $query->condition('n.status', 1);
  $query->orderBy('ml.weight');
  $query->orderBy('ml.link_title');
  $query->addTag('node_access');
  $result2 = $query->execute();
  foreach ($result2 as $link) {
    $link['href'] = $link['link_path'];
    $link['options'] = unserialize($link['options']);
    $all_books[$link['bid']] = $link;
  }
}

```

`$query->addTag('node_access')` allows other modules to alter the query to return only the nodes to which the currently logged-in user has access.

In the other cases, it is preferable to use a static query, which are faster. The only case you should not use static queries is when the query involves the value of entity fields; in which case, you should use the `EntityFieldQuery` class, which avoids you need to know any details about how entity fields are implemented (e.g. which database classes contain the field values).

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year . '%', 'like')
  ->fieldOrderBy('field_photo', 'fid', 'DESC')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

```
> 1 votes

---
Tags: 7, database
---


title: How to use menu_get_object()?

text:
# Question
Title: How to use menu_get_object()?
I was using `menu_get_object()` to load node information in Drupal 6.

```
if ($node = menu_get_object()) {
    // Get the nid
    $nid = $node->nid;
  }

```

Since `menu_get_object()` is deprecated in Drupal 8, I was using the following code.

```
if ($node_id = \Drupal::request()->attributes->get('node')) { #menu_get_object()
    //load all the information of the node
    $node = node_load($node_id);
  }
  echo '<pre>';print_r($node);exit();echo '</pre>'; //its okay
  echo $node->type->value; //not working

```

This is not getting the node values, but printing the node information's in array. How do I resolve this ?

**UPDATE**

I am getting all other values like `$node->title->value` and `$node->nid->value`, but not `$node->type->value`.

# Answer
> 7 votes
See https://drupal.stackexchange.com/a/202185/45409

In Drupal 8, you can get url arguments based on what's in the routing.

To get the id alone:

```
$nid = \Drupal::routeMatch()->getRawParameter('node');

```

If you plan to load the node object, you can simply get it this way:

```
$node = \Drupal::routeMatch()->getParameter('node');

```

To find the parameter names, you can use:

```
$possible_parameters = \Drupal::routeMatch()->getParameters();

```

To find the node type, use:

```
$node->bundle();

```

# Answer
> 4 votes
`\Drupal::request()->attributes->get('node')` will return the node object, not the node id.

```
if ($node = \Drupal::request()->attributes->get('node')) {
  kint($node);
  echo $node->getType();
}

```

# Answer
> 3 votes
If you compare what Drupal 7 does in `template_preprocess_page()` with what Drupal 8 does in the same function, you will see that the first function uses the following code.

```
  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

```

The second function uses the following code.

```
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }

```

page.html.twig descrives `node` as follows:

> **node**: Fully loaded node, if there is an automatically-loaded node associated with the page and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

Also, `node_load()` should be replaced with the following code.

```
use \Drupal\node\Entity\Node;

$node = Node::load($nid);

```

You don't need `Node::load()` since `$variables['node']` already contains a full-loaded node object.

---
Tags: nodes, 8
---


# Question
Title: How do I redirect to www and https in settings.php?
I want to include code in settings.php which would handle redirects to the www alias and also https.

Because it is for a distribution I would prefer not to have hard-coded URLs and I would also prefer not to be changing the .htaccess file so that core updates are easier.

I am using the code below, and I just want to be sure it doesn't have any security issues. Does it have any security issues, and I should therefore use different code?

```
// Redirect to www
  if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
  header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
exit;
}
// Redirect to HTTPS
  if($_SERVER["HTTPS"] != "on")
{
  header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}

```

# Answer
> 5 votes
The caveat to the **settings.php** approach is 2 issues:

1. Your redirect requires that Drupal be bootstrapped to work. If there's a resource that bypasses Drupal (e.g. any hosted files), you're not going to see the www redirect occur.
2. It's arguably bad practice. **settings.php** is for Drupal settings; depending on your intent this might be considered a *web server* setting. A developer working on your project in a local environment might have trouble understanding where the redirect is coming from as standard Drupal configurations use the **.htaccess** file for this.

An alternative to prevent **.htaccess** overwriting would to be place the rewrite directive in an Apache configuration (e.g. vhost.conf if you're using virtual hosts) that defines your host.

# Answer
> 1 votes
You can also choose to use the htaccess module that allows these options with some radio buttons. It comes with Drush integration for re-deploying the .htaccess file after a core update, and monitors and warns if the file has changed. You might find it interesting.

From the module page:

> this module is dedicated to webmasters who don't want to manually modify htaccess every time during a version upgrade to use Drupal.

---
Tags: 7, redirection, security
---


# Question
Title: How should I link (public) files to nodes?
I have many resources (mainly PDFs) that need to be imported to my site. Previously the files would manually be placed in sites/default/files/mydir and linked to the node like this:

```
<a href="/sites/default/files/mydir/mypdf.pdf">Read More</a>

```

This does work, but I am guessing there are probably strong advantages to actually using the content system - perhaps being able to better organize/track/update files.

How do I place files inside of nodes so the file still appears inline with the rest of the content, while actually being tracked by Drupal?

# Answer
UPDATE: I missed the 8 tag

**Drupal 8.x**

UPDATE 2:

So this got trickier. The only way I was able to accomplish it was using these steps:

1. Add a field to the node, I called mine "Media"
2. Instead of selecting "File" from the dropdown list, I selected "Other" under reference, and "File" on the next page, this creates an entity reference field rather than a file field.
3. Add a file through `file/add`
4. In your node, start typing the filename of the file you've added
5. In the body field, enter this token: `[node:field_media-formatted:0:entity_reference_entity_view:default]`

The token inserts the rendered entity for the reference field into your content, you can edit how it looks (for images e.g.) through the display settings for file types (May require the File Entity module), so you can display a link rather than a rendered file.

Someone pointed out in a thread I saw a couple of months ago:

> Drupal 8 is stable with exactly 0 contributed modules installed

That said, moving to Drupal 8 with requirements that fall outside of the scope of core may be premature for someone who isn't prepared to develop their own solutions yet, and this particular solution may change since parts of it rely on contributed modules.

---

Hopefully this will be an appropriate answer in the future

Very similar to how it would be handled in Drupal 7, but because of module availability there are some tweaks. The modules you would need are Token, Token Filter, and File Entity Browser.

The steps are the same as below essentially, but I think the token may use the underscore instead of a dash: `[node:field_files:0:url]`.

Also, once the Token module is installed you can see a list of tokens at `admin/help/token`.

**Drupal 7.x**

There are several mechanisms available to achieve this. If you are using a wysiwyg editor (such as CKEditor), they sometimes have plugins available to allow you to add files directly into the content, but based on what you've stated you need, I think possibly the Media, Token, and Token Insert modules would be a good place to start.

The media module provides a file browser and upload mechanism that works with the core Drupal file system, making it possible to reuse files easily in different pieces of content.

The Token module extends Drupal's core token mechanism, and the Token Insert module allows you to use tokens in text fields.

The basic steps would go something like this:

1. Install all 3 modules, make sure you have the core File module enabled.
2. Go to the "Manage Fields" page for the content type you plan to use these files in and add a "files" field.
3. Add the files that would be used in your article to the files field, either through uploading or using the file browser.
4. Reference the files by index in a token in the text field, a list of available tokens are available here.

This is untested so may require some tweaking, but if the machine name for your file field is "field\_files", the link in the text area would probably look something like this:

`<a href="[node:field-files:0:file:url]">Read More</a>`

That would print the link for the first file that is attached to the node.

There will, of course, be some configuration pages you will have to go through for the media module and field settings, but it's hard to give you any direction on those since they are all very much dependent on your particular installation.
> 1 votes

# Answer
I accomplished this by using Entity embed in WYSIWYG.

1) "Add Embeded Button" in /admin/config/content/embed

2) Configure button to desired needs

3) Create/configure new desired display mode for "File" in /admin/structure/display-modes/view.

4) Edit node that files will be placed in. Click new embed button, reference desired files. Set display mode to the newly created display.

The part of the resulting HTML I care about (download link) is nested within 3 divs, so I used a little JS to style it. I'm leaving Trey's answer as accepted, because tokens would be the better way to do this, but using tokens I couldn't figure out how to select a single value out of a field containing multiple values.
> 0 votes

---
Tags: theming, 8, files
---


# Question
Title: How do I override headers displayed in permissions tables?
I'm using Organic Groups on my (D7) site. I've set it up so that group managers can create new roles and change permissions in their groups. I've overridden some of the permissions using hook\_og\_permission\_alter() to limit what they can actually change, and this seems to work well.

The problem I'm having is I want to alter/remove the section headers (ex. Organic Groups, Organic groups UI) that are set up by the different OG modules in this permissions table (I currently have three modules generating their own heading), and I can't find a way to do this. I can't find a hook that does what I want, and I've tried making sure none of the permissions are associated with the headings, but that didn't remove them. I guess I could edit the modules generating these headings and change their names to what I want the headings to display, but that really doesn't feel like the right approach here (and I'd rather remove the headings altogether anyways).

Does anyone know how I can approach this?

# Answer
Implement hook\_page\_alter() and

```
function mymodule_page_alter(&$page) {
  if (current_path() == 'admin/people/permissions') {
    foreach ($page['content']['system_main']['permission'] as $index => $permission) {
      if ($permission['#markup'] == 'Organic Groups') {
        $page['content']['system_main']['permission'][$index]['#markup'] = 'Foobar';
      }
    }
  }
}

```
> 0 votes

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


# Question
Title: How to combine several form objects into one?
i'm working with Drupal 8 and i want to combine the user form and a node creation form into my custom form.

So i've created the form skeleton :

```
<?php

namespace Drupal\fritr_register_friterie\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class RegisterFriterieForm.
 *
 * @package Drupal\fritr_register_friterie\Form
 */
class RegisterFriterieForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'register_friterie_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form = [];

//        $form = \Drupal::formBuilder()->getForm();

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {

    }

}

```

But i don't know how to import the user\_profile form and the node creation form of a custom content that i've created in the back office.

I know drupal\_get\_form('form\_id') is replaced in drupal 8 by `\Drupal::formBuilder()->getForm(class, parameter);`

Maybe it's something like this : `\Drupal::formBuilder()->getForm(Drupal\user\Form\UserForm::class);`

But i have not find the documentation which show all the locations of form or examples.... And i have not find how to load a node creation form :/

Can you help me please ? Thanks :)

EDIT : i've found how to include my node creation form (but i don't know how to modify my fields... D8 So complex u\_u) by :

```
$type = node_type_load('friterie');
        $node = \Drupal::entityManager()->getStorage('node')->create(array(
          'type' => $type->id(),
        ));

        // OPTIONAL - Set default values for node fields
        // $node->set('field_age', "32") ;
        $node_create_form = \Drupal::service('entity.form_builder')->getForm($node);
        $form['friterie'] = array(
            '#type' => 'markup',
            '#markup' => render($node_create_form),
        );
        return $form;

```

need to find how to load user\_profile form ^^

# Answer
I've created a working example of a combined form object. Please read the comments below if you want to understand how it works and the workarounds that were applied.

The gist can be found here

**Note: There may still be unforeseen issues with the solution below.**

```
<?php

namespace Drupal\sandbox\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;

class ComboForm extends FormBase {

  /**
   * This constant is used as a key inside the main form state object to gather
   * all the inner form state objects.
   * @const
   * @see getInnerFormState()
   */
  const INNER_FORM_STATE_KEY = 'inner_form_state';

  const MAIN_SUBMIT_BUTTON = 'submit';

  /**
   * @var \Drupal\Core\Form\FormInterface[]
   */
  protected $innerForms = [];

  /**
   * The ComboForm constructor needs to initialize the inner form objects
   * that this form will later use.
   *
   * Because both the user and the node forms are entity forms then an entity
   * object needs to be assigned to them.
   *
   * Because the node entity has bundle, the bundle (type) must be defined
   * before the form is generated.
   *
   * @TODO If the node type is customizable then a custom controller is needed.
   *
   * @TODO should this form allow edits? If so then the form objects should
   *       be assigned with the edited entities.
   */
  public function __construct() {
    $this->innerForms['user'] = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity(User::create());

    $this->innerForms['node'] = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity(Node::create([
        'type' => 'article'
      ]));
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId() {
    return implode('__', [
      'combo_form',
      $this->innerForms['user']->getFormId(),
      $this->innerForms['node']->getFormId()
    ]);
  }

  /**
   * The build form needs to take care of the following:
   *   - Creating a custom form state object for each inner form (and keep it
   *     inside the main form state.
   *   - Generating a render array for each inner form.
   *   - Handle compatibility issues such as #process array and action elements.
   *
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#process'] = \Drupal::service('element_info')->getInfoProperty('form', '#process', []);
    $form['#process'][] = '::processForm';

    foreach ($this->innerForms as $key => $inner_form_object) {
      $inner_form_state = static::createInnerFormState($form_state, $inner_form_object, $key);

      // By placing the actual inner form inside a container element (such as
      // details) we gain the freedom to alter the wrapper of the inner form
      // with little damage to the render element attributes of the inner form.
      $inner_form = ['#parents' => [$key]];
      $inner_form = $inner_form_object->buildForm($inner_form, $inner_form_state);
      $form[$key] = [
        '#type' => 'details',
        '#title' => $this->t('Inner form: %key', ['%key' => $key]),
        'form' => $inner_form
      ];

      $form[$key]['form']['#type'] = 'container';
      $form[$key]['form']['#theme_wrappers'] = \Drupal::service('element_info')->getInfoProperty('container', '#theme_wrappers', []);
      unset($form[$key]['form']['form_token']);

      // The process array is called from the FormBuilder::doBuildForm method
      // with the form_state object assigned to the this (ComboForm) object.
      // This results in a compatibility issues because these methods should
      // be called on the inner forms (with their assigned FormStates).
      // To resolve this we move the process array in the inner_form_state
      // object.
      if (!empty($form[$key]['form']['#process'])) {
        $inner_form_state->set('#process', $form[$key]['form']['#process']);
        unset($form[$key]['form']['#process']);
      }
      else {
        $inner_form_state->set('#process', []);
      }

      // The actions array causes a UX problem because there should only be a
      // single save button and not multiple.
      // The current solution is to move the #submit callbacks of the submit
      // element to the inner form element root.
      if (!empty($form[$key]['form']['actions'])) {
        if (isset($form[$key]['form']['actions'][static::MAIN_SUBMIT_BUTTON])) {
          $form[$key]['form']['#submit'] = $form[$key]['form']['actions'][static::MAIN_SUBMIT_BUTTON]['#submit'];
        }

        unset($form[$key]['form']['actions']);
      }
    }

    // Default action elements.
    $form['actions'] = [
      '#type' => 'actions',
      static::MAIN_SUBMIT_BUTTON => [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#validate' => ['::validateForm'],
        '#submit' => ['::submitForm']
      ]
    ];

    return $form;
  }

  /**
   * This method will be called from FormBuilder::doBuildForm during the process
   * stage.
   * In here we call the #process callbacks that were previously removed.
   *
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param array $complete_form
   * @return array
   *   The altered form element.
   *
   * @see \Drupal\Core\Form\FormBuilder::doBuildForm()
   */
  public function processForm(array &$element, FormStateInterface &$form_state, array &$complete_form) {
    foreach ($this->innerForms as $key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $key);
      foreach ($inner_form_state->get('#process') as $callback) {
        // The callback format was copied from FormBuilder::doBuildForm().
        $element[$key]['form'] = call_user_func_array($inner_form_state->prepareCallback($callback), array(&$element[$key]['form'], &$inner_form_state, &$complete_form));
      }
    }

    return $element;
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormValidatorInterface $form_validator */
    $form_validator = \Drupal::service('form_validator');
    foreach ($this->innerForms as $form_key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $form_key);

      // Pass through both the form elements validation and the form object
      // validation.
      $inner_form->validateForm($form[$form_key]['form'], $inner_form_state);
      $form_validator->validateForm($inner_form->getFormId(), $form[$form_key]['form'], $inner_form_state);

      foreach ($inner_form_state->getErrors() as $error_element_path => $error) {
        $form_state->setErrorByName($form_key . '][' . $error_element_path, $error);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormSubmitterInterface $form_submitter */
    $form_submitter = \Drupal::service('form_submitter');

    foreach ($this->innerForms as $key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $key);

      // The form state needs to be set as submitted before executing the
      // doSubmitForm method.
      $inner_form_state->setSubmitted();
      $form_submitter->doSubmitForm($form[$key]['form'], $inner_form_state);
    }
  }

  /**
   * Before returning the innerFormState object, we need to set the
   * complete_form, values and user_input properties from the main form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The main form state.
   * @param string $key
   *   The key used to store the inner form state.
   * @return \Drupal\Core\Form\FormStateInterface
   *   The inner form state.
   */
  protected static function getInnerFormState(FormStateInterface $form_state, $key) {
    /** @var \Drupal\Core\Form\FormStateInterface $inner_form_state */
    $inner_form_state = $form_state->get([static::INNER_FORM_STATE_KEY, $key]);
    $inner_form_state->setCompleteForm($form_state->getCompleteForm());
    $inner_form_state->setValues($form_state->getValues() ? : []);
    $inner_form_state->setUserInput($form_state->getUserInput() ? : []);
    return $inner_form_state;
  }

  /**
   * After the initialization of the inner form state, we need to assign it with
   * the inner form object and set it inside the main form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The main form state.
   * @param \Drupal\Core\Form\FormInterface $form_object
   *   The inner form object
   * @param string $key
   *   The key used to store the inner form state.
   * @return \Drupal\Core\Form\FormStateInterface
   *   The inner form state.
   */
  protected static function createInnerFormState(FormStateInterface $form_state, FormInterface $form_object, $key) {
    $inner_form_state = new FormState();
    $inner_form_state->setFormObject($form_object);
    $form_state->set([static::INNER_FORM_STATE_KEY, $key], $inner_form_state);
    return $inner_form_state;
  }

}

```
> 7 votes

---
Tags: 8, entities
---


# Question
Title: How to check if view is added in a feature?
For Drupal views is there any way/field which tells us if your view is added to a feature or not. And if yes in which feature it is added?

I have a view which I need to check if it is added in a feature or not.I have lot of features on my site and I am searching all the features one by one to check if the view is added in any of them. Is there any other efficient way to check this?

Any guidance is appreciated.

# Answer
The features export views' code in files like this: `my_module.views_default.inc`. Every feature module with a file `my_module.views_default.inc` contains views.

**Manually:**

Searching against those modules by using the view's machine name as an input, will show whether that view machine name is tracked or not, to any of these modules.

**Using drush:**

Having all your features updated `drush fu-all -y` do some changes to a view (save) and `drush fl`. The feature that will appear with an `overridden` status contains that view, otherwise the view is not tracked yet. To see which features contains views code do `drush fc --exported` and select `views_view`, that will narrow down significantly the searching range.

More Features & Drush
> 0 votes

---
Tags: views, features
---


title: Show as expanded doesn't work

text:
# Question
Title: Show as expanded doesn't work
I am trying to make my own theme for drupal 8. but I am struggling with the menu. my menu looks something like this

```
parent1
- child 1.1
- child 1.2
parent2
- child 2.1
- child 2.2

```

but only the parents are visible.

I used the menu.html.twig file from the classy theme.

edit: I tried my theme on other site and there the children are displayed. so guess the problems was not because of theme. so i activated the stark theme, but also there I can't see my full menu tree. and the checkboxes show as expanded are checked

# Answer
> 2 votes
Make sure your parent links are set to **Show as expanded** on the `/admin/structure/menu/manage/main` page

---
Tags: theming, 8, navigation
---


# Question
Title: Alter Ubercart Billing/Delivery Panes with User Profile Info
I'm trying to set a user's profile fields into the checkout process. A user must change these data only in own profile. The uc\_addresses module is unsuitable for my needs. In the order form I need to hide these fields.

Right now I'm using `uc_cart_checkout_form_alter` to do this:

```
function my_module_form_uc_cart_checkout_form_alter(&$form, $form_state, $form_id) {
        // load user data
        global $user;

        $user_fields =user_load($user->uid);

        $first_name   = $user_fields->field_name['und']['0']['value'];

        // add data to order form
        $form['panes']['delivery']['delivery_first_name'][LANGUAGE_NONE][0]['value']['#default_value'] = $first_name;
}

```

But default value isn't there. Where did I go wrong? How can I fill out an order form (Delivery & Billing information) programmatically in Ubercart?

# Answer
The billing/delivery address panes are driven by a custom `uc_address` form field. You need to alter it's `#default_value` object to alter the fields.

For example:

```
$form['panes']['delivery']['address']['#default_value']->delivery_first_name = $user_fields->field_name['und']['0']['value'];
$form['panes']['billing']['address']['#default_value']->billing_first_name = $user_fields->field_name['und']['0']['value'];

```
> 2 votes

---
Tags: 7, users, ubercart, forms
---


title: Return content type

text:
# Question
Title: Return content type
With core search, in `template_preprocess_search_result()` I could access `$vars['result']['type']`. Switching over to Search API Solr, how can I access node type and send it to the theme? Content type is being indexed, but I'm not sure how to return it with the result.

# Answer
> 1 votes
Using Search API pages, I switched to `template_preprocess_search_api_page_result(&$vars)`, and can achieve this by getting the nid.

```
$node = node_load($vars['id']);
$vars['pass_to_template'] = node_type_get_name($node);

```

---
Tags: 7, search
---


# Question
Title: How to change to another image when mouseover using Views?
I need to change the big image "A" to "D" when mouseover thumbnail "D" in a view (using Views).

How can I do this? Preproces page or jquery in a custom text in view?

# Answer
You can try Views Slideshow module with its ThumbnailHover slide feature. You can find its full documentation page in here.

Basically create a view with fields and a pager, set it as slider (Content: *slide*) and check *Activate slide and pause on pager hover* option.

For more details, see: What you'll need to crete a jQuery slideshow in Drupal.
> 3 votes

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


# Question
Title: Save values after add more ajax in form api - field name issue
I've created a form using Form API and AJAX for an add more button, but I think I have problems assigning names to the new ajax fields in the loops, cause when I try to insert my data into my database I get an error:

> Undefined index

What am I doing wrong? Here's a section of my code:

```
<?php
function main_form_form($form, &$form_state) {

  $form['group_tabs'] = array(
      '#type'     => 'horizontal_tabs',
      '#attached' => array('library' => array(array('field_group', 'horizontal-tabs'))), // Converts fieldsets into tabs
      );

  $form['main_film_tab'] = array(
      '#type'  => 'fieldset',
      '#title' => t('Film General Info'),
      '#description' => t('Use this tab to enter basic info about the film.'),
      '#group' => 'group_tabs',
      );

  $form_state['storage']['main_film_tab']['add_title'] = isset($form_state['storage']['main_film_tab']['add_title']) ? $form_state['storage']['main_film_tab']['add_title'] : 0;

  $form['main_film_tab']['film_title']= array(
      '#type' => 'textfield',
      '#title' => t('Film Title'),
      '#size' => 60,
      '#maxlength' => 120,
      '#required' => TRUE,
      '#group' => 'main_film_tab',
      '#description' => t('Enter Film Title.'),
      '#attributes' => array(
        'title' => t("Title of Film"),
        )
      );

  $form['main_film_tab']['add_title'] = array(
      '#type' => 'container',
      '#tree' => TRUE,
      '#prefix' => '<div id="add_title">',
      '#suffix' => '</div>',
      );

  if ($form_state['storage']['main_film_tab']['add_title']) {
    for ($i = 1; $i <= $form_state['storage']['main_film_tab']['add_title']; $i++) {
      if ($i <= 2) {
        $form['main_film_tab']['add_title'][$i] = array(
            '#type' => 'fieldset',
            '#tree' => TRUE,
            );

        $form['main_film_tab']['add_title'][$i]['main_film_tab']['film_title_'.$i] = array(
            '#type' => 'textfield',
            '#title' => t('Film Title '.$i),
            '#size' => 60,
            '#maxlength' => 120,
            '#required' => FALSE,
            '#group' => 'main_film_tab',
            '#description' => t('Enter Film Title.'),
            '#attributes' => array(
              'title' => t("Title of Film"),
              )
            );
      }
      else {
        return FALSE;
      }
    }
  }

  $form['main_film_tab']['button_add_title'] = array(
      '#type' => 'button',
      '#value' => t('Add another title.'),
      '#href' => '',
      '#ajax' => array(
        'callback' => 'custom_registration_ajax_button_add_title',
        'wrapper' => 'add_title',
        ),
      );

  $form['main_film_tab']['button_add_title']['#executes_submit_callback'] = FALSE;
  $form['main_film_tab']['button_add_title']['#limit_validation_errors'] = array();

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

  $form_state['storage']['main_film_tab']['add_title']++;

  return $form;
}

function custom_registration_ajax_button_add_title($form, $form_state) {
  return $form['main_film_tab']['add_title'];
}

function main_form_form_submit($form, &$form_state) {
  $film_id = db_insert('film_main')
    ->fields(array(
          'film_title' => $form_state['values']['film_title'],
          'film_title_1' => $form_state['values']['film_title_1'],
          'film_title_2' => $form_state['values']['film_title_2'],
          ))
    ->execute();
}

```

# Answer
> 1 votes
I was having problems with the fieldset, since it was set to #tree. The submit handler should look like this:

```
function main_form_form_submit($form, &$form_state) {
  $film_id = db_insert('film_main')
  ->fields(array(
     'film_title' => $form_state['values']['film_title'],
     'film_title_1' => $form_state['values']['add_title'][1]['main_film_tab']['film_title_1'],
     'film_title_2' => $form_state['values']['add_title'][2]['main_film_tab']['film_title_2'],
     ))
 ->execute();

```

---
Tags: 7, forms, ajax
---


# Question
Title: Remove the strict warnings from being shown
I have a site using Drupal 6; after upgrading PHP to 5.4 , some strict warning appear.

I set error\_reporoting in settings.php with the following code, but I still see the E\_STRICT warnings.

```
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_WARNING);
ini_set('display_errors', TRUE);

```

Why do I still see them? What can I do to avoid seeing them?

# Answer
> 4 votes
From the link :

> If you're going to hack core, a much better solution is to properly fix the error handler. Add this line to the top of the drupal\_error\_handler function in includes/common.inc:
>
> if ($errno == E\_STRICT) { return; }

# Answer
> 3 votes
Go to this url admin/settings/error-reporting and set the option write errors to the log for Error reporting dropdown.

# Answer
> 1 votes
If anyone is reading this in 2016 or beyond (what are you still doing using Drupal 6? :P) then there is now a module that does what harshal's answer suggests to suppress PHP warnings - without hacking core.

See: https://www.drupal.org/project/\___drupal\_php\_strict\_suppress

# Answer
> -3 votes
Watch this youtube video this is axactly what you want its easy and helpfull and don't forget to change resolution to 460 before watching https://www.youtube.com/watch?v=i5Hq6t8Z6Fo

---
Tags: 6, configuration
---


# Question
Title: How do I find all objects under an object?
When I try to print out the possible options of `Node::load(10)`

I just get null. But I know that there are options as `Node::load(10)->field_name->value` gives the value of the field.

I have tried using dpm as well as json\_encode.

examples:

```
dpm(Node::load(10)->getFieldDefinitions());
dpm(Node::load(10)->toArray());
json_encode(Node::load(10))

```

# Answer
> 1 votes
I tried the following command, and it returns the expected output.

```
drush php-eval 'var_export(\Drupal\node\Entity\Node::load(1));'

```

The only case where I get `NULL` as output is when I pass to `Node::load()` a node ID that doesn't exist.

The fact `Node::load()` loads the data from the database doesn't matter; in fact, the method still returns an object of the `Node` class.

```
Drupal\node\Entity\Node::__set_state(array(
   'in_preview' => NULL,
   'values' =>
  array (
    'vid' =>
    array (
      'x-default' => '1',
    ),
    'langcode' =>
    array (
      'x-default' => 'en',
    ),
    'revision_timestamp' =>
    array (
      'x-default' => '1465363710',
    ),
    'revision_uid' =>
    array (
      'x-default' => '1',
    ),
    'revision_log' =>
    array (
      'x-default' => NULL,
    ),
    'nid' =>
    array (
      'x-default' => '1',
    ),
    'type' =>
    array (
      'x-default' => 'page',
    ),
    'uuid' =>
    array (
      'x-default' => '88E2D589-473B-4FE9-9A5A-F1F768A5E4E8',
    ),
    'isDefaultRevision' =>
    array (
      'x-default' => '1',
    ),
    'title' =>
    array (
      'x-default' => 'Test',
    ),
    'uid' =>
    array (
      'x-default' => '1',
    ),
    'status' =>
    array (
      'x-default' => '1',
    ),
    'created' =>
    array (
      'x-default' => '1465363684',
    ),
    'changed' =>
    array (
      'x-default' => '1465363710',
    ),
    'promote' =>
    array (
      'x-default' => '0',
    ),
    'sticky' =>
    array (
      'x-default' => '0',
    ),
    'revision_translation_affected' =>
    array (
      'x-default' => '1',
    ),
    'default_langcode' =>
    array (
      'x-default' => '1',
    ),
    'body' =>
    array (
      'x-default' =>
      array (
        0 =>
        array (
          'value' => '<p>Test.</p>
',
          'summary' => '',
          'format' => 'basic_html',
        ),
      ),
    ),
  ),
   'fields' =>
  array (
  ),
   'fieldDefinitions' => NULL,
   'languages' => NULL,
   'langcodeKey' => 'langcode',
   'defaultLangcodeKey' => 'default_langcode',
   'activeLangcode' => 'x-default',
   'defaultLangcode' => 'en',
   'translations' =>
  array (
    'x-default' =>
    array (
      'status' => 1,
    ),
  ),
   'translationInitialize' => false,
   'newRevision' => false,
   'isDefaultRevision' => '1',
   'entityKeys' =>
  array (
    'bundle' => 'page',
    'id' => '1',
    'revision' => '1',
    'uuid' => '88E2D589-473B-4FE9-9A5A-F1F768A5E4E8',
  ),
   'translatableEntityKeys' =>
  array (
    'label' =>
    array (
      'x-default' => 'Test',
    ),
    'langcode' =>
    array (
      'x-default' => 'en',
    ),
    'status' =>
    array (
      'x-default' => '1',
    ),
    'uid' =>
    array (
      'x-default' => '1',
    ),
    'default_langcode' =>
    array (
      'x-default' => '1',
    ),
  ),
   'validated' => false,
   'validationRequired' => false,
   'entityTypeId' => 'node',
   'enforceIsNew' => NULL,
   'typedData' => NULL,
   'cacheContexts' =>
  array (
  ),
   'cacheTags' =>
  array (
  ),
   'cacheMaxAge' => -1,
   '_serviceIds' =>
  array (
  ),
))

```

Even running `drush php-eval 'var_export(\Drupal\node\Entity\Node::load(1)->toArray());'` (i.e. using the `toArray()` method you tried) gave me an output different from `NULL`. In this case, using a node ID that doesn't exist, you get a *Call to a member function toArray() on a non-object* error.

```
array (
  'nid' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'uuid' =>
  array (
    0 =>
    array (
      'value' => '994535DB-7C4E-42F2-94CE-576DA3E9FC0B',
    ),
  ),
  'vid' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'langcode' =>
  array (
    0 =>
    array (
      'value' => 'en',
    ),
  ),
  'type' =>
  array (
    0 =>
    array (
      'target_id' => 'page',
    ),
  ),
  'title' =>
  array (
    0 =>
    array (
      'value' => 'Test',
    ),
  ),
  'uid' =>
  array (
    0 =>
    array (
      'target_id' => '1',
    ),
  ),
  'status' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'created' =>
  array (
    0 =>
    array (
      'value' => '1466285938',
    ),
  ),
  'changed' =>
  array (
    0 =>
    array (
      'value' => '1466285973',
    ),
  ),
  'promote' =>
  array (
    0 =>
    array (
      'value' => '0',
    ),
  ),
  'sticky' =>
  array (
    0 =>
    array (
      'value' => '0',
    ),
  ),
  'revision_timestamp' =>
  array (
    0 =>
    array (
      'value' => '1466285973',
    ),
  ),
  'revision_uid' =>
  array (
    0 =>
    array (
      'target_id' => '1',
    ),
  ),
  'revision_log' =>
  array (
  ),
  'revision_translation_affected' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'default_langcode' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'path' =>
  array (
  ),
  'body' =>
  array (
    0 =>
    array (
      'value' => '<p>Testing a Drupal function.</p>
',
      'summary' => '',
      'format' => 'basic_html',
    ),
  ),
)

```

Also, remember to fully qualify the class with its namespace, or add a `use \Drupal\node\Entity\Node;` line before using the class.

Using `drush php-eval 'print json_encode(\Drupal\node\Entity\Node::load(1));'` I just get `{"in_preview":null}` because `json_encode()` doesn't prints out all the object properties.

---
Tags: nodes, 8
---


title: Add hook after registration form submit

text:
# Question
Title: Add hook after registration form submit
I'm trying to club Drupal & Magento together. So I want to make the registration seamless. If any user register in Drupal they want to register in Magento automatically using a custom module in Drupal. I have scripts to register in Magento by sending data to Magento script file.

I want to know how to make a AJAX call to that script file, using a custom Drupal module. I'm using Drupal 7 version.

# Answer
For achieving this goal you have to Implement drupal hook\_user\_insert and Use php cURL
> 1 votes

# Answer
You can use hook\_user\_insert, in which you can easily execute CURL, in hook\_user\_insert you will have all your data regarding the user.
> 2 votes

---
Tags: 7, forms
---


title: How do I get a field value?

text:
# Question
Title: How do I get a field value?
I am using the Business Hours module. It allows you to specify two time periods per day, for the 7 days of the week. So you could, for example, say: 9 t 1 Mondays to Fridays, and 2 - 5, Mondays to Fridays.

My problem is getting access to these values as I need to expose it in a custom module. With `print_r($node)`, I can see the following.

```
[field_office_hours] => Array(
  [x-default] => Array(
    [0] => Array(
      [day] => 0
      [starthours] => 900
      [endhours] => 1700
    )
    [1] => Array(
      [day] => 1
      [starthours] => 900
      [endhours] => 1700
    )
    /* Omissis */
  )
)

```

I have no idea how to get this as array. I know that the module requires the "Date" module, so these are probably Date fields, but how do I actually get the values as array?

`$node->field_office_hours->value` doesn't work.

# Answer
> 12 votes
Nevermind, this worked for me:

```
$node->get('field_office_hours')->getValue();

```

---
Tags: 8, datetime
---


# Question
Title: How to split taxonomy checkboxes on node edit form
I figured how to do it on node output, but i can not figure how to add css for specific field, in this case taxonomy checkboxes, 50 of them, and split in 4 columns on node edit form.

# Answer
> 0 votes
Works in Firefox, Chrome, Safari and Opera. This is example for 4 columns for Seven theme.

```
#edit-field-name {
  width:100%;
  margin-bottom:20px;
  overflow:hidden;
  border-top:1px solid #ccc;
  -webkit-column-count: 4; /* Chrome, Safari, Opera */
  -moz-column-count: 4; /* Firefox */
}

```

# Answer
> 1 votes
You can do it with css. You will need to add the following to your Admin theme's css file.

The Drupal default admin theme is **Seven** theme, located in `/core/themes/seven`. You may want to create a sub theme of Seven and use that as your admin theme, so when you upgrade Drupal your css file does not get overridden; thus, you will not lose all your changes.

```
#edit-field-name {
  width:760px;
  margin-bottom:20px;
  overflow:hidden;
  border-top:1px solid #ccc;
}

#edit-field-name div {
  line-height:1.5em;
  border-bottom:1px solid #ccc;
  float:left;
  display:inline;
  width:25%; }

```

replace **-name** with the actual name of your field.

Source: http://csswizardry.com/2010/02/mutiple-column-lists-using-one-ul/

---
Tags: 7, theming
---


# Question
Title: Can we call submit handler of one form into another form?
Can we call submit handler of one form into another form?

I have two forms say **user profile form** and **choose membership plan** I want to unset submit function of **choose membership plan** and want to show in **user profile form** and also both forms field must save.

like multi-step form.

```
 function myform_form_alter(&$form, &$form_state, $form_id) {
   if($form_id === "ms_membership_list_memberships_form") {
     $form['#validate'][] = "_myform_form_submit_handler";
   }
   if($form_id === "user_profile_form") {
     $form['#validate'][] = "_myform_form2_submit_handler";
   }
 }

 function _myform_form_submit_handler($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = '/user/1/edit';
 }

 function _myform_form2_submit_handler($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = '/ms/checkout';
 }

```

# Answer
You could pass the page number as argument to your hook\_menu()

```
<?php
function mymodule_menu() {
    $items['abc/def/%'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(2),
    );
    return $items;
  }

```

Then if it is step-one for example, get your subscription plan form, render it then submit. In the submit function use:

```
 <?php
// Force the form to rebuild. If we do not do this, the value(s) in $form_state['storage'] will be lost
$form_state['rebuild'] = TRUE;
//Redirect to step two
$form_state['redirect'] = 'abc/def/2';

```

In step 2 get the user profile so that in the next submission you'll have the data from both forms in the submit function.
> 0 votes

---
Tags: 7, forms
---


title: How do I change ID to a custom one?

text:
# Question
Title: How do I change ID to a custom one?
How can I change the view block ID from block-views-portfolio-view-block to portfolio?

# Answer
> 1 votes
Add this to your theme's template.php file:

```
function THEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-portfolio-view-block")
    $variables['block_html_id'] = "portfolio";

}

```

# Answer
> 0 votes
An alternative without coding would be to use Token Embed Views, to embed the view in a custom block. You can use something like Block attributes (Drupal 7) to set an id to that block.

Or you could override the Views display output. If you go the the right bottom of the views interface, click `Information` next to theme you'll see a list of names. You could wrap the contents of the used template (probably `views-view.tpl.php`) into another div with your id, and save the file in your theme folder. Use the most accurate filename suggested that still applies to all pages (some with built in node id's etc.).

---
Tags: views, blocks
---


# Question
Title: How to override base url when creating links to public files?
I need storage the upload into drupal file in another server and I need change public path to files to example http://server\_with\_image/image How I can do this?

# Answer
> 2 votes
You are basically describing the use case of a CDN (Content Delivery Network).

Check CDN module:

> This module provides easy Content Delivery Network integration for Drupal sites. It alters file URLs, so that files are downloaded from a CDN instead of your web server.
>
> It provides two modes: "Origin Pull" and "File Conveyor".
>
> * In Origin Pull mode, only "Origin Pull" CDNs are supported. (These are CDNs that only require you to replace the domain name with another domain name.)
> * In File Conveyor mode, this module integrates with File Conveyor, which allows for much more advanced setups (e.g. optimize images, transcode videos, and so on, before syncing to the CDN).

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


title: EntityFieldQuery with Workflow

text:
# Question
Title: EntityFieldQuery with Workflow
I need to filter an EntityFieldQuery with a given workflow state, let's say workflow it is state 21 (`sid = 21`). Below, the query I am using

```
$query_formularios_completos = new EntityFieldQuery();
  $query_formularios_completos
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array(
        'evento_agencia',
        'evento_energia'
      )
    )
    ->propertyCondition('workflow', 21)
    ->fieldCondition('field_e_expositor', 'target_id', $node_expositor_nid);
  $result_formularios_completos = $query_formularios_completos->execute();

```

When using DEVEL to inspect my node, I can see there is a property `->workflow`, side by side with ordinary properties like `->title` or `->created`. Although I can see it there and I expected to filter only items with workflow state 21, I get a horrid database error when trying to execute the code above. Here is more or less the message I get:

> Column not found: 1054 Column 'node.workflow' unknown in 'where clause'

Any ideas on how I should filter an entity query using a workflow state as filter? Maybe what I am trying to do isn'tpossible and I have to actually run a query using db\_query and applying the appropriate joins.

# Answer
> 0 votes
As described in `EntityFieldQuery::propertyCondition()`, you can use that method for every database field defined in the `hook_schema()` implementation for the base database table used from the entity.

> **$column**: A column defined in the hook\_schema() of the base table of the entity.

The code that effectively handle that is in `EntityFieldQuery::propertyQuery()` which contains the following code.

```
  $entity_type = $this->entityConditions['entity_type']['value'];
  $entity_info = entity_get_info($entity_type);
  if (empty($entity_info['base table'])) {
    throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
  }
  $base_table = $entity_info['base table'];
  $base_table_schema = drupal_get_schema($base_table);
  $select_query = db_select($base_table);
  $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
  // Process the property conditions.
  foreach ($this->propertyConditions as $property_condition) {
    $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
  }

```

You could implement `hook_entity_query_alter()`, which is invoked before `EntityFieldQuery::propertyQuery()` is called, and which (by default) it's the `EntityFieldQuery::executeCallback` callback, the same callback `hook_entity_query_alter()` is suggested to change. Using your own callback, you could make a join with the tables the Workflow module is using.

---
Tags: entities, workflows
---


# Question
Title: Make PDF,XLSX,DOCX,PPTX output for drupal REST server
When I tried to configure drupal service `admin/structure/services/list/MyServiceName/server`, I only see the following response content types.

Is it possible to provide pdf, docx, pptx, xlsx etc. as response format?

# Answer
> 4 votes
Yes it's definitely possible, but you'll need to write a formatter class for each type of file as the bundled REST server only has support for XML, JSON, JSONP, serialized PHP, bencode, and optionally YAML.

To start, you need to implement `hook_rest_server_response_formatters_alter` to let the REST server know about your new type, e.g.:

```
function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['pdf'] = array(
    'mime types' => array('application/pdf'),
    'formatter class' => 'MyModuleServicesPDFFormatter',
  );
}

```

Then add your formatter class, which needs to implement `ServicesFormatterInterface` and provide the `render` method:

```
class MyModuleServicesPDFFormatter implements ServicesFormatterInterface {
  public function render($data) {
    return some_function_to_convert_data_to_pdf_string($data);
  }
}

```

Then make sure that class is auto-loaded by putting this in your module's .info file:

```
files[] = relative/path/to/MyModuleServicesPDFFormatter.php

```

Repeat the process for all of the new formatters you wish to provide, clear the cache when you're done.

---
Tags: 7, services
---


# Question
Title: How to convert username to hyperlink in comment reply similar to StackExchange?
Is there any contributed module or usable functionality which is somewhat similar to StackExchange reply comment, where when we add username with "`@`" sign, it notifies user. However in my case I would like to convert them into users profile page hyperlink.

For example, if user added in reply `@foobar`, if username with `foobar` exists will be converted in hyperlink to foobar profile page.

# Answer
You are looking for the Mentions module:

> The Mentions module offers Twitter like functionality, recording all references to a user's username - using the \[@username\] or \[@#uid\] filter format - from various locations, providing a centralized page to track all mentions (via the Views module).
> 3 votes

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


title: Unable to delete a file with services

text:
# Question
Title: Unable to delete a file with services
I am making an AJAX call to /file/.json. Webserver log says `DELETE /services/file/5710.json HTTP/1.1 200`, console log says the file has been deleted; yet the file is still there when you go here. What am I missing? My code is as follows:

```
$.ajax({
  url: 'http://www.rejicast.com/services/file/' + oldFID + '.json',
  type: "delete",
  dataType: "json",
  beforeSend: function(r) {
    r.setRequestHeader("X-CSRF-Token", token.token)
  },
  success: function() {
    console.log('Deleted the file');
  },
  error: function(xhr, status, err) {
    console.error(xhr);
    console.log(status);
    console.log(err);
  }
})

```

(Note: oldFID is something I set at the beginning)

UPDATE: As per @Clive's answer, there is still a reference to the file in the database as seen below .

# Answer
> 0 votes
The file *reference* has been deleted, i.e. the record in the `file_managed` table; the file itself will be deleted later during the `system_cron` run.

See the 10 or so lines under this comment in that function:

```
// Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.

```

---
Tags: 7, ajax, services
---


# Question
Title: Ckeditor - Not displaying text on edit node option
I've been using Ckeditor for a while to add text to created nodes.

But when editing the same nodes as an authenticated user, Ckeditor doesn't show the text in the body.

It still works for the administration role.

# Answer
Try updating the Ckeditor, its usually due to the security update.

Do a update or uninstalling and reinstalling the Ckeditor and

do download the newest Ckeditor and

place in the `sites\all\modules\ckeditor\ckeditor`.

Just enable the module and clear the cache and you're ready to go.
> 0 votes

# Answer
You have to give the `Authenticated user` role the rights to use the input format CKEditor used to save the page. Look on the access rights page, URL depending on Drupal version.
> 3 votes

# Answer
Try setting the permission 'VIEW THE ADMINISTRATION THEME' for that role in admin/people/permissions
> 0 votes

# Answer
I had a blank page issue after upgrading to the newest ckeditor 4.5. All I did to correct it is to go the top of the browser of the editing page and refresh. Then everything started populating correctly. I hope this works for you as well. Give a feedback if it works. Thanks.
> 0 votes

# Answer
Authenticated user and admin have the same text format permissions? If the admin use the "full html" and the authenticated user use "filtered html", then the ckeditor will strip the html tags for "filtered html", check the ckeditor content filtering options.

You can turn off the filtering, but not an good ideea for security ...

```
config.allowedContent = true;

```

Document more about `config.allowedContent` and how to allow specific tags for user input.
> 0 votes

---
Tags: users, wysiwyg
---


# Question
Title: Why exposed filter doesn't appear, when ajax is off in block view
I have a view as a block and I am using the exposed filter for content.I need a exposed filter value in the url but due to ajax ON its value doesn't pass to url, when ajax OFF then exposed filter is not appear. Please give me solution. how to resolve this problem.

# Answer
Simply because it is not a page. If you notice on page view, with ajax off, you will see a parameter passes through the url.

```
/example?something=yes

```

If you go to that url directly, it automatically filters your value.

Since blocks are not pages (do not have urls), you cannot do that. Therefore, reloading the block with AJAX is the only option for exposed filters in blocks.
> 0 votes

# Answer
You can use "Views Block Exposed Filter Block" module to display the exposed filters as block for blocks and you can still have ajax on filtering.
> 0 votes

---
Tags: views
---


# Question
Title: How to attach a CSV file with the Google Chart API?
I have created a Google Chart based View and it is working nicely.

How to give the facility as the user should be able to upload a CSV file and the data comes accordingly?

# Answer
To my knowledge there is no way using Google Chart API to "\* to upload a csv file and the data comes accordingly\*" (as in your question).

However, you may want to have a look at the Easychart module as a possible alternative (which already has an official release for both Drupal 7 and Drupal 8).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

* It defines a new content type (= *Chart*) used to add charts to your site.
* It creates a chart widget that can be used in your own content types.
* It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (*CKeditor* and *TinyMCE* are supported).
* It provides an intuitive interface to configure charts through the Easychart plugin.
* It supports pasting of CSV data to create charts from it.
* overheid.vlaanderen.be contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

Especially the bullet about "***It supports pasting of CSV data to create charts from it.***" seems close to what you're looking for.

# Resources:
> 0 votes

---
Tags: views, charts
---


# Question
Title: Webform no duplicate selections with multiple select lists
I have a webform (7.x-4) with two selection lists, with the same content, like

```
A
B
C
D

```

so I would like to prevent users, who fill out this form, from using the same options in both lists.

i.e., if they check **A** they should get an error when they check **A** on the the second list.

what is the best way to do that?

# Answer
> 0 votes
You can do it by writing custom module. If you want to go for a contributed module, the Webform Validation module does that

> This module adds an extra tab to each Webform node, allowing you to specify validation rules for your Webform components. You can create one or more of the predefined validation rules, and select which Webform component(s) should be validated against those. By using the hooks provided by this module, you can also define your own validation rules in your own modules.
>
> The following validation rules are currently included:
>
> * Numeric values (optionally specify min and/or max value)
> * Minimum length
> * Maximum length
> * Minimum number of words
> * Maximum number of words
> * Equal values on multiple fields
> * Unique values on multiple fields
> * Specific value
> * Require at least one of two fields
> * Require at least one of several fields
> * Minimum number of selections required
> * Maximum number of selections allowed
> * Exact number of selections required
> * Plain text (disallow tags)
> * Regular expression
> * Must be empty (anti-spam: Hide with CSS)
> * Words blacklist
> * Must match a username

# Answer
> 0 votes
Did you tried "Webform Validation" module ? "Unique values on multiple fields" applied on those fields I guess it must work.

---
Tags: 7, forms, webforms
---


# Question
Title: getFieldDefinitions on Drupal 8 (why all these deprecated functions on DP8?)
I don't understand why they are so much functions deprecated on Drupal 8. From the basics (node load, node delete,...) to more complicated (getFieldDefinitions,...).

And their is no explanation for using the new way of implementation in the official documentation.

For example, I want to get the definitions of all my fields for a content type. The old way was :

```
Drupal::service('entity_field.manager')->getFieldDefinitions(xxx, xxx);

```

For somes reasons, its now deprecated. Now, we have to use this. But how use it... that's the question. Their absolutely no example or help. I would use the getFieldDefinitions function from this class, but I have to create a instance from it, the function is not static.

How do I do :( ?

# Answer
```
Drupal::service('entity_field.manager')->getFieldDefinitions(xxx, xxx);

```

Is the *current* way to get field definitions.

It's the `EntityManager` service that has been deprecated, not `EntityFieldManager::getFieldDefinitions`. A deprecation notice on a method doesn't apply to the code used within the method, just the use of the method itself.

The former currently proxies straight through to the latter, so it isn't really useful any more.

As a general rule, functions are deprecated when they're no longer useful, or when they break convention with the rest of the codebase. Don't fear it, embrace it. Progress is a good thing :)
> 10 votes

# Answer
The development cycle for Drupal 8 took a long time, much longer than anyone anticipated. Because of this, early decisions that were made were refined and changed, as the system evolved. This is why some things are marked as `@deprecated`.

Some things, mainly the global functions like `format_date()` still exist to aid in the transition to Drupal 8. Others, like `EntityManager` have outgrown their initial purpose.

For the specific example you give, you can read the change record (all @deprecated classes / methods / functions should have a CR (except for some really early ones). Essentially, `EntityManager` grew in scope so it was decided to split out into individual services to allow code (and core maintenance) to be more manageable. The current version of `EntityManager` actually gets all of the sub-services injected into it, and the old methods call out to the methods on the sub-service.

Deprecated code will not go away in Drupal 8. Usage in core will go away.

Your last part about "I would use the getFieldDefinitions function from this class, but I have to create a instance from it, the function is not static." sound like a different question that needs to be fleshed out more.
> 3 votes

---
Tags: entities, 8
---


title: Add a new Taxonomy term page

text:
# Question
Title: Add a new Taxonomy term page
I use drupal 8 and I want to add a new view page to taxonomy view.

I tried to dublicate default taxonomy page view and changed path

```
from: taxonomy/term/%/
to : taxonomy/term/%/newpath

```

but this is not working. why would this not work?

# Answer
Did you tried to change the "**Contextual filter**" settings ?

**WHEN THE FILTER VALUE IS NOT IN THE URL** to -\> Provide default value (taxonomy term from url)

or check the **WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED** validation
> 0 votes

---
Tags: views, taxonomy-terms, 8
---


# Question
Title: Creating a redirect for content type conditionally
I'm new to Drupal and have inherited a fully functional system (Drupal 7.43), I've had a look on Google with no joy, so hopefully you can help.

For a specific content type it has the following fields (simplified)

URL info1 info2

When the user clicks to read the page if info1 is empty I would like to redirect to the URL (which is an external, absolute URL) if there is content in info1 I would like to show the page as normal.

How would I go about doing this?

# Answer
> 1 votes
No problem bro, its pretty simple. I'll write you a step by step tutorial as an edit. Standby.

You will need to create a preprocess function. Add a folder and a file in your theme. THEMENAME/preprocess/node.preprocess.inc with this code:

```
<?php

/**
 * Implements hook_preprocess_node().
 *
 * Hyjacking the nodes normal node link if an external link is specified
 *
 */
function YOURTHEMENAME_preprocess_node(&$variables) {

  $url = NULL;

  switch ($variables['type']) {
    case 'article':
      if (isset($variables['alternate_link']['und'][0]['url'])) {
        $url = (!empty($variables['alternate_link']['und'][0]['url'])) ? $variables['alternate_link']['und'][0]['url'] : NULL;
        $variables['node_url'] = $url;
      }
    break;
  }

}

```

My example states that In the case of a Content Type with the machine name of 'article' (yours may be different) do something.

THEN check if my field with the machine name of 'alternative\_link' (your machine name will be different) has a value then do something.

It will then use the node's default $url variable.

If it is not set, it will ignore this code and leave your $url clean

---
Tags: views, redirection
---


# Question
Title: How to check the value from data sheet during Feeds import?
I am trying to import some data by using feeds importer. I want to check if there is any information under "equivalent" Source in the sheet. If there is no value, just skip the import. If it has, continue and finish the import process.

I saw there is an event called "Before saving an item imported via Recommended Product Import(importer name)."

Does anyone have any idea about how can I set the condition and action parameter for implementing this rule?

This is one column from my sheet and rule sheet (you can see some products have equivalent, some do not have):

# Answer
> 1 votes
Thanks everyone, I got the answer. Instead of using Rules, I created a "custom feeds module."

Steps:

1. Create a folder named "custom\_feeds"
2. Create two files, one is "custom\_feeds.info", another is "custom\_feeds.module"
3. Add following information in the .info file:

```
name = custom feeds module
description =custom feeds module
core = 7.x
package = Feeds
dependencies[] = feeds</code>

```
4. Add following code in the .module file inside `<?php ?>`:

```
function custom_feeds_feeds_presave(FeedsSource $source, $entity, $item) {
  // check that this is fired only for the importer being used
  if($source->importer->id=='recommended_product_import'){
     // "equivalent" is the column name in excel sheet
     if(!strcmp($item['equivalent'],"")){
       $entity->feeds_item->skip = TRUE;
     }
  }
}

```

---
Tags: 7, rules, feeds
---


# Question
Title: Restrict vocabulary on entity_autocomplete form field targeting taxonomy terms
I'm creating a form with an `entity_autocomplete` field targeting taxonomy terms, and I would like to restrict it to a certain vocabulary. Is there a way to do that with `'#selection_settings'`? I can't find any example.

This is the code I am using.

```
$form['p_cat_ac'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Product Category'),
    '#target_type' => 'taxonomy_term',
    '#selection_settings' => [
        'include_anonymous' => FALSE,
    ],
);

```

# Answer
> 4 votes
The vocabulary is the taxonomy term's bundle, so you just have to add a `target_bundles` array to the `#selection_settings` entry. In my case the desired vocabulary ID is 'category'.

```
$form['p_cat_ac'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Product Category'),
    '#target_type' => 'taxonomy_term',
    '#selection_settings' => [
        'include_anonymous' => FALSE,
        'target_bundles' => array('category'),
    ],
);

```

---
Tags: forms, taxonomy-terms, ajax
---


# Question
Title: Is it possible to include a forward slash in a route dynamic property?
Is it possible to include forward slashes in routing parameters?

```
// routing.yml
mymodule.route
    path: '/mymodule/{param}'
    defaults:
        path: ''
    requirements
        path: '[A-Za-z0-9\-\/]+'

```

`/mymodule/this/is/a/single/param` would then result in

```
$param = 'this/is/a/single/param';

```

being passed into the controller method.

# Answer
I tested this out, and it doesn't work in Drupal 8, unfortunately.

```
mymodule.test:
  path: '/mymodule/{testparam}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\TestController::build'
    _title: 'Variable Parameter'
  requirements:
    _permission: 'access content'
    testparam: .+

```

It picks up the route with "/mymodule/hello", but not "/mymodule/hello/world".

There's some more discussion of this here: Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params

It looks like there's a solution, but it's pretty heavy handed.
> 1 votes

---
Tags: 8, routes
---


# Question
Title: How do I correctly add cache information for breadcrumb parts?
Visiting a node *Foobar* a breadcrumb gets created which adds the parent menu structure like so:

```
$currentPluginId = $menu_link->getPluginId();
$trailIds = $this->menuActiveTrail->getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    // @todo add cache per item
    $instance = $menu_link_manager->createInstance($value);
    $breadcrumb->addLink(
      new Link(
        $instance->getTitle(),
        $instance->getUrlObject()
      )
    );
  }
}

$breadcrumb->addCacheContexts(['route.menu_active_trails:main']);

```

So the breadcrumb looks like:

> Home \> John Doe \> **Foobar**

But if the node/ menu item of *John Doe* changes, the breadcrumb for *Foobar* stays the same.

```
dpm($instance->getUrlObject()->getRouteName());
dpm($instance->getUrlObject()->getRouteParameters());

```

gives me:

> entity.node.canonical

and

> array( \[node\] =\> 25 )

How can I use that for adding each breadcrumb part as cache context/ tag?

# Answer
> 0 votes
So I came up with the following:

```
foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    // @todo add cache per item
    $instance = $menu_link_manager->createInstance($value);
    $breadcrumb->addLink(
      new Link(
        $instance->getTitle(),
        $instance->getUrlObject()
      )
    );
    $routeParams = $instance->getUrlObject()->getRouteParameters();
    if (is_array($routeParams) && count($routeParams) && isset($routeParams['node'])) {
      $breadcrumb->addCacheTags(['node:' . $routeParams['node']]);
    }
  }
}

```

As it turns out, changing a menu item without really changing the node though does not invalidate the cache so the breadcrumb would still have old menu titles. This line somehow has no impact, either

```
$breadcrumb->addCacheContexts(['route.menu_active_trails:main']);

```

So I added this to the breadcrumb:

```
$breadcrumb->addCacheTags(['config:system.menu.main']);

```

And voila. As soon as the menu title of John Doe changes, the breadcrumb on page Foobar also updates.

Maybe it's even a better idea to not add the node cache tags but only the menu cache tag. Guess you have to play with how the site behaves over time.

# Answer
> 0 votes
Look at `\Drupal\book\BookBreadcrumbBuilder::build()` for an example. You'll want to add the cacheability metadata (or at minimum the cache tags) of the node/menu item *John Doe*.

So:

```
$breadcrumb->addCacheableDependency($entity);

```

---

You could have easily figured this out yourself: you're building a `\Drupal\Core\Breadcrumb\Breadcrumb` object… which implements `RefinableCacheableDependencyInterface`, and that interface lists all things related to cacheability.

I highly recommend you read https://www.drupal.org/developing/api/8/cache and all documentation it points to.

---
Tags: 8, caching, breadcrumbs
---


title: Create a custom area plugin

text:
# Question
Title: Create a custom area plugin
I'm looking to add a plugin for Views to provide some custom functionality in the footer of a view.

First, I created the following in `my_module/src/Plugin/views/area/MyPlugin.php`:

```
namespace Drupal\my_module\Plugin\views\area;

use Drupal\views\Plugin\views\area\AreaPluginBase;

/**
 * Defines a views area plugin.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("my_plugin")
 */
class MyPlugin extends AreaPluginBase {

  /**
   * {@inheritdoc}
   */
  public function render($empty = FALSE) {
    if (!$empty || !empty($this->options['empty'])) {
      return array(
        '#markup' => 'test footer content',
      );
    }

    return array();
  }
}

```

When that didn't work on its own, I realized I needed to declare the plugin in `my_module.views.inc`:

```
/**
 * Implements hook_views_data().
 */
function my_module_views_data() {
  $data['views']['my_plugin'] = array(
    'title' => t('My Plugin'),
    'help' => t('My plugin description.'),
    'area' => array(
      'id' => 'my_plugin',
    ),
  );
  return $data;
}

```

With that added, I can get as far as seeing the plugin available for selection in an area under the Views admin screen. However, when I select the checkbox for it and click Apply, the button text changes to "Add and configure footer" but it doesn't move to the next step in the process.

I've had this happen when writing custom block plugins; the system don't let me place a block when the plugin has something wrong with it. Any thoughts as to what I have here that is wrong?

# Answer
> 1 votes
There was a typo in my plugin filename. :-/

# Answer
> 0 votes
It looks like you need to declare the plugin in a `views.schema.yml` file (in this case, in `config/schema/my_module.views.schema.yml`, relative to your module root):

```
views.area.my_plugin:
  type: views_area
  label: 'My Plugin'

```

---
Tags: views, 8, plugins
---


# Question
Title: drush features-list-packages in drupal 8 doesn't include prefix
I've just started using Drush and Features with Drupal 8. I'm running into a point of confusion, and I can't figure out if it's a feature or a bug.

In the past our team prefixed all the site-specific features with some abbreviation, let's say, `whg_`. Then, when I run `drush fl` the features would show up as `whg_calendar, whg_events, etc.` It now appears that features automatically appends the bundle's abbreviation to the feature, great.

The issue is when I `drush fl` I now get a list of features without the abbreviation: `calendar, events, etc.` I can use the feature commands to `update`, `revert`, etc, but I can't use the `pm-` commands to modify the modules, since, they are in fact, prefixed. So, in order to uninstall the module I have to `pm-uninstall whg_calendar`.

Additionally, `drush fu calendar` creates a new feature at `modules/custom/calendar`

This seems like an inconsistent way to work with features. This might be a meta question, but, is this a bug, should I report it to the github project?

# Answer
For configuration management in Drupal 8, you don't need to use features, you can use the configuration management module, which outputs .yml files.

The files are saved at sites/default/sync

to export them, use

```
drush cex

```

(drush configuration export)

and to import them use

```
drush cim

```

You can also manually do this from /admin/config/development/configuration

See https://www.drupal.org/documentation/administer/config
> 1 votes

---
Tags: 8, drush, features
---


# Question
Title: Creating a Feeds Plugin Child from a custom module and calling the new method
I’ve got a module where I need to overwrite a method from another Feeds Plugins class. To do this I’ve followed the developer's guide to Feeds.

So I have implemented hook\_feeds\_plugins and hook\_enable. These are being reached fine. The aim of my new child class is to override the parse method in FeedsCSVParser

In my code I have this line:

```
$result = $this->importer->parser->parse($this, $result);

```

This still runs through the parent class and not the child one I’ve created. How do I tell my Module to use the new parse method instead?

When i break point this line I can see in `$this->importer->parser->pluginDefinition` that this array should probably be of the new info I've entered in `hook_feeds_plugins`, but is showing that previous class instead.

Thanks for any guidance that can be given.

# Answer
I have the issue fixed however this may not be the best method. If you know what is then please let me know.

You can set a Plugin with 'setPlugin'

```
$this->importer->setPlugin('PreviewFeedsParser');

```

This wipes the config though. So the following code shows - getting the config, setting the plugin and readding the config.

```
$this->importer->setPlugin('PreviewFeedsParser');
$this->importer->parser->setConfig($config);
$result = $this->importer->parser->parse($this, $result);

```
> 0 votes

---
Tags: 7, feeds, plugins
---


# Question
Title: How can I create special search with check/uncheck image field in filter criteria of views
How can I create special search with check/uncheck image field in filter certia of views module in drupal 8 ?

I want if users check image field checkbox and click on "go" button , they whatch only content that have image and when uncheck that they can watch all content .

# Answer
You will need BEF module to get exactly what you want, **but it's not ready yet**.

**The workaround:** Although Drupal still has a query checkbox value bug (pretty ugly:(), there is a workaround and you can come up with the following close solution:

1. Create a new filter criteria
2. Choose your image field "target\_id" property.
3. Configuring the filtering critera check "Expose this filter to visitors"
4. Choose "Grouped filters"
5. Mark "Optional" checkbox.
6. Widget type: radios.
7. Allow multiple selections.
8. Mark the first grouping (Grouping 1), give it a label and choose operator "Is not empty(NOT NULL).

You are now half way through. Altough it's working like this in view preview mode, it won't on the real page (because of the bug above).

Now you need to write a hook\_form\_FORM\_ID\_alter in one of your .module file, mine's looks like this:

```
function base_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-page-1') {
    $request = \Drupal::requestStack()->getCurrentRequest()->query->all();
    $filter_identifier = 'field_image_target_id';
    if (!$request[$filter_identifier]) {
      $user_input = $form_state->getUserInput();
      unset($user_input[$filter_identifier]);
      $form_state->setUserInput($user_input);
    }
  }
}

```

WHERE:

"views\_exposed\_form" =\> form\_id (you will get the same, but check it) "views-exposed-form-search-page-1" =\> is the '#id' parameter of your form. (this will be probably different) "field\_image\_target\_id" =\> This is your filter identifier, which can be found (also renamed) in when clicking on views this filter criteria.
> 0 votes

---
Tags: 8, search
---