# Question
Title: Combine two content types in one using search api views
I am using search api views for site search.

I have 4 content types `A, B, C and D`.

In the views filter when I expose a content type filter, it display as following on the search page

```
All
A
B
C
D

```

I want to combine the `C and D` content types.

```
All
A
B
Combined

```

Where `Combined` will be a custom text and when click , it should filter the content with Content type `C and D`.

Is it possible with search api or is there any workaround?

# Answer
You have to:

1) allow multiselect for the field; 2) implements hook\_form\_views\_exposed\_form\_alter and edit the filter - replace 2 values on new value and in validate function to replace back.

Example for the simple field:

```
/**
 * implements hook_form_views_exposed_form_alter
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){

        $form['#validate'][] = 'MYMODULE_form_views_exposed_form_validate';

        $form['field_your_field_value']['#multiple'] = false;
        $form['field_your_field_value']['#size'] = 1;
        $options = $form['field_your_field_value']['#options'];
        unset($options[3]);
        unset($options[4]);
        $options['3+4'] = 'name of combine value';
        array_unshift($options, '- ALL -');
        $form['field_your_field_value']['#options'] = $options;
    }
}

/**
 * our validate for  form views-exposed-form-list-your-views
 */
function MYMODULE_form_views_exposed_form_validate($form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){
        if(in_array('3+4', $form_state['input']['field_your_field_value'])){
            form_set_value($form['field_your_field_value'], array(3,4), $form_state);
        }
    }

}

```
> 2 votes

---
Tags: 7, views, search
---


# Question
Title: how to get banner image based on the role?
I want to have a banner in home page which should change according to the logged in user role.How can i achieve this?
I'm trying edit '`page--front.html.twig`'. But i'm not able to fetch logged in users role.How to check user roles inside this twig file?

# Answer
Considering you have created multiple Blocks for individual role from Drupal admin UI.

You can restrict each block role wise.
> 3 votes

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

```
function themename_preprocess_page(&$variables) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['role'] = \Drupal::currentUser()->getRoles();
  }
}

```

Then in your **page--front.html.twig**, example:

```
{% if role == 'administrator' %}
  <p><img src="/sites/default/files/banner/banner.jpg"/></p>
{% elseif role == 'anonymous' %}
  <p><img src="/sites/default/files/banner/banner2.jpg"/></p>
{% endif %}

```

**Note**: If you need to be able to switch these images in the future and the person who maintains the site does not know Twig or FTP, this is the better answer.
> 2 votes

# Answer
You can create the slider as a block and set the permission of that block according to required roles.
> 0 votes

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


# Question
Title: How to implement a node limit per taxonomy term?
I added a `field_limit` to Taxonomy, so that I can add term within "limit" number. Here is a steps that I did:

Question: How to limit the number of nodes to be equal or less the `field_limit`?

# Answer
> 3 votes
You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed in the "blueprint" below.

### Step 1

Use the Views and Views Bulk Operations module to create a view of all nodes that have a specific taxonomy term, in which you add a VBO field to it. Simply include a field like `nid` for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

### Step 2

Create a Rules Component like so:

* Using these Rules Component parameters:

+ a parameter of data type that matches with the data type of your '***Taxonomy with "limit" field***' (probably "integer"), let's assume the parameter has machine name `node_limit`.
    + a parameter that matches with the term reference field as defined in your node's content type, let's assume the parameter has machine name `node_termreference` (which can be either a single value, or it can have multiple values, depending on how you defined it in your content type).
* With a Rules Condition "***Check number of results returned by a VBO view***", whereas:

+ you select the VBO view created in Step 1.
    + you want to check if that number of results is greater or equal to `node_limit` (which is the 1st parameter used by this Rules Component).
* Rules Actions:

+ Set an appropriate Drupal message (that the node limit for that term has been reached already).
    + Remove the term that was entered from the `node_termreference` field (which is the 2nd parameter used by this Rules Component); Which Rules Action to use for doing so depends on how that field is defined, e.g if it is a multi value field, then you should use "remove from list".

### Step 3

Create a custom Rule like so:

* **Rules Events**:
    + Before saving a new node (optionally limited to relevant content types).
    + Before updating an existing node (optionally limited to relevant content types).
* **Rules Conditions**:
    + Entity has field, for the field that refers to your taxonomy term (to make this field available for further processing in your subsequent Rules conditions/actions). More specifically we'll need it (as a token) to specify a value for the `node_termreference` parameter to execute the Rules Component from Step 2 later on.
* **Rules Actions**:
    + Fetch entity by ID, whereas you fetch the taxonomy term entered in the node being created or updated. By doing so, your '***Taxonomy with "limit" field***' will become available as a token in subsequent Rules Actions. More specifically we'll need it (as a token) to specify a value for the `node_limit` parameter to execute the Rules Component from Step 2 later on.
    + Execute the Rules Component from Step 2, by passing that Rules Component the appropriate values for `node_limit` and `node_termreference` to actually perform its logic.

***Done!*** .... ***`only using (popular) contributed modules, with no custom code involved`*** .... All you need is Rules, Views and Views Bulk Operations.

PS: the above is only a blueprint ... Mostly because your question has not sufficient details. E.g you didn't explain how those terms are defined in your content type).

# Answer
> 1 votes
I do not think any contributed module having this feature yet. You need to do little bit customization for this.

You put some condition in hook\_node\_validate to check how much node associated with that node and compare with the limit you have set.

You can use ***function taxonomy\_select\_nodes*** to Return nodes attached to a term across all field instances.

> Limitation :::This function requires taxonomy module to be maintaining its own tables, and will return an empty array if it is not. If using other field storage methods alternatives methods for listing terms will need to be used.

Learn how to add custom validation to an existing Drupal form

# Answer
> 1 votes
I think if you work with node using Node Form, you should use hook\_node\_validate

---
Tags: 7, nodes, taxonomy-terms, hooks
---


# Question
Title: Composer: Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring
When i remove drupal/pathauto or another module contrib composer print: Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.

Why ?

# Answer
> 5 votes
`Composer remove` removes the selected package and its dependancies. However there are, some dependencies like `drupal/core` that shouldn't be removed. For example, if we try to remove `drupal/pathauto` this message would pop up, as `Drupal/pathauto` depends on `drupal/path` core module, and should/can not remove anything from core or any dependencies shared with other packages. You can see in `pathauto.info.yml` file what it depends on.

---
Tags: 8, composer
---


# Question
Title: How to resolve my database connection error when using the Wordpress Migrate module?
I have a Drupal8 site and I've installed the Wordpress Migrate module and it's dependencies for migrating a Wordpress site to Drupal8.

When I start to import the exported XML file from Wordpress, I get this error:

```
The website encountered an unexpected error. Please try again later.

```

When I checked the error messages pages I found this:

> Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: migrate in Drupal\Core\Database\Database::openConnection() (line 361 of /media/mosama/Content/test\_poc/drupal8\_2/core/lib/Drupal/Core/Database/Database.php).

Any solution for this?

# Answer
> 6 votes
Solved! By adding anothe data base configuration with \['migrate'\] in **settings.php** under the default database like this

```
$databases['migrate']['default'] = array (
  'database' => 'NAME',
  'username' => 'USER',
  'password' => 'PASS',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

---
Tags: 8, database, migrations
---


# Question
Title: How to modify if a field is required in a form?
Use case: I have added a required field for users. When user 1 (or an administrator) adds a user, the field should not be required.

Code that doesn't work (in Drupal 8):

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    if (\Drupal::currentUser()->id() == 1) {
      $form['field_fieldname']['#required'] = FALSE; // No effect
      $form['field_fieldname']['widget']['#required'] = FALSE;
    }
  }
}

```

Changing the widget "works", but the validation fails. The solution for Drupal 7 doesn't seem to be usable anymore.

```
$form['field_fieldname'][<lang>][0]['value']['#required'] = FALSE;

```

# Answer
It can be tricky to bybass D8 entity validation scheme in this way. Why don't you just set this field settings as "not required" and then set

```
$form['field_fieldname']['widget'][0]['#required'] = TRUE

```

when

```
\Drupal::currentUser()->id() != 1

```
> 4 votes

---
Tags: 8, forms
---


# Question
Title: Failed opening required" symfony/class-loader/ApcClassLoader.php on line 110
I get this error after installing a module in modules/contrib and then uninstalling and moving it to a different directory. I accidentally installed the module in the wrong place.

This is in a local BLT/Drupal-VM environment. I've tried `drush cr` and rebuilding the drupal core directory as well as nuking the vendor folder that composer installs.

Seems that the paths to the installed modules gets stored in PHP memory some how and after the move php is not picking up the changes.

Restarting apache doesn't do anything either.

# Answer
> 16 votes
Restarting php from within the VM seems to have done the trick.

`sudo service php5.6-fpm restart`

---
Tags: 8, caching
---


# Question
Title: How to programmatically update the allowed values of a list field?
I have created a select list for a Profile2 account in Drupal 7. In the allowed values list, I have added some values. Now what I would like to do is programmatically update the values in that list (add, delete or update). I don't want to use form\_alter as I want these updates committed to the database. My problem is I can't seem to find where these values are stored in the database or how to pull those values from Profile2, update them and then save them.

I have Googled high and low on this particular issue and can't find an answer on how to do this. I hope someone can help me out.

Thanks.

# Answer
> 23 votes
Something along the lines of...

```
// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);

```

# Answer
> 3 votes
You'd better use the `allowed_values_function` with a callback:

```
'settings' => array(
  'allowed_values' => array(),
  'allowed_values_function' => '_my_feature_module_options_list',
),

```

See Creating dynamic allowed values options for an entity field.

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


# Question
Title: How to display multiple default items for field collection with unlimited cardinality?
I have used following code and it works fine i.e 3 items are displayed, but the issue in my code is add another item button remains inactive on click.

