title: Is it possible to inherit theme files?

text:
# Question
Title: Is it possible to inherit theme files?
I have 'Theme A' and 'Theme B'. The only difference between them is `colors.css`.

If I want to add Theme B, I have to copy the entire theme folder, change the info file and correct the name of the theme hooks in my `.tpl` files.

Is there a way I can have my second theme inherit all the files from Theme A (or just make 'theme A' use a different `colors.css` when user wishes to do so)?

Point of this is to make theming more easy for the end user, so that they just have to upload `theme_b.info` and `colors.css`?

# Answer
If I am not mistaken, base themes do exactly what you describe.

In your case, you can use 'Theme A' as the base theme, and specify that 'Theme B' uses 'Theme A' as the base in the .info file. You can then override the CSS and other theme features as you wish.
> 1 votes

---
Tags: theming
---


# Question
Title: How to use / configure the Course Requirements module?
When using the Course module, you may also want to use the Course Requirements module, so that a user cannot be enrolled in a 2nd course until a 1st course is completed.

However, it's not obvious how to actually use / configure the Course Requirements module. So how is this module supposed to be used/configured?

# Answer
> 2 votes
The Course Requirements module does not have a lot (any?) docu. But comment nr 3 of issue # 2148985 helps to make it work, i.e.:

1. Add a node reference field to your Course content type (to references other courses).
2. Go to `admin/config/course/requirements` and select that node reference field you just added.
3. Add courses through the node reference field.

After completing these steps, this is how it should work:

* The courses you add in the field should block that course from being enrolled into without completing the referenced courses.
* After completing a course it should also tell you what courses required that course for completion.

---
Tags: 7
---


# Question
Title: Hide "language menu" next to search bar / login menu
I have inherited maintanance of quite horrible looking website that is currently running version 6.x of Drupal. I am now trying to streamline / delete / disable as many unnecessary things as we can on the website.

http://sejong.ff.cuni.cz/

One of the features is a multilingual menu next to search bar / login menu. I visited the multilingual settings but I have been unable to find a way to get rid of that menu.

How can I achieve that? (I am new to Drupal so I am not sure if this is something that was custom put to the system or if it is a default Drupal feature)

# Answer
Head over to relative path `admin/build/block/list`, to bring up a list of *blocks* configured for the theme that you're using. Pretty sure you'll find a block titled something like "language switcher" (or similar to that), which is locate in your "header" region (or some other theme region). Change that to `<none>` (to not show that block in any theme region. Then check if it solved your question.
> 1 votes

---
Tags: 6, i18n-l10n
---


title: How to use Message Subscribe module?

text:
# Question
Title: How to use Message Subscribe module?
I have installed Message Subscribe module. But I am not sure how to configure this. I also have installed all the required modules. I can see the Message Subscribe UI but there is nothing I can configure.

Does anyone have any experience with this?

# Answer
> 1 votes
(I know this question is old. This answer is for if is useful for others). Message Subscribe module is a part of the Message Stack system:

> The message stack comprises three main modules: Message, Message Notify and Message Subscribe.

You 'must' understand the concepts behind each of these modules and its integration to understand the Message Subscriber's role under this stack. As I understand, the module does not work as an isolated module. Also, please note that Message Subscribe uses the Flag module to give users functionalities related to subscribe or not of its account to receive messages notifications related with the event that generates the message.

Here an interesting document about the Message stack to understand the main concepts behind the stack. Another resource here.

# Answer
> 1 votes
The Message Subscribe module is part of the Message Stack, which consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Just looking at the available documentation it's not obvious to get going with it. But if you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to ***subscribe*** to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

---
Tags: notifications, message-subscribe
---


# Question
Title: Simple Apache Redirect not working in Drupal .htaccess file
I migrated a site from a custom built php site (with file types in the urls) to a Drupal site recently. I want to preserve the old url (because they are indexed on search engines) and redirect to the respective new Drupal paths. I have placed this at the top of the .htaccess file: `Redirect 301 /path/oldfile.php /node/22`

However, the redirect is not taking and the site shows a 404 at http://example.com/path/oldfile.php. If I place this in my .htaccess: `Redirect 301 / http://example.org/` then the site is redirected when I go to http://example.com/ so I know that the Apache mods are working.

Any thoughts?

# Answer
Have you tried altering the form of the redirect? That might be invalid -- the target of a redirect should be a full URL.

Try

```
Redirect 301 /path/oldfile.php http://www.newdomain.com/node/22

```
> 0 votes

# Answer
I solved this by adding the directory `/path` to my site root. For some reason even though there is no equivalent directory on the new site that corresponds to the url path of the old urls, I still needed an empty directory with the same name, otherwise it was responding with a 404.
> 0 votes

# Answer
I suggest that you add you rewrite directives right after this (around line 57):

```
RewriteEngine on

```

So don't put it right in top/beginning of your .htaccess.

And secondly, I recommend that you try following directives:

```
RewriteCond ${REQUEST_URI} /path/oldfile.php
RewriteRule (.*) /node/22 [R=301,L] //or index.php?q=node/22

```
> 0 votes

---
Tags: redirection, .htaccess
---


# Question
Title: How to create a view of duplicate entities based on title, showing the most recently created ones
I have investigated a number of solutions that came close to my requirements, but not one that actually solves this, I think very common, use case:

Often after using feeds, there are duplicate entities created with the same title. Apart from the methods to prevent this from happening, I want to find a solution to list the most recently created entities of which the title already is in use.

When the most recent duplicates are listed, I want to bulk-delete them using views bulk operations.

My approach is as follows:

1. Create a view that lists titles of all entities of a certain bundle.
2. Turn on aggregation
3. Add the entity ID as field, with aggregation 'Count'
4. Add a filter: entity ID with aggregation 'Count' is 'more than 1'

The result is a list of entity titles with a column of the count of entities having that title.

**Question 1:**

So far so good, but I need to see the latest entities listed with an already existing title. How to make that happen?

**Question 2:**

I need to bulk-delete these most recent duplicates, preferably using Views Bulk Operations. However, when I add VBO(for entities) to the view, this results in an empty output. Probably because the aggregated list shows titles and not entities. This is caused by question 1 not being resolved.

EDIT: I came up with the idea to use this view of duplicate titles, as a filter for another view that should show the latest entities having those titles. So my 3rd question would be:

QUESTION 3: How to create a view that uses the aggregated view mentioned above as its filter, to show the entities having those titles.

# Answer
> 2 votes
I solved this using the modules

* Flags
* Rules
* Views Rules
* Rules links

with the following method:

1. Added a flag 'in bucket' connected to the entity
2. Created A views Rules display listing all entities
3. Created a rules link, which includes a rule with an action 'Views loop' that performs an action on each entity in the views Rules display. The action performed is a rules component that again uses a views loop checking if a duplicate title is present. So for every views list item, all views list items are compared.
4. If a duplciate title is found, the entity is flagged with the 'in bucket' flag. The Rules link has as a last action the redirection to the view that shows all entities in the bucket.
5. To make this more reliable, add as first action of the rules link, a loop to remove all entities from the bucket (remove all flags).

In this way, with one click all entities are checked on duplicate titles, and the found duplciates are shown.

However, this is not the most efficient and performant way for large lists. For example when having 2000 entities, rules will need to process 2K x 2K = 4M times the comparison. I had to limit my list to 350 items in order to have processing time of 5 minutes. I tried to implement batch processing of the views loops, but did not succeed yet.

A more efficient way would probably be to use the view as mentioned in the question, and use that list of titles as a filter for another view which should show the most recent entities having one of this titles. I haven't figured out how to do this yet.

---
Tags: entities, views
---


# Question
Title: How do I use a drush alias to connect to a docker container?
I have a droplet setup on Digital Ocean with two docker containers, one for Drupal (using modified alpine-drupal8 image) and another running a simple mysql server.

I am able to run drush commands on this container by connecting over ssh into the droplet and running `docker exec -it <container_name> /bin/sh` I have also set up an ssh server (listening on port 2222 on the same ip address) on the container itself with a little port forwarding:

```
ssh root@<droplet_ip> -p 2222 # Connects from remote dev machine to drupal container using ssh key

```

My sites/default/drush/aliases.drushrc.php file:

```
<?php

$aliases['container'] = array(
  'root' => '/usr/share/nginx/html',
  'uri' => 'http://default',
  'path-aliases' =>
  array (
    '%drush' => '/usr/local/bin/drush',
    '%site' => 'sites/default/',
    '%files' =>'sites/default/files/',
    '%modules' =>'modules/'
  ),

  'remote-host' => '<droplet_ip>',
  'remote-user' => 'root',
  'ssh-options' => '-p 2222',
);

?>

```

Starting an ssh session with the drush alias is working:

```
$ drush @container ssh
186203cca:/usr/share/nginx/html# ### Connected to ssh session in droplet
186203cca:/usr/share/nginx/html# which drush
/usr/local/bin/drush
186203cca:/usr/share/nginx/html# drush status
 Drupal version                  :  8.1.8
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  <removed>
 Database port                   :  <removed>
 Database username               :  <removed>
 Database name                   :  <removed>
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  <removed>
 Administration theme            :  seven
 PHP configuration               :  /etc/php7/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /usr/local/bin/drush
 Drush version                   :  8.1.3
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :
 Install profile                 :  standard
 Drupal root                     :  /usr/share/nginx/html
 Drupal Settings File            :  sites/default/settings.php
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp
 Sync config path                :  sites/default/files/config_vxs7qxuAqrfCtOXdbGYLvLAIKl1_bN4J_BvmrEn1l1EUIsn4Du_CKck2QWYSmkNDgUVfdZUZVQ/sync

```

However, I still can't seem to run actual drush commands:

```
$ drush @container status
env: can't execute 'drush': No such file or directory

```

My theory is that the port forwarding is not working correctly, and drush is trying to run on the container, not the droplet

This may be related to my issue: Why does drush say "command not found" when I try to execute remote commands?

---

Update:

A little more testing and I found out I can use drupal console without issues, so it seems this is isolated to drush only:

```
$ drupal @container cr all

 Rebuilding cache(s), wait a moment please.

 [OK] Done clearing cache(s).

```

# Answer
So this one threw me for a while this evening as well.

Here's what ended working:

```
$aliases['docker'] = array(
  'uri' => 'http://localhost:8080',
  'php' => '/usr/bin/php',
  'root' => '/var/www',
  'remote-user' => 'root',
  'remote-host' => '0.0.0.0',
  'ssh-options' => '-p 8022 -o PasswordAuthentication=no -i ~/.ssh/id_rsa',
  'path-aliases' =>
  array (
    '%drush' => '/root/.composer/vendor/drush/drush/drush'
  )
);

```

The remote host of 0.0.0.0 ended up doing the trick. Seems that if you use localhost or 127.0.0.1 drush doesn't actually try to ssh in.
> 2 votes

---
Tags: 8, drush
---


# Question
Title: What is the correct way for a Drupal 8 custom theme to override the JS collection renderer?
I would like to implement a custom theme, and in my theme, I need to change the way that JavaScript is rendered. By default, Drupal 8 will use the Drupal\Core\Asset\JsCollectionRenderer class, and create a bunch of html\_tag render arrays.

I want to change this to allow returning just the name of the JS file, so I can present it in a different way using Twig.

It would appear that I need to define a ServiceProvider class that can register a change to asset.js.collection\_renderer (core.services.yml), and implement a custom class to replace JsCollectionRenderer's behaviour.

However, it looks as though I would need a custom module in order to get the ServiceProvider's register() method to fire.

If possible, I wanted to avoid needing a custom module just to have a custom theme, because that seems like needless overhead, so I'm wondering if there's a way to fully encapsulate this behaviour in a single theme, or whether my approach is misguided in some way and there's a better way to handle this.

# Answer
> 1 votes
Themes have no mechanism to provider or alter services. A custom module is needed.

---
Tags: theming, 8
---


# Question
Title: What happens to a render array after hook_form_alter() that does not happen after an AJAX callback?
I have a multi-value field type in a content type. During hook\_form\_alter(), I add an `#ajax` property to the field.

Upon execution, the `ajax callback` loads a node's custom view mode and two form inputs from another content type into the div.

I am using field\_default\_form() to generate the form elements.

In order for these addons to persist through clicking the 'Add more' button, I use hook\_form\_alter() to call the same function that is called by the ajax callback, and I add them into the results/wrapper div.

My problem is that the form elements of the #ajax callback results are not rendered correctly. For example, they do not have a name or id for the \<input\> tag. One of the fields is an autocomplete field and autocomplete functionality does not get applied to the element.

However, the results of the 'add more' button, which calls `hook_form_alter()`, DOES render these elements correctly.

As far as I can tell, the render arrays are identical during generation. It seems to me like some additional processing happens after `hook_form_alter()` that does not happen after my #ajax callback.

I have tried adding #theme, #theme\_wrapper, #after\_build and #rebuild = TRUE keys to the resulting render array elements, but it does not appear to have any effect.

How can I get these elements to render correctly?

# Answer
> 1 votes
Since hook\_form\_alter() is returning the correct results, there is a way to use that to our advantage.

By calling drupal\_rebuild\_form() in our ajax callback, we can return the specific part of the resulting array that should fill in our wrapper div.

e.g.

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

    $delta   = $form_state['triggering_element']['#delta'];
    $lang    = $form_state['triggering_element']['#language'];

    $new_form = drupal_rebuild_form('mymodule_node_form', $form_state);

    return $new_form['mymodule_item_id'][$lang][$delta]['item_data'];
}

