title: No route found for custom REST resource

text:
# Question
Title: No route found for custom REST resource
I'm trying to create a custom REST GET resource for a specific node type, and I have the class created and enabled via the REST UI module settings (using the current 1.x-dev release so configs are generated w/o me having to manually create a routing.yml file). For reference, here's the class code:

```
<?php
/**
 * @file
 * Custom Rest resource for video nodes.
 */

namespace Drupal\video_export\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "video_export_source",
 *   label = @Translation("Video Export Source"),
 *   uri_paths = {
 *     "canonical" = "/videos/feed/{site}"
 *   }
 * )
 */

class VideoExportResource extends ResourceBase {
  /**
   *  A curent user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
    * @param array $configuration
    *   A configuration array containing information about the plugin instance.
    * @param string $plugin_id
    *   The plugin_id for the plugin instance.
    * @param mixed $plugin_definition
    *   The plugin implementation definition.
    * @param array $serializer_formats
    *   The available serialization formats.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
    * @param \Drupal\Core\Session\AccountProxyInterface $current_user
    *   A current user instance.
  */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }

  /**
    * Responds to GET requests.
    *
    * Returns a list of video nodes to be imported into the target site.
    *
    * @return \Drupal\rest\ResourceResponse
    *   The response containing a list of bundle names.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
  public function get($site = NULL) {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

```

However, when I access my URL via `http://mysite/videos/feed/sourcesite?_format=xml`, all I get is this error:

> No route found for "GET /videos/feed/newsbusters"

and my debugger doesn't even hit my get() function. In reading the RESTful Web Services API overview docs it appears that I might be missing the second part of the `uri_paths` setting in the class annotation. However, the example doesn't make sense to me for my use. if the canonical url is just `/videos/export/{site}` (where `{site}` is a parameter), what is the correct second part? Just `http://myite.com/videos/export`?

Or,

Thanks.

# Answer
> 0 votes
As far as I can see, the REST UI module is just thought to change the content of the YAML files for the REST resources. It is up to the module correctly define the URL to use.

In your case, the annotation of the class should contains:

```
 uri_paths = {
   "canonical" = "/videos/feed/{site}",
   "https://www.drupal.org/link-relations/create" = "/videos/feed"
 }

```

I am not sure the placeholder makes any difference, but all the examples use `{id}`.

---
Tags: 8
---


title: Smart IP doesn't show countries

text:
# Question
Title: Smart IP doesn't show countries
I want to get visitors' latitude, longitude, and country name. I am using the Smart IP module, but it won't show those details.

>

How can I get that data?

I need this information to create view's filters.

# Answer
To address your edit about the Views filter requirement, there's a submodule included with the main module, called "Smart IP Views Bridge". It has the functionality you're looking for. An extract from its README:

> Smart IP Views Bridge exposes Smart IP visitor's location details to Views field (coordinates, country, ISO 3166 2-character country code, region, region code (FIPS), city and zip) and filter (country, ISO 3166 2-character country code, region, region code (FIPS), city and zip).

Enable that module and the filters you need will become available in Views.

The README goes on to provide full installation and configuration instructions for Views integration, so it's worth reading it thoroughly.

If solving programatically becomes a requirement:

> It's right in the module description:
>
> Other modules can use the function `smart_ip_get_location($ip_address)` in Drupal 6 and 7 and `\Drupal\smart_ip\SmartIp::query($ipAddress)` in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code.
> 1 votes

---
Tags: location
---


# Question
Title: Drupal 7 form missing from $form object during Ajax callback function
I'm using this example code to create a 'add another field' to my custom Form. The form itself is quite big and showing a full example here isn't possible.

The problem I'm having is that when I hit my callback button to 'add another field' the `$form` variable is missing most of the form I wish to utilise. My form is an admin area only form, but using the above example works fine in my implementation as POC.

The form utilises vertical\_tabs but I have also tried without. I have a lot of validation around this form and in essence it's being built of a yaml file but I can't work out why the form elements are missing during the ajax callback. `$form_state` contains all the values submitted by the form including the missing data from `$form`.

I had assumptions that `#tree` was the issue but, I have this set to `TRUE` from the start.

# Answer
> 0 votes
Just incase anybody wants to know the issue was I was trying to obtain a value from `arg()` and this was different for the ajax callback funtion. So in my `hook_form` function I set the following:

```
  // This is needed for the ajax callback
  if (arg(1) != 'ajax') {
    // We need to set the variable before we load the form.
    $form_state['value'] = arg(3);
    $key = arg(3);
  }
  else {
    // Ajax callback can now reference correct key.
    $key = $form_state['value'];
  }

```

This allowed me to obtain the correct value during the ajax callback function.

---
Tags: forms, ajax
---


# Question
Title: Custom block for anonymous users is shown to every user
I have a simple problem that has me stumped. I created a block with custom "login" and "create an account" links, which I only want to display to anonymous users, naturally. I deployed the block using a Glazed Builder drag&drop feature, but it's showing up for all users. I also set the block so that it should not show up on /user/ or /user/\* but it is showing up on http://example.com/user and http://example.com/user/login, etc.

I used `drush cc all` and am using an incognito window in Chrome, but cleared the browser cache anyway.

I'm on Drupal 7.54. I am using Glazed Theme from SooperThemes, which allows us to place blocks using a drag & drop editor. The block is still in the "disabled" list in the block list for some reason.

# Answer
> 2 votes
First of all, you have to **remove the first slash** in the show block on specific pages text area :

```
user/
user/*

```

will hide your blocks in user pages as expected, while `/user/ /user/*` won't.

This will solve half your issue. Then check if maybe your theme was complaining because of this misconfiguration detail, and may show now your block for anonymous users only.

---
Tags: 7, users, blocks
---


# Question
Title: Print admin toolbar icon in custom module
How can I print the admin toolbar icon for my module?

I created a module and it has a menu in the admin toolbar. I want to show an icon (module/costum\_module/image/00/icon.svg) in this path for my admin toolbar tab.

I created a CSS style for that, but it doesn't work.

Module path :

/module/my module/css/styles.css =\>

```
.toolbar-icon-mymodule-list:before {
    background-image: url(../icons/787878/icon.svg);
}
.toolbar-icon-mymodule-list:active:before,
.toolbar-icon-mymodule-list.active:before {
    background-image: url(../icons/000000/icon.svg);
}

```

/module/my module/mymodule.libraries.yml =\>

```
mymodule.styles:
  css:
    theme:
      css/styles.css: {}

```

# Answer
If you want to add svg icon for your menu link item in admin toolbar, you have to alter toolbart.

In your mymodule.libraries.yml file

`toolbar:
 version: VERSION
 css:
 theme:
 css/styles.css: {}`

And you need to implement hook\_toolbar\_alter() in your mymodul.module

```
function mymodule_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'mymodule/toolbar';
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: How to allow users to rotate a picture upon upload?
On my site, users are able to upload images one at a time as nodes of content type *Picture*. The *Picture* content type uses the core (D7) image field.

Some of my users have pictures which are taken such that they need to be rotated 90 or 180 degrees. These users do not have easy access to image editing software, so **I'd like to allow users to rotate the image on the edit node screen.**

After the image is saved, I want to apply an image style (that forces scaling and cropping, etc.) I'm also using the Manual Crop module to allow users to crop the image if necessary.

Is there a module for this, or some easy way to do it in code? (I'm not a developer.)

I would prefer to have a solution where I can present users with a button to rotate the picture; I don't want to give them a full image editor.

If such a solution is impossible, is there an easy way to rotate the images on the back end (for admins)? I'm happy to do it myself, as I have to check all the images anyway.

# Answer
> 2 votes
I found a way to fix the issue. I used the Image EXIF Autorotate module in conjunction with Imagecache Actions and Autorotate to apply autorotation as the image is being uploaded. Not after it is uploaded. So you will still need Imagecache Actions and Autorotate, this module just automates the process and applies autorotation without the need of an image style. Meaning you can use Manual Crop with it.

> **Note:** that autorotate requires the **Exif PHP extension** to be enabled.

# Answer
> 2 votes
I've been fighting this issue for some hours now and have something that seems to work for me. It's not extensively tested yet, though.

My setup:

* ImageMagick instead of GD as Image Toolkit (because GD strips EXIF data)
* Imagecache Autorotate, part of \[Imagecache Actions\](Imagecache Autorotate) that provides an Image Action that automatically rotates pictures according to their EXIF orientation
* EPSA Crop module: EPSA crop was the only cropping module that allowed me to use its *after* the Autorotate action in my image style preset (I tried at least with manualcrop, imagefield\_crop, simplecrop)

In my image style I use the following actions:

1. Autorotate Autorotate image based on its EXIF data
2. EPSA Image Crop, 150x150 (with Aspect Ratio of one, as the resulting image has a square AR)
3. Scale and Crop, 150x150, scale and crop it even if it wasn't manually cropped.

Only drawback so far: EPSA Crop doesn't show you the cropped image on the thumbnail of the edit page, so users might be confused if their cropping was successful after all.

Hope this helps others saving some hours of research.

# Answer
> 1 votes
So, right now there is not a solid way to do this. I ran across quite a few requests for this feature and there is no working solution I can find that exists today. It would actually be worthwhile to write a module to accomplish this. I would be up to the task for sure, but I do not have any time at the present moment to do so. I would in a month or so though if you still do not have a viable solution. (I tried many different modules and lots of searching to find no existing solution in Node Edit. There are plenty that work with styles though.)

As for doing it in the administration, that would be very easy. All you need to do is apply a style to the image. Create 3 new styles. One rotates the image 90 deg clockwise, the other 90 deg counter-clockwise and the last rotates 180 degrees. When you are approving them, just apply the appropriate style by choosing the proper type.

See this Drupal Documentation on the subject.

Sorry for being wrong earlier. I am really disappointed in the modules that implement ImageMagick or even extend the GD. There really should be more node specific options exposed.

# Answer
> 1 votes
You can write a custom module that intercepts the file as it is being uploaded by the user, and saves it back to the Drupal schema. For that there's the Drupal Field Attachment API and Drupal File API. You will find that both APIs are meticulously documented. You use the Field Attachment API to implement a hook that gets the new (user uploaded) file URI as it is being uploaded (I think it was hook\_field\_attach\_insert(), but I would need to verify my code). You use the File API (drupal\_realpath()) to convert that URI into an absolute filesystem path that ImageMagick will understand (it doesn't accept relative paths).

Once ImageMagick has successfully loaded the file, the sky (or rather Imagick's API) is the limit. You'll need to save the modified file back into Drupal using the previously mentioned APIs. Both ImageMagick and GD libraries are well documented on the web.

I am personally not aware of an existing module that does this in D7? Although I admit it would be a nice to have. The only way I think this can can be done is with custom code, sorry.

# Answer
> 1 votes
The Plupload integration module looks promising. Plupload supports client-side image resizing so it should work for your use case assuming one of the Drupal modules allow you to configure it as needed.

# Answer
> 1 votes
Simple Image rotate module may help you as it rotate image before upload

---
Tags: media
---


title: Search results replace & with &

text:
# Question
Title: Search results replace & with &
When, for example, I search for *Eat & Drink*, the search results show `&` instead of `&`.

>

Is there any way to avoid this?

# Answer
> 0 votes
Got it! Used the below code and everything works fine.

```
filter_var($snippet, FILTER_SANITIZE_STRING);