```
<?php

function two_form_alter(&$form, $form_state, $form_id) {

  if($form_id == 'product_culinary_node_form') {
    $field_language = $form['field_tabs']['#language'];
    $items_count = 3;

    $field_name = 'field_tabs';
    $form_theme = $form[$field_name][$field_language]['#theme'];

    // Remove delete and add more buttons
    // $form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
    $form[$field_name][$field_language]['add_more']['#access'] = TRUE;

    $items = &$form_state['field'][$field_name][$field_language];

    // Generate required number of fields collection
    if ($items_count > 1 && $items['items_count'] != $items_count) {
      $items['items_count'] = $items_count;

      // $items['field']['cardinality'] = $items_count;
      $wrapper = $form[$field_name][$field_language]['add_more']['#ajax']['wrapper'];
      $field_parents = $form[$field_name][$field_language]['#field_parents'];
      $language = $form[$field_name][$field_language]['#language'];
      $after_build = $form[$field_name][$field_language]['#after_build'];
      $form[$field_name][$field_language] = field_multiple_value_form($items['field'], $items['instance'], $field_language, array(), $form, $form_state);
      // Reset theme function, as field_multiple_value_form hijacks it
      $form[$field_name][$field_language]['#theme'] = $form_theme;
      $form[$field_name][$field_language]['#after_build'] = $after_build;
      $form[$field_name][$field_language]['#language'] = $language;
      $form[$field_name][$field_language]['#field_parents'] = $field_parents;
      $form[$field_name][$field_language]['add_more']['#ajax']['wrapper'] = $wrapper;
    }
  }
}

```

# Answer
1 solution to this is https://www.drupal.org/node/1337804#comment-6326678. I will post another solution if found without form rebuild.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Field-Group Tabs not displaying on product page
I'm trying to display a handful of fields as tabs on my product detail pages, but it seems that the field-group tabs are being completely ignored by the Commerce product display. Anyone else have this problem? Did I miss something in the tab setup/display?

The fields display as any other field for the Product, just output as regularly expected. As mentioned, just seems to ignore the 'tabs' display.

# Answer
Kind of late to the party, but I ran into this same problem earlier today and it appears to be caused by the fact that the Field Group module hardcodes the entity types that it latches onto.

The 1.x-dev version now includes a `HOOK_field_group_content_element_keys_alter()` that you can use to expose any entity type to the Field Group module.

To expose products and product variations you need to create a custom module and hook into the above alter function like this

```
MYMODULE_field_group_content_element_keys_alter(&$keys) {

  if (!isset($keys['commerce_product_variation'])) {
    $keys['commerce_product_variation'] = 'product_variation';
  }

  if (!isset($keys['commerce_product'])) {
    $keys['commerce_product'] = 'product';
  }

}

```

Hopefully this will be integrated into Drupal Commerce in the near future, but for now this is the only way.

*Edit* You can read up on the actual issue here https://www.drupal.org/node/2842280
> 0 votes

---
Tags: 8, commerce, entities
---


title: Timeformat timelineview Bat module

text:
# Question
Title: Timeformat timelineview Bat module
I had a reservations system with the .bat module. But I want to change the timeformat in my timelineview from am/pm to 24hours time notation. I have been looking in batfullcalander and the library of fullcalendar and fullcalanderscheduler. Can someone help me out with this?

# Answer
To change the timeformat I had to change TimeFormat from .replace(':m', ':mm') to .replace('h', 'HH') in fullcalendar.js
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Restriction on specific content types for admin content page filter
I need help with removing a content type from admin/content page's content type filter in D8.

Let's say I have content type1, content type2 and content type3.

I want to have an exposed filter in admin/content page for content type1 and content type3.

Thanks in advance.

# Answer
> 3 votes
Just go to the /admin/structure/views/view/content and edit the Content: Content type (exposed) filter in the "Filter Criteria Tab" of your view.

Then just select your type1 and type 2.

---
Tags: 8, views
---


# Question
Title: How to add an action button to item of content type page?
I have a page which shows the details of an **Event** content type item. I added in my second sidebar a block which content a button. Here is a screenprint of what I have so far:

I want to use this button to update the status of the item (a field with machine name "`field_event_status`"). Before the validation I want to show a confirm popup.

Any help to get this to work?

# Answer
It appears to me that you should start with using the Flag module, with a so called "global" flag. And configure your flag so that it would show an appropriate "confirmation" whenever such node gets flagged.

Next you could use the Rules module and create a custom rule like so:

* **Rules Event**: A node has been flagged, under "Some flag" (= the flag's label).
* **Rules Condition**: Entity has field (related to your `field_event_status` field), to make it available for further processing in subsequent Rules Events and/or Rules Actions.
* **Rules Action**: Set a data value (related to your `field_event_status` field).

With that you have the mechanics (logic) in place, and the only think left is theming the flag link(s) to have them shown as buttons. If you wonder how to make that happen also, then have a look at my answer to "How to add a custom icon or symbol to a flag link?" (i.e. the **Option 2** part of it).

### Tutorials

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the Flag module. Especially these tutorials from it:

### More info

Refer to Flag's Community documentation for (way) more details.
> 2 votes

---
Tags: 7, views, theming, nodes, rules
---


# Question
Title: How to get the view fields in rows in the word document generated using Views data export module?
I am using Views data export module (version 7.x-3.1) to download content in Microsoft Word Format.

I am able to download the content but the fields of the view are coming out in columns rather than rows.

Please guide.

# Answer
As an alternative to using the Views data export module, you may want to use the Forena module (disclosure: I'm a co-maintainer of it) to create a "report" that includes the data that you're interesting in (i.e. the "content" as in your question). As part of the report design, indicate which export formats you want to allow for exporting the data included in it. **DOC** (for MS Word) is one of the typical formats that are supported (apart from CSV, XML, HTML, etc). By using Forena, the layout of the exported table (in your MS Word doc) would ***not*** be "*coming out in columns rather than rows*" (as in your question).

Have a look at the Simple Table of States example, and think of it as the equivalent of your "posts that you want to export". And note the hyperlinks in the upper right, which are:

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.

### Forena versus Views

Forena can be used together with the Views module, or as an alternative to it, more specifically:

* As an ***alternative*** to Views, to create reports (and derivatives such as charts and/or exports of data) which you cannot, or not easily, create with only Views. E.g. to pivot data, where you want to create tables in the format of what in Forena is called "Render a report in FrxCrosstab format".
* ***Integrated*** with Views, as explained in the Forena tutorial pages, i.e.:

> Using the Forena integration with the Views module, it is possible to use Forena reports as a views row style, so that in a view you can use the Forena templating engine to do the formatting. Although this can be done through the views templating engine Forena users may find they have more control with this engine.
> 3 votes

---
Tags: 7, views, importing-exporting
---


# Question
Title: How can I hide menu items based on permissions?
In my main menu I have a "menu item 1" that links to mynode1.

I have successfully implemented `hook_permission()` and `hook_node_access()` so that users who do not have the "access menu item 1" permission cannot access mynode1.

I assumed that the menu item link "menu item 1" would automatically be hidden by Drupal, but this is not the case. Therefore I now would like to hide that menu item to users who do not have "access menu item 1" permission.

Does anyone have a code sample that would hide a menu link based on permission? (I tried `hook_menu_alter()` with no luck.)

# Answer
> 1 votes
Hi have done it this way:

```
function mymodule_menu_link_alter(&$item)
 {
  $item['options']['alter'] = TRUE;
 }

function mymodule_translated_menu_link_alter(&$item, $map)
 {

  if (!empty($item['access'])) {

  if(
   ( $item['link_title']=="MyLinkToHide1" && !user_access("access link 1") ) ||
   ( $item['link_title']=="MyLinkToHide2" && !user_access("access link 2") )

   )
   {
            $item['access'] = FALSE;
   }

 }
}

```

# Answer
> 0 votes
I think the best way to hide the menu items according to permissions is to use `hook_menu_link_alter` and set `$item['hidden'] = 1;` if `user_access` returns false.

**Resources**

1. user\_access
2. hook\_menu\_link\_alter

# Answer
> 0 votes
There is the Menu item visibility module.

> This module exposes configurable and extendable visibility settings for menu links. For example, if you want to create a 'My account' link that points to /user, both anonymous and registered users have access to the /user path, so both will see the link, even if anonymous users do not technically have an account. Using this module will allow you to only have your 'My account' link visible to registered users, and hide it from anonymous users.

---
Tags: routes, users
---


# Question
Title: Views table output change row into column
In Drupal 7, I have Views table-output like this:

```
+--------+----------+--------+
| Tool   | Status   | Number |
+--------+----------+--------+
| Hammer | Broken   | 3      |
| Hammer | Borrowed | 10     |
+--------+----------+--------+

```

I want to change the output into:

```
+--------+--------+----------+
| Tool   | Broken | Borrowed |
+--------+--------+----------+
| Hammer | 3      | 10       |
+--------+--------+----------+

```

Is this possible? I prefer without custom coding.

# Answer
Use views template, In `advanced` section, there is an option for theming - `Theme:Information`. Choose template from there or simply use `views-view-table--yourviewname.tpl.php`.

debug your rows here and add css classes to customize the output as per you want.

Take below code as a reference.

```
<?php
/**
 * @file
 * Template to display a view as a table.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $header: An array of header labels keyed by field id.
 * - $caption: The caption for this table. May be empty.
 * - $header_classes: An array of header classes keyed by field id.
 * - $fields: An array of CSS IDs to use for each field id.
 * - $classes: A class or classes to apply to the table, based on settings.
 * - $row_classes: An array of classes to apply to each row, indexed by row
 *   number. This matches the index in $rows.
 * - $rows: An array of row items. Each row is an array of content.
 *   $rows are keyed by row number, fields within rows are keyed by field ID.
 * - $field_classes: An array of classes to apply to each field, indexed by
 *   field id, then row number. This matches the index in $rows.
 * @ingroup views_templates
 */
$i = 0;
$cnt = count($rows);
?>

<?php foreach ($rows as $row_count => $row): ?>
    <div class="col-md-3 col-sm-3 col-xs-12">
        <div class="bod-item">
        <div class="member-wrapper" id="<?php print $row_count; ?>">
            <?php
            $url = $row['field_profile_image'];
            ?>

        </div>
    </div>
    </div>
<?php endforeach; ?>

```
> 1 votes

# Answer
I think I managed to solve this, using these modules: views\_php and views\_aggregator.

With option **use aggregation ON** and using views\_php, I create two **Global PHP Fields** which utilize `$data` variable.

Then, using views\_aggregator table format, I apply **Group Function** to the Global PHP Fields above.
> 0 votes

# Answer
IMO there is no **easy** solution to create such kind of view using the Views module. The previous answers seem to somehow confirm this.

However the Forena module (disclosure: I'm a co-maintainer) can be used for this type of reporting. More specifically by using its facility to create a Display of a table in ***crosstab*** format.

A ***crosstab*** table is a table with a special layout. It is formatted as a grid, with:

* the **rows** representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), etc.
* the **columns** representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
* the **intersections of rows and columns** containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) **include a hyperlink to a drill-down report**.

Below is a sample of a ***crosstab*** report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).
> 0 votes