```

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


# Question
Title: How to handle separated stock for a product bundle?
Following the scenario that I want implement in my store. There are three products: A, B, C. My purpose is to sell two bundle composed by AB and BC. Each product has its stock: A x10, Bx5, Cx20. The bundle products are dependable by the stock of every single product so it will not possible to order more than 5 AB product (or BC product) because every time a bundle product is bought the stock of every single must descrease.

When a single product's stock runs out, every bundle product composed by that single product can't be sold.

Is there any way to achieve my purpose?

# Answer
I am the author and maintainer of the Commerce Product Kit module which is close to your requirement.

> It provides a "field formatter" for the "product reference" or an "entity reference" fields to add all the commerce products referenced that field to the cart at once.

It also has support to the commerce stock module. If a product kit has 3 products in it (A, B, and C), and say one of them is out of stock (B), it is not added to the cart.

Not allowing *any product* to be added to cart even if one of the product from kit is not in stock makes sense and can be considered a good addition to the cart.

I have created a feature request in the issue queue for the same :
#2821442 : Disallow adding product kit to cart if one product is out of stock.

While I do not have the time to implement it myself now, I would be happy to review any patches and make this a part of the module.
> 2 votes

---
Tags: commerce, entities
---


# Question
Title: Within a field template, how can I print the value of another field from the same node?
I have an email field that I would like to present on the node as a name that links to the email address. As such, I am trying to edit the email field template to embed the name from a text field. However, I'm having difficulty figuring out how to access the content of this text field. I've gotten as far as figuring out that `twig(_context['element']['#object'])` will give me some info about the node object, but I cannot figure out how to access the field values. Am I even in the right ballpark for accessing this data?

# Answer
This is the node object that you have found in the field template.

You can access the field values like this:

```
{{ element['#object'].field_field1.value }}

```
> 2 votes

---
Tags: theming, 8, entities
---


# Question
Title: Remove entities programmatically from view results before pager is generated
I want to remove certain entities from the view results (Views core module), before the view's pager is generated.

By now I am doing it in **hook\_views\_post\_execute()**. The problem here is, that the number of results on the view pages is different then. There should be 10 results per page and not 7, 8 or 6 etc.

I do not want to create a views filter, which would require manual interaction from the user inside the views interface in the webbrowser.

I have tried also **hook\_views\_query\_alter()**. The problem here is, that my module's class methods are processing entity id's (node id's in particular). It might would work with the SQL **NOT IN** statement, but this is probably a problem for bigger site's and a huge performance impact. Since I need to iterate over all entity id's from the site and check access then.

My questions:

* Is there any method inside the Views module, which allows me to remove the entity id's from the view results or shall I really use **hook\_views\_query\_alter()**?
* Also - if it comes to the **hook\_views\_X** methods - isn't there any more elegant class method or *event*? Since hooks are a mostly deprecated way in Drupal 8.

Thanks for your attention!

# Answer
You need to alter the query in one way or another, that is the only way the pager can work.

Sounds like you are using nodes, then you can use the node access grant system. Basically, it allows you to "index" the access checks and assign attributes to the nodes, like the group they belong to. And then there is a second hook, that allows you to define what groups (or whatever it is in your case) the user has access to. This will then be combined into a query for you.

Be aware that this is one of the most complicated systems in Drupal, but if you can't do the access check directly as part of the query (like checking the value of a certain field), then this is the only way.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Is it possible for the front page view to use a different image style for each teaser item?
Im trying to build a complicated grid ui with a different image size and aspect ratio for each consecutive item in the list. How can I select a different image style for each item?

# Answer
First, you need to go one level up, don't think about image styles, think about enity view modes. Then you can control which image style is used for each view mode.

The reason for that is that entity output is cached by view mode. You could theoretically alter each entity and switch out the view mode, the data might actually even be available there, but it will fall apart when the same entity is suddenly in a different position but still cached.

You could try to implement preprocess or another views hook to change the view modes programatically in the render array. That will however not be configurable if that is a requirement.

What we build for our project is a views display plugin that allows to not select a single view mode but one for each entity that is being displayed.
> 0 votes

---
Tags: views, 8, media
---


title: Variable in base path

text:
# Question
Title: Variable in base path
I need to change the BasePath in drupal 8 of all views and all node in such a way that it contains a variable (which will manage as country) Like this:

```
site.locl/{lang}/{variable}
site.locl/en/testvar/node/100
site.locl/en/testvar/myview

```

# Answer
> 2 votes
Search for path inbound and outbound processing, that's what the alias and language prefix systems use for example. Both are tagged services, see PathProcessorAlias and the corresponding service definition path\_processor\_alis.

In Inbound, you cut off the part you want and store it somewhere in a service or so, where you can access it again where you need it. And in outbound, you add it again. As you seem to require both language and country, you will need to make sure the priorities are correct in relation to the language prefix handling.

Keep in mind that this will not give you any possibility to have different interface or content translations as there isn't really a way to store it. If you need that, you more likely need to use a language per language/country and figure out how to do fallbacks correctly.

There is also a module available that helps with this: https://www.drupal.org/project/purl. It apparently has an 8.x dev version, but I have no idea about the state of it.

---
Tags: 8, i18n-l10n, path-aliases
---


# Question
Title: Can we automate scheduled published/Unpublished nodes in drupal 8?
Schedular Module helps to schedule Nodes publish and un-published in Drupal 8. But it affect took place on each cron run only.

For example. If I set Publish a Node A on `19/10/16 14:30` but site configure to run cron after each hour. So it's get published on `14:00`. Is their any way to make it publish on exactly `14:30`.

Thanks

# Answer
The Scheduler module has it's own cron: http://example.com/en/admin/config/content/scheduler/cron, so you can configure any granularity you need
> 1 votes

# Answer
As an alternative, you could also use the Ultimate Cron module, which allows you to configure the granularity for each cron hook separate. So you can run drupal cron every minute, and scheduler also every minute, but system cron only every 3 hours.
> 1 votes

---
Tags: 8, cron
---


# Question
Title: Can I change the HTTP user agent when writing browser tests?
My module has some special functionality based on the user agent of the request. I want to write tests for this functionality based on D8's BrowserTestBase, but it doesn't seem possible to change the user agent string.

The `prepareRequest` method of `BrowserTestBase` sets the user agent to the value of `drupal_generate_test_ua($this->databasePrefix)`.

For a test, I tried changing this value to something else, and it breaks the tests.

Now I realize that there appears to be some functionality built into core based on this value that `drupal_generate_test_ua` returns and there's checks all over core to detect if Drupal is running within a test or not.

Is there a workaround or any hope for writing tests with a custom user agent?

# Answer
> 1 votes
No, you can't.

BrowserTestBase, just like other other tests that support web requests uses the user agent to identify which test environment you're in (there could be multiple, parallel ones). Changing the user agent would result in your request being sent against the main site.

The only workaround that I see is to send another header (if that's actually possible through the API, not sure). In your could you would then look at that header instead. It's not perfect and it requires you to write special code for tests, but I can't really see another way if you really rely on the user agent.

---
Tags: 8, testing
---


# Question
Title: Commerce billy mail: how to attach multiple files to an email
I have module commerce billy mail working. Additionally to the invoice PDF that is attached to the mail, I would like to send two more files (terms & conditions and a price list).

Here's the function \_commerce\_billy\_mail\_get\_attachments from the file commerce\_billy\_mail.module, it seems to be the appropriate function (?), but I don't know how to add the additional files:

```
function _commerce_billy_mail_get_attachments($order) {
  $attachments = array();

  list($html, $filename) = commerce_billy_mail_pdf_prepare($order);
  $pdf_filecontent = commerce_billy_mail_pdf_create($html, $filename);
  $filemime = 'application/pdf';
  $attachments[] = array(
    'filecontent' => $pdf_filecontent, // we use a dynamically created file.
    'filename' => $filename, // can use any alias name here
    'name' => $filename, // required for mandril and other libraries.
    'filemime' => $filemime, // mime file type
    'type' => $filemime, // required for mandril and other libraries
    'list' => TRUE,
  );

  return $attachments;
}

