# Question
Title: How to upload files using the Feeds module?
I created a custom content type and I want to upload an XML file using the Feeds module. Can somebody explain how to do the mapping correctly? Should I add a new importer or use a node importer?

I want to perform the upload using an XML file. I have unicode characters in my file.

I am not able to convert it to a CSV file. I have tried converting using Open Office but it is not working.

I find using feeds a bit complicated.

Are there other solutions to upload files into database?

Note: When I try to upload to says no new nodes created.

# Answer
You need to use Feeds XPath Parser module.

You may need this module if you would like to:

> * Import XML or HTML documents into nodes, users, taxonomy terms, or regular database tables.
> * Scrape webpages like regular feed sources with scheduling, updating, and expiring.
> * Extract content from HTML documents to create a semantic data bank or mashup.

Below links will help you to set up.
> 1 votes

# Answer
Using the Forena integration with the Feeds module it is possible to import ***data blocks***.

***Data blocks*** are files that are located in a database repository, which is a (secured) directory on the web server that contains all data block files related to a specific data source. The actual format of these files is dependent on which data provider or driver is being used for the data source:

* the most common format for these files is SQL, used for all supported data engines (Drupal, Oracle, PDO other than Drupal, Postgres or MSSQL), except for FrxFiles (XML Files).
* an alternative format for these files is XML.

For an illustration of how it is like to use Forena in combination with Feeds, have a look at the video about How to import data and reports based on data as Drupal nodes.

Disclosure: I'm a co-maintainer of the module.
> 1 votes

# Answer
I am able to create new node by creating a csv file using google spreadsheets instead of a xml file.I created a new feed importer and mapped the elements of feed to the appropriate fields.
> -1 votes

---
Tags: nodes, feeds
---


title: Commerce Rules OR Condition

text:
# Question
Title: Commerce Rules OR Condition
I am trying to set up a simple OR condition.

If these "blocks" (red) are TRUE or these "blocks" (green) are TRUE execute the rule.

So I've tried added a OR block in various ways, but it does not succeed.

Basically what I want to achieve is that, if red block is NOT EMPTY or green block has value YES, the rule should execute.

# Answer
This thread helped me understand the logic.

https://www.drupal.org/node/1784196

Basically what tobiasb said:

> OR (All conditions below this or between the lines are OR-Conditions) \- condition1 (OR) \- AND (All conditions below this or between the lines are AND-Conditions, default condition) -- condition2 (AND) -- condition3
>
> This means:
>
> condition1 OR (condition2 AND condition3)
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: How can I set the date format to a custom one?
The default date format used by Drupal 8 is *d.m.Y*. I want to change it to *d-M-Y*.

I tried the following code, but it doesn't change the date format.

```
$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start date'),
  '#format' => 'd-m-Y',
];

```

Even when I replaced `#format` with `#date_format`, the date was still using the default format.

What is the correct property to use for the date format, if `#format` and `#date_format` aren't recognized?

# Answer
In Drupal 8, the properties for the date format and the time format are two different and separated properties: `#date_date_format` sets the date format, while `#date_time_format` sets the time format, as in the following code.

```
$date_format = 'Y-m-d';
$time_format = 'H:i';

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start date'),
  '#date_date_format' => $date_format,
  '#date_time_format' => $time_format,
];

```

Unfortunately, when HTML5 form elements are used for a *datetime* form element, the date and time formats must be one of the HTML5 formats. This is described in the documentation for `Datetime::processDatetime()`, which contains the following text.

> **#date\_date\_format**: A date format string that describes the format that should be displayed to the end user for the date. When using HTML5 elements the format MUST use the appropriate HTML5 format for that element, no other format will work. See the `DateFormatterInterface::format()` function for a list of the possible formats and HTML5 standards for the HTML5 requirements. Defaults to the right HTML5 format for the chosen element if a HTML5 element is used, otherwise defaults to `DateFormat::load('html_date')->getPattern()`.

> **#date\_time\_format**: A date format string that describes the format that should be displayed to the end user for the time. When using HTML5 elements the format MUST use the appropriate HTML5 format for that element, no other format will work. See the `DateFormatterInterface::format()` function for a list of the possible formats and HTML5 standards for the HTML5 requirements. Defaults to the right HTML5 format for the chosen element if a HTML5 element is used, otherwise defaults to `DateFormat::load('html_time')->getPattern()`.

As Christian pointed out in his comment, there is an issue that (as of today, December 3, 2021) is currently open: Datetime element formats are confusing.
> 14 votes

---
Tags: forms, 8, datetime
---


# Question
Title: Attach webform on each node of specified content type
I am currently working on real-assets project in which user can add property using property-listing content type for listing and searching property on portal.

if any visitor is interested in any property than he/she can directly fill the form, which will be present in full view of property node and send it to admin and also admin will get to know for which property visitor fill the form same like as comment for node.

# Answer
I had the same question and found answer in drupal community, that was using of Webform Default Fields module.

Here are a brief description about this module :

> Description
>
> With this module you can easily create a lot of nodes with same webform fields. It can be applicable in case of job vacancies with reply form, kind of quality feedback control or whatever your mind suggests you.
>
> Because you can create more than one webform-enabled content types, you respectively can attach different default fields for each of them.
> 2 votes

# Answer
you can create a webform and add it with Context under all nodes of certain content-type. This is the easiest way to configure this.
> 1 votes

# Answer
Webform allows you to enable the webform components for any content type. Choose the types on which you would like to associate webform components.

You can configure it like the following.

1. Go to Home » Administration » Configuration » Content authoring (/admin/config/content/webform)
2. Select the content types which you want to add the Webform

Here in the following screenshot, I've enabled webform for Basic content type.

So this way, you add webform to content type nodes.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Add inline JavaScript to end of page dynamically
Use case:

I have a custom block:

```
/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "my",
 *   admin_label = @Translation("My Block"),
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $build = array(
      '#markup' => 'SOME WEIRD ADS HTML HERE'
    );

    SOME_COOL_STUFF_TO_ADD_INLINE_JAVASCRIPT_TO_THE_CLOSING_BODY_TAG

    return $build;
  }
}

```

Is there a way to add inline javascript to the end of the page just when this block is rendered anywhere (in theme or panel page)?

# Answer
> 3 votes
You just use the following code.

```
$build = [
  '#markup' => 'SOME WEIRD ADS HTML HERE',
  '#attached' => [
    'library' => ['mymodule/mylibrary'],
  ],
];

```

Follow Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module to learn how to define a library for Drupal 8, and keep in mind that, by default, JavaScript files are added to the footer, as explained in `LibraryDiscoveryParser::parseLibraryInfo()`.

> By default, JavaScript files are included in the footer.

Also, `#markup` is filtered out, as explained in Render API overview.

> **#markup**: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through `\Drupal\Component\Utility\Xss::filterAdmin()`, which **strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors**. (For example, `<script>` and `<style>` are not allowed.) See `\Drupal\Component\Utility\Xss::$adminTags` for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed\_tags to alter which tags are filtered.

---
Tags: 8, javascript
---


# Question
Title: Hiding regions for a node page without creating a unique twig file for that node?
In Drupal 7 I could hide regions as reactions to certain conditions with Context; Here is a pseudocode to explain what I actually did with this module:

> If $node = 1;
>
> Than programmatically hide $region = sidebar;

In Drupal 8 for some reason, at least in this era, this functionality has been removed from the module. You can no longer hide regions as a reaction to whatever condition.

Hiding regions is still possible with CSS but it should be noted that programmatically hiding regions is better than CSS hiding as it is more swift and sound, as well as more elegant.

## What I've tried instead:

Given the fact **Context 8** doesn't include that functionality, I tried to use CSS to hide the region in the given node; I knew from Drupal 7 that if you are inside an node and go to the DOM tree, you can see a unique node class that will serve you in such a particular CSS action (hiding a region in a particular node).

In my Drupal 8 site I went to the DOM but didn't quite find such a class (as appears in Drupal 7 sites).

Therefore I tried using what worked for me in Drupal 7 wondering if from any case it just no longer appear in the DOM. I went to my CSS file and added:

```
.page-node-364 .region-sidebar-first {display: none !important}

```

It didn't work, nor similar tryings such as:

```
#node-364 .region-sidebar-first {display: none !important}
.node-364 .region-sidebar-first {display: none !important}
.364 .region-sidebar-first {display: none !important}

```

And so forth...

Other actions on that node class variations (neglecting region-sidebar-first) also didn't work even with !important declarations on the CSS and what I tried seemed just to be invalid.

* I flushed all caches after each try.

## Why I'm confused:

What I did saw at DOM and used as a class didn't cause any effect (.364 as mentioned above):

---

## My question:

Due that Context isn't the solution this time, and that seemingly, no usable id or class appears in DOM, I thus ask professional themers here if it is even possible to hide regions for a node in Drupal 8, solely through the CSS, without creating a unique twig file to that particular node.

# Answer
4k4 suggestion to use the **preprocess\_page** Drupal-function can be done like this:

Preprocess functions go in your themes themeName.theme file, you may need to create this file if your theme does not have one - be sure to clear the Drupal cache after adding or changing code in this file.

```
function theme-name_preprocess_page(&$variables) {
  // Set the node ID if we're on a node page.
  $nid = isset($variables['node']) ? $variables['node']->id() : '';

  // Unset a region for one node ID.
  if ($nid == '7') {
    unset($variables['page']['sidebar_second']);
  }

  // Unset a region for multiple node ID's.
  if (in_array($nid, ['1','2','3'])) {
    unset($variables['page']['sidebar_first']);
  }
}

```

If you would rather use CSS (not a bad technique at all), you can add path classes to body also from theme-name.theme, but this time via the **preprocess\_html** function:

```
use Drupal\Component\Utility\Html;

function theme-name_preprocess_html(&$variables) {
  // Add path classes to body.
  $path = \Drupal::request()->getPathInfo();
  $path_args = explode('/', $path);
  if (count($path_args) >= 3) {
    $variables['attributes']['class'][] = 'path-' . Html::cleanCssIdentifier(ltrim($path, '/'));
  }
}

```
> 5 votes