---
Tags: 7, views
---


# Question
Title: File management- preventing the deletion of files referenced by nodes
I'm not a Drupal user normally but a client wants to move from a 200 page flat file site managed in DreamWeaver to a Drupal site.

Issue is that their secretarial staff who have been managing the site in DW want Drupal 8 to warn them before they delete a media file referenced by Drupal nodes. This is for them primarily images and PDFs which they intend to add to the server via FTP.

Can anyone direct me to a module that provides either that warning functionality or a list of nodes referencing media and PDF files?

# Answer
> 6 votes
> This is for them primarily images and PDFs which they intend to add to the server via FTP.

No... I would advise installing the Media Entity and set of modules designed for handling media.

This will allow you to add media in a way that has better treatment than core. You will be able to:

* Use one file in multiple places without uploading it again
* Build displays based around media, if you need to
* Add a button in CKEditor for referencing or uploading new media

If you only upload files in an FTP, you *can't* do basic things, like:

* Resize an image with an image style
* See how many times / where an image or file is being used
* Generate different displays for different files
* Create Views based around media which may be mixed with access grants later on (spitballing)

Core upload fields, or FTP copying, will not grant you anything - and giving non technical people access to FTP instead of a GUI backend like Drupal is far more error prone.

Also, there is a known core issue where files can be deleted without warning, and it is suggested to set the core file system setting of "Delete orphaned files after.." to "**Never**". No matter how you choose to approach media management, change this setting ASAP until it is fixed.

One of the major benefits of moving from a static setup to Drupal 8 are for reasons like this.

# Answer
> 1 votes
Drupal provides a huge number of excellent features, but managing your FTP interaction with the server is not one of them.

When moving an organization from DreamWeaver to Drupal (or any good CMS for that matter) you need to have a real change strategy that helps them understand they can't just keep doing what they do now. They need to totally interact with Drupal in the ways you setup for them, and not try to bring over any of their existing tools or habits. Even when that is possible it will cause more problems than it solves because they don't embrace the change, and value, of the CMS.

Drupal 8 core does track files that uploaded through fields or CKEditor so it can clean up when they are no longer referenced. You can also add the editor file module to provide a good single file linking field (instead of uploading through imce and using an interface optimized for images). The Editor Advanced Link module also provides some useful extensions.

---
Tags: 8, files, media
---


# Question
Title: Search index stuck at 0%, mysql error on public search, can't clear error
I have just discovered that the Drupal 7 search on my website is giving 'website encountered an unexpected error. Please try again later.' to users who are not logged in. (it's fine for logged in users.)

Checking the logs, I can see that when a non-logged in user runs a search it causes a mySQL error, which looked like there was a problem because I'd excluded content type admin\_only\_help from public search.

OK, I'll include that content type in search. Nope, still the same error. OK, re-index the search: nope, won't re-index the search, stalls at 0%.

I tried:

* setting content type admin\_only\_help to be indexed.
* unpublishing all nodes of content type admin\_only\_help
* re-indexing the search from the admin panel (it stalls)
* running drush search-index from the command line (it stalls)
* turning off the Custom Search module
* clearing cache (after all of the above).

I'd be very grateful for any further suggestions.

The exact error from my logs is:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have
an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE (c.nid = '873') AND
(c.status = '1') AND (n.type <> 'admin_only_help')' at line 2: SELECT COUNT(*)
AS expression FROM {comment} c INNER JOIN {node} n ON n.nid = .nid WHERE
(c.nid = :db_condition_placeholder_0) AND (c.status =
:db_condition_placeholder_1) AND (n.type <> :db_condition_placeholder_2) ;
Array ( [:db_condition_placeholder_0] => 873 [:db_condition_placeholder_1] =>
1 [:db_condition_placeholder_2] => admin_only_help ) in PagerDefault-
>execute() (line 74 of /home/mysite/public_html/includes/pager.inc).

```

Edit with update: I tried completely removing the problem content-type admin\_only\_help and completely removing the two nodes that belonged to that content type.

Now I have this error:

```
SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'WHERE (c.nid = '421') AND (c.status = '1')' at line 2: SELECT COUNT(*) AS expression
FROM {comment} c INNER JOIN {node} n ON n.nid = .nid WHERE (c.nid = :db_condition_placeholder_0)
AND (c.status = :db_condition_placeholder_1) ;
Array ( [:db_condition_placeholder_0] => 421 [:db_condition_placeholder_1] => 1 ) in PagerDefault->execute()
(line 74 of /home/mysite/public_html/includes/pager.inc).

```

And I still can't re-index my database.

# Answer
> 0 votes
I have traced this particular problem to the Node View Permissions Module. Disabling this module allowed my search to re-index and be seen by users who are not logged in.

There is a patch available here : https://www.drupal.org/node/2564273

---
Tags: 7, search
---


# Question
Title: Memory size exhausted when trying to run cron manually
On my Drupal 6 website, when I run manually cron, I get this error message.

> Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4181580 bytes) in /dirname/includes/database.mysql-common.inc on line 34

Cron is set to automatically run every night; the last few days it wasn't running, so I tried it manually.

Where should I increase memory, in the settings.php file, in the php.ini file for PHP, or somewhere else? I'm using AWS RDS and EC2 instances.

I have this line in the settings.php file.

```
ini_set('memory_limit', '128M');

```

# Answer
> 1 votes
All you need to do is increase your PHP Memory Limit from 128M to 265M, for example adding the following line in the *settings.php* file.

```
ini_set('memory_limit', '256M')

```

For more information on other ways to change it, see Changing PHP memory limits.

---
Tags: 6, cron
---


# Question
Title: How to unblock my own admin account after 5 failed login attempts?
I entered the wrong admin password more than 5 times, so Drupal has blocked my entry.

I've change the user password directly in MySQL and then tried to login, but is still doesn't work. Also, if I click the request new password link, I don't get an e-mail.

How can I unblock my account?

# Answer
To answer the question in your title (which appears to become more complicated following your actual question), you just need to clear the `flood` table in your database. If you're running Drush, then the following should sort you out:

> drush php-eval 'db\_query("DELETE FROM `flood`");'

Failing that, just clear the `flood` table from your database manually :)
> 19 votes

# Answer
Clearing the flood table will give the OP another 5 tries guessing the password. (And if he has messed with the password field directly in MySQL, the passord field may have become munged and therefore useless.)

Clearing the flood table will not allow him to login as admin, which is what I assume the OP actually want to do.

However, there are a couple of other drush commands that may be handy. The first will produce a one time password reset link for uid 1, the second sets a new password for user `admin`:

```
drush uli
drush upwd admin --password="newpassword"

```
> 8 votes

# Answer
If you are not much experienced with Drush kind of stuff, you can run the following sql in your phpmyadmin

```
DELETE FROM flood;

```

The same error can be happened if you tried same user name with 5 or more times
> 6 votes

# Answer
Much better solution, which is noticeably absent from other posts about this:

`drush user-unblock {username}`

https://drushcommands.com/drush-7x/user/user-unblock/

EDIT: this still doesn't clear the 'flood' table, unfortunately, which is dumb. As others have mentioned, to actually enable login after `drush user-unblock` in the case of a user being blocked by too many login attempts, you have to get into the database and truncate (dump all data from) the 'flood' table.

As others have mentioned when asking this question, this seems problematic in a production environment.

As usual, someone has already made a module that adds drush commands to clear out the flood table: https://www.drupal.org/project/flood\_unblock
> 6 votes

# Answer
Just truncate the table flood

> Truncate flood;
> 2 votes

---
Tags: users
---


title: How to override twig templates

text:
# Question
Title: How to override twig templates
I'm having a bit of a hard time with Drupal 8.

I've created a custom theme and am trying to override twig files. I've got debugging enabled so I know which files to copy to my template directory. However, when I copy a twig template it outputs nothing.

For example, I'm trying to wrap the site title in an `H1` element. The core template file used in this case is /core/themes/stable/templates/block/block--system-branding-block.html.twig. If I add the `H1` element in that file the header is inside a `H1` element, but when I copy the twig file to my template directory the whole header is gone.

I can see in the source code that the file was found:

```
<!--  BEGIN OUTPUT from 'themes/mytheme/block--system-branding-block.html.twig' -->
<!--  END OUTPUT from 'themes/mytheme/block--system-branding-block.html.twig' -->

```

The documentation suggests that copying the relevant twig file is all that's needed but maybe I'm missing something? And if this should work, how can I debug this issue (the Apache error log doesn't report any errors).

# Answer
> 2 votes
Yes, to override twig file you just need to have the twig file with filename suggestion you get with debugger.

In case you are not able to see it, make sure of following:-

* Your custom theme is enabled.
* Folder where you kept your twig file has right permission.
* Clear your Drupal caches.

---
Tags: theming, 8
---


# Question
Title: Password request redirect to another page
I click on forgot password page

it redirect me to **http://example.com/user/password** which is fine

now when i enter email id . it redirect me to

**"http//example.com/user \*/**. I want it to redirect another page

**http://example.com/request-access**

Any idea?

Thanks

# Answer
You can add your own submit handler to the form :

```
function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_reset') {
    $form['#submit'][] = 'CUSTOM_form_submit';
  }
}