```

Hope someone can help out!

# Answer
I found out, how to attach multiple Attachments:

```
  $attachments[] = array(
    'filename' => 'MyDoc.pdf', // can use any alias name here
    'name' => 'MyDoc.pdf', // required for mandril and other libraries.
    'filemime' => 'application/pdf', // mime file type
    'type' => 'application/pdf', // required for mandril and other libraries
    'list' => TRUE,
    'filepath' => 'sites/default/files/mail_attachments/MyDoc.pdf',
  );

```
> 1 votes

---
Tags: commerce, emails
---


# Question
Title: Are use Drupal\Core\Form\FormStateInterface statements for a Drupal 8 hook required?
This may be obvious to expert D8 users, but; If I am implementing hook\_form\_alter in Drupal 8, the hook definition looks like this:

```
hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

```

In that there is a direct reference to FormStateInterface, so am I right in saying that it is redundant to also have the use statement in my file:

```
use Drupal\Core\Form\FormStateInterface; // Still works if I comment this out

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  ...
}

```

When generating the code using Drupal Console I get:

```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  ...
}

```

Best practice? It seems neater to me that the hook itself references FormStateInterface, making the use statement redundant.

# Answer
> 1 votes
It is recommended to use the use + short reference. Technically, it makes no difference, but it results in shorter lines and is easier to read.

The reason the hook documentation always uses full namespace is to make it easier to copy it into a module file, as you'd otherwise also have to look up the use statement.

---
Tags: 8, console
---


# Question
Title: How to make custom entity type revisionable with existing content?
I'm trying to make a custom entity (with existing data!) revisionable, but I run into multiple very serious issues including schema update errors, difficulties with creating revision data for existing content, and so on...

Has anyone done something similar successfully? Is there a fairly simple way to do it?

# Answer
> 0 votes
Yes, it is highly complicated and there is currently no easy for such a switch.

Upgrade path between revisionable / non-revisionable entities is the core issue to make this easier. You could rely on the patch there but I'm not sure if it is fully working right now.

---
Tags: 8, entities
---


# Question
Title: How do you force Drupal login to encrypt the credentials
To make the Drupal login as secure as possible, we don't want to send the login credentials as clear text, but want to somehow encrypt the credentials or the entire request.

Ideally the solution should both for the actual login page, but also if the user logs in via the login block on any page.

# Answer
You can't really do that.

Drupal 8 hashes and salts the password on the server side.Both the form and the authentication API require the plain password which is then validated. You should use HTTPS to protect the password during submission.

To be able to do something like this, you'd either need to use encryption, so you can decrypt again on the server or bypass the API somehow, but that isn't really possible since Drupal's hashing implementation has a dynamic salt and each hash has its own salt that you do not know in JS. Also keep in mind that anyone can read/debug the JS and figure out your salt or encryption key if you have it in JS.
> 1 votes

---
Tags: users, security
---


# Question
Title: Load EForm programmatically in block plugin
I'm trying to load a form inside a block plugin. However when I try to load it I get an error

> The form argument information\_request is not a valid form

'information\_request' is the machine name of the form I'm attempting to load. This is an EForm I created, not a built in core form such as the user login form, or search form.

Here is the method I'm using that fails

```
$fb = \Drupal::formBuilder();
$inforequest = $fb->getForm('information_request');
$render['form'] = $inforequest;

return $render;

```

I've seen other examples for loading core forms like so

```
$form = \Drupal::formBuilder()->getForm('Drupal\search\Form\SearchBlockForm');

```

and I do see that a full address is being given in this example instead of just the machine id, but I don't know what address you could give for a custom eform. I've tried the following with no luck.

```
$inforequest = $fb->getForm('\Drupal\eform\information_request');
$inforequest = $fb->getForm('\Drupal\eform\Form\information_request');

```

How do you load an EForm programmatically to render inside a block plugin?

UPDATE: I made some more attempts to try to render it in another way. I attempted to load all entities like so

```
$content_entity_types = [];

foreach (\Drupal::entityManager()->getDefinitions() as $entity_type_id => $entity_type_definition) {
    if ($entity_type_definition->getGroup() == 'content') {
        $content_entity_types[$entity_type_id] = $entity_type_definition;
    }
}

$entities = array();
foreach ($content_entity_types as $type_key => $entity_type) {
    // Entities that do not declare a form class.
    // Exclude Comment entities as they have to be attached to another entity.

    // Get all bundles for current entity type.
    $entity_type_bundles = \Drupal::entityManager()->getBundleInfo($type_key);
    foreach ($entity_type_bundles as $bundle_key => $bundle_info) {
        // Personal contact form requires a user recipient to be specified.
        $entities[(string) $entity_type->getLabel()][$type_key.'.'.$bundle_key] = $bundle_info['label'];
    }
}

die('<pre>'.print_r($entities).'</pre>');

```

Doing so did actually show that $entities did contain the form I was looking for

```
Array
(
    [Custom block] => Array
        (
            [block_content.basic] => Basic block
        )

    [EForm Submission] => Array
        (
            [eform_submission.donate] => Donate
            [eform_submission.information_request] => Information Request
        )

    [File] => Array
        (
            [file.file] => Drupal\Core\StringTranslation\TranslatableMarkup Object
                (
                    [string:protected] => File
                    [translatedMarkup:protected] =>
                    [options:protected] => Array
                        (
                        )

                    [stringTranslation:protected] =>
                    [arguments:protected] => Array
                        (
                        )

                )

        )

    [Content] => Array
        (
            [node.book] => Book page
            [node.landing_page] => Landing Page
            [node.news] => News
            [node.newsletter] => Newsletter
            [node.page] => Basic page
        )

    [Shortcut link] => Array
        (
            [shortcut.default] => Default
        )

    [User] => Array
        (
            [user.user] => Drupal\Core\StringTranslation\TranslatableMarkup Object
                (
                    [string:protected] => User
                    [translatedMarkup:protected] =>
                    [options:protected] => Array
                        (
                        )

                    [stringTranslation:protected] =>
                    [arguments:protected] => Array
                        (
                        )

                )

        )

    [Custom menu link] => Array
        (
            [menu_link_content.menu_link_content] => Drupal\Core\StringTranslation\TranslatableMarkup Object
                (
                    [string:protected] => Custom menu link
                    [translatedMarkup:protected] =>
                    [options:protected] => Array
                        (
                        )

                    [stringTranslation:protected] =>
                    [arguments:protected] => Array
                        (
                        )

                )

        )

)

```

I see my form in $entities\['EForm Submission'\]\['eform\_submission.information\_request'\]; But I'm still not sure how to access or render it.

# Answer
> 0 votes
I did the exact same thing the other day. If you're having trouble setting up your classes, you can use Drupal console to generate a new block plugin. It can make it easier. Basically, the rendering happens inside the build method of your class. This method is inherited from BlockBase (which is a core Drupal class).

The process is to load the entity in one step and then use the form builder service to build the entity form of your entity. Then all you have to do is return the $form variable. It takes care of the rending for you.

Here's the code I used.

```
<?php

namespace Drupal\application_form\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'CallBackBlock' block.
 *
 * @Block(
 *  id = "call_back_block",
 *  admin_label = @Translation("Call back block"),
 * )
 */
class CallBackBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Drupal\Core\Entity\EntityFormBuilder definition.
   *
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entity_form_builder;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entity_type_manager;

  /**
   * Construct.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   */
  public function __construct(
        array $configuration,
        $plugin_id,
        $plugin_definition,
        EntityFormBuilderInterface $entity_form_builder,
        EntityTypeManagerInterface $entityTypeManager
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entity_form_builder = $entity_form_builder;
    $this->entity_type_manager = $entityTypeManager;
  }
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.form_builder'),
      $container->get('entity_type.manager')
    );
  }
  /**
   * {@inheritdoc}
   */
  public function build() {

    // Get the Call backs entity form and render it.
    $call_back_entity = $this->entity_type_manager->getStorage('call_backs')->create();
    $form = $this->entity_form_builder->getForm($call_back_entity);
    return $form;
  }

}