# Answer
Go to your theme's folder and in your **themename.theme** file:

```
function themename_preprocess_page(&$variables) {
  $variables['nid'] = str_replace('/node/', ' ', \Drupal::service('path.current')->getPath());
}

```

Then in templates folder edit **page.html.twig** (if you don't have one, copy the one from core `/core/themes/bartik/templates` and copy it to your theme's templates folder).

Find `{{ page.sidebar_first }}` and change it to:

`{% if nid not in [364, 367] %}{{ page.sidebar_first }}{% endif %}`

clear/flush cache to see changes.
> 1 votes

# Answer
Here are some ways to do this:

**The first way: Reuse class visually-hidden**

```
<?php
use Drupal\node\NodeInterface;
function YourTheme_preprocess_region(&$vars) {
  if ($vars['region'] == 'sidebar_first') {
    if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
      $nid = $node->id();
      if (in_array($nid, ['1', '2'])) {
        $vars['attributes']['class'][] = 'visually-hidden';
      }
    }
  }
}

```

this way very simple. You just need use function hook\_preprocess, don't need add css, don't need override twig template. But I don't like this way because region is hidden. But server need process to render this region.

**The second way: unset region before render.**

```
<?php
function YourTheme_preprocess_page(&$vars) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
    $nid = $node->id();
    if (in_array($nid, ['1', '2'])) {
      unset($vars['page']['sidebar_second']);
    }
  }
}

```

In this case. You may be need override twig template, but better for performance.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Send email with html template programmatically
**On board:**

* Drupal 7
* Mail System
* Mime Mail

`mimemail-message.tpl.php` is configurated

E-mails sends by Rules with HTML template, but template not used when it call programmatically:

```
$mail = array(
  'subject' => 'Test e-mail',
  'message' => '
    <p>Lorem <a href="http://google.com">ipsum dolor sit amet</a>, consectetuer <b>adipiscing</b> elit, sed <i>diam</i> nonummy <s>nibh</s> euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
  ',
);
drupal_mail('system', 'mail', 'to@example.com', language_default(), array('context' => $mail));

```

# Answer
In the `mimemail-message.tpl.php` info you can read

> Copy this file in your default theme folder to create a custom themed mail. Rename it to mimemail-message--\[module\]--\[key\].tpl.php to override it for a specific mail.

Try to change your tpl name from `mimemail-message.tpl.php` to `mimemail-message--system.tpl.php`
> 1 votes

---
Tags: 7, emails
---


# Question
Title: How do I create a custom search and filter?
I have created a custom module to render forms on the front end (modules\custom\_mod\src\Form\Contact\ContactUserForm.php) and stored the form values to a custom table.

I have also created a listing (admin end) of the stored data from table which I acheived with the help of controller (modules\custom\_mod\src\Controller\Contact\ContactController.php).

In that listing, I have the *Edit* and *Delete* actions based on the ID from the table.

The file structure is below.

```
modules/custom_mod/
├── js
├── css
├── custom_mod.routing.yml
├── custom_mod.info.yml
├── custom_mod.module
├── custom_mod.libraries.yml
└── src
    ├── Form
        └── Contact
            └── ContactUserForm.php
            └── ContactUserStorage.php
            └── ContactAdminForm.php
            └── ContactAdminEdit.php
    ├── Controller
        └── Contact
            └── ContactController.php

```

Now I need a search box, a *From date* and *To date* filter, with an *Export (CSV)* button above the listing, so that the administrator user can filter or search accordingly.

How can I achieve this?

# Answer
> 1 votes
I created a very easy month/year filter select box. For that I created a new form class which extends the FormBase class of Drupal 8.

To add filter and search inputs I added following values to the returning array:

```
namespace Drupal\my_sandbox\Controllers;

use Drupal\Core\Controller\ControllerBase;

class TestController extends ControllerBase
{

public function test()
{

    $form = [];

    //add you custom code here...

    $form['form'] = [
        '#type'  => 'form',
    ];

    $form['form']['filters'] = [
        '#type'  => 'fieldset',
        '#title' => $this->t('Filter'),
        '#open'  => true,
    ];

    $form['form']['filters']['text'] = [
        '#title'         => 'text',
        '#type'          => 'search'
    ];

    $form['form']['filters']['year'] = [
        '#title'         => 'Year',
        '#type'          => 'select',
        '#empty_value'   => 'none',
        '#empty_option'  => '- None -',
        '#size'          => 0,
        '#options'       => ['value1' => 'label1', 'value2' => 'label2'],
        '#default_value' => 'none'
    ];

    $form['form']['filters']['actions'] = [
        '#type'       => 'actions'
    ];

    $form['form']['filters']['actions']['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Filter')
    ];

    //place the table in the form
    $form['table'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => array(
        'id' => 'bd-contact-table',
      )
    );

    return $form;

}

}

```

The array for the key 'filters' is the container in which all the filter will be placed. I choose the type 'fieldset', you can change the type of container to any element you want.

Afterwards I added the search and filter input and at the end the button to submit the filter-form. If you use the a class that extends the FormBase class the form will be send the the submitForm method of your class.

A thing here to notice is that every "#type" key maps to Drupal element. All elements are located in the DRUPALCORE/lib/Drupal/Core/Render/Element folder. Example: The #type search will map to the file Search.php within the Element folder. Every file includes a comment where all options of the element are explained.

I hope I could help you.

Nicolas

---
Tags: 8, search
---


# Question
Title: Server Error 500 when changing pager of Views to display all items
I have a View with 1,000 potential items. When it is paged, it works perfectly, both with Ajax paging or normal paging. But when I try to switch off the display type, the server throws a Server Error 500. No log in the watchdog table of the database or any other registry. I guess that there must be some problem with memory or something, but I would expect a PHP memory allocation error or something. It is not practical to show the 1,000 items at a time for the first time, but if I would want to change to some Page scroll pager like jScroll, I am worried that this is not entirely possible in Drupal.

# Answer
> 1 votes
Answering your last statement displaying multiple nodes at once is totally possible in Drupal. (Bear in mind though the power of hosting and caching is something to consider.) Unfortunately, the 500 error isn't helping a lot; a good approach is checking the error logs for any indications there.

If you are suspecting a PHP memory allocation error, try increasing the memory\_limit variable in php.ini to a higher value. This link might be helpful.

Displaying thousands of nodes at once needs caching, so your site can be nice and quick. First, enable the caching in the advanced section of your View UI. Also consider using modules like memcache and boost.

As I said, first check what this 500 error you are getting is, because maybe it has nothing to do with the amount of nodes you are displaying.

---
Tags: 7, paging
---


# Question
Title: Check if a node exist where field_a = Sessionvalue && field_b=arg1
Hello I need a an if else statment to check if a node with 2 given field values exist.(1 value from a Session and 1 from an Url argument)

I dont need to load the node I only want to check if it exist.

thanks for your help.

# Answer
> 0 votes
If you want to get value from entity without loading the entity object. You can use EntityFieldQuery

**Example:**

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_id', 1)
      ->fieldCondition('field_custom_field', 'value', '', '!=')
      ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (!empty($result['node'])) {
  // field value exists!.
}

```

---
Tags: nodes
---


# Question
Title: How to get list of module folders which can be deleted safely?
I've uninstalled a lot of unnecessary modules recently through `admin/modules/uninstall`.
Now I want to understand what folders of the modules can be deleted from `sites/all/modules`.

I've tried `drush pmi`, but there is too much information.

How can I get list of folders which can be deleted safely now? Any drush command may be?

# Answer
This works on Linux Machines. But you can do something similar on windows also I think.

Use the following command to get a list of disabled or uninstalled modules.

```
    drush pml --type=Module --status="disabled,not installed" --no-core
--pipe | paste -s -d,

```

You will get a comma separated list like this

```
    admin_toolbar,admin_toolbar_tools,features,features_ui,entity_browser,
entity_browser_example,config_update,content_types_full_export

```

If you want to remove only the uninstalled module you can remove disabled from status option in the first query.

Once you have the comma separated list of un-installed modules you can pass it on to the drush pmi query like this.

```
drush pmi --format=csv --fields=path
admin_toolbar,admin_toolbar_tools,features,features_ui,entity_browser,
entity_browser_example,config_update,content_types_full_export

```

You will get the ouput as

```
modules/admin_toolbar
modules/admin_toolbar/admin_toolbar_tools
modules/features
modules/features/modules/features_ui
modules/entity_browser
modules/entity_browser/modules/example
modules/config_update
modules/features_modules/content_types_full_export

```

You can use this to safely delete the folders :)
> 4 votes

# Answer
Use this:

```
drush pmi --fields=type,project,title,status,path --format=table|sort

```

This gives you a module list with five columns:

* First is the type of project: module or theme.
* Second one is the module project, for exampe views, logintoboggan, admin\_menu, etc.
* The third one is the installation status: enabled (in use), disabled (not in use but install info in DB) and not installed (it hasn't been installed yet or it have been already uninstalled).
* Fourth column is module name. A module downloaded from drupal.org can have several modules inside (the downloaded module is the project and the inside modules are the real modules).
* The fifth column is the path to the module.

With this information you can safely remove every project (second column) that all of its modules are in 'not installed' state.

For example, see this fragment list:

```
module  job_scheduler  Job Scheduler                enabled        sites/all/modules/contrib/job_scheduler
module  job_scheduler  Job Scheduler Trigger        not installed  sites/all/modules/contrib/job_scheduler/modules/job_scheduler_trigger
module  jquery_update  jQuery Update                enabled        sites/all/modules/contrib/jquery_update
module  l10n_client    Localization client          enabled        sites/all/modules/contrib/l10n_client
module  l10n_update    Localization update          enabled        sites/all/modules/contrib/l10n_update
module  languageicons  Language Icons               enabled        sites/all/modules/contrib/languageicons
module  ldap           LDAP Authentication          not installed  sites/all/modules/contrib/ldap/ldap_authentication
module  ldap           LDAP Authorization - Roles   not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_drupal_role
module  ldap           LDAP Authorization           not installed  sites/all/modules/contrib/ldap/ldap_authorization
module  ldap           LDAP Authorization - OG      not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_og
module  ldap           LDAP Feeds                   not installed  sites/all/modules/contrib/ldap/ldap_feeds
module  ldap           LDAP Help                    not installed  sites/all/modules/contrib/ldap/ldap_help
module  ldap           LDAP Query                   not installed  sites/all/modules/contrib/ldap/ldap_query
module  ldap           LDAP Servers                 not installed  sites/all/modules/contrib/ldap/ldap_servers
module  ldap           LDAP SSO                     not installed  sites/all/modules/contrib/ldap/ldap_sso
module  ldap           LDAP Test Module             not installed  sites/all/modules/contrib/ldap/ldap_test
module  ldap           LDAP User Module             not installed  sites/all/modules/contrib/ldap/ldap_user
module  ldap           LDAP Views                   not installed  sites/all/modules/contrib/ldap/ldap_views
module  libraries      Libraries                    enabled        sites/all/modules/contrib/libraries