function CUSTOM_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'request-access';
}

```
> 4 votes

# Answer
I'm not sure if this is within the feature set of the LoginToboggan module, but you may want to give it a try since at least similar features are on the featre list:

> 7. Optionally redirect the user to a specific page upon validation of their e-mail address.

and also plays together with Rules:

> 12. Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
> 0 votes

# Answer
I think **Login Destination** module will be helpfull. Just try it. Check https://www.drupal.org/project/login\_destination
> 0 votes

# Answer
To achieve this, I prefer to have a custom trigger which will give freedom to end user to select the page of his choice whenever he/she wants, instead of fiddling with code every time. Use below code to create a custom module and install it in your environment. Once done you will find the trigger in your triggers list.

```
/**
 * Implements hook_trigger_info().
 *
 * Below we have created one trigger for passoword reset which will help user to define an action for it based on the req.
 *
 * The trigger belongs to User group and has a custom created hook called user_password_reset
 *
 * This will appear in the list of triggers
 */

function your_module_trigger_info() {
    return array(
            'user' => array(
                    'user_password_reset' => array(
                            'label' => t('After password reset'),
                    ),
            ),
    );
}

/**
 *
 * @param  $form Form data
 * @param  $form_state
 * @param  $form_id
 *
 * Implemtents hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)
 *
 * This is used to call our trigger event on password reset request form submit
 */

function your_module_form_user_pass_alter( &$form, &$form_state, $form_id) {
    $form['#submit'][] = 'your_module_user_password_reset';
}

/**
 *  Custom function your_module_user_password_reset()
 *
 *  This will execute actions assigned to the trigger.
 */

function your_module_user_password_reset() {
    $aids = trigger_get_assigned_actions('user_password_reset');

    $context = array(
            'group' => 'user',
            'hook' => 'user_password_reset',
    );

    actions_do(array_keys($aids), (object) $options, $context);
}

```

Please let me know if you find any issues with it.

Thanks!!
> 0 votes

# Answer
If you want to close all the sessions after reset password, you can play with Rules and hybridauth modules.

Steps:

1. Install the module and configure it.
2. Add a rule "Logout after password update" or whatever name you want to give here.
3. Select event "After updating an existing user account" .
4. Once you select an event you will have to add conditions and actions based on which your rule works. Add a condition "Execute php code".
5. Now a page will get opened where you can add your one liner php code.

return $account\_unchanged-\>pass != $account-\>pass;

save it and go back to your rules page.

6. Add an action "Destroy session" and you are done.
> -1 votes

---
Tags: 7, rules, users
---


title: Reordering login form components

text:
# Question
Title: Reordering login form components
I am using the very helpful hybridAuth module to allow people to login with their social media accounts.

However, the login form shows up as shown below:

Looks a bit confusing, doesn't it?

**I want to move the social media login button either to the top or bottom and create distinction with the actual login form**

The form structure displayed at the top of the page is from **hook\_form\_alter** but I saw no obvious way to manipulate the form to achieve the desired effect.

I implemented the following code in an attempt to get my hook\_form\_alter to execute after hybridAuths' and perhaps find a way to reorder the form:

```
function mymodule_module_implements_alter(&$implementations, $hook){
    if($hook == 'form_alter '){
        dsm($hook, 'Hook');
        dsm($implementations, 'Implementations - form-alter');

        $group = $implementations['mymodule'];
        unset($implementations['mymodule']);
        $implementations['mymodule'] = $group;

        dsm($implementations, 'Implementations #2 - form-alter');
    }
}