```

---
Tags: search
---


# Question
Title: Add programmatically created field to content type form
I've programmatically created a content-type with 3 fields (in D8).

The fields are created but do not show up on node creation. If I go to the content-type form display, the fields are there, but I need to save this page to get the fields to show up on node creation.

The content-type and fields are created in yml-files and the Looks like this:

config/install/field.field.node.slideshow\_slide.slide\_weight.yml

```
langcode: en
status: true
dependencies:
config:
    - field.storage.node.slide_weight
    - node.type.slideshow_slide
module:
    - text
enforced:
    module:
        - custom
id: node.slideshow_slide.slide_weight
field_name: slide_weight
entity_type: node
bundle: slideshow_slide
label: 'Weight'
description: 'This slides weight'
required: false
translatable: false
default_value: 0
default_value_callback: ''
settings: { }
field_type: string

```

config/install/core.entity\_form\_display.node.slideshow\_slide.default.yml

```
langcode: en
status: true
dependencies:
config:
    - field.field.node.slideshow_slide.slide_image
    - field.field.node.slideshow_slide.slide_link
    - field.field.node.slideshow_slide.slide_weight
    - node.type.slideshow_slide
module:
    - image
    - link
id: node.slideshow_slide.default
targetEntityType: node
bundle: slideshow_slide
mode: default
content:
slide_image:
    label: visible
    weight: 101
    settings: {  }
    third_party_settings: {  }
slide_link:
    label: visible
    weight: 100
    settings: { }
    third_party_settings: {  }
slide_weight:
    label: visible
    weight: 100
    settings: { }
    third_party_settings: {  }
links:
    weight: 100

```

# Answer
> 2 votes
Found out that it needed "type" for all the fields in the form\_display.

---
Tags: nodes, entities
---


# Question
Title: Better tagging / taxonomy reference widget
The *Term Reference* field type has three stock widget types:

* Select List
* Check boxes/radio buttons
* Autocomplete term widget (tagging)

We need an alternative to the autocomplete widget that shows all existing terms in a vocabulary and allows users to enter another.

Here is a sample of what I'm looking for (I just made this in Firebug—I don't have a viable option yet). In this option, the vocabulary would include two terms, banana and pear, and the user could enter a different term.

# Answer
> 10 votes
Select (or other) module looks like provide similar UI.

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

Unfortunately it doesn't support Term References.

Try Autocomplete Deluxe module or Chosen module for better UI and functionality.

# Answer
> 0 votes
Look at this powerful module Hierarchical Select

---
Tags: taxonomy-terms, ajax, entities
---


title: Print menu and output as selectlist

text:
# Question
Title: Print menu and output as selectlist
is there possibilty to print menu and output as selectlist ?

```
<?php
  // https://api.drupal.org/api/drupal/includes!menu.inc/function/menu_tree_all_data/7
$tree = menu_tree_all_data('menu-example');
menu_tree_add_active_path($tree);
echo drupal_render(menu_tree_output($tree));
?>

```

# Answer
> 1 votes
You cannot do this within the template tpl like that. You still wind up calling `render` which pipes the array back to a theme function anyway. You will need to override the corresponding theme hook that is rendering the menu and links to do what you want.

It almost sounds like you want a jump menu, to which I would first direct you here to Jump Menu.

Overriding theme hook(s) for menu and menu links is a fairly daunting task.

---
Tags: theming, navigation
---


# Question
Title: How to send email to submitter anytime webform modified
I have a webform page to submit data from authentic users. The moderator should see this to verify the data. When the moderator changes the submitted data, I want the system send an email to the submitter notifying the data has been changed.

How Can I do that. Is that any additional module(s) to handle that task?

# Answer
Finally I can send an email to the submitter by using webform rules module.

**Event:** After a webform submission has been updated

**Condition:** Data selector: form-id Webforms: select the webform that i use

**Action:** Send email:

To: `<?php print $data['components']['email']['value'][0]; ?>`

From: ...just leave it blank
> 2 votes

---
Tags: webforms
---


# Question
Title: How do I get rid of "Mismatched entity and/or field definitions"
After installing mailchimp successfully and uninstalling succesfully I am left with

```
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Custom block

The block_content.field_subscription field needs to be uninstalled.

```

in `admin/reports/status`

I have tried numerous times to install mailchimp again and then unistall it but the error is still there

what is the best way to get rid of it because it creates a problem with `entity construction kit` module

I have a feeling that mailchimp was not properly uninstalled if I properly uninstalling the module it might clean this error

**UPDATE:** `drush entity-updates` can't fix it something is badly broken

I have also removed the mailchimp directory and run update.php but still no go

```
giorgos@glaptop:~/domain/docroot$ drush entity-updates
The following updates are pending:

block_content entity type :
  The field block_content.field_subscription needs to be uninstalled
Do you wish to run all pending updates? (y/n): y
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'alpha.dev.block_content__field_subscription' doesn't exist in                                                                [error]
/home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Statement.php:59
Stack trace:
#0 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Statement.php(59): PDOStatement->execute(Array)
#1 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Connection.php(610): Drupal\Core\Database\Statement->execute(Array, Array)
#2 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(81): Drupal\Core\Database\Connection->query('UPDATE {block_c...', Array, Array)
#3 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Query/Update.php(148): Drupal\Core\Database\Driver\mysql\Connection->query('UPDATE {block_c...', Array, Array)
#4 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php(1444): Drupal\Core\Database\Query\Update->execute()
#5 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Field/FieldStorageDefinitionListener.php(112):
Drupal\Core\Entity\Sql\SqlContentEntityStorage->onFieldStorageDefinitionDelete(Object(Drupal\field\Entity\FieldStorageConfig))
#6 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/EntityManager.php(429):
Drupal\Core\Field\FieldStorageDefinitionListener->onFieldStorageDefinitionDelete(Object(Drupal\field\Entity\FieldStorageConfig))
#7 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/EntityDefinitionUpdateManager.php(242):
Drupal\Core\Entity\EntityManager->onFieldStorageDefinitionDelete(Object(Drupal\field\Entity\FieldStorageConfig))
#8 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/EntityDefinitionUpdateManager.php(116): Drupal\Core\Entity\EntityDefinitionUpdateManager->doFieldUpdate(3, NULL,
Object(Drupal\field\Entity\FieldStorageConfig))
#9 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/update.inc(250): Drupal\Core\Entity\EntityDefinitionUpdateManager->applyUpdates()
#10 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/batch.inc(163): drush_update_entity_definitions(Object(DrushBatchContext))
#11 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/batch.inc(111): _drush_batch_worker()
#12 /opt/drush-8.x/vendor/drush/drush/includes/batch.inc(98): _drush_batch_command('768')
#13 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/update.inc(174): drush_batch_command('768')
#14 /opt/drush-8.x/vendor/drush/drush/commands/core/core.drush.inc(1224): _update_batch_command('768')
#15 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(422): drush_core_updatedb_batch_process('768')
#16 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#17 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(199): drush_command('768')
#18 /opt/drush-8.x/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#19 /opt/drush-8.x/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#20 /opt/drush-8.x/vendor/drush/drush/drush.php(12): drush_main()
#21 {main}

Next Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'alpha.dev.block_content__field_subscription' doesn't exist: UPDATE
{block_content__field_subscription} SET deleted=:db_update_placeholder_0; Array
(
    [:db_update_placeholder_0] => 1
)
 in /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Connection.php:671