```

You can safely remove the ldap module because all modules are not installed but not job scheduler because one of its modules is enabled.
> 8 votes

# Answer
I have two suggestions for you on how to filter that drush command. One is with pipes and grep. The other is with the option arguments.

First off I think you want drush pml (lowercase "L", not lowercase "I").

**(1) Pipes and Grep** See the command below to list everything with status of "Not installed". The following may help give you a better picture of what's around your site. For example, here is what is there but "not installed" on my dev box.

```
$ drush pml | grep 'Not installed' | grep -v Core
 Administration                       Actions permissions (VBO) (actions_permissions)               Module  Not installed  7.x-3.2
 BackgroundField                      BackgroundField (backgroundfield)                             Module  Not installed  7.x-1.5
 Chaos tool suite                     Better Jump Menus (jump_menu)                                 Module  Not installed  7.x-1.4
 Chaos tool suite                     Chaos Tools (CTools) AJAX Example (ctools_ajax_sample)        Module  Not installed  7.x-1.6
 Chaos tool suite                     Chaos Tools (CTools) Plugin Example (ctools_plugin_example)   Module  Not installed  7.x-1.6
 Chaos tool suite                     Custom content panes (ctools_custom_content)                  Module  Not installed  7.x-1.6
 Chaos tool suite                     Custom rulesets (ctools_access_ruleset)                       Module  Not installed  7.x-1.6
 Chaos tool suite                     Page manager existing pages (pm_existing_pages)               Module  Not installed  7.x-1.4
 Chaos tool suite                     Stylizer (stylizer)                                           Module  Not installed  7.x-1.6
 Chaos tool suite                     Term Depth access (term_depth)                                Module  Not installed  7.x-1.6
 Chaos tool suite                     Views content panes (views_content)                           Module  Not installed  7.x-1.6

```

Taken individually that is

```
drush pml \               # Shows table of modules/themes and their status
| grep 'Not installed' \  # Filters for any line WITH 'Not installed'
| grep -v Core            # Filters OUT any line containing string 'Core'

```

Given that you could do the following too :

```
$ drush pml  | grep 'Enabled'
$ drush pml  | grep 'Disabled'

```

**(2) With options arguments to drush pml**

You could also vary it up a bit with different arguments in the drush pml command

```
$ drush help pml
Show a list of available extensions (modules and themes).