```

However, my debug dsm code does not show up on my **user/login** page even though there is a form and **hook\_form\_alter** does respond to it on the same page.

Can anyone suggest something that might help, please?

# Answer
> 2 votes
HybridAuth module can make the block for this icons then you can place that icons block top of the main content block. it will show top of the login form

# Answer
> 2 votes
You can alter the form and check \['#weight'\] for reordering form element.

---
Tags: 7, hooks, forms
---


# Question
Title: Custom block is not visible to anonymous users
I have created 2 blocks from my custom module; those blocks mainly collect and show data from the recent content of sub-domain.
So, in these blocks I have pulled data using `db_query()` from another database using `db_set_active('another_db')`.

All works fine.

My problem is that those blocks show to logged-in users only, and I want to show those blocks for all users.

I can't figure it out.

This is the code I am using.

```
function myblocks_block_info() {
  $blocks['latest_products'] = array(
    'info' => t('Latest Product'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function myblocks_theme() {
  return array(
    'grid_list_view' => array(
      'variables' => array('items' => NULL),
      'template'  => 'grid_list_view',
    )
  );
}

function myblocks_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'latest_products':
      // Create your block content here
      $block['subject'] = t('Latest Products');

      $block_categories_data = "";

      // Connect Electronics Database.
        db_set_active('another_db');
        $block_terms_id = array('76','83','42');

        for ($i=0; $i<count($block_terms_id); $i++) {
          $sql = 'SELECT DISTINCT node_taxonomy_term_data.nid AS node_taxonomy_term_data_nid
                    FROM
                    {taxonomy_term_data} taxonomy_term_data
                    LEFT JOIN {node} node_taxonomy_term_data ON (SELECT nodeINNER.nid AS nidINNER
                    FROM
                    {node} nodeINNER
                    LEFT JOIN {taxonomy_index} taxonomy_indexINNER ON nodeINNER.nid = taxonomy_indexINNER.nid
                    LEFT JOIN {taxonomy_term_data} taxonomy_term_data_nodeINNER ON taxonomy_indexINNER.tid = taxonomy_term_data_nodeINNER.tid
                    WHERE (( (taxonomy_term_data_nodeINNER.tid = taxonomy_term_data.tid ) ))
                    ORDER BY nodeINNER.nid DESC
                    LIMIT 1 OFFSET 0) = node_taxonomy_term_data.nid
                    INNER JOIN {field_data_field_pks_category} node_taxonomy_term_data__field_data_field_pks_category ON node_taxonomy_term_data.nid = node_taxonomy_term_data__field_data_field_pks_category.entity_id AND node_taxonomy_term_data__field_data_field_pks_category.entity_type = \'node\'
                    INNER JOIN {field_data_field_pks_sold_out} node_taxonomy_term_data__field_data_field_pks_sold_out ON node_taxonomy_term_data.nid = node_taxonomy_term_data__field_data_field_pks_sold_out.entity_id AND node_taxonomy_term_data__field_data_field_pks_sold_out.entity_type = \'node\'
                    WHERE (( (node_taxonomy_term_data.type IN  (\'pk_service\')) AND (node_taxonomy_term_data__field_data_field_pks_category.field_pks_category_tid = '. $block_terms_id[$i] .') AND (node_taxonomy_term_data.status = \'1\') AND (node_taxonomy_term_data__field_data_field_pks_sold_out.field_pks_sold_out_value = \'0\') ))
                    LIMIT 3 OFFSET 0';

            $result = db_query($sql);

            $rows = array();

            foreach ($result as $data) {
              // Collect All Fields Data from NID.
              $node = node_load($data->node_taxonomy_term_data_nid);
              $image_name = $node->field_pks_image['und'][0]['filename'];
              $path = drupal_get_path_alias('node/'. $node->nid);
              $category_name = taxonomy_term_load($node->field_pks_category['und'][0]['tid']);
              $category_path = strtolower(preg_replace('/[^a-zA-Z0-9-]+/', '-', $category_name->name));

              $rows[] = array(
                'title' => $node->title,
                'category_path' => $category_path,
                'category_name' => $category_name->name,
                'image_name' => $image_name,
                'path' => $path
              );
            }

            // Block Content.
            if (!empty($rows)) {
              $block_categories_data .= theme('grid_list_view', array('rows' => $rows));
            }
            else {
             // dpm($rows);
            }
        }

        // Block Content.
        $block['content'] = $block_categories_data;

        // Main DB Connect Again.
        db_set_active();
        break;
    }

    return $block;
}

```

# Answer
> 0 votes
Replace this theme

```
$block_categories_data .= theme('grid_list_view', array('rows' => $rows));

```

with add direct html code here, like -

```
$block_categories_data .= '<div>my html element goes here.</div>';

```

---
Tags: 7, blocks
---


title: user permission and roles

text:
# Question
Title: user permission and roles
I'm very beginning to the Drupal. I created on role from my admin part, I need to access the roles with some permissions like i listed below.

My concept is ticket raising system in various categories. As an admin I assign some ticket to some roles(user), now how to give permissions to assign roles(user)?

Also, the assigned user have to do action what they have to do, but they don't have permission to access admin part. How to give permission to the user to do the reply?

# Answer
You can set permissions to users under permissions tab of people module in admin .Please check below screenshot.Hope it helps
> 1 votes

---
Tags: 7, users
---


# Question
Title: Change site logo for specific content type and page
How to add different logo images for specific content type and page. It want to be dynamic.When user add content, user want to select logo

# Answer
> 3 votes
create multiple custom blocks with logo image and display with page the page you need.

# Answer
> 9 votes
Do not know weather this method fulfill the requirements but you can take a look. As Drupal 8 creates a block for logo. You can create separate block for each content type and depends on visibility condition you can show.

# Answer
> 5 votes
Create a dynamic View Block and use that as your logo block.

1. Add image field to your content type
2. Create a View Block in `/admin/structure/views/add`

4. In View, for Fields, add your Image
5. **Click on Advanced** (far right), for Contextual Filter add `ID` .Provide default value, Content ID from URL. (**Note:** The view preview will go blank, which is normal, since the View edit page does not have a Content ID.)

6. Go to blocks (`/admin/structure/block`), and add the View block to a region. For Visibility settings select the content type that you want this to appear in.

# Answer
> 1 votes
Add your logo field to your specfied content type, then create a custom page template for that specified content type, get and add logo field URL to page template variables and use it on page twig file.

if you want more details tell me I provide it for you.

---
Tags: theming, 8
---


# Question
Title: "Allow multiple selection" not available in exposed filters
I'm having trouble making some options appear as checkboxes in an exposed view form. The problem is that the "Allow multiple selection" option is not available in the filter.

How can i make it visible. "Allow multiple selection" option.

# Answer
> 0 votes
You can go for Better Exposed Filters module.

> The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.

# Answer
> -1 votes
You Can use the Better Exposed Filters for the filters. Follow the Screenshots

---
Tags: views
---


# Question
Title: How to remove empty div created by routing.yml file by specified routes?
I have 2 routes

```
games.one:
  path: '/math/one'
  defaults:
    _controller: '\Drupal\games\Controller\GamesController::one'
    _title: 'My Title'
  requirements:
    _permission: 'access content'

games.two:
  path: '/math/two'
  defaults:
    _controller: '\Drupal\games\Controller\GamesController::two'
  requirements:
    _permission: 'access content'

```

Route `games.one` has `_title` and Route `games.two` does not have. Now the issue is When I access route game.two, It shows an empty div for title.

**How to remove this empty div?**

# Answer
You can do this by overriding the page.html.twig for that page and stripping out the title.

To override the template for that specific page you should probably alter the hook suggestions:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getRouteName() == 'games.two') {
    $suggestions[] = 'page__no_title';
  }
}

```

Now you can copy the page.html.twig template to your theme folder, rename it to page--no-title.html.twig and strip out the title tag.

Hope this helps
> 3 votes

---
Tags: 8, routes
---


# Question
Title: How do I hide the page title based on node type using template_preprocess_page()?
In Drupal 7, this was possible. (See How to hide page title based on node type using template\_preprocess\_page().)

```
function MYTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'concert') {
    $variables['show_title'] = FALSE;
  }
}

```

What is the equivalent in Drupal 8?

# Answer
> 5 votes
**OUTDATED - please use this solution instead ...**

In D8 i used

```
function MYTHEME_preprocess_page(&$variables) {
    if (!empty($variables['node']) && $variables['node']->getType() == 'page') {
        $variables['title'] = '';
    }
}

```

You still find the "node" object but you can't simply call the "type". The variable is protected, so you have to get the value via the function getType(). To get an overview install Devel and print with Kint the methods. This should only be a simple help, but maybe someone can deeper explain the concepts. Is it better to unset $variables\['title'\] in some way then to use $variables\['title'\] = ''?

# Answer
> 3 votes
Similar to @joekers it was not working for me either and had to use `theme_preprocess_page_title()` here is the details. Put this in your `MY_THEME.theme` file or modify that function if it already exists.

```
function MYTHEME_preprocess_page_title(&$variables) {
    $node = \Drupal::routeMatch()->getParameter('node');
    if( $node->getType() == 'page' ) {
        $variables['title'] = "";
    }
}

```

To use it you might have to substitute the variable `page` with your content type machine name.

# Answer
> 0 votes
For some reason this wasn't working for me in `theme_preprocess_page()` so I had to use `theme_preprocess_page_title()` as suggested by Twig debug.

---
Tags: theming, 8
---


title: How to put icon in field label?

text:
# Question
Title: How to put icon in field label?
Is it possible to add an icon in front of a field name?

I have a field name called Tel and would like to put a phone icon in front of it?

I've searched for a while and can't seem to find an answer to this.

# Answer
Use Font Awesome classes to add the icons for the field label.
> 0 votes

---
Tags: entities
---


title: Simplesamlphp behind reverse proxy

text:
# Question
Title: Simplesamlphp behind reverse proxy
I have configured my application and simplesamlphp behind reverse proxy. I have created a test SP But when I am going to test the SP, it redirects to https://web-server-ip/adfs/ls/?SAMLRequest=nZL instead of redirecting to ADFS server url https://adfs.server.com/adfs/ls/?SAMLRequest=nZL

I have changed the baseurlpath in config.php to "https://web-server-ip/simplesaml/". But still same error.

SP is working with App server. If I am trying to test the SP using https://app-server-ip/simplesaml, it redirects to ADFS server login.

But no luck via web server.

Please suggest any solution.

# Answer
> 0 votes
In my case it was the the problem of reverse proxy. It is fixed now.

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


title: Access denied on register form

text:
# Question
Title: Access denied on register form
I wanted to edit my register menu link so I could show the registration link in the menu account only for anonymous user (not logged in users). But when I try to edit the register menu link the following error occurs:

> Access denied
>
> `Home >> Administration >> Structure >> Menus`
>
> You are not authorized to access this page.

The link I'm trying to access supossedly

> localhost/admin/structure/menu/item/8/edit?destination=/admin/structure/menu/manage/account

PS: I created a new registration form and in that one I could edit and show the the link in users menu only not logged in users but in this one I can't access even I have an admin role.

Log message:

# Answer
Since nobody told me an answer, I figure a way to bypass the error, creating other menu link and this time as I wanted when I was creating so I didn't need to edit.

It's not a permanent solution but it's a way to go through.
> 0 votes

# Answer
Please visit to the permission page- /admin/people/permissions page and scroll down to check menu permissions for administrator and allow the checkbox to create and edit menus, check the checkbox for Administrator menus and menu items. It is checked by default, but in your case you can verify it. Also I have seen your localhost link has a missing foldername, should be like this- localhost/foldername/admin/structure/menu/item/8/edit?destination=/admin/structure/menu/manage/account
> 0 votes

---
Tags: 8, users, navigation
---


# Question
Title: How to resolve my warning in my custom service?
I am getting the following error:

> Warning: Missing argument 1 for Drupal\custom\_forms\Service\CustomFormsService::\__construct(), called in /drupal/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php on line 264 and defined in Drupal\custom\_forms\Service\CustomFormsService-\>\__construct() (line 13 of modules/custom\_forms/src/Service/CustomFormsService.php).

And my code (`service.php`) is:

```
public function __construct($request) {
$this->cityname = \Drupal::request()->get('cityname');

if($this->cityname != ''){
  $result = \Drupal::database()->select('city_municipality','cm')
    ->fields('cm',array('municipality'))
    ->condition('city', $this->cityname)
    ->execute()->fetchAll();
    $result = json_encode($result);
    print $result;
    exit;
 }

```

custom\_forms\_services.yml

```
  services:
       custom_forms.custom_forms_service:
           class: Drupal\custom_forms\Service\CustomFormsService

```

But the form functionalities are working fine.

Can anyone help me out on this?

# Answer
You need to add an argument to your services.yml for the class to be injected:

```
services:
  custom_forms.custom_forms_service:
    class: Drupal\custom_forms\Service\CustomFormsService
    arguments:
      - @request_stack

```

Note that you should make a few changes to your service as well:

First, add an type hint for the argument:

```
public function __construct(\Symfony\Component\HttpFoundation\RequestStack $requestStack) {

```

Next, you will use the `$requestStack` instead of `Drupal::request()`:

```
$this->cityname = $requestStack->getCurrentRequest()->query->get('cityname');

```
> 2 votes

---
Tags: 8, symfony-services
---


# Question
Title: Best way to Improve live site and then push changes from dev to live?
Currently I am applying a new Drupal theme on an existing site. I have created a separate instance for Development and copied the live site database and started working.

The new theme requires many new features ( modules, blocks, views etc ). I am just writing down every thing and of-course I need to redo it on live site once the theming is completed.

Is it possible that my Dev database gets updated automatically if changes are made on live site?

So once the theming is finished, I can drop the live DB and replace with Dev DB? Seems like a dream to me ..

Any help ?

# Answer
> 2 votes
> Is it possible that my dev database gets updated automatically if changes are made on live site ?
>
> So once the theming is finished, i can drop the live DB and replace with Dev one:) Seems like a dream to me ..

Databases shouldn't be migrated up (ie dev -\> prod), only down (ie prod -\> dev). If you migrate a database up, you will overwrite anything new on the production server. For example, any new accounts, comments, pages, or anything else that is in the database.

If you use the Features module, it will allow you to migrate some database settings as code (a features module) that can potentially solve your issue. Or if you are on D8, you can export configuration and import it in the other site.

---
Tags: 7, database
---


# Question
Title: How to add auto create feature to custom taxonomy_term field while creating custom entity
I created a custom module which has an custom entity. I added base field term\_id to it using below code

```
$fields['term_id'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Category'))
    ->setDescription(t('Default Category.'))
    ->setRevisionable(TRUE)
    ->setSetting('target_type', 'taxonomy_term')
    ->setSetting('handler', 'default:taxonomy_term')
    ->setSetting('handler_settings', [
            'target_bundles' => ['question_category' => 'question_category']
        ]
    )
    ->setTranslatable(TRUE)
    ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
    ))
    ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => array(
            'match_operator' => 'CONTAINS',
            'size' => '60',
            'autocomplete_type' => 'tags',
            'placeholder' => '',
        ),
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

```

I have a YAML file taxonomy.vocabulary.question\_category.yml, which create question\_category vocabulary, I can see it in admin too.

But when I try to add a new text in it. I get an error There are no entities matching ||new enitity title||

I want user to create terms and add it to question\_category taxonomy.

Please suggest, what might be the error.

--

Thanks

# Answer
> 2 votes
I did it using below handler setting

setSetting('handler\_settings', \['target\_bundles' =\> \['question\_sub\_category' =\> 'question\_sub\_category'\], **'auto\_create' =\> TRUE**\])

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


# Question
Title: How to create a view that links an image from a field collection item to the field collections host node
I have a custom content type "FH Portfolio" item that contains (among other fields) a Field Collection of "Geoimages". Each Geoimage contains (among other fields) one or more "Portfolio image" fields.

I'm trying to construct a view (block) that displays 3 'featured' FH Portfolio items, showing the first Portfolio Image. On hover, the title of the FH Portfolio item should be displayed. When the image is clicked, it should link to the FH Portfolio item, **not** the Geoimage that has provided the image.

I can get the images displayed correctly, with an Image Hover Effect (using Image Hover Effects module, which relies on a link being wrapped around an image to work)) that displays the title of the relevant FH Portfolio item (by using the token \[host:node:title\] ), but I can't make the image/title link to the FH Portfolio item; is there any way to do this? (I have Image linked to content).

I've tried rewriting the image field as a link going to \[host:node:url\] but that doesn't work. (I've also tried including Content:Path as a field in the view (excluded from display) and rewriting the image field to display a link to \[path\]. That works, but I lose the image hover effect displaying the title.).

# Answer
> 0 votes
Edit the image field and link image to 'content'

Another method:

```
    1. Add the nid field in view.
    2. Edit the image field, Go to the rewrite result and check "Output this field as a link". and put node/[nid] token in it.

```

---
Tags: views, tokens, entities
---


# Question
Title: configuration error directories not present
I am brand new to trying to create a web blog so I am hoping you can help me get started. I haven't been able to find answer online.

My status report has this error.

Configuration directories Not present Your sites/recoverypractices.dd/settings.php file must define the $config\_directories variable as an array containing the names of directories in which configuration files can be found. It must contain a sync key.

I don't know what thes sync key is but I did find a sync folder here D:\Sites\devdesktop\drupal-8.2.5\core\modules\field\tests\modules\field\_test\_config I found the following code in my settings.php file but I don't know exactly how to fill in the array or define the sync key.

* @code
* $config\_directories = array(
* CONFIG\_SYNC\_DIRECTORY =\> '/directory/outside/webroot',
* );
* @endcode \*/

Can you assist me in figuring out how to fix this error?

Thanks, David

# Answer
You can define it in settings.php like so:

```
$config_directories[CONFIG_SYNC_DIRECTORY] = '/../config/sync';

```

This sets the default sync directory outside my webroot.

`CONFIG_SYNC_DIRECTORY` is a constant defined for 'sync'.
> 1 votes

# Answer
Just replacing up this code instead of $config\_directories in settings.php file fixed the issue.

$config\_directories = array( CONFIG\_SYNC\_DIRECTORY =\> 'sites/default/files/config\_acqTmp-2017-02-06T19.38.23-2536', );

I am not sure how much secure this is but now in my status report tab the Configuration files shows **Protected**
> 0 votes

---
Tags: configuration
---


title: Get a list of services programatically

text:
# Question
Title: Get a list of services programatically
I've recently started working with Drupal 8. I'm looking for a way to programatically(no drupal console or other CLI thing) get a list of all the services available.

Since it's built on top of Symfony I figured that the container should have a list of all the available services. Well, I was wrong.

I've searched around and I can't find any specific answers, other than the CLI option, which is not what I'm looking for.

If anybody can point me in the right direction here, I'd be grateful.

# Answer
You can get all services from the container by using the kernel method `getCachedContainerDefinition()`:

```
$container = \Drupal::getContainer();
$kernel = $container->get('kernel');
$services = $kernel->getCachedContainerDefinition()['services'];
foreach ($services as $service_id => $value) {
  $service_definition = unserialize($value);
}

```

Now you can output a list, for example containing the service id and the class name in `$service_definition['class']`.
> 3 votes

# Answer
You can use tags for services and can get list of services with same tag like this. I didn't test this code, but there is a method *findTaggedServiceIds*.

```
services:
  process_text.text_filter:
    class: Drupal\process_text\TextFilterService
    tags:
      - { name: text_filter }

```

In your controller

```
//use Symfony\Component\DependencyInjection\ContainerBuilder;
public function process(ContainerBuilder $container) {
    $taggedServices = $container->findTaggedServiceIds('text_filter');
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Using 'return' with an ajax callback renders an entire page before my content is loaded
I'm developing a module that uses Openlayers maps and Drupal Commerce. When you click on the map, you should see products that relate to those coordinates of where you click. I have this working perfectly.

I've got a 'foreach' inside of my function that creates each product row:

```
foreach($alldata as $data) {
    $content = '';
    $date = substr($data['_source']['ver_date'], -4);
    $content .= '<div class="product-row" data-date="' . $date . '" data-id="' . $id . '" data-scale="' . $data['_source']['scale'] . '">';

    $titleString = '';
    $titleString .= $data['_source']['longname'] . ' ';
    $trimmedTitle = strlen($titleString) > 80 ? substr($titleString,0,80)."..." : $titleString;
    $content .= '<span class="title">' . $trimmedTitle . '</span>';

    $content .= '</div>';
    print $content;
}

```

This works exactly like it should and renders the rows of products exactly like I want.

The problem I am having is that there is an 'Add to Cart' button that was created within another function somewhere else in the site that I have to render in this foreach.

```
$arr = explode(".", $data['_source']['price']);
$inner_html = '<span class="btn-text">$'.$arr[0].' Print</span><span class="glyphicon glyphicon-shopping-cart"></span>';
$add_to_cart_btn = drupal_get_form('myModule_product_cart_button', $inner_html, (object)$data['_source']);
$content .= '<div class="product-cart">' . drupal_render($add_to_cart_btn) . '</div>';

```

The button loses it's Ajax properties when I use 'print $content'. So I changed it to 'return $content' and moved it outside the 'foreach'.

I get all of the content properly as well as a working ajax 'Add to Cart' button. However, I also get the entire page template rendered prior to all of my content that I'm returning.

```
<--- Content Rendered In Div via Ajax --->

Full Empty Page Template
---------------------------
Ajax content formatted properly and working properly

```

I've tried using ajax\_render. I've tried using ajax\_command\_html. I've tried completely redoing my function and ajax to use drupal.behaviors. Nothing is working to remove that full page from rendering prior to my content. It only happens I when use 'return'. I've also tried adding drupal\_page\_footer().

Even when I have absolutely nothing in my foreach, if I use 'return $content', I get a full page rendered. And it's not the use of '$content'. I've changed that to other variable namespaces and it still renders an empty page template.

Here is my ajax call:

```
 $('.products').mousedown(function() {
    $.ajax({
      url: Drupal.settings.myModule.ajaxUrl,
      method: 'post',
      data: {
        longtitle : title,
        id : id
      },
      dataType: "text",
      success: function(data) {
        var markup = '';
        markup += data;

          $('.products-pane').html(markup);

      }
    });
  });

```

Anyone know what is causing this?

# Answer
> 0 votes
You are missing the Drupal settings that include the Ajax settings, which is why the server doesn't know it should be ajaxified. You should (may) be able to fix it by changing this:

```
$content .= '</div>';
print $content;

```

To this:

```
$content .= '</div>';
$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
    $settings .= ');</script>';
}

print $content . $settings;
drupal_exit();

```

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


# Question
Title: How to securely access the data from another Drupal instance?
I have a site setup which feels fairly unconventional so please bare with me while I try to explain.

I have 2 Drupal sites based on different servers.

The main site (site A) contains the front-end site and holds user data. The second site (site B) is our internal system and has 2 databases. This is a standard Drupal db and a db that contains other customer data (e.g. sales information, downloads and product info etc).

When a user logs in to their account on the main site, I need to be able to access information on the second database and display this to the user.

I know I can do this without using Drupal with a mysqli statement. **However, I need to be able to access this information securely via SSL**.

I have very little knowledge of encryption so my initial thought was that if both sites had SSL, the information received would be sent encrypted when using mysqli. However, I think I am very wrong.

My next thought would be to request the information via the second Drupal site perhaps via an API of some sort. However I'm not sure this would offer any more security or if I have missed the point entirely.

Would anyone be able to advise me on the best way access this information please?

# Answer
The easiest way to do this would be to set up a new MySQL user on Server B that had something like: GRANT SELECT ON serverBdata TO 'serverAuser'@'serverA-IP';

Then you can write a module on server A that connects and retrieves that data.

If that's not going to work, you can look at setting up a menu hook on Server B that delivers the data in a sensible way, such as JSON, over HTTPS.

if you wanted to get really fancy, you could also encrypt the JSON.
> 0 votes

---
Tags: 7, database, security
---


# Question
Title: PHPUnit calling external function as object
I'm doing a unit testing with my `CVRClient` file using the code below.

```
//CvrapiTest.php

<?php

namespace Drupal\cvr\test\Cvrapi;

use PHPUnit_Framework_TestCase;
use cvr\src\Cvrapi\CVRClient;

class CvrapiTest extends PHPUnit_Framework_TestCase {

public function testSearchOnlyVAT()
    {
        $result = \Cvrapi\CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');

        $this->assertTrue(property_exists($result, 'vat'));
        $this->assertTrue((int)$result->vat === 29910251);
    }

```

I have a `CVRClient` class under `cvr/src/Cvrapi` folder that queries data from an api.

I know that `phpunit` command is working fine but I'm getting the error below.

> Fatal error: Class 'cvr\src\Cvrapi\CVRClient' not found in /Applications/MAMP/htdocs/query/modules/custom/cvr/test/Cvrapi/CvrapiTest.php on line 17

NOTE: It's the `\Cvrapi\CVRClient::` that causes the error. If I remove this line, I need to have a code to assign values to `$result`.

# Answer
The problem is that your `use` declaration is incorrect, and is causing your call to the client to look in the wrong namespace. You probably need to change this:

```
use cvr\src\Cvrapi\CVRClient;

```

To this:

```
use Cvrapi\CVRClient;

```

And change this:

```
$result = \Cvrapi\CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');

```

To this:

```
$result = CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');

```
> 0 votes

---
Tags: testing
---


# Question
Title: Why does the eMail in my Rules Component use a theme that differs from page-theme?
I use the Rules module to send follow-up emails, which works fine.

In the past I used a different theme for my site, and somehow this theme (call it "old-theme" for now) is applied when a follow-up email is sent (Mime Mail).

How do I apply the current site-theme to my Rules Component?

# Answer
You may want to check the result you get if you do NOT tell Mime Mail to use the site's stylesheet. And combine this with creating a file in your theme that is named `mail.css`. If you do that, then Mime Mail should automatically use that when sending emails. For more details on that, refer to its README.txt, i.e.:

> Email messages are formatted using the `mimemail-message.tpl.php` template. This includes a CSS style sheet and uses an HTML version of the text. The included CSS is either:
>
> * the `mail.css` file found anywhere in your theme folder or
> * the combined CSS style sheets of your theme if enabled.

Also make sure your theme is set as "Theme to render the emails" within `admin/config/system/mailsystem`. Without that, the stylesheets used by emails sent via cron (for example) may not look like you want them to look.
> 0 votes

---
Tags: theming, rules, emails
---


# Question
Title: How to Invalidate cache for views by user's location
My site using Drupal 8 last version (8.2.5) and we have the views which contains the filter based on user's location (time-zone). For example, the users are coming from UK will get the time in UK timezone, and the Users are coming from the US, will get the time in the US. The problem is, when anonymous users from UK accessing to the site, it's display as US time instead, because the page has cached from US when the users from US visited.

On Drupal 7, I had implements DrupalCacheInterface and set custom cache for APC. And it's working fine.

How can I customize Drupal 8 cache for this requirement? My web server enabled the opcache and I and a custom module already.

Updated:

* After reference from Cache API from drupal.org, I tried to use Cache Context for TimeZone.

Inside default.services.yml, I modified:

```
# @default ['session', 'user']
  contexts: ['timezone']
  # Tags with a high invalidation frequency.

```

For make it filter by context request, when detect difference timezone will render cached pages according. But seems it's not working on Anonymous page cache.

Anyways for resolve my issue?

# Answer
I resolved it by copy the Core Page Cache Module to my owner module, then disable Page Cache Module.

```
getCacheId(Request $request)

```

this function should be return a custom key is reach my goal.
> 0 votes

---
Tags: views, 8, caching
---


# Question
Title: Is it possible in Drupal Commerce to have 2 price fields according to role?
Is it possible to have 2 price fields, with manually added price?

Currently I have second price calculated. User with role "EUR\_price" will see only EUR prices and others + anonymous will see USD. And this for product, in cart, order etc.

I'm not sure, if Rules (and separate price field) is enough for this.

# Answer
Are you looking to have a different price depending on the role of the user? If you want to have a price based on user role then the Commerce Pricelist module can help with that.

From the module list

> Different prices for different roles or individual users
>
> Different prices for different quantities
>
> Different prices based on order date (like a time-limited discount)
> 0 votes

---
Tags: 7, commerce, rules
---


# Question
Title: The "entity_reference_revisions_entity_view" plugin does not exist
This is related to Paragraphs module in Drupal 8. I have enabled paragraphs module and Entity Reference Revisions module. Then I created a new paragraph type in Admin\> Structure\> Paragraph types. After that I added fields to the new paragraph type. After some configuration I tried to add the newly created paragraph type to a content type, in my case article. But I got the following error:

There was a problem creating field Paragraphs: The "entity\_reference\_revisions\_entity\_view" plugin does not exist.

This is a persistent error. As I have rebuild the site from the scratch, and I am getting the same error. I will appreciated a help.

# Answer
> 1 votes
This looks like a problem when installing the module.

Check this with drush.

```
drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

```

Acc. to the error message the plugin is missing. Now reinstall the module:

```
drush pmu entity_reference_revisions
drush en entity_reference_revisions

```

and check again:

```
drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

```

If the plugin is not discovered report any errors you see.

Only debug this on a test site with no field data in this field type.

---
Tags: 8, paragraphs
---


# Question
Title: Problem with HOOK_preprocess_breadcrump (Caching?)
I run in a strange issue with breadcrumb modifying. In my template, I created a hook to show the current page in the breadcrumbs (for testing):

```
function business_preprocess_breadcrumb(&$variables){

if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
    $variables['breadcrumb'][] = array(
                    'text' => $node->getTitle(),
                    'url' => $node->URL()
                   );
     }

}

```

The code above works after clearing the cache and loading the first node page. However, as soon as I load any other node page, it's always showing the title of the first loaded node (like it is cached). Even when I echo the Node id, I always see the same ID from the first node. How can I fix this? I even tried to create a custom module which overrides the breadcumb generation - same result here.

Drupal 8.1.1.

# Answer
Change the cache context from 'url.path' to 'url'

```
function xxx_preprocess_breadcrumb(&$variables) {
    ...
    $variables['breadcrumb'] = array(
      array(
        'text' => 'some text',
        'url' => "/someurl"
      )
    );
    ...
    $variables['#cache']['contexts'][] = 'url';
}

```

I ran into the same problem with Drupal 8.2.4
> 4 votes

# Answer
In Drupal 8.1.1 the cache context for breadcrumbs was changed from `url.path` to `url.path.parent` to reduce the cache data for the breadcrumbs block.

Issue: url.path cache context for breadcrumbs is unnecessarily granular

After the change in core the title of the node gets cached on the first request and then all subsequent requests with the same path parent, in this case /node/, will get the same result from cache.

You can put the old context back in breadcrumbs in this hook:

```
function hook_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  $breadcrumb->addCacheContexts(['url.path']);
}

```

As alternative you can set the context in a render array in preprocess:

```
'#cache' => [
    'contexts' => [
      'url.path',
    ],

```
> 2 votes

---
Tags: theming, 8, breadcrumbs
---


title: Paragraphs not displaying on front-end

text:
# Question
Title: Paragraphs not displaying on front-end
I've created some paragraph types and added them to the "basic page" content type. I've filled in some data, but nothing shows up on the front-end. Only the content of ckeditor does. Any idea why this is?

# Answer
> 1 votes
Okay, it can be a few things...

If that twig template is the node, you would not use `{{ page.content }}`, but rather just `{{ content }}`. `{{ content }}` is the entire render array for the node.

If you wanted to split the fields up within the node twig template, you can use the format `{{ content.field_foo }}`.

It is already set to render the paragraph entity - so this should be all that is needed.

Another thing to check, if `{{ page.content }}` is totally blank, ensure that the **Main page content** block is set to output in the Main Content region of your theme.

---
Tags: 8, paragraphs
---


# Question
Title: why "errors validating the config synchronization" when UUID's match?
I'm moving a d8 config from dev to stage and I have edited `system.site` so that the primary UUID on the stage system is identical to the dev system; and yet `drush` still reports: "There were errors validating the config synchronization."

This is an initial import; so it wants to replace almost all the objects on the stage site with objects from dev which differ only by UUID. There is almost no data (just site name, etc.) This used to work fine under `8.0.0-beta12`; but I recently updated to `8.0.0-beta15` (which may or may not be significant). I'm using `drush` tag `8.0.0-beta14`.

```
# grep uuid configs/from_dev/system.site.yml
uuid: c3b4a4a7-e8ab-44d2-b349-73dc5a8dea63
# drush8 @iron.stage cget system.site | grep uuid
uuid: c3b4a4a7-e8ab-44d2-b349-73dc5a8dea63
#

```

I checked the whitespace and rebuilt the cache.

```
# drush8 @iron.stage cim from_dev
 Collection  Config                                                Operation
             system.menu.account                                   create
             block.block.bartik_breadcrumbs                        create
             block.block.bartik_content                            create

       blah.. blah.. blah..

             block.block.bartik_breadcrumbs                        delete
             system.menu.account                                   delete
Import the listed configuration changes? (y/n): y
exception 'Drupal\Core\Config\ConfigImporterException' with message      [error]
'There were errors validating the config synchronization.' in
/usr/local/www/d8_iron_stage/d8/core/lib/Drupal/Core/Config/ConfigImporter.php:730
Stack trace:
#0
/usr/local/www/d8_iron_stage/d8/core/lib/Drupal/Core/Config/ConfigImporter.php(517):
Drupal\Core\Config\ConfigImporter->validate()
#1
/usr/local/www/d8_iron_stage/d8/core/lib/Drupal/Core/Config/ConfigImporter.php(464):
Drupal\Core\Config\ConfigImporter->initialize()
#2 /usr/local/src/drush/commands/core/config.drush.inc(622):
Drupal\Core\Config\ConfigImporter->import()
#3 /usr/local/src/drush/includes/drush.inc(719):
_drush_config_import(Object(Drupal\Core\Config\StorageComparer))
#4 /usr/local/src/drush/includes/drush.inc(705):
drush_call_user_func_array('_drush_config_i...', Array)
#5 /usr/local/src/drush/commands/core/config.drush.inc(600):
drush_op('_drush_config_i...',
Object(Drupal\Core\Config\StorageComparer))
#6 [internal function]: drush_config_import('from_dev')
#7 /usr/local/src/drush/includes/command.inc(359):
call_user_func_array('drush_config_im...', Array)
#8 /usr/local/src/drush/includes/command.inc(210):
_drush_invoke_hooks(Array, Array)
#9 [internal function]: drush_command('from_dev')
#10 /usr/local/src/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#11 /usr/local/src/drush/lib/Drush/Boot/BaseBoot.php(62):
drush_dispatch(Array)
#12 /usr/local/src/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#13 /usr/local/src/drush/drush.php(11): drush_main()
#14 {main}

```

# Answer
> 1 votes
Drush can't properly deal with this error yet.

Use the UI, that will tell you exactly what the problem is.

For example, one common case is trying to delete a node type when you have content of that type.

# Answer
> 2 votes
If you set the `uuid` to `null` into `shortcut.set.default.yml` it will also works ok.

# Answer
> 1 votes
To resolve this error:

> Entities exist of type Shortcut link and Default. These entities need to be deleted before importing.

* Go to admin/config/user-interface/shortcut
* Click on 'List links' for the 'Default'
* Delete every link you see there

---
Tags: drush, 8, configuration
---


title: If form ==form1 and form2

text:
# Question
Title: If form ==form1 and form2
How can I make a hook form alter work on 2 forms?

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
if ( $form_id == 'node_page_form && node_page_edit_form'){

```

# Answer
> 0 votes
Use `||`:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'node_page_form' || $form_id == 'node_page_edit_form') {
    ...
  }
}

```

---
Tags: forms
---


# Question
Title: Why is this Drupal services RESTful API not working?
I'm using the Services module on Drupal 7. I want to implement a service that allows me to submit a search term via AJAX and receive an array containing the top 5 nodes (node `id` and `title`) that loosely match the title. When connecting to http://example.com/api/ I receive this message

> Services Endpoint "search" has been setup successfully.

but when attempting to navigate to something like http://example.com/api/search/Test, I get a 404.

# Answer
Later of try and try, when read from other tutorial, i make a resource with rest, soap for me is imposible in drupal, i try but without success, you can copy and page this code and modify only the custom module name and hooks.

```
/**
 * Implements hook_ctools_plugin_api().
 */
function core_custom_webservice_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'core_custom_webservice.services.inc'
    );
  }
}