```

---
Tags: forms, 8, blocks
---


# Question
Title: Send a regular reminder (or do other normally cron-dependent tasks) while in maintenance mode
I recently had an episode where I put a site into maintenance mode to perform a security upgrade and forgot to go live again afterwards, resulting in almost a day of downtime before I caught the error.

I thought I could set up a rule to send me an e-mail whenever cron runs if it detects that the site is in maintenance mode, but I don't think that's going to work because cron can't execute when maintenance mode is on. A preliminary test seems to confirm that. I put the site in maintenance mode, attempted to run cron manually, and no e-mail was generated.

Is there another module or method I could use to send myself a reminder so this won't happen again?

# Answer
> 1 votes
I, personally, can think of a hamfisted, hacky way do do this, but I would prefer for someone else to provide a more elegant solution.

My web host doesn't allow SSH, but does have a "tasks" feature that essentially pulls a designated website URL at regular intervals; I'm currently using it to run Cron externally and get around Drupal 7's default Poormanscron implementation.

So I could bootstrap Drupal from a custom script and have it get pulled as an hourly task. It would `variable_get('site_offline')` and do nothing (or maybe redirect to index.php in case a 'bot discovers it) if false and invoke the Rule that sends the reminder e-mail if true.

Heck, if Rules or Drupal's e-mail abilities are also disabled while in maintenance mode, I can just generate the e-mail with straight PHP.

# Answer
> 0 votes
A possible solution to answer this question is to create a custom rule (using Rules) that looks like so:

* **Rules Event**: Drupal is initializing.
* **Rules Condition**: check if the site is in maintenance mode, using the Rules Condition Site Variable module (see below for more details).
* **Rules Action**: Send an appropriate eMail.

More details about the above Rules Condition:

* The Rules Condition Site Variable module allows a rule to have a Rules Condition that explicitly references a variable by name. That way the Rules Condition does NOT (repeat: NOT) have to rely on inline PHP code to check the value of site variable `site_offline` (= the equivalent of `variable_get('site_offline')`).
* How to use this module (quotes from its project page):

+ In your rule, create a new condition, and select 'Site variable to check'.
    + Set the 'The site variable you want to check' field to be the name of the variable you wish to check against. You do not need to surround the variable name with quotes.
    + Set the 'The value that the site variable should have' field to be the value that the variable should be in order for the condition to return true.

Obviously, because of the nature of the Rules Event used here, it does NOT depend on the execution of a cron job.

A possible refinement is to enable this rule when putting a site in maintenance mode, and disable the rule again when maintenance mode is finished.

---
Tags: rules, cron, maintenance-mode
---


# Question
Title: Fetching field values only if they exist and applying them automatically as entity labels
I have a content type with these fields, among others:

* `field_address` – required
* `field_entrance` – not required
* `field_apartment_number` – not required (or actually required if a previous field meets a certain criteria, otherwise not shown at all)

With the Automatic Entity Label modul I can use tokens to save the node title using this pattern:

`[node:field_address] [node:field_entrence] [node:field_apartment_number]`

If any of the non required fields are left blank there's no value from those fields saved to the node title. However, the whitespace between the tokens is still saved, and I don't want that. I'm not good at PHP but this I what I have, copy-pasted from various sources:

```
<?php

$address = field_get_items('node', $node, 'field_address');
$entrance = field_get_items('node', $node, 'field_entrence');
$apartment_number = field_get_items('node', $node, 'field_apartment_number');

print $address['value'];

if ($entrance) {
   print ' ' . $entrance['value'];
}

if ($apartment_number) {
   print ' ' . $apartment_number['value'];
}

?>

```

But it doesn't work. Instead, no title is saved at all. How do I correct my code?

# Answer
> 1 votes
As far as I remember, field\_get\_items() returns an array of items. In your case something like:

```
    if (count($address)) {
       print $address[0]['value'];

       if (count($entrance)) {
          print ' ' . $entrance[0]['value'];
       }

      if (count($apartment_number)) {
         print ' ' . $apartment_number[0]['value'];
      }
   }

```

should work.

---
Tags: 7, entities
---


# Question
Title: How to hide user picture based on the value of a field in their profile
This last bug is the only thing between be and launching this site. Please help!

I have a field called publish photo? that is a checkbox in the user's profile. For users with this box unchecked, I would like to hide the user picture for users that are not logged in. I would like it to be hidden everywhere, in a display suite view and in the views view. I had the following in my template.php, which I could have sworn was working, back before I added on display suite, but it seems not to be working now.

```
function MYMODULE_preprocess_user_picture(&$variables) {
    if ((!isset($variables['account']->field_user_publish_photo) || $variables['account']->field_user_publish_photo[LANGUAGE_NONE][0]['value'] == '0') && $variables['logged_in'] != 1) { // hide user photo when Publish photo is turned off
        $variables['user_picture'] = '';
    }
}

```

What is the proper way to do this?

# Answer
template\_preprocess\_user\_picture seems to be fair enough approach to me, the hook should be able to unset profile picture from any instance including views etc.

Only thing I doubt could go wrong in your code is conditional unsetting of images. To make sure could you comment out the condition

```
function MYMODULE_preprocess_user_picture(&$variables) {
        $variables['user_picture'] = '';
}

```

If that unset your field than problem can be narrowed to make the condition working.

Probable problem with your condition
Can you check if you are getting fields in $variables\['account'\] object$variables\['account'\], if not you might need to object the user account and check the field conditions

```
$uid = $variables['account']->uid;
$account = user_load($uid);
function MYMODULE_preprocess_user_picture(&$variables) {
  if ((!isset($account->field_user_publish_photo) || $account->field_user_publish_photo[LANGUAGE_NONE][0]['value'] == '0') && $variables['logged_in'] != 1) { // hide user photo when Publish photo is turned off
      $variables['user_picture'] = '';
  }
}

```
> 0 votes

---
Tags: 7, theming
---


title: db_select only ever returns one result

text:
# Question
Title: db_select only ever returns one result
I am constructing a query that has to fetch the field collection line item, and it's associated field collection field to get the node id that the field collection field is being used on. The problem is it's only ever returning one single result when I know for sure there are at least two to return. Perhaps a fresh set of eyes can help.

Run list field table

```
"entity_type","bundle","deleted","entity_id","revision_id","language","delta","field_run_list_item_value","field_run_list_item_revision_id"
"node","run_list",0,100000018,48,"und",0,4,12
"node","run_list",0,100000017,47,"und",1,3,11
"node","run_list",0,100000017,47,"und",0,2,10

```

Run List field's line item table:

```
"entity_type","bundle","deleted","entity_id","revision_id","language","delta","field_story_target_id"
"field_collection_item","field_run_list_item",0,2,10,"und",0,100000004
"field_collection_item","field_run_list_item",0,3,11,"und",0,100000009
"field_collection_item","field_run_list_item",0,4,12,"und",0,100000004

```

This is my query:

```
$rl_query = db_select('field_data_field_story', 'fci');
$rl_query->fields('fci', array('field_story_target_id', 'bundle', 'entity_id'));
$rl_query->leftJoin('field_revision_field_run_list_item', 'rl', 'rl.field_run_list_item_value = fci.entity_id');
$rl_query->fields('rl', array('entity_id', 'field_run_list_item_value'));
$rl_query->condition('fci.field_story_target_id', $node->nid);
$rl_results = $rl_query->execute()->fetchAll;

```

When I `dpm($rl_results);` it ends up looking like:

```
... (Array, 1 element)
    0 (Object) stdClass
       field_story_target_id (String, 9 characters ) 100000004
       bundle (String, 19 characters ) field_run_list_item
       entity_id (String, 1 characters ) 2
       rl_entity_id (String, 9 characters ) 100000017
       field_run_list_item_value (String, 1 characters ) 2

```

I should expect to see more than one result returned. In this example, there should be two.

# Answer
> 0 votes
You also put another condition in your query

```
"$rl_query->condition('fci.field_story_target_id', $node->nid);"