Options:
 --core                                    Filter out extensions that are not in drupal core.
 --no-core                                 Filter out extensions that are provided by drupal core.
 --package                                 Filter by project packages. You can use multiple comma separated values. (i.e. --package="Core
                                           - required,Other").
 --pipe                                    Returns a whitespace delimited list of the names of the resulting extensions.
 --status=<disabled>                       Filter by extension status. Choices: enabled, disabled and/or 'not installed'. You can use
                                           multiple comma separated values. (i.e. --status="disabled,not installed").
 --type=<module>                           Filter by extension type. Choices: module, theme.

```

For example, you could use

```
$ drush pml --no-core --status="not installed" --type=module
 Package                                Name                                                                     Version
 Administration                         Actions permissions (VBO) (actions_permissions)                          7.x-3.2
 BackgroundField                        BackgroundField (backgroundfield)                                        7.x-1.5
 Chaos tool suite                       Better Jump Menus (jump_menu)                                            7.x-1.4
 Chaos tool suite                       Chaos Tools (CTools) AJAX Example (ctools_ajax_sample)                   7.x-1.6

***Note and caution:***  Always try this stuff on a development or vagrant box first. NEVER blindly do this to a production box.

```
> 2 votes

# Answer
You could also query the DB.

**List of disabled but NOT uninstalled modules (can’t be deleted from the codebase)**

```
drush sqlq "select name from system where type = 'module' and status = 0 and schema_version NOT IN (0, -1)"

```

**List of disabled AND uninstalled modules (can be deleted from the codebase)**

```
drush sqlq "select name from system where type = 'module' and status = 0 and schema_version IN (0, -1)"

```
> 2 votes

---
Tags: 7, drush, installation
---


# Question
Title: How can I develop a custom theme from scratch?
I wonder how to develop a custom theme from scratch. I understand the overall structure of Drupal theme. I've created an `.info` file and enabled the theme through the admin interface, but I get a blank screen.

I haven't yet coded any of the theme files. I'm unable to define `html.tpl.php`, `page.tpl.php`, `node.tpl.php`, `region.tpl.php`.

I do have empty `css`, `js` and `images` folders. In my `templates` folder I've an empty `html.tpl.php`, `page.tpl.php`, `node.tpl.php`, `region.tpl.php`, `field.tpl.php`.

Any suggestions?

# Answer
> 1 votes
### Hello World

It seems that the current version of your theme works as designed: empty templates that result in a blank screen, that's exactly what "I" would expect. Try adding "Hello Umair" in any of those empty files, and see what you get next.

### Start from an example

A much more effective approach however might be as suggested by longboardnode : copy from whatever theme you like, and apply the "same-as-except"-strategy.

### Start from a base theme

Or maybe create a subtheme from your favorite base-theme (Omega, Zen, Bootstrap, ... there are plenty to pick from).

### Follow the instructions in the documentation

An extremely basic example you may want to look at: Create a new custom theme with CSS alone. And if you're ready for it, study the Theming guide, especially the Theming Drupal 6 and 7 child pages of it.

---
Tags: 7, theming
---


# Question
Title: How to pass an array from module to template file?
I have an array printing in module file. I want to theme that array data,so I am not getting how can I get that array data in template file. I don't want to create theme function and all. is there any inline solution to pass from module to template. My code is like below.

```
$data['listfiles'] = array(
    '#theme' => 'table',
    '#header' => $filesheader,
    '#rows' => $rows,
    '#empty' => t('No content available.'),
  );

  return $data;

```

I want to pass $data variable to the template file, so that I can theme the data.Thanks in advance for any suggestions.

# Answer
In form.

```
/**
 * Implements hook_theme().
 */
function YOURMODULE_theme() {
  $themes = array(
    'example' => array(
      'template' => 'templates/example',
      'arguments' => array('data' => NULL),
    ),
  );
  return $themes;
}

```

after this you can pass your data as

> return theme('example', array('data' =\> $data));

Refer this

And if want to use preprocess to alter data, see hook\_preprocess\_HOOK
> 1 votes

# Answer
hook\_preprocess\_HOOK. You can add your data like `$vars['my_data'] = $my_data` then access it using `$my_data` in the tpl.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to print a field in a view only when it appears first?
I have a View which lists products (nodes). In the View, I first display the taxonomy the node belongs to, and then the title and image of the product. I have ordered the query by taxonomy. The problem is that I get a repeated taxonomy for each row of the View (each product). How can I display the taxonomy just once, the first time it occurs, and then all the products belonging to that taxonomy, then another different taxonomy and its products and so on...

Now I have this result

```
Sports
    - The great book of soccer
Sports
    - Practicing tennis
Sports
    - Mastering Chess
Science
    - Quantum Mechanics
Science
    - Cold fusion

```

and I want this result

```
Sports
    - The great book of soccer
    - Practicing tennis
    - Mastering Chess
Science
    - Quantum Mechanics
    - Cold fusion

```

# Answer
> 1 votes
You can achieve this using the **Grouping field** setting in the view's Format settings. You will need to be using Fields (as opposed to Content) in the Format section of your view.

In your Fields list, click on the taxonomy term field to open the field configuration. Check **Exclude from display** and apply:

In the Format section of your view, click on the Format Settings.

The **Grouping field Nr. 1** select list is available in each Format type, so no worries if you have it set to HTML list or another format. Change the field from None to the taxonomy field you want to group by and apply.

Your view will now show products grouped by the taxonomy term. From this point you can use the Sort criteria of the view to get the ordering of products or taxonomy terms you need.

---
Tags: views, entities, taxonomy-terms
---


# Question
Title: Views Table Grouping not working if group field is blank
I'm using Drupal 7. In a field collection view, I have data in a table that has field groups. I have 3 fields I want to group on, the first two are required, the third is optional. Everything worked until I added the 3rd field. When there are records with no data in that field, the record shows up as a row of empty table cells. Can anyone suggest a fix for this?

# Answer
I had a similar issue. If the field I was grouping by was empty in all the nodes under another grouping, no results would show. In my case it was State-\>Administrative Area, and if none of the nodes in the state had administrative areas no results would show under the state.

The solution that ended up working for me was to uncheck the 'Hide rewriting if empty' box in the Configure field: Content: Administrative Area-\>No Results Behavior section. 'Hide if empty' was already unchecked so I didn't fool about with it.
> 1 votes

# Answer
On the edit screen for your view:

* Under 'Fields', click on the third grouping field.
* Then click 'No results behavior'.
* Check the box labeled 'Hide if empty'.
* Click apply, and then save your view.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How can I export all users in a CSV format?
A site we have over 8000+ users with Views, Ctools and VBO installed. Is it possible to export all users data into 1 CSV file? We tired Views Data Export with no luck(memory limit), even we increase the memory to 128MB. Please help.

# Answer
> 5 votes
Stick the following in a file named `expusers.module`

```
<?php
/**
 *  Implementation of hook_menu()
 */
function expusers_menu() {
  $items['expusers'] = array(
    'page callback' => '_expusers_select',
    'access arguments' => array('administer expusers'),
  );
  return $items;
}

/**
 * Callback
 */
function _expusers_select() {
  //
  $csvfile_name = 'expusers.csv'; // the file to save to
  $users = array();
  $result = db_query('SELECT * FROM {users}');
  foreach ($result as $record) {
    unset($userarray);
    foreach ($record as $key => $value) {
      $userarray[] = (empty($value)) ? '' : '"' . $value . '"';
    }
    $user = implode(',',$userarray);
    $users[] = $user . PHP_EOL; // Remove this if file_save_data don't work.
    // Use PHP statement below to append to file here if file_save_data don't work.
    // file_put_contents(..path to file.., $user, FILE_APPEND);
  }
  $file = file_save_data($users,'public://' .$csvfile_name); // Remove this if file_save_data don't work.
  return '<p>CSV dump of {users} table written to file "' . $file->uri . '".</p>';
}

```

Stick the following in a file named `expusers.info`;

```
name = Export users
description = "Exports the {users} table to a CSV file in the public file area."
core = 7.x

```

Create a directory named `expusers` in your in your `modules` directory, and place both files in it.

Enable the custom module "Export users" on the site's module page.

Navigate to the path `expusers` (e.g. `http://example.com/expusers`).

The message:

```
CSV dump of {users} table written to file "public://expusers.csv".

```

Should appear.

Go to your public file area and pick up your file.

The above tiny custom module should be far less resource hungry than **Views data export**, so, hopefully, you will get your CSV without hitting a memory limit .

However, it first collects *all* the user data into an array in memory, before dumping into the file.

If you still hit a memory limit, you can't use Drupal's very convenient `file_save_data` to save to a file. Instead, you must save the data one line at a time. There is no built-in Drupal function to do this, but you should be able to use PHPs `file_put_contents` instead.

I've used comment to indicate how to change the code to replace Drupal's `file_save_data` with PHP's `file_put_contents`.

# Answer
> 0 votes
Another option to consider for addressing these requirements is the Forena module.

You would use it's report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file.

Here is a quote from one of the forena community docu pages, i.e. Reasons for considering Forena:

> Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

The Forena Video demos and tutorials contain quite some links to live demos.

# Answer
> 0 votes
Here is simple function (D7):

```
/**
  * Export all active users into CSV.
  */
function foo_export_users_csv($filename = 'users-' . REQUEST_TIME) {
  drupal_add_http_header('Content-Type', 'text/csv');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $filename . '.csv');
  $results = db_query("SELECT * FROM {users} WHERE status = 1", array());
  $csvdata = 'Uid,Username,Email,Created,Access,Login' . PHP_EOL;
  foreach ($results as $record) {
    $row = array();
    $row[] = $record->uid;
    $row[] = $record->name;
    $row[] = $record->mail;
    $row[] = $record->created;
    $row[] = $record->access;
    $row[] = $record->login;
    $csvdata .= implode(',', $row) . PHP_EOL;
  }
  print $csvdata;
  drupal_exit();
}

```

Then call this function from hook\_menu, some submit function or somewhere else, like:

```
/**
 * Some callback function.
 */
function foo_export_users_submit(&$form, &$form_state) {
  ini_set('max_execution_time', 0); // Set unlimited time for large sizes.
  $values = $form_state['values'];
  $op = $values['operation'];
  switch ($op) {
    case 'export':
      foo_export_users_csv();
      break;
  }
}

```

---
Tags: users, importing-exporting
---


title: Pass argument in view from custom form

text:
# Question
Title: Pass argument in view from custom form
I have a view content page. I want to filters its content on the base of a custom form data. So how we can pass or filter a view content using custom form data there?

View is built on node. In this particular node we have a field type select list. The same select list we have created in our form. Now what ever option is selected in form, we want to use it's value in view. We also do not have idea how to use its value.

# Answer
> 1 votes
Assuming the custom form sits in its own page. You can rewrite the output of the field, using replacement patterns, in the view to pass the required information as part of the url.

Then using hook\_menu, define parameters to pass to the form

```
function hello_world_menu() {
  $items=array();
  $items['hello_world/%/%'] = array (
    'title' => 'My Custom Form',
    'page callback' => 'hello_world_form_function',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);
return $items;
}

```

---
Tags: 7, views
---


# Question
Title: How can I fix, or troubleshoot, Fatal Error Class not found with XHProf Module
I'm seeing the following error when I enable xhprof in Drupal 8 either via Drush or via Composer.

> Class 'Drupal\xhprof\RequestMatcher\XHProfRequestMatcher' not found in /var/www/mysite/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php on line 272

I had xhprof working for a day or so, and randomly started seeing this issue. This feels very much like a Symfony/Composer autoloader issue to me, but I'm struggling with a technique or strategy for fixing or troubleshooting this.

The Call Stack feels pretty useless in this context.

I'm looking for any fix to this issue specifically, but I'm also looking for some technique or strategy for troubleshooting the missing class fatal error. The missing class error seems to keep cropping up for me with Drupal 8. I've tried to trace through the object hierarchy via xdebug, but Drupal 8 and Symfony, have a very abstracted object hierarchy. This makes it nearly impossible to be able to logically backtrack from where the error is thrown.

Why is the class not found, even though the class is definitely here: docroot/modules/contrib/xhprof/src/RequestMatcher/XHProfRequestMatcher.php?

**Update**:

After trying everything I could think of, I decided to just try and rebuild my VM with:

`vagrant reload --provision`

Sure enough, the fatal error went away. Is there some cache somewhere that drush or Drupal Console wouldn't have access to? Maybe it has something to do with the RAM or OPCACHE as @cilefen mentioned?

Note that I do not have memcache or redis running on this VM. Per a conversation on the Drupal-VM issue queue I may have been able to solve the problem by restarting PHP or just doing a reload without having to do a --provision.

# Answer
The backtrace what you see could be improved by adding the following settings in your `xdebug.ini` file:

```
; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=200        ; int: Controls the protection mechanism for infinite recursion protection.

```

This will give you more meaningful data.

Basically you're missing a class, so you should try to clear you caches and rebuild your registry. Also restart memcached/redis if it's in use.
> 2 votes

---
Tags: 8, debugging
---


# Question
Title: Disable Webform Componotent (field) after certain number of submissions
I'm working on a registration form that collects student information and the class session they're signing up to. Class sessions are of select type and has four options (sessions). Each sessions has a cap of 38 students. Is there any way to automatically disable options once submission count reaches the cap..? Please note that this is a field level condition, not the entire form level. Would that be rules? Any pointers... thanks!

# Answer
I would approach this by using

hook\_webform\_submission\_insert (which is triggered after the submission is inserted into the database)

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21webform.api.php/function/hook\_webform\_submission\_insert/7

Once in that hook i would use webform\_get\_submission\_count to get the number of submissions , if this was the last allowed submission i would then unpublish the node and create a redirect to a "this class is now closed page".

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21includes%21webform.submissions.inc/function/webform\_get\_submission\_count/7

You could also approach it by using hook\_webform\_submission\_presave or a custom form validator to generate a form error.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How can I run a query with php before entering a view
Is there any way to specify that a certain query has to run before entering a view? in a module with php .

# Answer
I used hook\_views\_pre\_execute and was able to run what I wanted before the view is created
> 1 votes

---
Tags: 7
---


# Question
Title: How to set the default value of an entity reference to an entityform type
I'm using the module EntityForm to create a couple of different forms.

Each form should be attached to a different content type as an entity reference field.

I can create an entity reference field that shows a select list of "EntityForm Type" from which the user can choose when creating content. I would like to set a default value however (and will hide the field so it can't be changed), since there shouldn't be choice as it's always the same kind of form that needs to be attached.

I know this is possible with nodes by loading a specific node, but in this case they're entityform types and not nodes.

# Answer
> 0 votes
I've found a way, but it might not be the best way. I remove all the other options from the select list so the one I want is the only one left. (What is strange, is that in some content types I can set a default value for the entity reference and in some I cannot, but this worked anyway)

```
if ($form_id == 'inschrijvingsformulier_testdag_p_node_form'){

    $form['field_inschrijvingsformulier_tes']['und']['#options']=array(1 => 'inschrijvingsformulier testdag',);
    $form['field_inschrijvingsformulier_tes']["#attributes"]['class'][] = 'element-invisible';
}

```

---
Tags: 7, entities
---


title: drush: list of update-locked modules

text:
# Question
Title: drush: list of update-locked modules
We excluded some modules from drush update (--lock=module\_name). Is there a way to get a list of locked modules? A drush command or a file with the list?

# Answer
There is no way to do this via Drush; the easiest way to find the locked files is with the `find` command:

`find . -name ".drush-lock-update"`
> 3 votes

# Answer
If listing the locked Drupal modules is something you do often you can create a drush shell alias.

Add the following code to your drushrc.php file. Your personal one is normally located at ~/.drush/drushrc.php There are 6 locations that drush will look for drushrc.php, see the example.drushrc.php file for more information.

```
$options['shell-aliases']['locked-modules'] = '! find . -name ".drush-lock-update"| sed \'s#/[^/]*$##\' | sed \'s!.*/!!\' ';

```

You can then run,

```
drush locked-modules

```

to see a list of locked modules. The code above in addition to finding the .drush-lock-update files strips this filename off and then strips off all but the module name from the path.
> 2 votes

---
Tags: drush
---


title: Notifying drupal user on publishing

text:
# Question
Title: Notifying drupal user on publishing
I'd like to be able to notify a fellow publisher within the drupal permissions group that a new piece of content relevant to their page has been published. NOT an end-user alert, but just an internal alert on Drupal.

# Answer
Sounds like a perfect use case for the Menu Badges module, which can be used to add notifications to any **menu item** and/or **menu tab** of your choice. Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)

Because of how it integrates with the Views module, you basically reduce the solution specific to your question here to something like this:

* Create an appropriate view about "*new pieces of content relevant to their page has been published*" (as in your question).
* And create a menu item or menu tab for it.
* Grant access to that view for those users who fit "*a fellow publisher within the Drupal permissions group*" (as in your question).
* Perform the required Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Refer to the video Defining Menu Badges with Views in Drupal (from the module maintainer) for more details. It shows a scenario that might be close to what you'd want to implement also.

PS: I'm assuming this question is about D7 ...
> 0 votes

---
Tags: notifications
---


# Question
Title: How can I access block field values in mytheme_preprocess_block?
My fundamental question is this: in Drupal 8 how can I access block field values in mytheme\_preprocess\_block.

I am trying to achieve something like https://www.drupal.org/project/block\_class\_styles in Drupal 8.

So far I have created the block field, and extracted the raw field value in twig (and then add classes or conditional statements) by doing something like:

```
{{ content.field_layout_style[0]['#markup']|escape }}

```

This looks really bad, I would rather access this field value in mytheme\_preprocess\_block, and then pass it to twig, and/or access it in mytheme\_theme\_suggestions\_block\_alter and make separate template suggestions based on it.

Help very much appreciated.

# Answer
> 1 votes
Here is a code snippet that we use to create block template suggestions based on the block content type (bundle), doing something similar based on a field should be fairly easy (...-\>yourfield-\>value):

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for block templates.
 */
function ourtheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle();
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle() . '__' . $variables['elements']['content']['#view_mode'];
  }
}