Stack trace:
#0 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Connection.php(635): Drupal\Core\Database\Connection->handleQueryException(Object(PDOException), 'UPDATE
{block_c...', Array, Array)
#1 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(81): Drupal\Core\Database\Connection->query('UPDATE {block_c...', Array, Array)
#2 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Database/Query/Update.php(148): Drupal\Core\Database\Driver\mysql\Connection->query('UPDATE {block_c...', Array, Array)
#3 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php(1444): Drupal\Core\Database\Query\Update->execute()
#4 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Field/FieldStorageDefinitionListener.php(112):
Drupal\Core\Entity\Sql\SqlContentEntityStorage->onFieldStorageDefinitionDelete(Object(Drupal\field\Entity\FieldStorageConfig))
#5 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/EntityManager.php(429):
Drupal\Core\Field\FieldStorageDefinitionListener->onFieldStorageDefinitionDelete(Object(Drupal\field\Entity\FieldStorageConfig))
#6 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/EntityDefinitionUpdateManager.php(242):
Drupal\Core\Entity\EntityManager->onFieldStorageDefinitionDelete(Object(Drupal\field\Entity\FieldStorageConfig))
#7 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Entity/EntityDefinitionUpdateManager.php(116): Drupal\Core\Entity\EntityDefinitionUpdateManager->doFieldUpdate(3, NULL,
Object(Drupal\field\Entity\FieldStorageConfig))
#8 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/update.inc(250): Drupal\Core\Entity\EntityDefinitionUpdateManager->applyUpdates()
#9 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/batch.inc(163): drush_update_entity_definitions(Object(DrushBatchContext))
#10 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/batch.inc(111): _drush_batch_worker()
#11 /opt/drush-8.x/vendor/drush/drush/includes/batch.inc(98): _drush_batch_command('768')
#12 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/update.inc(174): drush_batch_command('768')
#13 /opt/drush-8.x/vendor/drush/drush/commands/core/core.drush.inc(1224): _update_batch_command('768')
#14 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(422): drush_core_updatedb_batch_process('768')
#15 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#16 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(199): drush_command('768')
#17 /opt/drush-8.x/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#18 /opt/drush-8.x/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#19 /opt/drush-8.x/vendor/drush/drush/drush.php(12): drush_main()
#20 {main}
Cache rebuild complete.                                                                                [ok]
Finished performing updates.

```

**UPDATE 2:** Tried to install the module again but there is configuration still in the table and can't be installed

```
giorgos@glaptop:~/domain/docroot$ drush en mailchimp_signup, mailchimp_campaign, mailchimp_lists, mailchimp -y
The following extensions will be enabled: mailchimp_signup, mailchimp_campaign, mailchimp_lists, mailchimp
Do you really want to continue? (y/n): y
Drupal\Core\Config\PreExistingConfigException: Configuration objects (mailchimp.settings) provided by mailchimp already exist in active configuration in                                              [error]
/home/giorgos/domain/docroot/core/lib/Drupal/Core/Config/PreExistingConfigException.php:65
Stack trace:
#0 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Config/ConfigInstaller.php(471): Drupal\Core\Config\PreExistingConfigException::create('mailchimp', Array)
#1 /home/giorgos/domain/docroot/core/lib/Drupal/Core/ProxyClass/Config/ConfigInstaller.php(132): Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module',
'mailchimp')
#2 /home/giorgos/domain/docroot/core/lib/Drupal/Core/Extension/ModuleInstaller.php(141): Drupal\Core\ProxyClass\Config\ConfigInstaller->checkConfigurationToInstall('module',
'mailchimp')
#3 /home/giorgos/domain/docroot/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(83): Drupal\Core\Extension\ModuleInstaller->install(Array, true)
#4 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/environment.inc(131): Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array, true)
#5 /opt/drush-8.x/vendor/drush/drush/commands/core/drupal/environment.inc(198): drush_module_install(Array)
#6 /opt/drush-8.x/vendor/drush/drush/commands/pm/pm.drush.inc(1167): drush_module_enable(Array)
#7 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(422): drush_pm_enable('mailchimp_signu...', 'mailchimp_campa...', 'mailchimp_lists...', 'mailchimp')
#8 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#9 /opt/drush-8.x/vendor/drush/drush/includes/command.inc(199): drush_command('mailchimp_signu...', 'mailchimp_campa...', 'mailchimp_lists...', 'mailchimp')
#10 /opt/drush-8.x/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#11 /opt/drush-8.x/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#12 /opt/drush-8.x/vendor/drush/drush/drush.php(12): drush_main()
#13 {main}

```

# Answer
You have to run the drush command entity updates to correct this.

https://drushcommands.com/drush-8x/core/entity-updates/

```
drush entity-updates

```

Edit: sounds like the Mailchimp module potentially broke your database. I would cross report this to the Mailchimp module issue queue.
> 3 votes

---
Tags: 8
---


# Question
Title: How to limit a user to specific OG groups based on user role?
In a quite complex project page, I have several user roles (from Drupal core). Further, the page has an internal area which is built upon Organic Groups (OG). There are a lot of groups available, each group is part of a so-called "area". These areas correspond to user roles and what I want to achieve is that users of a role may only subscribe to groups of the area with the same name.

To visualize the concept, let's say I have three user roles (besides anonymous, authenticated and administrator): A, B and C.

There is a node type called "Group" which has a select field for area, the available options are A, B and C.

There are nine groups, called A1, A2, A3, B1, B2, B3, C1, C2 and C3. I don't want users to apply for a group but immediately join (subscribe) to it, but only if the group's area matches the user's role. So user Alex of role A may only see and join A1 through A3 but not any other group.

The OG group permissions only distinguishes between non-member, member and manager. There's the option to subscribe to a group without approval, which I want. But how to combine that with the Drupal user role?

# Answer
> 0 votes
Due to other restrictions in OG I couldn't overcome, I ended up using the Group module instead. In addition to other advantages for my use case, it offers some functions to easily add group memberships (these are entities) by using something like

```
$entity_type = 'group_membership';
$entity = entity_create($entity_type, array('gid' => $gid, 'uid' => $uid));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->status = 'active';
$wrapper->added_on = time();
$wrapper->added_by = 1;
$wrapper->save();

```

Adding that into a `hook_user_update(&$edit, $account, $category)` function, I am able to add and revoke memberships based on the updated account's roles.

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


title: How to include RSS feeds inside a node?

text:
# Question
Title: How to include RSS feeds inside a node?
I would like to create a node that displays 5 RSS feeds from 5 different external sites. I have the RSS URL of the external sites, and I would like to find a simple way to display the last elements of these feeds inside my node.

I have already looked at the Feeds module, but it creates a node for each element of the given RSS feeds.
How can I display the last elements from different RSS feeds?

# Answer
> 1 votes
I think the best way is to use Aggregator, you dont have to map into a new content type RSS Feeds like on Feeds module.

Follow this:

1. Active Aggregator core module.
2. Add a new chanel per each feed URL under /admin/config/services/aggregator, defining a name and time for importing by cron.
3. Create a view with a display of type "Aggreator", Here you can make a comun view, ordering by date, limiting by 1 result, and filtering by each channel.

I hope this help.

---
Tags: 8, feeds
---


# Question
Title: Importing Joomla 1.5.23 to Drupal 7 by using Feeds
I'm trying to migrate Joomla 1.5 to Drupal 7 by using Feeds Module. I have tried the "Joomla to Drupal" with no luck. And the "Migrate" module requires some PHP coding, which I'm not an expert on this.

Question 1 - So, my question is which phpMyAdmin database for "Node Import" when I import CSV to Drupal? I know "jos\_users" is for the "User import". What about the rest of them?

Question 2 - How to import Joomla user password by using Feeds? The password format seems different.

Question 3 - How and where can I import the url formatting?

For details, please see below of my Joomla phpMyAdmin database list.

Thanks!

```
jos_banner
jos_bannerclient
jos_bannertrack
jos_categories
jos_components
jos_com_file_index
jos_com_file_index_errors
jos_contact_details
jos_content
jos_content_frontpage
jos_content_rating
jos_core_acl_aro
jos_core_acl_aro_backup
jos_core_acl_aro_groups
jos_core_acl_aro_map
jos_core_acl_aro_sections
jos_core_acl_aro_wtf
jos_core_acl_groups_aro_map
jos_core_acl_groups_aro_map_wtf
jos_core_log_items
jos_core_log_searches
jos_funrecaptcha
jos_groups
jos_jce_groups
jos_jce_plugins
jos_jcomments
jos_jcomments_custom_bbcodes
jos_jcomments_reports
jos_jcomments_settings
jos_jcomments_subscriptions
jos_jcomments_version
jos_jcomments_votes
jos_jobline_jobs
jos_jobline_jobs_types
jos_jobline_types
jos_jxcomments_comments
jos_jxcomments_ratings
jos_jxcomments_ratings_members
jos_jxcomments_threads
jos_jxtended
jos_menu
jos_menu_types
jos_messages
jos_messages_cfg
jos_migration_backlinks
jos_modules
jos_modules_menu
jos_newsfeeds
jos_plugins
jos_polls
jos_poll_data
jos_poll_date
jos_poll_menu
jos_redirects
jos_sbxss_categories
jos_sbxss_slides
jos_sections
jos_session
jos_stats_agents
jos_taxonomy
jos_taxonomy_config
jos_taxonomy_elements
jos_taxonomy_filters
jos_taxonomy_map
jos_templates_menu
jos_users
jos_weblinks
jos_xmap
jos_xmap_ext
jos_xmap_sitemap