function core_custom_webservice_services_resources() {
  $resources = array(
    'webservice_resources' => array(
      'operations' => array(
        'retrieve' => array(
          'help' => t('Response of webservice'),
          'file' => array('type' => 'inc', 'module' => 'core_custom_webservice', 'name' => 'core_custom_webservice.resource',),
          'callback' => '_core_custom_webservice_get_response',
          'access callback' => '_core_custom_webservice_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
          'args' => array(
            array(
              'name' => 'parameters',
              'type' => 'string',
              'description' => 'The parameters that define requested data',
              'source' => array('path' => '0'), // first argument in the url
              'optional' => FALSE,
            ),
          ),
        ),
      ),
    ),
  );
  return $resources;
}

/* * *************************************************************************************************
 * Access callback
 * For now only view/retrieve is implemented and if the user is logged in, he gets access
 */

function _core_custom_webservice_access($op) {
  global $user;
  $access = TRUE;

  switch ($op) {
    case 'view':
      if ($user->uid) {
        $access = TRUE;
      }
      break;
  }

  return $access;
}

function _core_custom_webservice_get_response($arg) {
  $response = 'something';
  return 'print '.$response;
}

```

try again in your service path and success with http://path.come/?q=webservice\_server\_rest/webservice\_resources/string.json
> 1 votes

# Answer
If you created a RESTful Resource with the Services module, then I believe it will expect to respond to HTTP requests in JSON format, therefore you could try navigating to `http://example.com/api/search/Test.json`
> 0 votes