```

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


# Question
Title: Call AJAX function in the beginning not just after change
I've built a form that uses ajax to determine the number of text fields there should be based on a select field. It successfully adds the text fields based off the select field when it is changed, but it does not add the fields in the beginning before there is a change.

```
    $this->configuration['test'] = '3';
    $form['columnNum'] = [
        '#title'   => t('Number of Columns'),
        '#type'    => 'select',
        '#options' => [
            1         => '1',
            2         => '2',
            3         => '3',
            4         => '4',
        ],
        '#default_value' => $this->configuration['test'],
        '#empty_option'  => t('-select-'),
        '#ajax'          => [
            'callback'      => [$this, 'columnCallback'],
        ],
    ];

public function columnCallback(array&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $number   = $form_state->getValue(['settings', 'columnNum']);

    for ($i = 0; $i < $number; $i += 1) {
        $columns[$i] = [
            '#type'  => 'textfield',
            '#title' => t('Column Title'),
            '#value' => $this->configuration['test'],
        ];
    }
    $content[] = [
        '#type'        => 'container',
        '#attributes'  => ['id'  => 'column_wrapper'],
        'columnTitles' => $columns,
    ];

    $response->addCommand(new ReplaceCommand('#column_wrapper', $content));
    return $response;
}

```

I've attempted lines this

```
$this->columnCallback();

```

But that failed. Is there a way to get an ajax callback in the beginning before the field as well? Or is there a better way to do this entirely?

# Answer
> 0 votes
Rather than calling the AJAX function at the beginning I simply built the form as it should be in buildForm. Like so

```
    for ($i = 0; $i < $this->configuration['test']; $i += 1) {
        $columns[$i] = [
            '#type'  => 'textfield',
            '#title' => t('Column Title'),
            '#value' => $this->configuration['test'],
        ];
    }
    $form['column_wrapper'] = [
        '#type'        => 'container',
        '#attributes'  => ['id'  => 'column_wrapper'],
        'columnTitles' => $columns,

    ];

```

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


# Question
Title: How to alter the URL path alias generated by content type programmatically?
Our current url pattern is \[node:menu-link:parents:join-path\]/\[node:title\]. What we need is a way to not to include the parent menu link items and only include the child menu link items.

For example:

The expected output is the following:

* When Any menu link is placed at the same level as "Fourth level 1" (under Top level), it should be ".com/Second-level1/Third-level-1/Fourth-level-3"
* Current issue is that the URL is generated as ".com/Top-Level/Second-level1/Third-level-1/Fourth-level-3"
* We want to remove Top level, Top level 2, top level 3, etc removed from URL path alias.
* Depending upon the placement of the menu link item, it should always contain the menu links 1 level above (if applicable)
* The expected url pattern for third level 2 (under Top level/Second level 1) is ".com/second-level-1/third-level-2"

---

Updated:

I ended up write a custom module to call the hook\_alter using the pathauto that just removes the first part of the URL before the node save event.

# Answer
> 1 votes
You can use this module https://www.drupal.org/project/pathauto with this you define the custom path use token

# Answer
> 1 votes
You might be able to get this to work using the Rules module, together with the Path Rules module, using an approach like so:

* Rules Event: around the time a node is saved (or updated, etc).
* Rules Condition: use Path Rules which provides various Rules Conditions "*for checking the URL against a given string*" (check this module's project page for examples of such checking). It seems that checking your URL patterns should be straight forward with this module.
* Rules Action: use the "Create or delete a node's URL alias" action to change the URL alias. This Rules Action is similar to using the Pathauto module, you can use tokens to create an appropriate path.

---
Tags: 7, path-aliases
---


# Question
Title: Drupal 8 Blog Autoposting To Facebook, Twitter, LinkedIn etc
I'm deciding what technology to use to build a social website. One of the features I'd like is autoposting to Facebook, Twitter, Linkedin, Youtube etc from a blog.

Joomla has a component called easyblog - http://stackideas.com/easyblog. I was wondering if there is anything similar for Drupal?

Normally I build basic websites with Joomla and more complicated things with Drupal 7 but with 8 out would ideally like to have used that.

Kind regards and many thanks for your time it is appreciated.

# Answer
There's a framework of modules under development as part of a 'Social initiative'. See https://www.drupal.org/project/social\_post
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Individually Print Exposed Filter Elements/Options
I'm using Better Exposed Filters on a view and want to individually print the elements/options within the 'widget', rather than all of them at once.

For example, lets say my options are: **Red**, **Yellow**, **Green**, **White** and **Black**, I want to be able to print **Red**, **Yellow** and **Green** in one , then **White** and **Black** in another.

From this:

To this:

The the template appears to only allow for an all or nothing approach:

```
    <div class="views-widget">
      <?php print $widget->widget; //this prints everything?>
    </div>

```

I imagine I could print the entire widget a number of times, then hide specific elements using CSS, but I feel this would create a a bit of a performance hit.

I've also tried separating options into different filters, but more than one exposed filter crashes my site as soon as the user selects options in more than one filter.

# Answer
I found a fairly reasonable solution to this - there may be better ways, but so far it works without any performance hit that I have been able to detect.

It seems as it's a fairly complex multidimensional array, you can only render an entire widget or not. So to do this you need to create different versions of the widget, with different options inside them, and render them in their entirety.

Step 1: Copy the form array (the widget) into a new array and create another array containing just the options

```
$formArray = $form['colours'];
$allColours = $form['colours']['#options'];

```

Step 2: Unset all the options from the new array, which is now just a shell, then create a few copies of it

```
unset($formArray['#options']);
$justColours = $formArray;
$justShades = $formArray;

```

Step 3: Cycle through your array containing just the options, and distribute them back into the shells you created

```
foreach ($allColours as $id => $result) {
    if ($id >= 0 && $id <= 2):
          $justColours['#options'][$id] = $result;
    elseif ($id >= 3 && $id <= 4):
          justShades['#options'][$id] = $result;
    endif;
}

```

Step 4: Render your new arrays where you need 'em

```
print render($justColours);
print render($justShades);

```

Snap!
> 1 votes

---
Tags: views
---


# Question
Title: Allow HTML style attribute for filtred HTML
I'm using the Wysiwyg module with CKEditor 3.6.6.2.7696. The HTML attributes is disallowed in HTML text format, so I can't use `font-size` and `text-align`. Any solution please?

# Answer
> 0 votes
go to `admin/config/content/formats/filtered_html`

In the limit allowed HTML tags, add the tags that you need. You could view source to see what tags are being added when you're trying to font-size and text align and then add them here.

go to:

`/admin/config/content/ckeditor/edit/Advanced` (for Filter HTML)

Then under Advanced Content Filter, select disabled.

---
Tags: wysiwyg
---


# Question
Title: Install Drupal into a different directory than drupal-vm is installed
I installed Drupal Virtual Machine (Drupal VM) from drupalvm.com using vagrant. This worked fine - but I want to install the drupal files into a different directory.

How can I modify the Vagrantfile in order to install drupal and the drupal vm into different directorys (drupal not as a sub diretory of drupal vm). Thank you.

# Answer
> 1 votes
You can override the default configured webroot directories by altering the `local_path` property in the `vagrant_synced_folders` array with a custom **config.yml** file (copy over **default.config.yml** if you don't have one).

Per default.config.yml:

```
# A list of synced folders, with the keys 'local_path', 'destination', and
# a 'type' of [nfs|rsync|smb] (leave empty for slow native shares). See
# http://docs.drupalvm.com/en/latest/extras/syncing-folders/ for more info.
vagrant_synced_folders:
  # The first synced folder will be used for the default Drupal installation, if
  # any of the build_* settings are 'true'. By default the folder is set to
  # the drupal-vm folder.
  - local_path: .
    destination: /var/www/drupalvm
    type: nfs
    create: true

```

---
Tags: virtual-machine
---


# Question
Title: Accessing the in-place editor with the keyboard
Can a administrator user open the in-place editor using the keyboard?

Editing multiple nodes would be less annoying than it is now.

# Answer
You can use my module, **Instant Transmission**.

> Why waste time moving the mouse cursor 7000 pixels or navigating drop downs or scrolling down the page to hit the save button, when you can use ... Instant Transmission.
>
> Instant Transmission allows you to quickly edit or configure nodes/blocks much faster than ever before.
> 1 votes

---
Tags: nodes, navigation
---


title: How to make Voting api not cache

text:
# Question
Title: How to make Voting api not cache
For my application with several different voters, I want the caching table (votingapi\_cache) to never be populated. Is there a hook or a configuration I can implement so that no caching happens at all?

# Answer
> 0 votes
The function `votingapi_add_results()` is responsible for writing records to the `votingapi_cache` table. Immediately afterwards, it invokes `hook_votingapi_results()` which any module can use to wipe out the table.

For example:

```
/**
 * Implements hook_votingapi_results().
 */
function MYMODULE_votingapi_results() {
  db_truncate('votingapi_cache')->execute();
}