```

You can check by commenting this line.

---
Tags: 7, database
---


# Question
Title: Build context menu for news articles (sample image included)
I have a complex view that queries and presents a lot of news articles depending on `year` and `month` contextual filter arguments. Everything works fine so far. However, now I want to show kind of context menu next to the view result that looks like this (shows multiple screens with different menu content depending on current display):

**What is the best/most elegant way to realize such a context menu? (no ugly hacks)**

---

## What I've already tried

I tried to accomplish that using the Views UI – no luck. Creating two different View blocks (one for a list of years and one for the months of currently selected year) didn't work, because in order to get a distinct result set I need identical fields that are used for "collapsing". The field I used was "Post date" – and this always differs.

I guess that I must write a custom module where I leverage the Views API and create that markup for the context menu. But where do I start? And how can obtain the current contextual filter arguments?

# Answer
> 0 votes
Not really an answer, but perhaps a lead. In Drupal 6, a similar thing was accomplished with the book navigation block. You could have the book navigation block filter to a certain number of steps up/down tree from the node page that you were currently viewing.

I am not sure how this could be accomplished with existing views configuration, as I think tree navigation is not a common thing for views.

This is more the kind of trick I would expect to find in Taxonomy, based on the vocab's hierarchy. There, navigation can be a more certain thing, as the structure is defined in the vocab, and they are just filling the tree leaves with tagged nodes. Again with the Drupal6 reference, but perhaps you can scavange code from http://drupal.org/project/taxonomy\_treemenu

If you do code something, release it back to the community?

# Answer
> 0 votes
Perhaps views tree can give you what you need

https://www.drupal.org/project/views\_tree

---
Tags: 7, views, routes
---


# Question
Title: Aegir fails on verify task after import task (Import an existing not aegir site)
i'm having many problems with importing sites into aegir hosting system: here is what i do to import a web site into Aegir:

1. import the directory of the web site into platforms dir
2. import the DB into the db of Aegir
3. create a dir in the sites dir calling it with the domain of the site.
4. cp -r sites/default/\* sites/
5. cp -r sites/all/\* sites/
6. from Aegir fron-end create the platform giving it the path of the root website dir
7. Aegir verify plaform and detect the site to be imported.
8. Execute the import task with success(i think here is the problem)
9. The task import has a success result (but i think is did not work because the scope is a wrong scope, it takes the main scope of aegir).
10. then the verify task fails, did not create the vhost.d/ , it didn't create drushrc.php file under the sits/.

i think the problem is: when drush overwrite settings.php and try to store the information of the DB access in the apache environment it fails. i don't know why...i already made many imports (last one was one week ago), i don't think i changed any thing.

please help me!

# Answer
I found the right way to make import in the docs, my problem was how to start my import site with my DB, the best way is here: http://docs.aegirproject.org/en/3.x/usage/sites/importing/#importing-a-single-site-manually. To load your DB you may use `drush @www.site-domain.it sqlc < file-db.sql` I hope this can help others to make import files.
> 0 votes

---
Tags: aegir
---


# Question
Title: field widget is not saving selected value to database
I am creating a widget under **taxonomy\_term\_reference** field and trying to use the same autocomplete used by taxonomy module, autocomplete is working fine but data is not getting saved.

```
    /**
     * Implements hook_field_widget_info().
     */
    function test_field_widget_info() {
      return array(
        'test_widget' => array(
          'label' => t('test Engine'),
          'field types' => array('taxonomy_term_reference'),
          'settings' => array(
            'size' => 60,
            'autocomplete_path' => 'taxonomy/autocomplete',
          ),
          'behaviors' => array(
            'multiple values' => FIELD_BEHAVIOR_CUSTOM,
          ),
        ),
      );
    }

    /**
     * Implements hook_field_widget_form().
     */
    function test_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      if ($instance['widget']['type'] == 'test_widget') {
        $form_field = array();
        $tags = array();
        foreach ($items as $item) {
          $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
        }
        $form_field['autocomplete'] = array(
          '#type' => 'textfield',
          '#title' => 'Tags',
          '#default_value' => taxonomy_implode_tags($tags),
          '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'], // Trying to use the same autocomplete path from taxonomy module.
          '#size' => $instance['widget']['settings']['size'],
          '#maxlength' => 1024,
          '#element_validate' => array('test_validate'),
          '#attributes' => array(
            'class' => array($element['#field_name']),
          ),
        );

        $form_field['search'] = array(
          '#type' => 'button',
          '#value' => t('Search Tags'),
          '#ajax' => array(
            'callback' => '_test_callback',
          ),
          '#attributes' => array(
            'reference_class' => $element['#field_name'],
          ),
          '#name' => $element['#field_name'],
        );
        $element += $form_field;
        return array('tid' => $element);
      }
    }
function test_validate($element, &$form_state, $form) {
  $value = array();
  if ($tags = $element['#value']) {
    // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);

    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }
  }
  $typed_terms = drupal_explode_tags($tags);
  foreach ($typed_terms as $typed_term) {
    // See if the term exists in the chosen vocabulary and return the tid;
    // otherwise, create a new 'autocreate' term for insert/update.
    if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
      $term = array_pop($possibilities);
    }
    else {
      $vocabulary = reset($vocabularies);
      $term = array(
        'tid' => 'autocreate',
        'vid' => $vocabulary->vid,
        'name' => $typed_term,
        'vocabulary_machine_name' => $vocabulary->machine_name,
      );
    }
    $value[] = (array)$term;
  }
  form_set_value($element, $value, $form_state);
}

```

# Answer
Try adding the following line below form\_set\_value().

```
$element['#value'] = 'new_value';

```

P.S. Borrowed from Alter taxonomy autocomplete value
> 0 votes

---
Tags: 7, entities, hooks
---


# Question
Title: Don't display block title on some content types
I try not to display the title block for one single content type. I do it in the settings of the title block under **Visbility -\> Content type** there I tick the content type which should *not* have the title block rendered and I check the options *Negate the condition*.

Basically this works but for example pages generated from the Views module also get *no* title block rendered then.

Does anybody know about this (in my opinion) "misbehavior" of the block system and how to work around it?

Maybe it's also a problem of the views module... I guess everything which has a content type gets the title except the excluded content type but Views pages do not have a content type and therefor get excluded too.

# Answer
> 1 votes
Do you have Ctools installed? Then you have two visibility plugins for content types. One from Ctools and one from core. Better use that from core, because Ctools is still alpha. If you install the module Block Visibility Groups, then you get the option to negate the condition also for the core plugin.

A core only workaround would be to use the path of the content type and negate this.

---
Tags: 8, blocks
---


title: Drupal 8 block cache

text:
# Question
Title: Drupal 8 block cache
I created a simple block where it shows good evening or good afternoon depending on the time.

But the problem is that i have to delete the cache otherwise it will stay at good evening ...

How do i disable the cache for this specific block ?

Here is the twig page:

```
  {% block content %}
{{ content }}
<p>{{ "now"|date("d,n,Y") }}
{% if "now"|date("H") >= '10' %}
 good afternoon,
{% else %}
good evening,
{% endif %}
</p>
{% endblock %}

```

# Answer
> 2 votes
This will disable the cache.

```
$build['#cache']['max-age'] = 0;

```

Block Cache API is removed; blocks now use standard caching patterns

# Answer
> 0 votes
Thank you for your help.

After all i just added my twig code in a views and it worked because i just choose to not cache and it worked.

---
Tags: 8, blocks, caching
---


# Question
Title: How to create a 'most popular content' view?
I'd like to get a view block listing the most viewed articles.

What are the options to do that with drupal 8?

**Note**: I have activated the core module named 'statistics' and configured 'Increment a counter each time content is viewed.' But I cannot select that field for sorting in Views.

# Answer
After activating the "Statistics" core module and checking the "Count content views" option in /admin/config/system/statistics, as you mention, you can select "Total views" as sort criteria (see screenshot).
> 3 votes

---
Tags: views, 8, nodes
---


title: Multiple entity quickedit problem

text:
# Question
Title: Multiple entity quickedit problem
I am utilising the basic page content type. When viewing my basic page the layout consists of:

* A view that outputs a block in the form of a header. Using the basic page fields "title" and "short description"
* A block that outputs the body of the page.

When I view my page, the node/articles markup is rendered as follows:

```
<article data-history-node-id="2058" data-quickedit-entity-id="node/2058" role="article" class="contextual-region clearfix" about="/node/2058" data-quickedit-entity-instance-id="0">...</article>

<article data-history-node-id="2058" data-quickedit-entity-id="node/2058" role="article" class="contextual-region clearfix" about="/node/2058" data-quickedit-entity-instance-id="1">...</article>

```

Analysing the markup we can gather that:

1. They both have the same node id
2. The latter can be differentiated by the data-quickedit-entity-instance-id="1" tag
3. Only the 'quick-edit' button appears for the first article
4. On quick-edit click, both of the articles are trying to be manipulated by some form of js - there could be conflict here.

So the question is. How come the quick edit feature does not work for a node that is rendered twice on one page?

Has anyone got any reason why it is not working or can provide a solution for this?

Thanks in advance

# Answer
> 3 votes
According to #15 of this Drupal issue

having a duplicate node on the screen is enough to disable the contextual menu functionality. It's a bug.

---
Tags: 8, nodes, javascript, entities
---


# Question
Title: Is it possible to display Entityform Types using Page Manager and Panels in D7?
Currently, I have a D7 site and my main Content region is displayed using Page Manager and Panels variants. I've created an Entityform Type that allows users to request an appointment, and I'd like this specific entityform type to have a different layout than what the default page.tpl.php provides.

I'd love to provide a default panels layout for all Entityform types, but I can't seem to find a way to do this (even using the Entityform Panels module.) I've come close by using the "Page manager existing pages", but submission pages display in the default page.tpl.php.

Is there a way to do this?

# Answer
What we have done so far, is to reference an Entity-Form in an node type with entityreference. This works so far. The Form will be displayed in the panelized theme and the preview will show up too in the correct context. But!

* The Preview will not show the labels of empty fields
* The submission Page will not show in the correct layout and is still loosing context (even with pm-existing-pages)
* List fields are broken, if core Patch https://www.drupal.org/node/1677598 is applied they don't break the form submit, but are empty in the preview and not saved.
* Date fields with time are somehow broken too. Time is not safed, Date only when using the PopUp Calender

We decided to use the redirect option instead of the submission page to workaround the layout problem with the submission. The Preview is still broken and we are trying to get it fixed.

Conclusion: Entityforms and Panels do not play well together. If we would have know this before we would have built a custom module or used Webform 4.x instead (we are still using webform 3.x in this site but there you don't have the option to use views to manipulate submitted data without loading another bunch of buggy modules!)

Hopfully Drupal 8 and YAML-Forms do a better Job in the future.
> 1 votes

---
Tags: theming, panels, entities
---


# Question
Title: Drupal is not saving any changes made through administrator, Drush works fine
I just began working for a company and am using Drupal for first time. I'm working locally on WAMP. I started by installing and configuring a few modules before making my own and everything worked fine. Then I needed to integrate it into the site. I downloaded the repositories and all dependency modules/themes needed, as well as exported from the server and imported into my machine the database Drupal was running on. That got the correct look/feel/content of the site. However, since then I have been unable to make any changes through the administrative menu/pages. I can't enable/disable modules, make configuration changes, etc. Here's where my troubleshooting starts:

I can enable/disable modules through Drush. I've verified my Drupal settings.php file has the correct database settings for the imported database. I've verified I can log into our dev server and edit things there. I've verified the user priviledges and roles databases transfered correctly. I've used Drush to add the "Superuser" role to myself. I've used Drush to log on as the root user. Since I can't change configuration of a module, I can't enable debugging through Devel.

I've spent hours trying things and searching online, and I'm out of ideas. The closest I've seen someone else post about is this:

Can't save settings after copying site to new server

However, the symptoms aren't a 100% match, as I can log out/in. Any recommendations would be appreciated.

# Answer
Problem is fixed. Late last night I tried investigating why my attempts to enable Mod Rewrite were not working properly, and when I figured out how to enable it natively in WAMP instead of manually in .htaccess, it fixed the issue. Apparently I was having the exact same problem as the linked post, just with slightly different symptoms, and I must have been attempting to enable it wrong so I didn't feel it was the same issue.

For other users in the same situation, you can't enable Mod Rewrite in .htaccess to fix it, you have to enable it through the WAMP server interface. It's under Apache \> Apache modules \> Rewrite\_modules.
> 2 votes

# Answer
Mike Beck answer fixed the issue for me. Try running 'sudo a2enmod rewrite' in your server and then restart the apache with 'sudo service apache2 restart'.
> 2 votes

# Answer
you can try to install drupal again, but with Acquia Dev Desktop ( from my experience, it run drupal faster than WAMP). You can also install Admin Menu ("drush dl admin\_menu","drush en admin\_menu"). And then, when you have everithing, you can go to your phpMyadmin and export the SQL file, then copy the files of the site you are working on to the server you are migrating, modify the settings.php and import the SQL file to your server
> 0 votes

---
Tags: users
---


# Question
Title: How to get the part of URI and pass it to as a argument?
I can access current path using method `\Drupal::request()->getRequestUri();` as shown below.

```
    function bartik_preprocess_node(&$variables) {
        $variables['current_path'] = \Drupal::request()->getRequestUri();
    }