```

# Answer
I've never considered how you would use Feeds to import from a database, but it works great for migrating content when that content is in a "feed".

If you have to use the DB, then there is Feeds SQL and Feeds DB, but I think both require you to write a query. That said, if you are using phpMyAdmin then when you "open" any of those tables phpMyAdmin will show the query it's running.

If you are able to expose your content as an xml/rss feed, a JSON feed, , or etc. then thing become very straight forward.

Using the Feeds Preview module may help you get your mapping correct.

You should be able to import the node alias (path) along with the content.
> 1 votes

# Answer
You could try to use cms2cms.

I don't have experience with it, but i must says'it costs you some.

To 10 pages it's for free, after that you need to pay.

http://www.slideshare.net/CMS2CMS/how-to-migrate-from-joomla-to-drupal
> 0 votes

---
Tags: feeds, migrations
---


# Question
Title: Should I enable a feature I created on the same site?
I created a view and some configurations and used features to save it into code. When doing so, I used the GUI interface and selected Advanced Features and named a file path (sites/all/modules/custom) and then clicked "generate". In doing so, the code was saved to that file path. It is now listed in the website under features \> custom but it is listed as disabled.

What is the best practice for this scenario: should I enable it or keep it disabled since I clearly would like it to be active and part of the code? Thanks!

# Answer
> 4 votes
Sure, you enable it. By that you keep track of changes you make on either development environment.

For example you edit some settings on your local dev site, then the activated feature will recognise the changes. Then you *recreate* the feature and commit the updated files to your repo. On live then you pull the file changes, which your activated feature there recognises as well.

Now you *revert* the feature on your live site and by that sync the settings you made on dev to live. All by having the feature activated on all instances you work with.

---
Tags: 7, views, features
---


# Question
Title: Use a file token for directory path when uploading a file via core file upload field?
Is there a way to use a token like `[file:fid]` when using the file upload field? I either want to use this, or, use the node id it is attached to with `[node:nid]`. It looks like I can only use global tokens, which are not unique enough to the way I want to store the file on the server.

# Answer
> 4 votes
In core this is not possible, because the file widget sets the #upload\_location when it builds the form element.

You need a module, for example File (Field) Paths. This module sets a temp path in #upload\_location of the form element and sorts this out later when the file and node entity are available.

---
Tags: 8, tokens, files
---


# Question
Title: How to remove Storage API without data loss
I'm working on application based on Drupal 7.39 that use the Storage Api module version 7.x-1.8 with FTP container.

I'm trying to achieve is to remove this module and use the normal flow to save assets (I think that all assets will be saved in app/sites/default/files).

I downloaded all files from FTP container in app/sites/default/files folder.

I tried to disable the module, but I noticed that images fields served by the plugin are not available anymore. The association in content pages are still present but I only see a broken link.

How can I update all the fields served by the plugin to use files that are in app/sites/default/files? In other words I want to remove the plugin and all his associations to files. Is that possible? Can I migrate these associations?

Thank you.

**UPDATE**

As Jonathan Rhodes suggests me, here's the procedure to update uris.

```
$queryString = "SELECT * FROM db.file_managed WHERE uri REGEXP '^storage-a*'";

try {
    $db = new PDO("mysql:host=localhost;dbname=db;charset=utf8", "root", "root");
    $query = $db->prepare($queryString);
    $query->execute();

    $rows = $query->fetchAll(PDO::FETCH_ASSOC);

    $func = function ($element) use ($db) {
        $uri = $element['uri'];
        $uriReplaced = preg_replace('/^(storage-.*)(:\/\/.*)/', "public$2", $uri);
        $queryUpdate = "UPDATE db.file_managed SET uri = :uri WHERE fid = :fid";
        $query = $db->prepare($queryUpdate);
        $query->execute(['uri' => $uriReplaced, 'fid' => (int) $element['fid']]);
    };

    echo count($rows);
    array_map($func, $rows);
} catch (PDOException  $e) {
    echo "Error: " . $e;
}

echo 'ok';

```

# Answer
You'll probably need to manually update the files\_managed database table and change the uri to use the public:// schema.
> 0 votes

---
Tags: 7, media, stream-wrappers
---


# Question
Title: 7 - Dynamically changing links based on environment
I am working with a Drupal site that is a central hub for several other pieces of software. The Drupal site and the other Software all have their own dev, testing and production environments. Each of these environments have their own url.

What I am looking to do is to change these urls based on the current envrionment by setting a variable/token of some kind. For example:

* If the site is in dev, it links to all other dev versions of the software. For example dev-drupal.website.com links to dev-software1.website.com and dev-software2.website.com
* If the codebase moves to testing, there is a file (for example the template.php) file that either doesn't need to be changed, or needs to be changed once to change all of the links.

There are over a dozens of these externally linking software pieces, and they are often linked in the content, but there are also menu items, blocks and a few views. Currently we have to do a find and replace to manually change these links one at a time. I'm trying to figure out if there is a better way, perhaps through a template variable or a token. Any ideas? This solution would ideally not be stored in the db, but I'm flexible.

I'm looking for suggestions on the best approach.

# Answer
> 0 votes
I don't think I would try to do this in Drupal. I would setup a small proxy server using Apache/mod\_rewrite. You can rewrite your url's based on the source url. There is some good starter information at on the Apache doc site. There is also full on mod\_proxy, but I think mod\_rewrite would be sufficient for your use case.

# Answer
> 0 votes
At best, you should set the $base\_url in settings.php per environment and use relative links everywhere. A module like Pathologic will also help here. The last thing you want is to use links with the domain in them that get saved to the database - with relative links, you'll be gold.

You can determine environment from settings.php a few ways, either by ENV variable or server IP. You could also supply a folder per site to utilize multiple settings.php files. Drupal will use the domain folder it finds under sites/.

You may also be interested in looking at hook\_url\_outbound\_alter.

---
Tags: 7, navigation, tokens
---


# Question
Title: How to install Accelerated Mobile Pages (AMP) without composer
I do not wish to use composer.
I wish to try out Accelerated Mobile Pages (AMP) (in D8). Is this possible and how do I do it?

# Answer
> 5 votes
Since the AMP module requires the Lullabot AMP Library, there really is not a great way to install this *without* Composer. That is because Composer will update the autoloader information with that namespace and vendor information and fetch dependencies. Downloading the tarball of the module and the GitHub download unfortunately will not do the trick - you must use Composer. The module will block installation if it cannot find the class namespace of `\Lullabot\Amp`.

The Lullabot AMP Library also has its own dependencies listed in its composer.json, so Composer is required here.

---
Tags: composer
---


# Question
Title: Getting bootstrap accordion in views to aggregate based on user name?
I would like to have an accordion with the users name as the title. The users name should appear once with the latest 3 articles for each user/author inside the accordion container.

```
John
 * Monday Post
 * Tuesday Post
Jake
 * Monday Post

```

I've got Drupal 7 & views\_bootstrap. The user profile is customised to have first and last names.

I can get a similar result starting from content or user objects and creating a relationship.

With one author it looks like the following

with an accordion for each content item.

Logically it is an 'aggregate' although I understand that in sql there are limitations in using group by and presenting columns that aren't in the group by. The views UI seems to represent this, with group by on all columns. Distinct doesn't do it. So how?

The experimental view is

```
$view = new view();
$view->name = 'authors';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Authors';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Research Team';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'views_bootstrap_accordion_plugin_style';
$handler->display->display_options['style_options']['title_field'] = 'name';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: User: Content authored */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'users';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: User: First name */
$handler->display->display_options['fields']['field_first_name']['id'] = 'field_first_name';
$handler->display->display_options['fields']['field_first_name']['table'] = 'field_data_field_first_name';
$handler->display->display_options['fields']['field_first_name']['field'] = 'field_first_name';
$handler->display->display_options['fields']['field_first_name']['label'] = '';
$handler->display->display_options['fields']['field_first_name']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_first_name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_first_name']['settings'] = array(
  'field_formatter_class' => '',
 );
 /* Field: User: Last name */
 $handler->display->display_options['fields']['field_last_name']['id'] = 'field_last_name';
$handler->display->display_options['fields']['field_last_name']['table'] = 'field_data_field_last_name';
$handler->display->display_options['fields']['field_last_name']['field'] = 'field_last_name';
$handler->display->display_options['fields']['field_last_name']['label'] = '';
$handler->display->display_options['fields']['field_last_name']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_last_name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_last_name']['settings'] = array(
  'field_formatter_class' => '',
);
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['text'] = '[field_first_name] [field_last_name] ';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'uid';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_1']['id'] = 'status_1';
$handler->display->display_options['filters']['status_1']['table'] = 'node';
$handler->display->display_options['filters']['status_1']['field'] = 'status';
$handler->display->display_options['filters']['status_1']['relationship'] = 'uid';
$handler->display->display_options['filters']['status_1']['value'] = '1';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'uid';
$handler->display->display_options['filters']['type']['value'] = array(
 'blog' => 'blog',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'authors';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'views_bootstrap_accordion_plugin_style';
$handler->display->display_options['style_options']['title_field'] = 'name';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
   'field_first_name' => 'field_first_name',
   'field_last_name' => 'field_last_name',
   'name' => 'name',
);
$handler->display->display_options['defaults']['row_options'] = FALSE;

```

# Answer
The views nested accordion module worked
> 1 votes

---
Tags: views
---


# Question
Title: What does the project: key in module.info.yml do?
**Note:** this **is not** the book module from core.

I inherited a custom module that was not written by me. Its `.info.yml` contains a `project:` key which I have never seen ever before.

**ps\_book.info.yml**

```
name: Book
type: module
description: Provides lesson page structure
package: Pivotal Science
dependencies:

version: '8.x-1.0'
core: '8.x'
project: 'ps_book'

```

I noticed that when I install the module I get 3 errors in the log.

I did a mouseover, so you can read the full error. The other two are the same except they end in `es.po.` and `fr.po.`

In Let Drupal 8 know about your module with an .info.yml file I couldn't find any mention of the `project:` key.

If I remove the `project: 'ps_book'` line, I no longer get those 3 errors when I install the module.

Is there any official doc for this key? If not, should someone add it the docs?

# Answer
The Drupal 8 documentation for the keys to use in a .info.yml file doesn't mention it, but that is the same key documented in Writing module .info files (Drupal 7.x).

> ### project (Discouraged, packaging use only)
>
> Module maintainers should not use this at all. The packaging script on drupal.org will automatically place a string here to identify what project the module came from. This is primarily for the Update status module, so that Drupal installations can monitor versions of installed packages and notify administrators when new versions are available.

Drupal uses its value for building URLs when finding information about the module, or any file related to it. Technically, every Drupal core module could use the value of the *project* key to build a URL for something related to a module. I take the documentation gives the primary use of that key, since the Update module is present in all the last versions of Drupal.

I guess that, since its usage is discouraged, they don't document it for Drupal 8 to avoid users add it in their .info.yml files. It could help users creating a module that handles new keys in .info.yml files, though.
As for documenting it, I would document it just to avoid a developer creates a module that handles custom keys that conflict with the ones already used from Drupal core. I can understand this is seen as a use case that remotely interest developers, though.
> 3 votes

---
Tags: 8
---


# Question
Title: Using getThirdPartySetting() to get node type configurations in other hooks
In a Drupal 8 instance, getThirdPartySetting() function to save node type configurations using the `NodeTypeInterface` object like below

```
  $type = $form_state->getFormObject()->getEntity();
  $fields = $type->getThirdPartySetting('field_config', 'type_fields', array(''));