```

---
Tags: 7, rating
---


title: Drupal modal form save data twice

text:
# Question
Title: Drupal modal form save data twice
In my Drupal site I am using Webform module Modal forms (with ctools) module.

When I place file field (to get opportunity attach files) on the form, form save data twice. But when I delete file field, form work perfect, e.g. save data once. Maybe someone has already faced this problem. Any help will appreciate.

**Image-1**

>

**Image-2**

>

# Answer
I found solution. In the file

> modal\_forms.pages.inc

inside the `function modal_forms_view_webform($js = NULL, $node)` place `$form_state['rebuild'] = TRUE;` after `$output = ctools_modal_form_wrapper('webform_client_form_' . $node->nid, $form_state);`

Then modal form will save data only once.
> 0 votes

---
Tags: webforms
---


# Question
Title: Menu alter for a particular content type
I am trying to add a custom access callback for the node edit page for a particular content type.

I am using `alterRoutes` function to change the access callback but I am unable to get the node type in this function.

Am I missing something obvious?

# Answer
in RouteSubscriber.php

```
namespace Drupal\MODULENAME\Routing;

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

/**
 * Class RouteSubscriber.
 *
 * @package Drupal\MODULENAME\Routing
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[RoutingEvents::ALTER] = ['onAlterRoutes',-9999];  // negative Values means "late"
        return $events;
    }
    /**
     * {@inheritdoc}
    */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.node.edit_form')) {
            $route->setRequirement('_custom_access','\Drupal\MODULENAME\Controller\MYCONTROLLER::access');
        }
    }

}

```

and in MYCONTROLLER.php

```
namespace Drupal\MODULENAME\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Class Inactiveusers
 * @package Drupal\MODULENAME\Controller
 */
class MYCONTROLLER extends ControllerBase {
    function access(AccountInterface $account){
        if($node = \Drupal::routeMatch()->getParameter('node')){
            if ($node->getType() == 'page' && $node->isPublished()) {
                return \Drupal\Core\Access\AccessResult::forbidden();
            }return \Drupal\Core\Access\AccessResult::neutral();
        }
        return \Drupal\Core\Access\AccessResult::neutral();
    }
}

```
> 0 votes

# Answer
There are o node type specific edit routes, only one. You'd have to alter that and then in your access callback, decide if it is your node type or not.

But, why don't you just implement hook\_node\_access() and check for the update operation? That allows you to control access to that page and also any edit operation elsewhere on th system, on whatever condition that you want.
> 1 votes

---
Tags: 8, routes
---


# Question
Title: How to programmatically manage taxonomies?
I'm working on a project with this requirement: there will be a couple of custom content types where many fields comes from taxonomies references.

Many of these taxonomies have plenty of terms (50+). These terms are periodically updated (added/corrected/removed) by a third party system in charge of this task, which later exposes these 'most current' terms list through a webservice.

So I don't need to force a human operator to manually check these terms lists and update D8 taxonomies accordingly, I thing that a good approach would be to periodically run a task to verify that webservice and then updated D8 with what have changed.

I've carefully read the following references:

The one that come closer to the project needs is the 4th one in the above list. It would suffice the requirements for now.

But I didn't quite get where this code should be typed. Does it need to be a custom module or should it go into `themes/mytheme/mytheme.theme` or so?

From where I stand, I think that an elegant solution is to have a routine somewhere (where?) that I could call via D8's cron so I can retrieve-then-update taxonomies periodically. But I have no clue on how I could achieve that goal.

Can someone provide any good references so I can fulfill this desire with code?

# Answer
A simple way to set this up would be a cron hook.

**function hook\_cron**

> Perform periodic actions.
>
> Modules that require some commands to be executed periodically can implement hook\_cron(). The engine will then call the hook whenever a cron run happens, as defined by the administrator. Typical tasks managed by hook\_cron() are database maintenance, backups, recalculation of settings or parameters, automated mailing, and retrieving remote data.
>
> Short-running or non-resource-intensive tasks can be executed directly in the hook\_cron() implementation.
>
> Long-running tasks and tasks that could time out, such as retrieving remote data, sending email, and intensive file tasks, should use the queue API instead of executing the tasks directly. To do this, first define one or more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items that need to be processed to the defined queues.

As mentioned a better way for D8 would be to use the queue API.

Or try the dev version of Feeds, which can do this without code:

https://www.drupal.org/project/feeds
> 2 votes

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


# Question
Title: how to add the value of a (list text) field as a class
I have a CT on which I have a field called `monetary-type` which is of type `List (text)` and its "Allowed values list" is:

```
EUR|Euros
USD|Dollars
GBP|Pounds

```

When this field is rendered from a view (FORMAT: Show: Fields) it's being rendered as:

```
<span class="views-field views-field-field-monetary-type">
  <span class="field-content">Dollars</span>
</span>

```

When rendered from a node view it shows as:

```
<div class="field field-name-field-monetary-type field-type-list-text field-label-above field-wrapper">
  Dollars
</div>

```

For both those 2 cases I'd like to also have a class with the selected value, in this case `value-USD`, appended into the classnames of the wrapper.

What is the easiest (non intrusive) way I can achieve this? Ideally without having to touch existing views or node displays.

I use https://www.drupal.org/project/zurb\_foundation if it matters.

# Answer
For view field, please implements `template_preprocess_views_view_fields()`

Reference: https://www.drupal.org/node/1407442#comment-6509858

**Code Example**

```
// assume the field name is 'field_text' and
// view name is 'text and view display id is 'page'
function mymodule_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'test' && $view->current_display == 'page') {
    foreach ($variables['fields'] as $id => $object) {
      if ($id == 'field_text') {
        $field_output = $view->style_plugin->get_field($view->row_index, $id);

        if (!empty($field_output)) {
          if ($object->element_type) {
            $class = '';
            if ($object->handler->options['element_default_classes']) {
              $class = 'field-content';
            }

            if ($classes = $object->handler->element_classes($view->row_index)) {
              if ($class) {
                $class .= ' ';
              }
              $class .=  $classes;
            }

            $class .=  ' ' . drupal_html_class("value-$field_output");

            $pre = '<' . $object->element_type;
            if ($class) {
              $pre .= ' class="' . $class . '"';
            }
            $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
          }
        }
        $variables['fields'][$id]->content = $field_output;
      }
    }
  }
}

```

For node field, please implements `template_preprocess_field()`

**Code Example**

```
// Assume the field name is 'field_text'
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];
  if ($element['#field_name'] === 'field_text') {
    $value = $element['#items'][0]['value'];
    $variables['classes_array'][] = drupal_html_class("value-$value");
  }
}

```

**Note 1**: I would recommend using lower case for class name.
**Note 2**: `view_field_name` is different from `node_field_name`
> 1 votes

# Answer
I used the following:

```
function mytheme_preprocess_views_view_field(&$vars) {
  if ($vars['field']->field == 'field_monetary_type') {
    $value = $vars['row']->field_field_monetary_type[0]['raw']['value'];
    $vars['output'] = '<span class="value-' . $value . '">' . check_plain($vars['output']) . '</span>';
  }
}

function mytheme_preprocess_field(&$variables, $hook) {
   if ($variables['element']['#field_name'] == 'field_monetary_type') {
     $value = $variables['element']['#items'][0]['value'];
     $variables['classes_array'][] = "value-$value";
  }
}

```

Note that for the view field I'm wrapping the output into a span containing the class I need.
> 0 votes

---
Tags: 7, theming, entities
---


# Question
Title: How to modify Parent Item under Menu Settings to display current language links only?
We have a multilingual site where the menu links are based on the current locale. If 100 nodes are created in English and 50 nodes are created in Italian, for example, then when the locale is set to English, then the English menu link should display, but if the locale is set to Italian then i should only see the 50 nodes set to Italian.

The locale/language detection is based on URL so if the URL has ".com/en/" then the locale should be English, but if the URL is ".com/it/" then the locale should be Italian. As a result, the menu will display based on that locale.

The issue we are having is that on the Italian pages under menu settings, when i view the Parent Item Dropdown, i am seeing all the English menu links (whose language=en) displays with "(disabled)" next to it. All Italian links display as normal without "(disabled)".

Current example with language in parenthesis:

* Parent Link (en)
* Child Link1 (en)
* Child Link2 (en)
* Child Link3 (disabled) \<-----this is an it (Italian)
* Child Link4 (disabled) \<-----this is an it (Italian)

The ideal scenario would be when i click on "Parent Item" dropdown that i only see links based on the current node's language (not other links assigned to a language that is different than the current node's language).

Expected behavior (if node's language = it):

* Parent Link (IT)
* Child Link3
* Child LInk4

Expected behavior (if node's language = en):

* Parent Link (en)
* Child Link1
* Child LInk2

# Answer
> 0 votes
I am not sure about settings, but I can suggest you way to do it programmatically.

You can use TEMPLATE\_preprocess\_menu\_tree *(replace TEMPLATE with your theme name)* in your `template.php` of theme folder. Inside the function you can loop through the tree & validate it's translation with current site language & reset or set access deny if it doesn't match.

---
Tags: 7, navigation
---


# Question
Title: Media Browser in WYSIWYG editor doesn't allow uploads for non-admins
As admin everything works as expected. I can upload images. As a non-admin user I can use the "Web" and "Library" functions but not the file upload function.

I have it enabled:

And the user has the correct permissions applied:

# Answer
There are two things need to be configured for WYSIWYG editor.

First settings can be found on `admin/config/media/browser`. Either you check all available plugins like you have done in screenshot or leave all unchecked for allowing all. That's already done by you.

Next is to check permissions, where you have to give Add and upload new files, view own files etc permissions (like my screenshot below)

Another permission to check is `Use media browser`, which you must have done & so that it's appearing. Once these are in place, it should work for the role you are checking.
> 1 votes

---
Tags: media
---


# Question
Title: How to make my blocks switch to another block when session was set?
I have 2 header block, default 1 is the login form and the other block was for logout button. I want to make this two blocks switching after triggering the login button

# Answer
You can do this in code:

```
if (\Drupal::currentUser()->isAnonymous()) {}