```

Now, this is giving me path, `/drupal8101/user/1` if I am on the user1 profile page. (Complete path of site:`http://localhost:8888/drupal8101/user/1`), which is working right.

So, if I want to put any argument in the twig file, it is fulfilling only for `/drupal8101/user/1`, that is understood.

```
    {% if current_path == '/drupal8101/user/1'%}
       .............
    {% endif %}

```

In above case it is working fine, But what can I do to get that condition worked for all users like `/drupal8101/user/*`.

In short, I want following kind of thing,

```
    {% if current_path == '/drupal8101/user/*'%}
       .............
    {% endif %}

```

# Answer
> 2 votes
Probably what you want to do, is to make some logic for the route name instead of the path.

So the user profile page has the route named `entity.user.canonical` which has the path `/user/{user}`. So if you compare on the route name, you will get all user profile pages. This also makes it very easy to limit your selection so you can do something different for the user edit page etc/

Anyways to get the current route you can do

```
$variables['current_route'] = \Drupal::routeMatch()->getRouteName();

```

`\Drupal::routeMatch()` is a shortcut for the `current_route_match` service.

# Answer
> 1 votes
You could use the twig operator `starts with`:

```
{% if current_path starts with '/drupal8101/user/' %}
  ...
{% endif %}

```

But this will probably catch more pathes than you want to.

Better use a route match in preprocess:

```
$variables['is_user_route'] =
  (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical');

```

And in twig:

```
{% if is_user_route %}
  ...
{* endif %}

```

---
Tags: theming, 8, hooks, uri
---


# Question
Title: How to use CKEditor for basic HTML formatting with webforms automatic emails?
How do I use CKEditor for the 'email template' field when setting an automatically generated email for a webforms submission.

The email template field is found when you go to Content of type 'webform' \> Click the Webform Tab \> Click the sub-tab Emails \> And edit an existing automatic email.

I want to render this textbox as CKEditor and have the email follow through with any bold, underline and heading HTML formatting.

# Answer
> 1 votes
I think the main goal is to receive HTML-formatted emails triggered by Webform module, right? This is how I achieved it:

1. Create and tune a new Text Format, specifically for emails (admin/config/content/formats)
2. Install Mime Mail module. It enables you to send HTML-formatted emails. Make it use the just-created text format in settings.
3. Install Mail System module. It provides you the UI for changing mail system globally or per module, if needed. Simply speaking, with this module you can easily configure HTML mail e.g. for Webform, but leave plain-text format for system emails.
4. You can use HTML tags in Webform \> E-mails \> Edit \> E-mail template textarea. Mails from the website will be HTML-formatted.

Yes, it does not bind CKEditor to E-mail template textarea, but do you really need it? (If yes, I believe it is possible by creating a custom module that overrides the *webform-email-edit-form* form changing the element type from "textarea" to "text\_format", see e.g. this topic).

**Upd**. I have just found a separate module for doing the latter thing: Webform Email Input Filter.

---
Tags: 7, webforms, wysiwyg
---


# Question
Title: Render menu item children without being 'expanded'?
In Drupal 8, how can I render a menu links children without checking 'expanded' on the menu link? I am building a drop down that displays on hover, the links need to render.

My code so far:

```
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    <ul>
    {% for item in items %}
      {% if menu_level == 0 %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}
      {% endif %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

When a parent link has children, they are not rendering unless 'expanded' is checked, which breaks the menu.

# Answer
> 1 votes
I was able to do this by adding a macro for children below the main one in my template.

```
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    <ul>
      {% for item in items %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}
        <li{{ item.attributes.addClass(classes) }}>
          {% if item.url.options.attributes['data-icon'] is defined and item.url.options.attributes['data-icon'] is not empty %}
            <svg class="icon"><use xlink:href="/themes/custom/pncb/build/img/svg-sprite.svg#{{ item.url.options.attributes['data-icon'] }}"></use></svg>
          {% endif %}

          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.submenu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}
        </li>
      {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

{% macro submenu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  <div class="global-top__submenu">
    {% for chunk in items|batch(7) %}
      <ul class="global-top__submenu-col">
        {% for item in chunk %}
          <li{{ item.attributes.addClass(classes) }}>
            {{ link(item.title, item.url) }}
          </li>
        {% endfor %}
      </ul>
    {% endfor %}
  </div>
{% endmacro %}

```

I split this out due to scoping, different markup for sub menu, and I needed to use the batch filter. Works great.

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


# Question
Title: How do I set the HTML5 date "min" attribute?
I have a date field set up on a node in Drupal 8 using the default date time field formatter. I would like the date picker pop-up to start with a specific date I have defined in a config variable.

How can I do this? I have tried the code suggested on How to add select years and months select Drupal 8.1 date picker? but it doesn't do anything for me.

I have also looked for a way to pass datepicker options to the field element (looks like you could do that in Drupal 7 date module), but couldn't find a way to do that either.

# Answer
In Drupal 8, the datetime fields are HTML5 inputs, so the popup is provided by the browser itself, or from a polyfill library for browsers that don't support these inputs (eg, Firefox).

If you want to provide a default value, you can do it from the settings for the field. You can use the **Current Date** or a **Relative Date** as the default. Despite the name and the docs on **Relative Date**, you can use this to set an actual date/time.

If you need to pull the default value from somewhere else (like config), you would `hook_form_alter()` the node form, and then check the field value. If it is empty, you would set the value there.
> 2 votes

# Answer
From mpdonadio's tip above, I actually need to set the min attribute value on the HTML 5 date value. I came across this article, which includes code to remove the seconds from the time element.

Combining those two tips, the following code works to set the min attribute on the date field:

```
/**
 * Implements hook_element_info_alter().
 */
function mymodule_element_info_alter(array &$types) {
    // Alter dateteime fields
  $types['datetime']['#process'][] = 'mymodule_datetime_set_startdate';
}

/**
 * Custom function to alter HTML 5 date fields.
 */
function mymodule_datetime_set_startdate($element) {
  if ($element['#parents'][0] == 'field_my_date_field') {
    // get the start date config value
    $config = \Drupal::config('mymodule.config');
    $start_date = strtotime($config->get('mymodule_start_date'));

    // For browsers using the HTML 5 date pop-up, set the min attribute value
    $element['date']['#attributes']['min'] = format_date($start_date, 'html_date');

  }
  return $element;
}

```

This method works better in my case than a standard form alter because there is another date field in nested paragraphs that are tricky to form alter.

The min value seems to be picked up by the fallback jQuery UI datepicker too - it works in all the browsers I've checked (including IE 11).
> 2 votes

# Answer
In drupal 7 You Can use date moduel(https://www.drupal.org/project/date). This module provide Date Popup Timepicker option for date field.
> 0 votes

---
Tags: 8, datetime
---


# Question
Title: Adding WYSIWYG to webform email template field
I want to enable the WYSIWYG editor so I can create HTML mail from webform email templates. (Yes, I know some people don't like HTML in emails.) I have created a module, and I'm using this code:

```
function mymodulename_form_alter(&$element, &$form_state, $context) {
  if (isset($element['template']['template'])) {
    $element['template']['template']['#wysiwyg'] = true;
    $element['template']['template']['#type'] = 'text_format';
  }
}

```

This is great, and the WYSIWYG is enabled. Unfortunately it changes the values from a string to an array, and I can't figure out how to convert them back again. I was hoping this would help, but `hook_field_attach_presave()` doesn't seem to fire for that form. In fact, I can't find any hooks that fire for that form.

Any suggestions?

# Answer
HTML emails have a different standard than WYSIWYG editors. For example HTML emails use tables instead of divs, you can't use paddings etc.

So I don't think that HMLT email creating with WYSIWYG editor is a good idea...
> 1 votes

# Answer
Thanks for your message. That helped me finding a solution! Here it is.

dd\_fixes is the name of my module.

```
function dd_fixes_form_webform_email_edit_form_alter(&$form, &$form_state, $form_id) {
    $form['template']['template']["#wysiwyg"] = true;
    $form['template']['template']['#type'] = 'text_format';
    $form['template']['template']['#format'] = 'full_html';

    $new = array("dd_fixes_webform_email_edit_form_submit");
    $form["#submit"] = array_merge($new,$form["#submit"]);
}

function dd_fixes_webform_email_edit_form_submit($form, &$form_state) {
    $form_state['values']['template'] = $form_state['values']['template']['value'];
}

```
> 0 votes

# Answer
There is a separate module for that: Webform Email Input Filter.
> 0 votes

---
Tags: webforms, wysiwyg
---


# Question
Title: How to override a twig template for only a specific page?
The title of this user view page contains the name of the user. I want modify it and, thanks to twig debug, I see the template used is `page-title.html.twig`:

```
{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}

```

If I override it, how can I make twig use my overrided template only in the user view page?

# Answer
As you mentioned your main issue is whatever data you are fetching it is overriding the all page-title on the site which you do not want. So to solve that follow following steps,

For common understanding I am referring `bartik` theme. I am showing with example to my local site so it will be very practical to understand.

***In bartik.theme file,***

```
function bartik_preprocess_page_title(&$variables) {
  $variables['staticString'] = 'Explorer ';
  $variables['user_profile_view'] = (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical'); }

```

***in page-title.html.twig file,***

```
{% if title %}
  {% if user_profile_view %}
    <h1{{ title_attributes.addClass('page-header') }}>{{ staticString }}{{ title }}</h1>
  {% else %}
    <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
  {% endif %}
{% endif %}

```

***Output image,*** *On user page,*

>

*On other page(It will not interfere),*

>

So, this way you can Override the page-title of user-profile page and can insert your own defined variable. So, this answer is with static variable, now same way, you have to just replace that variable with your dynamic variable, so it will get change based on your code.

**Note:** In solving this question, I have asked another question here: How to get the part of URI and pass it to as a argument?.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Update button for each line item in cart (drupal 7 commerce)
The update cart button in drupal commerce updates all quantities at once. Since on my site there will be very lengthy lists of line items in the cart, I would like to have an update cart button for each line item (see screenshot, red column). How can that be done?

# Answer
This is pretty simple to explain but building this will probably give you some headaches.

1. create a views handler (for the update button)
2. add the button in the cart view
3. done

Now the tricky part is building the form handler, you should take a look at `commerce_line_item_handler_field_edit_delete` which almost does what you need (only it deletes an item instead of saving it).

Since you only need to update the quantity you need to find out line item id and the new quantity. Load the line item and then update it. You don't need to update the order itself, commerce should handle everything when the order is updated.
> 1 votes

---
Tags: views, commerce
---


# Question
Title: Updated to Drupal 7.51 and website is now stuck in maintenance mode
I just went to update Drupal 7.5 to 7.51 and fortunately the update worked. Unfortunately our site is now locked in maintenance mode and I was logged out of the system and cannot get back in as an admin or anything on the site for that matter.

We tried to do a site rewind to go back to our original settings before the update but still no luck. We also tried using `/user` and also `/?q=user` but this doesn't work either. The site seems to be stuck in some sort of page refresh loop. Does anyone have any suggestions of what else we should try or what we should do?

# Answer
I am compiling here some points which I found. Following list I have ordered them from common to complex solution.

## 1. Clear cache:

First thing you can do is clear the cache. If you read the forum discussion on the Drupal forum page titled: Site stuck in maintenance mode!, you'll find various people solved this issue just by clearing the cache.

* **Through Admin UI:** As per this comment just clear the cache by going at `Administration/configuration/performance`.
* **Using Drush:** If you are using drush, you can do this by command `drush cc all`.
* **Other methods:** If above both methods are not accessible for you, you can try other methods witch are listed in this article: \[Drupal\]Methods to clear Drupal caches

## 2. Login to site:

You can try some methods to login into site while still site in maintenance mode.

## 3. Changing Maintenance Mode setting:

@mixerowsky has very well explained various ways of changing the maintenance mode in his answer at this DA question: How can get my site out of maintenance mode?
> 1 votes

# Answer
One thing worth trying if you can't get on is to go to the database and empty the table for sessions. This should allow you to get back in. Don't delete the table, jsut empty is (delete from sessions in sql)

Also see https://www.drupal.org/node/124562
> 0 votes

---
Tags: 7, users, maintenance-mode
---


# Question
Title: Drupal TableSelect in form, Header sorting error after Ajax update table call
I am new to drupal and currently using Drupal 8.1.8, so forgive me if the question is not in the correct format.

I have a database table with vehicles and their details which is presented to the user as sortable Tableselect table in a “vehicle update” form. When the user selects (select/update) a row in the table an Ajax call (ajaxUpdateCall) updates the relevant fields to allow the user to edit and re-submit the values.

The user can reduce the number of results in the table by entering a search phrase (search/filter) that is then used in a LIKE query, after pressing the “Search” or “Reset Search” buttons a Ajax (search\_ajax\_callback) call is run to update the table.

If the table is not or has not been filtered (search/filter), then the (select/update) and sorting table by the HEADER links works fine (header/sort).

The problem occurs when the table is filtered and updated with Ajax(search/filter), if I now try to sort the table (header/sort) I get an error, but (select/update) still works. The error is presented on a blank and is as follows.

```
[{"command":"add_css","data":"\u003Clink rel=\u0022stylesheet\u0022 href=\u0022\/sites\/fleetmanagement.dd\/files\/css\/css_eWmbbi3frMJPauCYHygIVEjcDmNqivacE1SJjDW017s.css?od92zv\u0022 media=\u0022all\u0022 \/\u003E\n\u003Clink rel=\u0022stylesheet\u0022 href=\u0022\/core\/themes\/bartik\/css\/components\/messages.css?od92zv\u0022 media=\u0022all\u0022 \/\u003E\n"},{"command":"insert","method":"replaceWith","selector":null,"data":"\n      \n    \u003Cdiv class=\u0022messages__wrapper layout-container\u0022\u003E\n          \u003Cdiv role=\u0022contentinfo\u0022 aria-label=\u0022Error message\u0022 class=\u0022messages messages--error\u0022\u003E\n          \u003Cdiv role=\u0022alert\u0022\u003E\n                  \u003Ch2 class=\u0022visually-hidden\u0022\u003EError message\u003C\/h2\u003E\n                    An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (128 MB) that this server supports.\n                \u003C\/div\u003E\n      \u003C\/div\u003E\n    \n    \u003C\/div\u003E\n  ","settings":null}]

```

This error seems to be related to https://www.drupal.org/node/2686005 where the table header links are “broken” after ajax. One of the suggestions was to diable the Devel Web Profiler, but this did not solve my problem.

Before (search/filter) the header links are **http:// fleetmanagement.dd:8083/manage\_vehicle/update?sort=desc&order=Reg%20Number** and the $\_GET variable contains the following:

```
$_GET = array(
    sort => "asc"
    order => "Reg Number");

```

After (search/filter) the header links are **http:// fleetmanagement.dd:8083/manage\_vehicle/update?ajax\_form=1&\_wrapper\_format=drupal\_ajax&sort=asc&order=Reg%20Number** and the $\_GET variable contains:

```
$_GET = array(
    ajax_form => "1"
    _wrapper_format => "drupal_ajax"
    sort => "asc"
    order => "Reg Number");

```

You can see that after search\_ajax\_callback, **“ajax\_form=1&\_wrapper\_format=drupal\_ajax&”** has been added to the header links and I don’t know how to edit it after the fact since I think this is the problem.

I attempted to edit $\_GET to influence the creation of the header links, but this was unsuccessful.

My question is, how do you I fix my code to allow for (header/sort) after (search/filter) Ajax has been run? Or is this a core problem and I should just disable (header/sort) altogether?

Here is most of my code, starting with the form.

```
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\manage_vehicle\manage_vehicle_storage;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\AjaxResponse;

class vehicle_updateform extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {

    $database = Database::getConnection();
    $query = $database->select('a_vehicle', 'rv')
        ->extend('Drupal\Core\Database\Query\TableSortExtender')
        ->extend('Drupal\Core\Database\Query\PagerSelectExtender')//->limit(1)
        ->fields('rv', ['vehicle_id', 'registration_number', 'make', 'model', 'vin_number', 'model_year', 'start_year', 'mileage', 'capacity', 'status', 'next_service_date', 'deleted']);
    $query->condition('rv.deleted','no', '=');

    // Attempt to change the $_GET values so that when table HEADER links are generated
    // after AJAX Filter table call, the link does not contain "ajax_form=1&_wrapper_format=drupal_ajax&"
    // Did not work.
    if (!empty($_GET['sort'])) {
        $sort = $_GET['sort'];
        $order = $_GET['order'];
        unset($_GET);
        $_GET['sort'] = $sort;
        $_GET['order'] = $order;
    }

    $UserInput = $form_state->getUserInput();
    if($UserInput['_triggering_element_value'] == 'Search') {
        $search_phrase = $UserInput['search']['search_phrase'];

    }else if($UserInput['_triggering_element_value'] == 'Reset Search'){ // triggering_element is the Reset Search BUTTON -> SHOW ALL
        $UserInput['search']['search_phrase'] = "";
        $form_state->setUserInput($UserInput);
        $search_phrase = "";
    }else{
        $search_phrase = $UserInput['search']['search_phrase'];
    }

    $DB_OR = $query->orConditionGroup()
        ->condition('registration_number', '%' . $database->escapeLike($search_phrase) . '%', 'LIKE')
        ->condition('status', '%' . $database->escapeLike($search_phrase) . '%', 'LIKE')
        ->condition('make', '%' . $database->escapeLike($search_phrase) . '%', 'LIKE')
        ->condition('model', '%' . $database->escapeLike($search_phrase) . '%', 'LIKE');
    $query->condition($DB_OR);

    $header = array(
      'vehicle_id' =>          array('data' => t('Vid'), 'field' => 'rv.vehicle_id'),
      'registration_number' => array('data' => t('Reg Number'), 'field' => 'rv.registration_number'),
      'make' =>                array('data' => t('Make'),       'field' => 'rv.make'),
      'vin_number' =>                          t('Vin Number'),
      'capacity' =>            array('data' => t('Capacity'),   'field' => 'rv.capacity'),
      'status' =>              array('data' => t('Status'),     'field' => 'rv.status',)// 'sort' => 'desc')
    );

    $result = $query
        ->orderByHeader($header)
        ->execute()
        ->fetchAll();

    $options = array();
    // This ensures that the pager uses the correct options after ajaxUpdateCall
    if (empty($form_state->getCompleteForm())) {
        // Populate Table
        foreach ($result as $row) {
            $options[$row->vehicle_id] = array(
                'vehicle_id' => $row->vehicle_id,
                'registration_number' => $row->registration_number,
                'make' => $row->make,
                'vin_number' => $row->vin_number,
                'capacity' => $row->capacity,
                'status' => $row->status,
            );
            $keyed_entries[$row->vehicle_id] = $row;
        }
    }else{
        $options = $form_state->getCompleteForm();
        $options = $options['filter']['table']['results']['#options'];
    }

    $selected = $UserInput['filter']['table']['results']; // Vehicle_ID

    if (!empty($selected)){
        $selected = array('vehicle_id' => $selected);
        $lastResult = manage_vehicle_storage::load($selected); // expect only one value to be returned
        $default_entry = $lastResult[0];
    }
    $form_state->setCached(FALSE);

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

    $form['search'] = array(
        '#type' => 'fieldset',
        '#title' => $this->t('Search'),
    );
    $form['search']['search_phrase'] = array(
        '#type' => 'textfield',
        '#title' => $this->t("Search for a vehicle"),
        '#size' => 8,
        '#default_value' => "",
        '#prefix' => '<div id="search_phrase-div">',
        '#suffix' => '</div>',
    );

    $form['search']['actions']['search_button'] = array(
        '#type' => 'button',
        '#value' => t('Search'),
        '#ajax' => array(
            'callback' => '::search_ajax_callback',
            'wrapper' => 'table-div',
            'method' => 'replace',
        )
    );
    $form['search']['actions']['clear_button'] = array(
        '#type' => 'button',
        '#value' => t('Reset Search'),
        '#ajax' => array(
            'callback' => '::search_ajax_callback',
            'wrapper' => 'table-div',
            'method' => 'replace',
        )
    );

    $form['filter'] = array(
        '#type' => 'fieldset',
        '#title' => $this->t('Available Vehicles'),
    );
    $form['filter']['table']['results'] = array(
        '#theme' => 'table',
        //'#theme' => 'pager',
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $options,
        '#multiple' => FALSE, // Radios
        '#prefix' => '<div id="table-div">',
        '#suffix' => '</div>',
        '#empty' => t('No content available.'),
        '#submit' => array(':updateCallback:'),
        '#ajax' => array(
            'callback' => '::ajaxUpdateCall',
        ),
    );
    $form['filter']['table']['pager'] = [
        '#type' => 'pager',
        '#result' => $result,
    ];

    $form['edit'] = array(
        '#type' => 'fieldset',
        '#title' => $this->t('Selected Vehicle'),
        '#prefix' => '<div id="edit-box-div">',
        '#suffix' => '</div>',
    );
    $form['edit']['edit_registration_number'] = array(
        '#type' => 'textfield',
        '#title' => t('registration_number'),
        '#size' => 9,
        '#maxlength' => 8,
        '#attributes' => array(
            'placeholder' => 'abc123EC',
        ),
        '#default_value' => isset($default_entry) ? $default_entry->registration_number : "",
    );
    /* The rest of the text/number/date fields that follow
    *  are the same as edit_registration_number so I left them out
    *  i.e. edit_make, edit_model, edit_vin_number, edit_mileage.....
    */

    $form['actions']['submit']= array(
        '#type' => 'submit',
        '#value' => $this->t('Submit Update'),
        '#button_type' => 'primary',
    );
    return $form;
}

```

Following is the Ajax callback that updates the form fields after a row in the table has been selected.

```
/**
 * AJAX callback handler for the vehicle_id select.
 * When a row in the table is selected, this function
 * then updates the related text fields so that they can be edited.
 */
public function ajaxUpdateCall(array $form, FormStateInterface &$form_state){ //

    //$selected = $_POST['filter']['table']['results']; // Row ID
    $UserInput = $form_state->getUserInput();
    $selected = $UserInput['filter']['table']['results']; // Row ID

    if (!empty($selected)){
        $rows = array('vehicle_id' => $selected);
        $lastResult = manage_vehicle_storage::load($rows);
        $row = $lastResult[0];

        $form['edit']['edit_registration_number']['#value'] = $row->registration_number;
        $form['edit']['edit_make']['#value'] = $row->make;
        $form['edit']['edit_model']['#value'] = $row->model;
        $form['edit']['edit_vin_number']['#value'] = $row->vin_number;
        $form['edit']['edit_mileage']['#value'] = $row->mileage;
        $form['edit']['edit_capacity']['#value'] = $row->capacity;
        $form['edit']['edit_status']['#value'] = $row->status;
        $form['edit']['edit_model_year']['#value'] = $row->model_year;
        $form['edit']['edit_start_year']['#value'] = $row->start_year;
        $form['edit']['edit_next_service_date']['#value'] = $row->next_service_date;
    }
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#edit-box-div', ($form['edit'])));

    return $response;
}

```

The last code is for the Ajax callback that updates the table based on a search phrase to limit the dispayed table options. Here is one of the places I tried to edit the $\_GET variable.

```
/**
 * AJAX callback handler for Search phrase filtering.
 * When search phrase is entered and Search button clicked,
 * the table updates showing only relavant values.
 */
public function search_ajax_callback(array $form, FormStateInterface &$form_state){
    $form = $form_state->getCompleteForm();
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#table-div', ($form['filter']['table']['results'])));

    $UserInput = $form_state->getUserInput();
    $trigger = $UserInput['_triggering_element_value'];// == 'Reset Search'

    // If Reset button was clicked, then display all rows from database
    // and clear search phrase textfield.
    if($trigger == 'Reset Search'){
        $form['search']['search_phrase']['#value'] = "";
        $response->addCommand(new ReplaceCommand('#search_phrase-div', ($form['search']['search_phrase'])));
    }

    // Attempt to change the $_GET values so that when table HEADER links are generated
    // after AJAX Filter table call, the link does not contain "ajax_form=1&_wrapper_format=drupal_ajax&"
    // Did not work.
    if (!empty($_GET['sort'])) {
        $sort = $_GET['sort'];
        $order = $_GET['order'];
        unset($_GET);
        $_GET['sort'] = $sort;
        $_GET['order'] = $order;
    }
    return $response;
}

```

Thanks in advance for your help!!

# Answer
> 1 votes
The error is caused by the url part string &ajax\_form=1&\_wrapper\_format=drupal\_ajax, which is inserted into the url by the core ajax library (ajax.js).So modifying the \_GET variable will not solve the problem, but we can add a few line of custom JS code to remove that part from the url. You can add a css class "ajax-container" to your table and then use this example JS code to do the job

```
 $(".ajaxfix-container a").each(function(){
    var $this = $(this);
    var newurl =   this.href.replace("&ajax_form=1&_wrapper_format=drupal_ajax",'');
    $this.attr('href',newurl);
 });

```

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


# Question
Title: How can I download a results set with a form built in Entity forms?
We've tried entity forms for a project and the client wants that collected data in a spreadsheet. (This was never a mentioned spec before the project.)

Is this possible? Is there a way to download entity form submissions to a CSV or spreadsheet?

# Answer
You can use Views Data Export: For downloading submissions, Entityform support that by default.
> 3 votes

# Answer
When enabling Views data export and Views Bulk Operations (VBO) modules, the export of all submission should be visible in form of feed icons on the submission list (as per `entityform.views_default.inc` file).

Although if you'd like to implement selective submission export, you need to modify the `entityforms` view, for example:

```
/**
 * Implements hook_views_default_views_alter().
 */
function MYMODULE_views_default_views_alter(&$views) {
  if (module_exists('entityform') && module_exists('views_bulk_operations')) {
    /* Display: Master */
    $handler =& $views['entityforms']->display['default']->handler;
    $handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '1';
    $handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
    $handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
    $handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
    $handler->display->display_options['fields']['views_bulk_operations']['vbo_operations']['action::views_bulk_operations_argument_selector_action']
      = array(
        'selected' => 1,
        'skip_confirmation' => 1,
        'override_label' => 1,
        'label' => 'Export to CSV',
        'settings' => array(
          'url' => 'entityform-submissions/downloads/[current-page:arg:4]/csv',
        ),
      );

    /* Display: CSV Data export */
    $handler =& $views['entityforms']->display['autofields_csv']->handler;
    /* Contextual filter: Entityform Submission: Entityform submission ID */
    $handler->display->display_options['arguments']['entityform_id']['id'] = 'entityform_id';
    $handler->display->display_options['arguments']['entityform_id']['table'] = 'entityform';
    $handler->display->display_options['arguments']['entityform_id']['field'] = 'entityform_id';
    $handler->display->display_options['arguments']['entityform_id']['default_argument_type'] = 'fixed';
    $handler->display->display_options['arguments']['entityform_id']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['entityform_id']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['entityform_id']['summary_options']['items_per_page'] = '25';
    $handler->display->display_options['arguments']['entityform_id']['break_phrase'] = TRUE;
    $handler->display->display_options['path'] = 'entityform-submissions/downloads/%/csv/%';
    // $handler->display->display_options['displays'] = array(); // Removes feed icon.

    /* Display: XML Data export */
    $handler =& $views['entityforms']->display['autofields_xml']->handler;
    // $handler->display->display_options['displays'] = array(); // Removes feed icon.
  }
}

```

Place above code in your custom module, e.g. in `views/MYMODULE.views.inc`. Then you need these extra hooks in your `.module` file (to invoke your view changes and make support for tokens for your VBO URL):

```
/**
 * Implements hook_views_api().
 */
function MYMODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/views',
  );
}

/**
 * Implements hook_drupal_goto_alter().
 */
function MYMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  if (module_exists('token') && user_access('administer nodes') && strpos($path, '[') !== FALSE) {
    // Required for entityform export pages.
    // E.g. /admin/structure/entityform_types/manage/%/submissions.
    $path = token_replace($path);
  }
}

```
> 0 votes

---
Tags: 7, entities, importing-exporting
---