# Answer
Try to use this module https://www.drupal.org/project/services\_views . It has currently two features: \- Create view based resource creating Services display in a view \- Execute any view of the system via views resource call
> 0 votes

# Answer
basically 404 is not found error

1. Make sure that your service end point is

http://example.com/api/search/{search-term}
2. what is the response body to be send is in correct format

3.the content headers is set to application/json and name Content-Type
> 0 votes

# Answer
Hi First thing you have to do is

STEP 1: create a custom module and implement `hook_services_resources()`

**EXAMPLE:**

```
function mymodule_services_resources() {
  return array(
    'search' => array(
      'create' => array(
        'help' => 'Search for a content',
        'file' => array('file' => 'inc', 'module' => 'your module name'),
        'callback' => '_function_to_call_when_this_service_is_called',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'access arguments append' => FALSE,
        'args' => array(
         array(
           'name' => 'data',
           'type' => 'struct',
           'description' => 'The id of the data to get',
           'source' => 'data',
           'optional' => FALSE,
         ),
       ),
      ),
     ),
  );
}

```

STEP 2: go to

> Structure -\> services

and enable your module

STEP 3: sending data to the client $data - data sent to client it should be array

```
  $url = $base_url.'/api/search';
            $response = drupal_http_request($url, array(
                'headers' => array('Content-Type' => 'application/json', 'Accept' => 'application/json'),
               'method' => 'POST',
               'data' => json_encode($data),
               'max_redirects' => 0,
               )
             );

```