```

Or in block layout by configuring the visibility of roles:

When the user has the following roles

* Anonymous user
* Authenticated user
* Administrator

The first block for anonymous users and the second block for authenticated users.
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: custom module to create multiple forms with pop-ups
I am working on a custom module to create a form. Functionality of the module is as follows: The first form has an url, on clicking the url it should show another form as a pop-up. How can i call these forms in the hook menu. Does tools\_js has any significance?

```
<?php

function patient_menu() {

$items['patient_add/mainpage'] = array(
    'title' => 'New Patient',
    'page callback' => 'patient_form',
    'page arguments' => array(),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);
//a link to add patient diseases

$items['patient_add/%ctools_js'] = array(
'page callback' => 'patient_callback',
'page arguments' => array(1),
'access callback' => 'user_is_logged_in',
'type' => MENU_CALLBACK,
);

return $items;
}

 // a function to make a  link
function _patient_make_link($link_text = '') {

 return '<div id="patient">' . l($link_text, 'patient_add/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '</div>';
}
//first form

function patient_form($form, &$form_state)  {
ctools_include('modal');
ctools_modal_add_js();

$form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#size' => 30,
    '#maxlength' => 128,
    '#required' => TRUE,
);

$form['age'] = array(
    '#type' => 'textfield',
    '#title' => t('Age'),
    '#size' => 30,
    '#maxlength' => 30,
    '#required' => TRUE,
    '#attributes' => array('placeholder' => t( 'in Years' )),
);

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

_patient_make_link('add disease details');

return $form;

}

//Ajax menu callback

function patient_callback($ajax) {
if ($ajax) {
ctools_include('ajax');
ctools_include('modal');

$form_state = array(
  'ajax' => TRUE,
  'title' => t('disease details'),
);
$output = ctools_modal_form_wrapper('disease_form', $form_state);
if (!empty($form_state['ajax_commands'])) {
  $output = $form_state['ajax_commands'];
}
print ajax_render($output);
drupal_exit();
}
 else {
  return drupal_get_form('disease_form');
  }
}
//second form
function disease_form($form, $form_state){
  $form['disease_ids'] = array(
    '#type' => 'select',
    '#title' => t('Disease IDs'),
    '#multiple' => TRUE,
    '#options' => array(
        'Cancer' => 'Cancer',
        'Dengu' => 'Dengu',
        'Viral Fever' => 'Viral Fever',
        'Malaria' => 'Malaria',
    ),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;

}

function patient_form_submit($form, &$form_state) {}

```

# Answer
> 0 votes
You are partial on the right path, I would suggest following a guide like https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 and then work your way towards what you need based on that.

---
Tags: forms, chaos-tool-suite
---


# Question
Title: Display error message when validating form in a specified region or div
I have a Drupal 7 form, built by using Form API. I just want to validate using the `hook_form_validate` function, and if there are errors, display them using `drupal_set_message`. It is working perfectly. The problem is that in another page, I have the same form in a div, in the left side of the page, and would want the error message to appear in this region only, and not at the top of the page, where now it is appearing (that is controlled in page.tpl.php via $message variable, I think). Any idea of how could I achieve this easily?

# Answer
> 0 votes
Inline Messages

> The Inline Messages module allows you to move form messages (error/status/warning) from the top of the page to just above where your form appears.

I think this module may suit your needs.

# Answer
> 2 votes
If you use the form\_set\_error function instead of drupal\_set\_message, then the error message will be displayed within the form, which would mean that it would display inside your block.

If you would like to retain the drupal\_set\_message behaviour for your main form page then you would either need to differentiate which method is called in the validation based on url (or Context), or provide two separate forms so that you can simply validate each separately. In this instance you could build form and validate using a shared function to avoid duplication.

---
Tags: 7, forms, status-messages
---


# Question
Title: How to set the value of a field "reference to a term" with the use of entity_metadata_wrapper?
In a content type with a have taxonomy field "reference to a term" which I want to connect to a webform submission.

I have the following code in rules:

```
$brancheid = $submissions[$sid]->data[1][0];
$oplossingsid = $submissions[$sid]->data[2][0];
$nodeid = $submissions[$sid]->data[3][0];

$node = node_load($nodeid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->title->set('done');   // this is working
$node_wrapper->save();
$node_wrapper->field_sector->set($brancheid);
$node_wrapper->field_dienst->set($oplossingsid);
$node_wrapper->save();

```

After submission of the webform the title is saved. But field\_sector and field\_dienst (taxonomy reference to a term types) and are not saved. I tried several combinations but do not get it.

What should I do?

# Answer
Strange. This is not working:

```
$node_wrapper->field_sector->set($brancheid);
$node_wrapper->field_dienst->set($oplossingsid);

```

But this is working:

```
$node_wrapper->field_sector = $brancheid;
$node_wrapper->field_dienst = $oplossingsid;

```
> 0 votes

---
Tags: 7, entities
---


title: Admin user is unable to login

text:
# Question
Title: Admin user is unable to login
I've just changed the view of login form to Drupal default view. Now I am not able to log in as administrator.

I have tried to change the password using `php .\scripts\password-hash.sh newpwd`. I got an hashed password, I used to update the password stored in the database with a SQL query, but still I am not able to log in. I have also cleared entries from flood table.

Any help will be appreciated.

# Answer
* Please check if you are using the correct username (you can see that in the database).
* Try to use the "Forgotten password" function to reset your password
* Check the last entries of the watchdog table to see if you can get more information from there
* Check your server logs to see if you get any error there (under Linux this would normally be somewhere under /var/logs).
* Install drush and use that to very easily log in (https://drushcommands.com/drush-7x/user/user-login/)
> 1 votes

# Answer
if drush is installed,

> use **drush uli** or **drush uli uid** (you have to copy like this http://YOURSITE/user/reset/1/1470908634/UyfrRRADUusWPoS2wbHZklaBzi1s111JsOeDsJA7Zus ) this is an example for admin(root)

and set password in admin page.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Form with throbber not responding to validate or submit methods
I have the following form built with Form API. Its method is GET. I try to validate or submit, but it does not work. I have checked the method names, etc., and are correct, in fact I see an "attempt" of validation in some cases. I guess that there is something weird for the way I use the select autofilling field. It is a "car models" select whose values are filled by selection of "car brand" select, and I think that the code somehow interferes with the normal use of Form API.

```
function mymodule_search_form(){
    $brands = get_brands();
    $brand = get_default_brand();

    $form['product'] = array(
      '#type' => 'textfield',
      '#title' => t('Product'),
      '#autocomplete_path' => 'product-busq/productos/all',
      '#attributes' => array("placeholder" => t('Product'), ) // 'class' => array('auto_submit')
     );

     $form['brand'] = array(
       '#type' => 'select',
       '#title' => t('Brand'),
       '#options' => $brands,
       '#default_value' => $brand,
       '#ajax' => array(
           'callback' => 'mymodule_models_update',
           'wrapper' => 'models_wrapper',
           'progress' => array(
           'message' => '',
           'type' => 'throbber',
          ),
         ),
        );

    $form['model'] = array(

      '#type' => "select",
      '#title' => t('Model'),
      '#required' => FALSE,
      '#multiple' => YES,
      '#attributes' => array("placeholder" => t('Model'), ), // 'class' => array('auto_submit')

       '#prefix' => '<div id="models_wrapper">',
       '#suffix' => '</div>',
       '#disabled' => TRUE,
      );

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

   $form["#action"] = $base_url . "/" . $language->language . "/" .   drupal_get_path_alias("node/3");
  $form["#method"] = "get";

  return $form;
} // function

```

And now the autofilling function which may be causing the problems, especially the last sentence. The code is copied from a tutorial somewhere:

```
function mymodule_models_update($form, &$form_state) {
   unset($form_state['input']['model'], $form_state['values']['model']);
   $brand = $form_state['values']['brand'];
   $brand_desc = "";
   $results = db_query("SELECT description FROM {taxonomy_term_data} tax WHERE tax.tid = :tid", array(":tid" => $brand));
    foreach($results as $row) $brand_desc = $row->description;

    if($brand_desc != "") $form['model']['#options'] =      _hook_list_models($brand_desc);
    unset($form['model']["#attributes"]['disabled']);
   $form['model']['#disabled'] = FALSE;
   $form["model"]["#attributes"]["id"] = "edit-model";
   return form_builder($form['#id'], $form['model'], $form_state);
 } // function

```

# Answer
> 1 votes
According to the Drupal official documentation on `drupal_build_form`.

> **method:** The HTTP form method to use for finding the input for this form. May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method forms do not use form ids so are always considered to be submitted, which can have unexpected effects. The 'get' method should only be used on forms that do not change data, as that is exclusively the domain of 'post.'

I would recommend you using POST method rather then GET method, so please remove the line `$form["#method"] = "get";`

Also, you should rewrite your ajax callback.

```
function hook_models_update($form, &$form_state) {
   unset($form_state['input']['model'], $form_state['values']['model']);
   $brand = $form_state['values']['brand'];
   $brand_desc = "";
   $results = db_query("SELECT description FROM {taxonomy_term_data} tax WHERE tax.tid = :tid", array(":tid" => $brand));
    foreach($results as $row) $brand_desc = $row->description;

    if($brand_desc != "") $form['model']['#options'] =      _hook_list_models($brand_desc);
    unset($form['model']["#attributes"]['disabled']);
   $form['model']['#disabled'] = FALSE;
   $form["model"]["#attributes"]["id"] = "edit-model";

   $form_state['rebuild'] = TRUE;
   return $form['model'];
}

```

**IMPORTANT NOTE:**

If you can, I would suggest you rename your function or module name to avoid using `hook_` prefix. It would cause unexpected function name conflict in future, because `hook_` prefix is reserved for building hook API in Drupal.

---
Tags: forms, ajax
---


title: Multiple select not working in drupal8

text:
# Question
Title: Multiple select not working in drupal8
I have a form element as follows :

```
$form['fieldset']['select-user'] = array(
            '#type' => 'select',
            '#title' => t('Select a user'),
            '#options' => select_user_dropdown_options(),
            '#description' => t('Select a user'),
            '#size' => 10,
            '#attributes' => array(
                'style' => 'width:600px',
                'multiple' => 'true'
            )
        );

```

And in the form submit handler i am processing it as follows :

```
    /**
     * #submit callback for node_adoption_transfer_form().
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $groupId = $form_state->getValue('select-user-group');
        $groupName = $form_state->getValue('group_name');
        $userId = $form_state->getValue('select-user');
        $groupName = empty($groupName) ? '' : $groupName;
        #print_r($userId);exit;
        foreach ($userId as $key => $value) {
            $query = "select * from {usergroup_user_map} where user_id=$value AND group_id ='$groupId'";
            if (count(db_query($query)->fetchObject()) > 0) {
                continue;
            } else
                db_query("insert into {usergroup_user_map} (user_id,group_name,group_id) values ($value,'$groupName','$groupId')");
        }
     }

```

But when am printing the **`$userId`** its only printing the last value , How to resolve this ?

**UPDATE**

> my issue solved .I was using '#multiple' =\> 'true' instead of '#multiple' =\> TRUE , my bad ;) . That saved my day ..

# Answer
I had same issue , but i solved like this

```
$form['fieldset']['select-user'] = array(
   '#type' => 'select',
   '#title' => t('Select a user'),
   '#options' => select_user_dropdown_options(),
   '#description' => t('Select a user'),
   '#size' => 10,
   '#multiple' => TRUE,
   '#attributes' => array(
      'id' => 'edit-select-user',
      'style' => 'width:600px',
   )
);

```

Code:

Form:

Output in submit:
> 6 votes

---
Tags: forms, 8
---


# Question
Title: How to use cache set and get to store time cron ran?
We have a new requirement where we need to run a job on a daily basis. We have setup cron to run every 1 hour. The goal is to have cron ron every 1 hour, but we want a specific job to run only if 1 day (24hours) has past since last run.

We used to use the Variables table to store the time the job was last run, but we need to change this to use the cache table. Below is the code (mymodule.module) we were reviewing, but it is not creating a cache table and not storing the appropriate date. So we need assistance in figuring out if we are using the correct logic so the job runs once everyday.

Note: $cache-\>data below is actually the last time the job ran.

```
mymodule_cron() {
     $data = '';
     if($cache = cache_get('last-run')) {
         $data = $cache->data;
         if($data <= strtotime('-1 day')) {
               //call helper function to perform some logic
               _some_func();
               $data = time();

               //set update date in cache
               cache_set('last-run', $data, 'cache'));
         }
    }
 }

```

# Answer
> 1 votes
I don't think there is something wrong on `cache_get()` and `cache_set()`. It seems a logic problem. In your code the cache is never set if a cache is not found.

```
/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  $data = '';

  if ($cache = cache_get('last-run')) {
    $data = $cache->data;
    if($data <= strtotime('-1 day')) {
      //call helper function to perform some logic
      _some_func();
      //set update date in cache
      cache_set('last-run', time(), 'cache'));
    }
  }
  else {
    // set cache if there is no cache.
    cache_set('last-run', time(), 'cache'));
  }
}

```

# Answer
> 0 votes
I would suggest storing this sensitive data to Drupal variables instead of cache because cache can be wiped by arbitrary code (which probably happens in your case).

Instead of `cache_get` and `cache_set` use `variable_get` and `variable_set` accordingly.

---
Tags: 7, hooks, caching, cron
---


# Question
Title: How can we catch the acces denied exception?
I've run into a case where users need to be redirected to the login page when they try to access a page without having the permission to access it.

How can I catch an exception of the `AccessDeniedHttpException` class?

# Answer
To catch the access error you can use a symfony event listener:

> If your listener calls setResponse() on the GetResponseForExceptionEvent, event, propagation will be stopped and the response will be sent to the client.

http://symfony.com/doc/current/controller/error\_pages.html#working-with-the-kernel-exception-event

This is an example how to return a `GetResponseForExceptionEvent` event:

**Drupal\Core\EventSubscriber\CustomPageExceptionHtmlSubscriber**

```
public function on403(GetResponseForExceptionEvent $event) {
    $custom_403_path = $this->configFactory->get('system.site')->get('page.403');
    if (!empty($custom_403_path)) {
      $this->makeSubrequestToCustomPath($event, $custom_403_path, Response::HTTP_FORBIDDEN);
    }
  }

```

For your own Event Subscriber extend `DefaultExceptionHtmlSubscriber`.

```
class MyCustomPageExceptionHtmlSubscriber extends DefaultExceptionHtmlSubscriber

```

See the complete example:

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/EventSubscriber/CustomPageExceptionHtmlSubscriber.php

which extends

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/EventSubscriber/DefaultExceptionHtmlSubscriber.php

You would have to use a higher priority, so that your code will run first.

---

In most cases it might be easier to configure a url pointing to a custom controller here:

```
/admin/config/system/site-information

```

BTW the example code above is how core implements this configuration.
> 8 votes

---
Tags: 8
---


# Question
Title: How to set manual crop to be compulsory for image?
I searched a lot for this problem but not getting any solution. Any help is very appreciate.

I am using Manual Crop (7.x-1.5) module for cropping the images. But problem is that I want to set cropping to be compulsory for image. I did not find any option in manual crop setting to set it as required.

# Answer
> 0 votes
I resolved my problem by using hook\_node\_validate.

---
Tags: 7, media
---


title: How do I fix an uncaught TypeError?

text:
# Question
Title: How do I fix an uncaught TypeError?
I am using Drupal 8.1.8. It is giving me many JavaScript errors.

```
Uncaught TypeError: Cannot read property 'permissionsHash' of undefined
Uncaught TypeError: Cannot set property 'StateModel' of undefined
Uncaught TypeError: Cannot set property 'AuralView' of undefined
Uncaught TypeError: Cannot set property 'KeyboardView' of undefined
Uncaught TypeError: Cannot set property 'RegionView' of undefined
Uncaught TypeError: Cannot set property 'VisualView' of undefined
Uncaught TypeError: Cannot read property 'uid' of undefined
Uncaught TypeError: Cannot read property 'currentPath' of undefined
Uncaught TypeError: Cannot read property 'currentPathIsAdmin' of undefined
Uncaught TypeError: Cannot read property 'url' of undefined
Uncaught TypeError: Cannot read property 'currentQuery' of undefined

```

There is no error in my local copy, but it happen when I uploaded in live hosting.

How can I fix this?

# Answer
All the properties can be searched and found from the code in Drupal core. And they seems to be the properties of `drupalSettings` object in JS.

This object is initialised in `core/misc/drupalSettingsLoader.js`.

```
(function () {

  'use strict';

  // Use direct child elements to harden against XSS exploits when CSP is on.
  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  ....

```

This code explained that the `drupalSettings` is contained in

```
<script type="application/json" data-drupal-selector="drupal-settings-json">

```

And it must be under `<head>` or `<body>`.

I suspect that your `<script>` tag is wrapped in other element. Please check your template files and remove the wrappers or check if there is a content with missing closing tag.
> 13 votes

---
Tags: javascript, 9
---


title: use admin theme to render modules pages

text:
# Question
Title: use admin theme to render modules pages
I want my custom module pages to be rendered using the admin theme, at the moment they only render using the admin theme for User 1 (see below).

I have a module called `mymodule` that defines many administrative views. It's setup in the following structure:

```
function mymodule_menu() {
    return [
        'admin/content/foo'     => ['page callback' => 'handle_foo', /*other opts*/],
        'admin/content/foo/bar' => ['page callback' => 'handle_foobar', /*other opts*/],
        /* list goes on*/
    ];
 }

 function handle_foo() {
    return ['#theme' => 'handle_foo'];
 }

 function theme_handle_foo() {
    /*database logic here, then return compiled html to be rendered. */
    return '<div> I am a foo!</div>';
 }