```

Now I need to use the configurations in a hook for validation, to be particular in `hook_entity_bundle_field_info_alter()`

```
function hook_entity_bundle_field_info_alter(&$fields
  , \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle)

```

It contains objects of `EntityTypeInterface` but not that of `NodeTypeInterface`. Now how can I access the configuration of the particular node type in the hook?

When I tried something like this in `hook_entity_bundle_field_info_alter`:

```
  $node_type = \Drupal\node\Entity\NodeType::load($bundle);
  $selected_fields = $node_type->getThirdPartySetting('field_config',
    'field_scope', '');

```

It throws an error as : *Call to a member function getThirdPartySetting() on a non-object*

# Answer
$bundle is the node type (ID), so you can load the node type based on that.

```
$node_type = \Drupal\node\Entity\NodeType::load($bundle);

```
> 3 votes

# Answer
There is scenario in Drupal 8, retrieve the third party settings of "field\_image" inside the preprocess function. below code used to getThirdPartySettings values.

```
$node_type = \Drupal::entityManager()->getFieldDefinitions('node', 'bundlename');
$settings = $node_type['field_image']->getThirdPartySetting('mymodule', 'field_scope');

```

It is working fine. :)
> 0 votes

---
Tags: hooks, 8, nodes
---


# Question
Title: View filtering based on entity reference revisions (Paragraph) type
I am working on a Drupal 8.3 installation and I want to create a single content type for each organization to be able to update their own content on the site (using the core permissions on content types).

For each content type, I want to use an entity reference revision field (Paragraph) and have the view display based upon the type of entity being referenced (there will a limit of one). I tried looking at using conditional fields (not production ready) and taxonomy term in the content type (not able to force matching of term to paragraph type).

I was hoping there was a way to build the filter criteria based on the paragraph type but only target\_id and target\_revision\_id are selectable.

The brute force approach would require I create 6 content types per organization, but having over 100 content types seems overwhelming effort to create. Is there another solution to keep this DRY and easily understood for novices to add content?

# Answer
Go to the Advanced section of the view and add a relationship:

```
RELATIONSHIPS
field_paragraph: Paragraph

```

Then you can add filters for all paragraph fields including the field for the paragraph type.
> 4 votes

---
Tags: views, 8, paragraphs
---


# Question
Title: Passing arguments into hook_block_view in custom module
I'd like to pass a variable ($myvariable) into the block\_view function in my custom module, so i can see the content of the variable in the block content.

But there must be something i do wrong, because the below code gives me the following error:

> Warning: Missing argument 2 for mymodule\_subscribe\_block\_view ...

```
/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
$myvariable = 'test';
function mymodule_subscribe_block_view($delta = '', $myvariable) {
  switch ($delta) {
    case 'mymodule_test':
      $block['subject'] = t('Test block');
      if (user_access('access content')) {
          // Pass data through theme function.
          $block['content'] = $myvariable;
      }
    return $block;
  }
}

```

I'd greatly appreciate any hints on what's going wrong here.

# Answer
The error is caused from the fact you are declaring that `hook_block_view()` implementation as requiring two arguments, but the code invoking `hook_block_view()` is passing a single argument. If you would not want to see that error, you should use this code.

```
function mymodule_subscribe_block_view($delta = '', $myvariable = 0) {
  switch ($delta) {
    case 'mymodule_test':
      $block['subject'] = t('Test block');
      if (user_access('access content')) {
          // Pass data through theme function.
          $block['content'] = $myvariable;
      }
    return $block;
  }
}

```

Now, although that code would fix the error message you are seeing, it would not solve the fact `mymodule_subscribe_block_view()` would always receive 0 as second argument, since Drupal doesn't know anything about that implementation needing a second argument.

The question really is: How do I pass a value I calculate in some other function to a hook I implement in my module?
I take you are interested in passing a dynamic value, or the `hook_block_view()` implementation could easily use a literal value in its code (e.g. `$myvariable = 42;`).

Leaving out the case of `hook_block_view()` calling a function to get the dynamic value it needs, you could use `drupal_static()` to share a value between two functions (also in the case one of those functions is a hook, or both are hooks).
Keep in mind that:

* If the value returned from `drupal_static()` is set from another hook, you need to be sure `hook_block_view()` is invoked after that hook; differently, `hook_block_view()` will always receive the default value (passed as second argument to `drupal_static()`)
* If the value returned from `drupal_static()` is set from a function (that is not a hook), you could as well directly call that function from the hook
> 1 votes

# Answer
If you need to pass a variable into a block, maybe you should try using template\_preprocess\_block ?

Inside this function you define your variable and afterwards in your block you use it.
> 1 votes

---
Tags: blocks, hooks
---


# Question
Title: Adding users to entity reference field by custom field
I have added some custom fields to my D8 site's user profiles. Would it be possible to add users to a entity reference field on a node using one of these? For example phone number, as that is one of the fields. Or am I stuck referring to only the users username?

# Answer
You can use any field to lookup a user in a entity reference field. You just need 2 things: an entity reference View & a configured entity reference field.

1. Through the Views UI, you can add a *User* view with an *Entity Reference* **Display**. Add any fields to the View that you'll want to search on. Once your do, the **Settings** link next to **Format:Entity Reference list** will popup a modal that will let select your **Search Fields**.
2. After you've created your view, add your node's entity reference field. Set the **Reference method** to *Views: Filter by an entity reference view*. Where **View used to select the entities** is set to the view you created in step #1. Once the new field config is saved, you'll be able to search for any users based of the text values in the fields selected in **Search Fields**.
> 2 votes

---
Tags: users, entities
---


# Question
Title: How do I apply loop into node twig template?
This is code I am using.

```
<div class="blog-main-content">
  <figure>{{ content.field_article_main_content[0] }}</figure>
  <p class="intro-pera">{{ content.field_article_main_content[1] }}</p>
</div>

```

How can I change that code to make it loop over `content.field_article_main_content`?

# Answer
I would use code similar to the following one.

```
<div class="blog-main-content">
  {% for key, item in content.field_article_main_content %}
    {% if key == 0 %}
      <figure>{{ content.field_article_main_content[key] }}</figure>
    {% else %}
      <p class="intro-pera">{{ content.field_article_main_content[key] }}</p>
    {% endif %}
  {% endfor %}
</div>

```

If it happens that some values of `key` start with #, then I would use the following code.

```
<div class="blog-main-content">
  {% for key, item in content.field_article_main_content if key|first != '#' %}
    {% if key == 0 %}
      <figure>{{ content.field_article_main_content[key] }}</figure>
    {% else %}
      <p class="intro-pera">{{ content.field_article_main_content[key] }}</p>
    {% endif %}
  {% endfor %}
</div>

```
> 2 votes

---
Tags: theming, nodes
---


title: Display the username in a custom block

text:
# Question
Title: Display the username in a custom block
I'm using D7 and I have a custom content type (Client) and I have a custom select list field for the User entity displayed in a custom block.

I have a custom display layout for the *Client* content type, wherein all fields are displayed in different blocks using Display Suite. The user's name is displayed only when the user field is enabled in the node main content, else it remains blank.

How do I display the username in the block without the need to keep the field enabled in another part of the node view?

# Answer
> -1 votes
try with arguments or use views module and configure your block view CONTEXTUAL FILTERS

---
Tags: nodes, display-suite
---


# Question
Title: Override page template and preserve administration navigation bar
Short version; I am trying to override the default page.html.twig (in D8) for a controller from my module and the following examples I've found have not worked:

My company is developing a custom module to embed a React app we originally built for another system inside the admin side of Drupal. As such, we would like to keep the admin navigation visible but the main body of the page should just be the react app.

So far, I have successfully embedded the app as the content of a page, but still have the page's header, footer, breadcrumbs, etc. I'm not sure if I'm declaring my module's theme incorrectly, or if my naming is wrong for my template, or something else.

Thanks in advance!

Module name: **my\_module**

---

my\_module.info.yaml

```
name: Overriding page module
description: "Module with a template that overrides the default page.html.twig"
package: mystuff

type: module
core: 8.x

```

my\_module.module

```
function my_module_theme() {
    $theme['page__my_module'] = [
        'template' => 'page--my_module',
    ];

    return $theme;
}

```

my\_module.routing.yml

```
my_module.content:
  path: '/hello'
  defaults:
    _controller: '\Drupal\my_module\Controller\HelloController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