print the response to check if its working fine.

**CHECK LIST:**

1. check for any log in by enabling DB logging module call your service.
2. check for any syntax error because that file is called only when services is call until then you wont see any error or warning.
3. print the response and test the data is passing correctly or not.
4. check the client end to check.
> 0 votes

# Answer
I was getting this error too and then I realized I needed to include both the path of my service endpoint and the path of my View in the URL.

Originally I was trying http://my.local/events but I needed to be using http://my.local/events/events (I had named my service endpoint path the same as my View).
> 0 votes

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


# Question
Title: How to pre-fill form fields with data from the node?
I have a site that list different courses that take place in real life (not virtual courses). For each course, there are different fields :

* title of the course
* start date
* end date
* place where the course will happen
* type of course
* ...

With View I have created a table that list all the courses. I would like that logged users can subscribe to a course by just clicking on it, and then I would receive an e-mail (or see in the back-end) that tells me that user X has subscribe to course Y (and I will have in the same time all the informations about the course the user subscribed to : title, dates, place...)

For the moment when a logged user click on a course, another page loads that displays informations about the course, and a form where the user have to write out again all the informations in blank fields...

Is there a way to pre-fill the form fields with the informations of the course ?

Or is there a smarter way to do this ?

Thanks

# Answer
You could use Prepopulate module to prefill fields in subscriptions. But:

I would redesign the model in order not to save the same information you already have in courses again with the subscription. It's redundant to store title, date, place, etc. twice, with all the implications changes of the primary information in courses would have.

Said this content type "subscription" only should save a entity reference to courses. I propose to add a link to each course in Views which allows to subscribe to it. To do this, follow this steps:

1. Add field "ID" and check "Exclude from display".
2. Add "Global: Custom text" to your fields and put a label like *Subscribe*.
3. Under Rewrite results, check "Output this field as a custom link".
4. In field "Link path" enter *node/add/subscription?edit\[course\]={{nid}}* \- where "course" is the name of entity reference field in content type subscription and "nid" is the replacement pattern for the course id.
5. Install and activate Prepopulute module

Clicking a subscription link in Views should now open subscription form and prefill the referenced course field. Making a custom module would allow you to create this content type without showing the form to the user.
> 1 votes

# Answer
You set a '#default\_value' in the form field. But this only makes sense, if the user is allowed to change the course data. If not you could add the displayed course data after submit to the confirmation e-mail. Add the node cache tag to the form, so that it gets updated when the node is modified.

**A way to approach this**

is to set up a form route `/subscription/add/{nid}` to use as a link in the view, where nid is the node id of the course.

The form loads this node from the route and displays the course data in the form as markup together with the form fields for the user to fill in the personal information. After submit you send a confirmation mail with the personal information and the course data, which you can load again if you keep the node id in a hidden field.

This is the cache tag you have to add to the form, when the form contains data from this node:

```
$form['#cache']['tags'][] = 'node:' . $node->id();

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: drush and connecting with a non-localhost database
I am attempting to update a Drupal website and the associated modules with drush 7. The MySQL database resides on another server within the same network. When attempting to run any command where drush would connect with the MySQL database the following error is returned:

> Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

Running drush pml --debug I see that drush appears to be reading the correct database credentials:

> Executing: mysql --defaults-extra-file=/tmp/drush\_EDQIvN --database=dlc\_ode --host=correct.internal.ip.address --silent \< /tmp/drush\_ltZVnl

But on the line just below:

> ERROR 1045 (28000): Access denied for user 'root'@'ip-ip.of.localhost.us-west-2.compute.internal' (using password: YES)

Neither the user root nor the AWS domain is correct. I am new to drush and am not certain what is overriding the database credentials in the settings.php file.

I can connect with MySQL from the command line with no problem using mysql -u username -p. Drupal itself connects fine.

Any suggestions of what I am overlooking will be appreciated.

Thank you.

# Answer
> 0 votes
Occurred to me right after I posted my question to check whether someone had created another my.conf or .my.conf file on the system at sometime in the past. And yes there was a .my.conf file that had been created some years ago. Renamed the file and viola, drush pml works as expected.

Hopes this helps someone puzzled by incorrect database connection.

---
Tags: database, drush
---


# Question
Title: Capturing return value from remote post hander
I have a number of forms set up using Webforms (the module formerly known as yamlforms) in Drupal 8.

This data is stored in Drupal, but is also sent to a remote CRM using a Remote post handler added to the form. The CRM handler generates a key for the newly added lead that I would like to use in my success message. There's no option for capturing data from a remote post though.

Does a solution already exist for this, or am I doomed to writing my own module?

# Answer
There is no built in solution for this, you have extend the Remote post handler and write some custom code.

Please open a ticket in the Webform issue queue. Ideally, the remote post handler would be able to populate some meta data that could be exposed via a token.
> 1 votes

---
Tags: 8, webforms
---