```

Say I have 2 users:

* User 1: All permissions available(including administration)
* User 2: 1 custom permission defined in the module

**When logged in as User 1**, all pages that follow `admin/*` are rendered with the drupal `admin_theme` including `mymodule` paths.

**When logged in as User 2** all of `mymodule` pages are rendered using the frontend theme.

I've tried using hook\_admin\_paths but this doesn't work:

```
function mymodule_admin_paths() {
  return [
    'admin/content/foo'   => TRUE,
    'admin/content/foo/*' => TRUE,
    '/admin/content/foo'  => TRUE,
  ];
}

```

I have also read on here that any path that follows the `admin/*` convention should use the `admin_theme` by default which appears to be true for user 1 but not user 2.

My take on this is that I need to give user 2 some kind of permission, however I don't want them to be able to do anything other than login and access the paths set out in `mymodule`

*(I don't want to use 3rd party modules)*

# Answer
I found 2 solutions to this:

**Solution one**

Use `hook_custom_theme()`: see hook\_custom\_theme()

```
function mymodule_custom_theme() {
 $use_admin = workout_when_you_want_to_use_admin(); //true or false
 if ($use_admin)
   return variable_get('admin_theme');
}

```

**Solution 2 (preferred)**

Ensure that the user account has the permission `View the administration theme` attached to their role.
> 1 votes

---
Tags: 7, theming, users
---


# Question
Title: Insert data from sql file when call hook_schema on drupal 7
I developed a module in drupal 7 that need a database table like "example\_table". And i create "example\_table" table using example\_schema() function. Now I need to insert some default data.

Here, I can use `drupal_write_record('example_table', $data);` function to insert data into `example_install()` function.

But, I want to insert data from example\_db.sql file.

How can I do it? Any Suggestions?

# Answer
> 0 votes
You can try this, hope it helps.

```
$db = new PDO($dsn, $user, $password);
$sql = file_get_contents('file.sql');
$qr = $db->exec($sql);

```

Otherwise try this, but i am also not aware of this correctly,

```
function my_module_install() {
  // Get the contents of the .sql file.
  $sql = file_get_contents(drupal_get_path('module', 'my_module') . '/module.sql');
  // Split into individual statements based on new lines.
  $statements = preg_split('/[\n\r]+/', $sql);
  foreach ($statements as $query) {
    db_query($query);
  }
}

```

---
Tags: database
---