```

templates/page--my\_module.html.twig

```
{#
  Taken from https://api.drupal.org/api/drupal/core%21themes%21seven%21templates%21page.html.twig/8.2.x
#}

  <header class="content-header clearfix">
    <div class="layout-container">
      {{ page.header }}
    </div>
  </header>

  <div class="layout-container">
    {{ page.pre_content }}
    {{ page.breadcrumb }}
    <main class="page-content clearfix" role="main">
      <div class="visually-hidden"><a id="main-content" tabindex="-1"></a></div>
      {{ page.highlighted }}
      {% if page.help %}
        <div class="help">
          {{ page.help }}
        </div>
      {% endif %}
      <h1 style="color:pink;">WHY DOESN'T THIS TEMPLATE GET USED!?</h1>
      {{ page.content }}
    </main>

  </div>

```

src/Controller/HelloController.php

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
    public function content() {
        return array(
            '#type' => 'markup',
            '#theme' => 'my_module',
            '#markup' => $this->t('Hello World!')
        );
    }
}

```

**UPDATED**

Thanks to @kiamlaluno, I found I could use the theme suggestions hook to tell drupal what theme to apply. I changed my\_module.module to:

```
<?php

function my_module_theme_suggestions_page(array $variables) {
  $path = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  if (isset($path[0]) && $path[0] == 'hello') {
    return 'page--my-module';
  }
}

function my_module_theme() {
    $theme['page--my-module'] = [
        'template' => 'page--my_module',
    ];

    return $theme;
}

```

and removed the #theme item from the controller's render array. It works now!

# Answer
> 2 votes
What the code is missing is the code that sets those variables the template file is using. Since you are using page--mymodule as template name, the module needs to implement `template_preprocess_page__mymodule()`.

Alternatively, you can suggest a template file using `hook_theme_suggestions_page()`.

```
function my_module_theme_suggestions_page(array $variables) {
  $path = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  if (isset($path[0]) && $path[0] == 'hello') {
    return 'page--mymodule';
  }
}

```

Implementing `hook_theme_suggestions_page()` like I show, page--mymodule.html.twig will get the variables set in `template_preprocess_page()`, which are the same variables passed to page.html.twig.

---
Tags: theming, page-controller
---


# Question
Title: Why is my rule that reacts on event "After updating an existing user account" firing twice?
I have a rule that e-mails me if a user updates a value of a field on their profile (this value is the name that is displayed for that user on the site; I e-mail changes to the names to make sure no one changes their name to something insulting, etc.)

However, the rule fires twice for a reason I don't understand.

The rule has a condition *compare data value* in which it checks to see if the account-unchanged and account variables have different values for the same field. When I look at the rules debug log, I see that during *Reacting on event 'After updating an existing user account'*, there is a second *Reacting on event 'After updating an existing user account'* within the first, and so the rule gets triggered twice. How can I prevent this from happening?

If it helps, here is the rule:

```
{ "rules_notify_if_user_changes_name" : {
    "LABEL" : "Notify if user changes name",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-acc-displayname" ],
          "value" : [ "account:field-acc-displayname" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "myemail@myemail.com",
          "subject" : "[account-unchanged:field-acc-displayname] changed name to [account:field-acc-displayname] (UID: [account:uid])",
          "message" : "[account-unchanged:field-acc-displayname] changed name to [account:field-acc-displayname] (UID: [account:uid])",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

# Answer
It sounds like some other module code is calling a `user_save` on `hook_user_update` triggering the rules event a second time.
> 3 votes

# Answer
It is a not ideal solution (meaning performance, rule still run twice) but IT WORKS!! I saw on drupal.org a patch for node module in core and did not like it. This solution need no code or patches. Only once my data is saved, I have a lot of modules enabled, so is very difficult to know which one is causing rules trigger twice. I added a hidden "Boolean Trick field" on my contentype (should work also on user bundle) and set it default value to true, you need conditional rules module to do it, and I did the following in rules, simple but effective:
> 3 votes

# Answer
If you're able to execute PHP in your rules you can do this as a condition:

`//lets see when we last changed this user
 $vnam = $account->uuid.":last_saved";
 $retVal = TRUE;
 $t_changed = variable_get($vnam,0);
 $now = time();
 variable_set($vnam,$now);
 //within 10 seconds, no second trigger
 if (($now - $t_changed) <= 10){
 $retVal = FALSE;
 }
 return $retVal;
 // done saving changed timestamp`
> 0 votes

---
Tags: rules
---


# Question
Title: Programatically get a list of node ids of a content type for a specified language
From the following code I get all the node ids of content type 'blog'

```
    $query = \Drupal::entityQuery('node');
    $query->condition('status', 1);
    $query->condition('type', 'blog');
    $query->sort('created', 'ASC');
    $entity_ids = $query->execute();

```

I want to retrieve all the node ids of specific language. Eg. Node ids of content type 'blog' for 'French' language.

# Answer
> 3 votes
You can just add `langcode` to the query:

```
$query->condition('langcode', 'fr');

```

---
Tags: database, i18n-l10n
---


# Question
Title: How to update the uid of a node in node revision table?
Is there any way to update the node's `uid` in the `node revision` table using rules.

I have used the `node:author` but it only update the `uid` in the `node` table and does not update in the `node revision` table.

Is there any other way?

# Answer
Along with what Japo said, the latest revision will mirror the update, it does not get applied retroactively, not sure why you would want that specifically. Unless this is a case where anonymous users create content or are assigned content and you want them to have edit access to all past revisions?

Either way, nothing will solve this for you short of a custom module that does a db query to force the UID value on the table.
> 0 votes

---
Tags: 7, rules
---


title: Taxonomy term issue

text:
# Question
Title: Taxonomy term issue
It is just one month that i started working on drupal8 and i am stuck with some taxonomy term issue.I created a vocabulary Skill Set and the terms included in that are: Php,.net,sql,java. In my content Jobs i have added this taxonomy Skill Set. When i select a term the id associated with it is displayed (e.g.,when i select Php,the id also is displayed as Php(23)). To overcome this issue i had installed chosen module and my problem was solved and their was no Id being displayed along with term.But the requirement is that the recruiters should be able to add new skill sets on the front end itself while posting a job and this is where i am facing the problem.When i try to post a job and add a new term to skill set(e.g., python) it displays:"no results match".Please help me to fix this issue. Thanks in advance for the help!!

# Answer
> 0 votes
Go in your field settings in the "REFERENCE TYPE" section and click on "Create referenced entities if they don't already exist"

---
Tags: taxonomy-terms
---


title: Cron task does not create images

text:
# Question
Title: Cron task does not create images
I've made a module which will parse a few RSS feeds, and automatically creates new content. But I've got an issue creating images.

Since D7, cron are run anonymously, so I think my problem comes from here.
Is there a way to allow anonymous user to create images?

Here's the way I'm doing it. It works if I call `FeedController::import` via a route, and connected ; but not if I call it through Drupal's cron task.

**rssfeed.module**

```
<?php
use Drupal\rssfeed\Controller\FeedController;

function rssfeed_cron() {
  FeedController::import();
}

```

**src/Controller/FeedController.php::import**

```
public function import()
{
  $params = array();
  // some stuff to fill $params array

  $hash = ...;
  $src  = ...;
  $alt  = ...;

  $data = file_get_contents($src);
  $size = getimagesize($src);
  $extension = image_type_to_extension($size[2]);
  $file = file_save_data(
    $data,
    sprintf('public://rss/%s.%s', $hash, $extension),
    FILE_EXISTS_REPLACE
  );

  if ($file) {
    $params['field_image_main'] = array(
      'target_id' => $file->id(),
      'alt' => $alt
    );
  }

  $node = Node::create($params);
  $node->save();
}

```

# Answer
As a possible (but possibly not the best) solution it might be the 'account\_switcher' service could help. It would elevate permissions for your cron job.

```
use Drupal\Core\Session\UserSession;

// call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// switch to the admin user
$accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// run your code here

// switch back to old session
$accountSwitcher->switchBack();

```

zessx, please share your solution, if you've found one.

See original Q&A here.
> 0 votes

---
Tags: 8, media, cron
---


# Question
Title: Export and import modules of an installation
In almost every drupal installation I set up, I use a package of modules. So my question is simple. Is there any way or module or something like that that will do this in an easy way?

To be more specific I am searching for a tool or something like that that will export a list of selected modules from one drupal installation. Then after a fresh installation, I would import this list and the modules would be automatically installed.

Is there any tool/module that can achieve what I described?

Thx in advance

# Answer
> 0 votes
Drush Make can easily create a makefile of all the modules installed on a site, and `drush make [make-file]` can instantly download those modules to an empty drupal project folder.

# Answer
> 0 votes
It sounds like you are describing two kinds of workflows.

One way is to use Features \- where you package functionality into modules. In your case, you would create a Feature, select modules as dependencies as well as any configuration you want to carry forward. When the feature is enabled, all those modules are enabled.

Another way is defining dependencies with Composer (8.x) and combine that using Features and build tasks to automate this further, where nuking and reinstalling Drupal returns to the same state, kind of like an install profile in a sense.

---
Tags: importing-exporting
---


# Question
Title: Calling user/token and system/connect through CORS returns anonymous user
I have two Drupal sites set up. On site A, I'd like to authenticate myself as the currently logged-in user on site B (the remote site) so that I can view and edit nodes on the remote site using the Services module.

The two sites are on different domains, so I'm using the CORS module on the remote site. My CORS config is as follows:

```
*|http://MY-SITE-URL|*|Content-Type,X-CSRF-Token,Authentication, Origin, Cookie|true

```

Calling `user/token` against the remote site gets me a valid X-CSRF-Token. However, when I send the X-CSRF-Token with `system/connect`, the remote server returns the anonymous user.

I'm trying to authenticate against the remote server with the following code:

```
$base_url_api = variable_get('tnb_sync_base_url'); //URL of the remote server

            $options = array(
              'headers' => array(
                'Content-Type' => 'application/json',
              ),
              'method' => 'POST',
            );
            //Step 1: grab the authentication token from the remote server
            $response = drupal_http_request($base_url_api . '/user/token', $options);
            $data = json_decode($response->data);

            // Check if login was successful
            if ($response->code == 200) {
              // Add the token to the request headers:
              $options['headers']['X-CSRF-Token'] = $data->token;

              //Step 2: pass along the token and check who we're logged in as
              $response = drupal_http_request($base_url_api . '/system/connect', $options);
              $data = json_decode($response->data);

              kpr($response);

              return $options;

            }

            else {
                return NULL;
            }

```

The **response** for the `system/connect` call looks like:

```
stdClass Object
(
    [request] => POST /sync/system/connect HTTP/1.0
Content-Type: application/json
X-CSRF-Token: 74xWvd5I5l1ad1WmrIjqZoACo9r7f30YtJx_uCFot_g
X-NewRelic-ID: VQQAU1JbChACUldTBgUFVw==
X-NewRelic-Transaction: PxQBVFRUXQJUUVQGVQkFBVIEFB8EBw8RVU4aVA0KA1cCAQxUVQMLUAcAAkNKQQgKVVAEUgEEFTs=
User-Agent: Drupal (+http://drupal.org/)
Host: dev.tnb.plus
Content-Length: 0

    [data] => {"sessid":"7u8CZ98Gvb1P3ZuKSnK85g2FMkyu8OlqbOp8mnsy7OM","session_name":"SSESS4be586c0dc3085a3ca4f49c7acb4e7d1","user":{"uid":0,"hostname":"2001:4801:7827:0104:be76:4eff:fe11:ccd8","roles":{"1":"anonymous user"},"cache":0,"timestamp":1492095786}}
    [protocol] => HTTP/1.1
    [status_message] => OK
    [headers] => Array
        (
            [date] => Thu, 13 Apr 2017 15:03:06 GMT
            [content-type] => application/json
            [connection] => close
            [set-cookie] => __cfduid=dc62becfa48db03b7f5e40b426d0f587c1492095786; expires=Fri, 13-Apr-18 15:03:06 GMT; path=/; domain=.tnb.plus; HttpOnly
            [access-control-allow-credentials] => true
            [access-control-allow-origin] => http://dan-northern-portal.pantheonsite.io
            [cache-control] => no-cache, must-revalidate
            [expires] => Sun, 19 Nov 1978 05:00:00 GMT
            [surrogate-key] => AuKS06yStxtoXZf2mZvq kFG3DJ+3z7Lu2WK6wNkS
            [surrogate-key-raw] =>
            [vary] => Accept-Encoding, Accept
            [x-content-type-options] => nosniff
            [x-drupal-cache] => MISS
            [x-pantheon-endpoint] => a9463df4-67b3-47b9-ad41-148336613222
            [x-pantheon-styx-hostname] => styx94699a92
            [x-styx-req-id] => styx-e58976d158f4a1f2e669efc5205db167
            [x-styx-version] => StyxGo
            [xkey] => AuKS06yStxtoXZf2mZvq kFG3DJ+3z7Lu2WK6wNkS
            [x-varnish] => 952125076
            [age] => 0
            [via] => 1.1 varnish-v4
            [server] => cloudflare-nginx
            [cf-ray] => 34ef4f698acf2513-ORD
        )

    [code] => 200
)

```

How can I properly authenticate myself on the remote site using Services and CORS?

# Answer
> 0 votes
You just haven't logged in to the remote site yet; you can do that with something like:

```
$options['headers']['X-CSRF-Token'] = $data->token;
$options['method'] = 'POST';

$post_data = ['username' => 'foo', 'password' => 'bar'];
$options['data'] = drupal_http_build_query($post_data);

$response = drupal_http_request($base_url_api . '/user/login', $options);
$data = json_decode($response->data);

```

Assuming a successful login, subsequent requests within the session timeout will be made in the context of that user.

---
Tags: 7, services
---


title: page.tpl.php override for Panels Pages?

text:
# Question
Title: page.tpl.php override for Panels Pages?
I want to use a specific tpl.php file for all Panels Custom pages.

I get some formatting issues if I try to use "Panels Everywhere" module, so would like an alternative.

# Answer
You can use a template\_preprocess\_page function to add your custom tpl for Panels page. Here's how:

```
/**
 * Implements template_preprocess_page().
 */
 function MODULEORTHEMENAME_preprocess_page(&$variables) {
    if (module_exists('page_manager') && count(page_manager_get_current_page())) {
        $variables['theme_hook_suggestions'][] = 'page__panels';
    }
 }

```

Then create a page--panels.tpl.php for your custom Panels page.
> 7 votes

# Answer
@arshacn answer is correct, as the question is to affect all panel pages, but if you need a separete tpl, or only affect a few, for any contentype do this:

```
// ads theme-hook-nodetype-suggestions
      function MYMODULEORMYTHEME_preprocess_page(&$vars, $hook) {
        if (isset($vars['node']->type)) {
        $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
        }
    }

```

this will add "page--yourcontentype.tpl.php" suggestion, then create a page--yourcontentype.tpl.php for every contentype needed, place tpl file in your subtheme template folder.
> 0 votes

---
Tags: panels, theming, 7, debugging
---


title: External JSON to create/update node

text:
# Question
Title: External JSON to create/update node
I have external REST service with some info about products. This comes from some software of the company.

How I can use this JSON I got to create nodes and fill in the fields in nodes?

Also, I need to detect when something is changed and to update field in existing node.

I'm on Drupal 8 and I'm getting JSON with POST method (I need to send 'id' parameter in order to get product for exact client).

Any ideas?

# Answer
The Feeds Module does this great for D7, offering cron imports and ability to update existing nodes/etc. Looks like they have a D8 branch, but I haven't tested. Might be helpful to look at for you.
> 0 votes

---
Tags: 8
---


# Question
Title: Wanna save text_format custom form in comment
I'm using a custom form in CTools Modal to alter comment.

```
$form['subject'] = array(
   '#type' => 'textfield',
   '#title' => t('Title'),
   '#default_value' => $comment->subject,
);
$form['comment_body'] = array(
   '#type' => 'text_format',
   '#default_value' => $comment->comment_body['und'][0]['value']
);

```

All is good. I get my comment title and my comment body which is pushed in ckeditor field. My submit :

```
$comment = comment_load($form_state['values']['cid']);
$comment->comment_body['und'][0]['value'] = $form_state['values']['comment_body']['und'][0]['value'];
$comment->subject = $form_state['values']['title'];

comment_submit($comment);
comment_save($comment);

```

The subject is goodly saved from my form but for the body, it save an empty value.

Ps: when I change `text_format` for `textfield`, it work.

# Answer
You forgot to add the format:

```
$comment->comment_body[LANGUAGE_NONE][0]['format'] = $form_state['values']['comment_body'][LANGUAGE_NONE][0]['format'];

```
> 0 votes

---
Tags: ajax, comments, wysiwyg, chaos-tool-suite
---


# Question
Title: 500 (Service unavailable (with message)) on login or register
Effectively the same as this (Drupal 500 Internal server error on login page) but i am unable to bump or comment so resorting to adding my own question.

The site is running Drupal 7.54 php version 7 and uses LoginToboggan module with login.

I am receiving "500 (Service unavailable (with message))" on the user and register pages, this occurs against user/login and ?q=user/login equivalent. Otherwise the site operates normally. There are no PHP errors in the log or browser console so i have nothing to try and trace.

I have amended the .htaccess file to use Rewrite as suggested elsewhere (this was already enabled anyway as the site sits in a subdomain).

Clean URLs are enabled.

I have added error reporting to settings.php to try and pick up on errors i've otherwise missed, nada.

I have used phpMyAdmin to clear the sessions table as suggested on another old thread. This resulted in me being kicked out and unable to get back in.

I can now only access the site db via phpMyAdmin and the site files via ftp (unable to log in as admin as login throws the error)

I tried to run update.php (removing login requirement from settings) out of sheer desperation but this had no effect.

Again in desperation i removed the LoginToboggan module (via ftp, i know) to try and revert the login to core but this had no effect.

I thought the main domain was conflicting in some way so i removed it (it wasn't actually used for anything and had an independent db so i just uninstalled it. No effect.

I really am at a loss, i can't figure out the cause and so have no way to implement a fix..

# Answer
As you have access to the database through PhpMyAdmin, have a look in the `watchdog` table for any errors.

Disable anything causing an issue ;)
> 0 votes

---
Tags: users, debugging, authentication-authorization
---


# Question
Title: How set specific input format for specific field like in Drupal 7?
I am in a need of the Drupal 7 functionality where I could select specific input format for specific field whereas in Drupal 8 this is based on permissions and I really dislike it and for a specific project I need the good old D7 behavior.

Right now I have to alter the input format's static cache during page load to achieve the goal of providing specific input format but it is very bad approach but I haven't found an easy way to do this yet.

Better yet, I need this for my custom form, not even a field but the permissions still apply so Field API has nothing to do with it but rather how the input formats and the text format element are tied together.

FYI this is my solution right now(it is ES service):

```
    $route_name = $this->routeMatch->getRouteName();
    $routes = [
      ...
    ];

    if (in_array($route_name, $routes)) {
      filter_formats($this->user);
      $formats = &drupal_static('filter_formats', []);
      $formats['user'][$this->user->id()] = [
        'my_format' => $formats['all']['my_format']
      ];
    }
  }

```

# Answer
> 1 votes
The way I recently did this on a Drupal 8 site was to use Better Formats.

https://www.drupal.org/project/better\_formats

You can force filter format per field - one option = no select box. Even for admins.

If you are using Paragraphs, you will also need this patch.

---
Tags: 8, input-formats
---


title: Conditional Fields Module in drupal 8

text:
# Question
Title: Conditional Fields Module in drupal 8
Hi I have enabled the drupal 8 conditional fields module , but I do not see anywhere to configure it, the "Malnage Dependencies" tab that is supposed to appear does not show. Am I missing a step? thanks,

# Answer
> 1 votes
According to the code, these are the admin routes. The links file would indicate that Conditional Fields should appear in the Structure area of the admin. Did you clear cache after enabling it? It should be in the Structure menu.

---
Tags: 8
---


# Question
Title: hide a view field content for anonymous only?
How can I hide a field for the anonymous user in a view?

Logged in users should still be able to see the field.

(Drupal 8.3.0)

# Answer
If this is in Views like you say, you can simply add an access restriction by role. Set it to 'authenticated' - the view display will only show for authenticated roles.

Outside of Views displays, you will need another mechanism like Field Permissions to control visibility.
> 1 votes

# Answer
This might be overkill for just one field, but you could take a look at the Field Permissions module: https://www.drupal.org/project/field\_permissions. This module allows you to set permissions on a per-field basis, so you can just remove all permissions for anonymous users for this field.
> 1 votes

# Answer
I assume this is not the cleanest solution, but it's simple.

Place the following code in your module's \*.module file. So, if you're module is called **module\_name**, place it in **module\_name.module** file. And the function name should begin with **module\_name** as written below:

```
function module_name_views_pre_build(ViewExecutable $view) {
    if ($view->id() == 'view_name') {
        if (\Drupal::currentUser()->isAnonymous()) {
            unset($view->field['field_first_name']);
        }
    }

}

```

For more information check hooks.
> 0 votes

---
Tags: views
---


# Question
Title: template associated with views style-plugin, and then customized for particular view: views does not find template
I have a style plugin, 'mystyle'. And I created a view, 'myview', with style set to 'mystyle'.

Here is the declaration of 'mystyle' in hook\_view\_plugins:

```
function mymodule_views_plugins() {
  $plugins = array(
    'module' => 'mymodule',
    'style' => array(
      'mystyle' => array(
        'title' => t('My Style'),
        'handler' => 'mymodule_views_plugin_mystyle',
        'theme' => 'mymodule_views_plugin_mystyle_template',
        'uses fields' => TRUE,
        'uses row plugin' => FALSE,
        'uses options' => TRUE,
        'uses grouping' => FALSE,
        'type' => 'normal',
        'even empty' => FALSE,
      ),
    )
  );
  return $plugins;
}

```

I have the following files in mymodule/views:

*(handler)* mymodule\_views\_plugin\_mystyle.inc

*(template associated with this style)* mymodule-views-plugin-mystyle-template.tpl.php

*(template associated with this style, and customized for the view 'myview')* mymodule-views-plugin-mystyle-template--myview.tpl.php

My problem: Views is using the first, less specific, template (mymodule-views-plugin-mystyle-template.tpl.php) to display this view.

When I edit 'myview' and click on "theme information", I see both templates listed under "style output":

* mymodule-views-plugin-mystyle-template.tpl.php
* mymodule-views-plugin-mystyle-template--myview.tpl.php

The first, less specific, template is in bold. If I understand correctly, this means that views found the first template but did not find the second.

I have tried rescanning, but that does not help. I have also tried deleting the cache.

Should this work? What do I need to do to get views to find the more specific template?

# Answer
Drupal by default doesn't scan for more specific templates in modules directories, but views allows you to do it by adding 'template path' to hook\_views\_api(), see: https://api.drupal.org/api/views/views.api.php/function/hook\_views\_api/7.x-3.x
> 1 votes

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


# Question
Title: How to make my custom theme suggestion the most specific
Is it possible to guarantee my custom theme suggestion is at the top of the list for theme suggestions? Something like the following

```
<!-- FILE NAME SUGGESTIONS:
  x my-custom-theme-suggestion.html.twig
  x input--textfield.html.twig  // ALSO WHY DO I HAVE TWO OF THESE
  x input--textfield.html.twig
  * input.html.twig
-->

```

Also I'm not sure why but I have two theme suggestions that are the same. Anyone else experience that?

# Answer
> 0 votes
Suggestions is a PHP array that is provided by a hook and an alter hook. The standard rules apply, alter hook is later, so add it there to be more likely to be the last.

And if you want to be sure, set the module weight and/or implements hook\_module\_implements\_alter() to ensure that your module is the one that is called last.

If you want to implement this in a theme then you only use the alter hook anyway and the module\_implements\_alter() won't work, but themes and especially the active themes are called last anyway.

The duplicate is possibly because the defaults include a suggestion for the field type and one for the field name, so if you name it the same as the field type, then you get the same suggestion twice

---
Tags: theming, 8
---


# Question
Title: Number of paragraph items and translation
I know that Paragraph field itself are not translatable for some reasons. I wanted to know if we could still have separate number of paragraph items between two translations of a node.

Example:

* Node 1 FR

+ Paragraph 1
    + Paragraph 2
* Node 1 EN

+ Paragraph 1
    + Paragraph 2
    + Paragraph 3

I found no clear explanations on that.

# Answer
> 2 votes
Not really in an easy way. We're working on an alternative approach to making the field translatable in the *experimental* paragraphs collection project: https://www.drupal.org/node/2846682.

Basically, this adds a setting to optionally control visibility of a paragraph in another language. This is a useful approach for use cases where differences between language are the exception and not the rule.

You can also build something similar yourself with a standard list field or an entity reference field to languages and then implement something in preprocess, twig or entity access to hide the paragraphs based on that.

But the only way to have completely different paragraph structures is to have the field translatable, and that's still a work in progress.

---
Tags: 8, i18n-l10n, paragraphs
---


# Question
Title: How to get file from managed_filed in drupal 8 generate image style and use as background image for a div
I had created a form filed to upload an image on a themes settings page like this

```
$form ['ad_tv']['tv_adbackground'] = array(
    '#type'     => 'managed_file',
    '#title'    => t('Hintergrundbild'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('tv_adbackground'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),

),

```

Now I like to know

with preprocess function to use in mytheme.theme to make sure the file gets overwritten, if a new one is uploaded. how to add the path of the uploaded file or its image style to add the path as background image to a div with a css id called advertisement

I hape that this is not to much for one question. I am new to drupal 8. So any help will be welcome-

thank you.

# Answer
Untested, but you should be able to do this:

```
$style = Drupal\image\Entity\ImageStyle::load(IMAGESTYLENAME);

$url = $style->buildUrl(theme_get_setting('tv_adbackground'));

$element['background'] = [
  '#prefix' => '<div style="background-image:url(' . $url . ')">',
  '#suffix' => '</div>',
  // Force rendering of this element
  '#markup' => '',
];

```

You'll need to change IMAGESTYLENAME to the actual image style you want to apply.
> 0 votes

---
Tags: theming
---


# Question
Title: Doing a php post to an api end point after a node is created or webform is submitted?
What modules are required to setup drupal to POST to an api endpoint when a node or a webform is created? I'd imagine it would be rules, but how would one set that up or is that even possible doing this via the interface without the need to code anything?

# Answer
> 1 votes
There's already a built in HTTP client function `drupal_http_request()` that's in Drupal core that can perform any HTTP verb, including POST.

As for what module, that's one of those broad, sorta DA off-topic, depends-on-your-use-case answers. Since you mentioned Rules, there's a Rules HTTP Client, that provides a Rules action wrapper around `drupal_http_request()`.

Also worth mentioning here, is the concern of adding an external web dependency within code responding node/webform submission; you're adding the possibility of locking up a node/webform submission request as PHP waits for a web response (e.g. if the API endpoint host is down). If you want to guarantee execution of an HTTP POST (and not hang your server), you should look at some sort of asynchronous solution (e.g. a queue job) if you can tolerate it.

---
Tags: 7, rules
---


# Question
Title: how to resend email to new created user with wrong email
I created a new user, after several hours the email sent by the system was undelivered because the email was not correct.

After changing the email with the correct email, how can I resend the email? I could not find this.

# Answer
> 1 votes
`_user_mail_notify()` is the underlying Drupal function that does the work of sending out a user account creation email. You can reference the API doc link on how it's used, then call the function in the appropriate code context (e.g. menu callback, submission function, drush eval, etc.) for your situation.

---
Tags: users
---


# Question
Title: Using entity query build to apply conditions on all revisions
Best practice deems that you should use `EntityFieldQuery` for queries that somehow involve fields and entities.

An example of query to look for nodes with a timestamp value set in the future would be the following code.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_foo', 'value', REQUEST_TIME, '>')
  ->execute();

```

Is applying the conditions on all revisions, instead of only the active revision, possible?

A direct query on the database tables used to store the field revision values could eventually stop to work when Drupal changes some implementation details, such as the name of the used database tables, or the data stored in those database tables.

# Answer
Yes. `EntityFieldQuery` has a method, `EntityFieldQuery::age()`, which is used to limit the revisions of the returned entities. It can be set to:

Support for this value ultimately depends on the query callback. The default query callback, `field_sql_storage_field_storage_query()`, which is the `hook_field_storage_query()` implementation done from the field storage module, uses it to query the appropriate revision tables.
> 1 votes

---
Tags: 7, entities, database
---


title: Alter login form in block by id

text:
# Question
Title: Alter login form in block by id
I have a small problem on D7, I need to alter the login form inside block (add class to inputs, placeholder and submit button text, custom pass reset and login links) im using hook\_form\_FORM\_ID\_alter. I don't need to use custom module.

block id = block-user-login, form id = user\_login\_block

My theme.php code

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

    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );

   // custom register link
    $form['actions']['signup'] = array(
        '#markup' => l(t('Register'), 'user/register', array(
            'attributes' => array(
                'class' => 'top-user-block-link register',
                'title' => t('Create a new user account.')
            )
        )),
    );

    // custom reset password link
    $form['actions']['request_password'] = array(
        '#markup' => l(t('Forgot my password'), 'user/password', array(
            'attributes' => array(
                'class' => 'top-user-block-link new-password',
                'title' => t('Request new password.'),
            )
        )),
    );
}

```

Links for password reset and login links renders fine, but i can't make the placeholders or class add to work.

i've tried to use

```
function theme_form_alter(&$form, &$form_state, $form_id){
  if ($form_id === 'user_login_block') {
$form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
}

```

but i works only on /login page.

# Answer
> 1 votes
```
$form['name']['#attributes']['placeholder'] = t( 'Username' );
$form['pass']['#attributes']['placeholder'] = t( 'Password' );

```

Both the code are working. If you can't see your changes or placeholder.

Please try with `var_dump($form)`. You will find `$form_id` and all other fields of the form. just check your debug (array) ordering and make sure that order is same as in your `form_alter()` function.

# Answer
> 1 votes
If I recall correctly, you need `$form['account']['name']['#attributes']`.

---
Tags: forms, hooks
---