# Question
Title: How can I show a block on a specific page if a custom PHP function evaluates to be true?
Follow-up to the question "How can I show a single block only if the user is on iOS?".

I am using D7 and trying to show a message to iOS users that their devices of choice do not support basic upload functionality. I have a block that I would like to show only on the following path: `node/add/profile-picture` if the function mymodule\_is\_iOS() returns TRUE.

On the block configuration screen, I can easily limit it to a given path by adding the path to **Show block on specific pages**. However, if I do that, I cannot select *Pages on which this PHP code returns TRUE* to limit it to users for which the function mymodule\_is\_iOS() returns true.

I found some documentation on Drupal.org here (**Combining PHP visibility control with specific page visibility**) but it isn't relevant to my case.

Is there a way to do this by adding another function to my custom module for the site or theme? I'm not an expert in PHP but I do have custom functions in a custom module and in my theme.

# Answer
If you have already a custom module, you can implement hook\_block\_view\_alter() using code similar to the following one.

```
function mymodule_block_view_alter(&$data, $block) {
  if ($block->module == $module_that_creates_the_block && $block->delta == $delta_for_the_block_to_change) {
    if (mymodule_is_iOS() && $_GET['q'] == 'node/add/profile-picture') {
      $data['content'] = '';
      $data['title'] = '<none>';
    }
  }
}

```

Instead of `hook_block_view_alter()`, you can implement hook\_block\_view\_MODULE\_DELTA\_alter() which would be invoked only for a specific block. Checking the block delta, and the module implementing it would not be necessary, with this hook, and the code would be executed only for that block.

Alternatively, you can use the following code when you select the "Pages on which this PHP code returns TRUE" option.

```
<?php
  return (mymodule_is_iOS() && $_GET['q'] == 'node/add/profile-picture');
?>

```
> 2 votes

# Answer
By enabling core PHP Filter module, you will see another option "**Pages on which this PHP code returns TRUE (experts only)**" under **Show block on specific pages** of the block configuration page. Select the option and write the following code in the box.

```
<?php
  if (mymodule_is_iOS()) {
    if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'profile-picture') {
      return TRUE;
    }
  }
  return FALSE;
?>

```

Your module must have a lower weight than the core PHP filter module to allow this code snippet to call `mymodule_is_iOS()`.
> 4 votes

# Answer
The Rules block visibility module might be another alternative available ... Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

Moreover, as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you have the power of Rules available to implement all sorts of custom logic. For this specific question, you could specify 2 Rules conditions that must both be satisfied:

* **Condition 1**: Verify the current path is what you want it to be.
* **Condition 2**: Execute your custom PHP code.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How to display a block for pages that don't show nodes?
My Drupal 7 module creates a block, and then in admin I can make it available for the Article content type only. I would also like it to be available to the result page for a Product Search. This page is not of a normal content type and comes to life in `hook_menu()`.

The path for the results will be `avantlink-search-results/search term` and I would like it to show the block with the search form again. I would rather not use the PHP code option in the block visibility options so as to keep it simple for users of the module.

The code is viewable on AvantLinker.

# Answer
I think you may want to take a look at the context module. That allows you to define multiple conditions for displaying blocks.

However, you should also consider making your module only return content on pages that it makes sense to appear on. So the user doesn't have to worry about complex configuration.
> 2 votes

# Answer
You could use the Rules block visibility module for this. ... ***which doesn't require the PHP filter to be enabled***. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your "*result page for a Product Search*", as in your question).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "avantlink-search-results/",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

If needed, further adapt the value of `avantlink-search-results/` to fit your needs. And/or replace the Rules condition in it with something using an appropriate regular expression.
> 1 votes

# Answer
If you only want the block to show up on certain pages, the block admin settings page is already fit to do that. If you are using URL aliases (say the URL alias for the article content type is example.com/article/....) and not using the PHP filter, you could try:

Unless I missed something in the question, this should work in a basic setup.
> 0 votes

---
Tags: 7, blocks
---


title: One user with several profiles (pages)

text:
# Question
Title: One user with several profiles (pages)
What modules are available (profile2 would come in handy i guess) to create something like pages on facebook. Like on facebook each containing description, galleries and some other content i make available. All handled by user who created pages.

I have idea in theory how would each user create pages, but i have no idea how would he for example when uploading gallery tell Drupal that the gallery he just uploaded belongs to page 3, while this user has 10 pages.

# Answer
The 'edit own' permission should be all you need. Allow the user to create content of a specific node type. Put a gallery, description and any other fields on it.

A little more detail:

1. Create a content type 'Pages'.
2. Make sure users can create new pages and edit own pages.
3. The user makes as much 'Pages' as he wishes.
4. Put a gallery and any other fields on the content type.

If you want to use other content types instead of fields, use entity reference.
> 1 votes

# Answer
It might be overkill, but have you looked at the Organic Groups module?

Allow each user to create their own Group. Create different content types associated with groups.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Drupal 8 override administration theme node form css
I need to override some of the styles on the Seven node form. My initial thought is to alter the form and add a custom css file. Is there a better Drupal 8 way to achieve this?

Thanks,

Dave

# Answer
> 0 votes
If you only has to add some custom css form alteration will does it.

If you also have to make some changes in field templates, or some theme function alteration, I suggest you to create your custom theme, and add Seven as a base theme

---
Tags: theming, 8
---


# Question
Title: How to add extra data to a programmatically created node
Using Drupal 8 i am importing data from an external source and creating the node programmatically from the controller:

```
$node = Node::create(array(
  'type' => 'article',
  'title' => 'some title'
));
$node->save();

```

I want to add some extra field with the external id (e.g. "3cru\_81pazBBRbj5e8LZkZ").

Adding of the field should happen programmatically within the module without the need of the user having to add it via the ui.

I have been reading up on this but i have come to the point that tutorials have confused me more then helped me.

Any help would be greatly appreciated.

# Answer
I found this can easily be done using the Features module. Now i could create the the fields manually and then export them using features and copy the export to my custom module.
> 0 votes

# Answer
Field entities can be created via FieldConfig::create($values).

For example, in the UserRegistrationTest of core, a 'user\_picture' field is added to the user entity like this:

```
$field_storage = FieldStorageConfig::create([
  'field_name' => 'user_picture',
  'entity_type' => 'user',
  'type' => 'image',
]);
$field_storage->save();

$field = FieldConfig::create([
  'field_name' => 'user_picture',
  'entity_type' => 'user',
  'bundle' => 'user',
]);
$field->save();

```
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to check if field exists in an entity?
In entity node, I want to check if '`abc`' field exists or not. If exists, I will get its value by `$value->get('abc').`

But the content type where this field doesn't exists, gives error:

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

How to check if field exists in an entity?

# Answer
Since Drupal 8, you can use `FieldableEntityInterface::hasField()`.

```
$entity->hasField('abc')

```
> 105 votes

---
Tags: entities
---


title: How do I create a custom rule action?

text:
# Question
Title: How do I create a custom rule action?
I have drupal 8, and I want to create a custom rule action. I have created it in Drupal 7, and it's working fine. I have no idea how to do it in Drupal 8.

Can you please explain which code should I use for Drupal 8?

### Drupal 7 Code

```
function custom_rules_action_info() {
    return array(
        'custom_action1' => array(
            'label' => t('custom_action1'),
            'group' => t('Custom'),
            'parameter' => array(
                'user_id' => array(
                    'type' => 'integer',
                    'label' => t('User ID'),
                    'description' => t('User ID.'),
                ),
            ),
            'provides' => array(
                'return_value' => array(
                    'type' => 'text',
                    'label' => t('User Created with return_value'),
                ),
            ),
        ),
    );
}

```

# Answer
Check the actions of the Rules module:

http://cgit.drupalcode.org/rules/tree/src/Plugin/RulesAction?h=8.x-3.x

These are the actions provided out of the box by Rules.

Each action class has a `@RulesAction` annotation. Wire that up and you should see your Rules action appear. Think of the annotation here very similar to what you would have in `hook_rules_action_info()`.

The only exception is instead of defining it in the .module file, it will live in `mymodule/src/Rules/Plugin/RulesAction/NameOfYourAction.php`.

Here is an example of what it might look like:

```
namespace Drupal\mymodule\Plugin\RulesAction;

use Drupal\user\UserInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Provides a 'custom action' action.
 *
 * @RulesAction(
 *   id = "mymodule_custom_action",
 *   label = @Translation("Custom Action"),
 *   category = @Translation("Custom"),
 *   context = {
 *     "user" = @ContextDefinition("entity:user",
 *       label = @Translation("User"),
 *       description = @Translation("Specifies the user we are taking action on.")
 *     ),
 *   }
 * )
 *
 */
class NameOfYourAction extends RulesActionBase {

  /**
   * Flag that indicates if the entity should be auto-saved later.
   *
   * @var bool
   */
  protected $saveLater = FALSE;

  /**
   * Does something to the user entity.
   *
   * @param \Drupal\user\UserInterface $account
   *   The user to take action on.
   */
  protected function doExecute(UserInterface $account) {
    // execution code
    // you may want to set $this->saveLater based on your use case
  }

  /**
   * {@inheritdoc}
   */
  public function autoSaveContext() {
    if ($this->saveLater) {
      return ['user'];
    }
    return [];
  }

}

```

Please note that at the time of this writing, Rules is in alpha release state. It may change with subsequent releases.
> 6 votes

---
Tags: 8, rules
---


# Question
Title: dump() not working in Drupal 8 (blank page, debbugging is enabled)
I want to use `dump()` in my `.twig` template (inside custom theme).

The problem is, when I place `{{ dump() }}` the page is just blank.

I have had:

1. Set `twig.confing debug: true` in `services.yml`.
2. Cleared cache.

The moment I remove `{{ dump() }}` everthing works.

After hours of googling I've found some information about mystery `$settings['twig_debug'] = TRUE;` here (I don't even have such line in my file, but adding it doesn't change a thing) and `$twig = new Twig_Environment($loader, array(...` (where to find it even?).

I work on clean & fresh Drupal 8 installation, turing debbuing on (step 1.) does include comments in source code (as it should) but use `dump()` once and all you see is just an blank page.

# Answer
I agree with the comment left for the question: It seems you have an *out of memory* issue. Check the error log for the server.

I had the same problem with `dump()` and `kint()` in an implementation of `template_preprocess_views_view_field()`, while trying to output the content of a row, on a clean and fresh Drupal 8 installation. I found a workaround for `kint()`, which seems to temporary fix the memory issue. Add the following settings in the config.default.php file for the Kint module.

```
/** @var int max array/object levels to go deep, if zero no limits are applied */
$_kintSettings['maxLevels'] = 4;

```

Take it as a hint: Print a specific variable, not the whole array of variables.
> 13 votes

---
Tags: theming, 8, debugging
---


# Question
Title: What is the correct way to cache blocks by language?
I have a multilingual site with custom blocks in the right-hand menu - the content of which is generated dynamically through the `build()` function of BlockBase and which changes depending on the interface language. I want to cache these once per language. Elsewhere I've used:

```
public function build() {
 $node = \Drupal::routeMatch()->getParameter('node');
 return array(
  '#theme' => 'my_template',
   ....
  '#cache' => [
    'tags' => [
      'node:' . $node->getId()
    ],
  ],
);

```

}

I've gone with this approach, which appears to work, although I'm not sure how to test that it isn't still processing templates on every call:

```
public function build() {
 return array(
  '#theme' => 'my_template',
   ....
  '#cache' => [
    'tags' => [
      'language:' . \Drupal::languageManager()->getCurrentLanguage()->getId()
    ],
  ],
);

```

}

Is this the correct way to do it? I could find examples of the `node:` prefix in the docs, but nothing about `language:`

# Answer
> 7 votes
You should use the languages context, don't use tags here.

Like this: `'#cache' => ['contexts' => ['languages:language_interface']],`

You'll find more here: https://www.drupal.org/developing/api/8/cache/contexts

---
Tags: 8, i18n-l10n, caching
---


# Question
Title: Where are {image_style} and {scheme} coming from?
I can't find much documentation on this subject other than https://www.drupal.org/node/2122201. This leads me to think that the subject is either much easier than I think, and doesn't have documentation because everybody knows it, or that there isn't much available.

I have been working with the last example on that page, but I can't figure out where {image\_style} and {scheme} are coming from.

I need to create something pretty simple, where there's a path that links to a page that requests some data from an API. For example, if someone browses to mysite.com/example/johndoe, then the page requests data from example.com/users/johndoe and displays it. So, I need to also have access to the entry in the URL to forward it to the API with my module, not just routing a ton of pages with a certain URL pattern to a single page.

I've found plenty of documentation on static page routing, and I have understood that.

# Answer
> 2 votes
They are route parameters. See here: https://www.drupal.org/node/2186285

---
Tags: 8, routes
---


# Question
Title: Reset all votes on a content type every week
I am trying to build a website where people vote on individual nodes of a content type using the rate module. Is it possible to reset these votes say every 7 days or every 30 days, so that another round of voting can take place. How would I do this within drupal. I do not want to have to go through phpmyadmin to clear the voting api cache. I would prefer if this is done from within the website I'm building.

Is this possible?

# Answer
> 0 votes
There's many ways to accomplish this. The voting data for the Voting API module is stored in the `votingapi_vote` & `votingapi_cache` tables. Essentially, you need a way to target the vote data you wish to eliminate in these tables (e.g. via a DB query) and then build some process on which to regularly execute it (e.g. a cron run).

A crude example would be a custom module that evokes `hook_cron()` to check the last query execution and fire it if it hits its time threshold:

```
/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Clear the vote every week.
  $vote_clear_timestamp = variable_get('MYMODULE_vote_clear_timestamp', 0);
  if ($vote_clear_timestamp <= strtotime('-1 week')) {

    // A more targeted process would use db_delete() to target criteria
    db_query("TRUNCATE {votingapi_vote}");
    db_query("TRUNCATE {votingapi_cache}");
    variable_set('MYMODULE_vote_clear_timestamp', time());
  }
}

```

---
Tags: rating
---


title: Change ID of webform hidden element

text:
# Question
Title: Change ID of webform hidden element
How can I change the ID of a hidden element (created with the Drupal 6 webform module) using hook\_form\_alter()?

The ID that it outputs is something like '#edit-submitted-component-name'. I need the ID to be something very custom and I need to avoid changing it with Javascript. The form API does not support the #atrributes token on hidden elements, so I can't set the ID via hook\_form\_alter();

Any suggestions would be really helpful. Thank You.

# Answer
I had a similar issue to deal with. I need to generate form IDs programmatically so I implemented below code.

```
function voci_comment_form($form, &$form_state, $cid) {
     $form['#attributes']['id'] = 'voci-comment-form-' . $cid;
     $form['#attributes']['class'][] = 'voci-comment-form';
     $form['body'] = array(
      '#title' => 'Post a comment',
      '#type' => 'textarea',
      '#resizable' => FALSE,
      '#rows' => 1,
     );
     $form['comment'] = array(
      '#type' => 'submit',
      '#value' => 'Comment',
     );

      return $form;
   }

```

It's true that you can set $element\['#attributes'\]\['id'\] and that will apply to the form field.

I hope this helps... :)
> 0 votes

---
Tags: forms, 6, webforms
---


# Question
Title: Feeds importer pass header values when fetching feed
We have been importing nodes with feeds importer from XML for awhile on this website and now the feed has been changed to a new XML but this time it's *password/username* protected. The XML feed is literally the same with the exception of a couple new fields.

When I used this XML feed inside of a custom module, I simply pass the *username/password* into a header of the curl call to authenticate. I currently cannot find the appropriate area to pass header values in within feeds import.

My question would be, is there any support for username/password authentication when pulling in a XML file with a HTTP Fetcher, with Feeds import? Are there any contrib modules that could extend feeds importer to provide the functionality i desire?

# Answer
feeds httpfetcher append headers was the module I needed. Once i switched the fetcher I was able to pass in the **password** & **user name** into the get request to authenticate the request.
> 0 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: Exporting the entire website, except users and content?
As the title says. I need to export a whole project I've been working on to a production website in a different location. I need to export the modules, views, blocks, everything BUT the content and the users. I don't want the content as I made dummy content, and the user is a dummy user as well.

I was thinking on making a distro, but then I'd be missing on the structure. I would export the structure, but I need the modules as well. What's the solution for this sort of issues? My other solution is to build everything on production again, which is going to be draining.

I would also use a Dev -\> Stage -\> Prod workflow, but this will be a one time thing.

# Answer
> 3 votes
I would suggest to put your code in a version control like Git. There are many free services you can use like Github and Bitbucket. With Git you can easily ship your code from one server to another.

> I need to export the modules, views, blocks, everything BUT the content and the users. I don't want the content as I made dummy content, and the user is a dummy user as well.

You can use Features to export your views, blocks, content types, permission and roles, configuration, and even settings stored in variable table (Strongarm).

With everything in Features you can then run a normal installation in production then enable the features one by one. Here are some execellent tuts about using Feature.

**Related modules:**

> My other solution is to build everything on production again, which is going to be draining.

One of the great things in Drupal is making the development easier and simple. With Features module, or `hook` like `hook_update_N` you will never do the same task on every environment you have. Development must only be done in local machine.

> I would also use a Dev -\> Stage -\> Prod workflow, but this will be a one time thing.

That is what Pantheon and Acquia are doing. You can build your own infra but that's another story.

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


# Question
Title: Add class to first field in fields views
How to add class to first fields in views?

I think that I need to add one if but I dont know what argument to put in if...

So how to add class just for first field in views-view-fields template.

```
{% for field in fields -%}
{%
        set colors = [
        'color-'~cycle(["red","yellow"],loop.index),
        loop.first ? 'first',
        loop.index== "1"?'color-first',
        ]
%}
        <b {{ field.element_attributes.addClass(colors) }}> {{ field.content }}</b>
{%- endfor %}

```

This code do this :

# Answer
I solve this problem by using loop.first. The joke was that in

**views-view-unformatted.html.twig** add loop.

```
{% for row in rows %}
    {% if loop.first %}
       <b class="is-visible">{{ row.content }}</b>
    {% else %}
       <b> {{ row.content }}</b>
    {% endif %}
{% endfor %}

```

And the code in **views-view-fields.html.twig** stay normal.

```
 {% for field in fields -%}
        {{ field.content }}
{%- endfor %}

```

On this way you add class to first field of fields.
> 1 votes

# Answer
You can use preprocess field hook which is supported in drupal 8 also . Example below:

```
function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}

```
> 4 votes

---
Tags: entities, 8
---


title: Customize user profile page

text:
# Question
Title: Customize user profile page
I want to fully customize the user profile page. I want to be able to show only the fields that I want, display views, blocks, etc...

Some users will be able to see others users pages so I really need to customize this my way.

Is this possible? Where should I code?

I found a user-profile.tpl.php and it only has this code:

Should I get rid of this code and write a new one?

# Answer
> 0 votes
Don't delete it, copy it into your theme with the other templates and adjust it there, your theme will override the one in core once you clear cache.

---
Tags: users
---


title: Convert two existing sites to multisite

text:
# Question
Title: Convert two existing sites to multisite
I have two sites running from separate installations. I would like to move them to a multisite configuration. I am currently developing in a localhost environment.

I am starting by moving the first site into a multisite config within its own installation. I have given it its own unique folder in the sites directory, set up the sites.php file and given the site its own settings.php in its directory. When I navigate to the location specified in the sites.php configuration I get a not found error, and when I go to the drupal install directory, Drupal would like to do a fresh install.

Do I need to set up a .conf file in the sites-enabled folder of apache2?

Any help is greatly appreciated.

# Answer
> 2 votes
Yes. Configure an apache virtual host for each site. They look something like this:

```
<VirtualHost *:80>
    DocumentRoot "/path/to/drupal/install"
    ServerName mysite.example.com
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/path/to/drupal/install"
    ServerName myothersite.example.com
</VirtualHost>

```

Every virtual host in the multisite must be configured with the same DocumentRoot. The ServerName directive should match what you have used as the respective site's key in sites.php. Note that in this case \*:80 signifies this virtual host listens on every IP of this server.

---
Tags: 8, multi-sites
---


# Question
Title: How do you recycle a css file from a different theme into your new theme?
I really like the form.css from Corolla. I have built a new theme, but would like to reuse Corolla's form.css.

1. Downloaded form.css from Corolla theme
2. Saved it to sites/all/themes/my\_theme/css

Now what? Do I need to add a reference to this css file in the main css file? New to site building / theming, so our of my element.

Thanks - keb

# Answer
As @cilefen pointed out you need to do a couple of things.

1. Put the `form.css` on `sites/all/themes/my_theme/css/`.
2. Update your `sites/all/themes/my_theme/my_theme.info` file to have `stylesheets[all][] = css/form.css`.
3. Clear the cache.

Oh and make sure that `my_theme` is set to **default** or **at least active** in the page that your are working.
> 1 votes

# Answer
In your theme's .info file, add the following:

```
stylesheets[all][] = css/form.css

```
> 0 votes

---
Tags: theming, webforms
---


# Question
Title: Establish relation between node and gmap marker
I have a gmap module (https://www.drupal.org/project/gmap) view that serves the map of locations. I also have a list of those locations under the map. I need to establish a relationship - a class, a rel attribute, or something like this, based on the node id, so that when I click the marker, the correct element in the list can be identified.

I tried adding identification to the marker objects so that they can be related to the list items on click. I have tried the `hook_gmap()` and the theming preprocess functions to add an attribute to the markers and failed.

I have also tried to hook into the Google Maps marker events, but could not do it without overriding the native infobubble events, which I don't want to override.

The actual question:

How can I pass information to markers created with GMap, so that they can be aware of the node id? Some html attribute like class or rel would be ideal. Adding it as a part of icon image path, like image.jpg?nid=1111 would also do the trick.

# Answer
I suggest you to use this module to create views related to your nodes to create gmap with markers:

https://www.drupal.org/project/ip\_geoloc
> 1 votes

---
Tags: 7, google-maps
---


# Question
Title: Read access to user's nodes based for referenced users
I am trying to figure out how to provide access to nodes of the users, which have referenced users. Please note that users are referenced not from nodes, but the user profiles, so I can not use the Node access user reference module. I also can not use roles-based access modules, because otherwise there would be too many roles to create as users on this website should be able to reference unlimited users. I also can not user organic groups.

So basically users have other users referenced from their profiles. All referenced users should have access to nodes authored by the users who referenced them.

# Answer
> 0 votes
That will require custom code.

Here's one way to achieve it:

You'll need to use hook\_node\_view to get involved when the node is about to be rendered. Your code should:

1. Check the node's author and use user\_load to gain access to the referenced users
2. Check to see if the current user (`global $user`) is in the list of referenced users
3. Permit or deny the node view, or change how the node displays, depending on the result.

---
Tags: nodes, users
---


# Question
Title: Where is the group of a fields group stored in datababase (to get it programatically)?
I have installed the Field group module, which, as the name implies, groups fields together. Once you have ordered the fields of content type, is there any way to programmatically get the group of the fields that are grouped together?

I have search in database (columns field\_config, field\_config\_instance) and there is not any column to save that information. Where is that information (the group of field) stored in database?

Thanks in advance.

# Answer
> 0 votes
I have never used field\_group module, but your approach seems wrong, looking in the database doesn't help often. I suggest you should install the module devel, turn it on. Then use the function dsm() to see the content of your node/form that you are in. If I assume you are in the hook\_form\_submit() to process something, dsm($form\_state), if you are in another hook with a node as parameter of your hook, just dsm($node), you might find what you are looking for.

Cheers

---
Tags: entities
---


title: Schedule a push notification

text:
# Question
Title: Schedule a push notification
I need to schedule a Push Notification, as in the push notifications module, every predefined set of time (e.g. every week). Looked into the Rules module, but could not find a way to program a rule based on time.

Is there a way to do this?

# Answer
The module **rules\_scheduler** present inside rules module is giving you what you need.

Details of implementation are here:
> 0 votes

---
Tags: 7
---


# Question
Title: Can you suggest any alternative for Statistics module?
We have a pretty descend traffic to our Drupal website, approximately 600 page views per minute. We have enabled the Drupal statistics module for storing the node page views.

At peek traffic hours, we observed a high usage of Disk I/O wait, and we doubt that it is due to statistics module. Please correct me if am wrong. If yes, kindly suggest some alternative method to implement node view counter.

# Answer
Have a look at the Visitors module. Here are some reports you get from it:

> * View pages that have recently been visited.
> * View pages that have been hit frequently.
> * View pages count per month, day of month, day of week, hour.
> * ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

* Top pages (table with columns Title, Path and nr of Hits).
* Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors\_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module, and co-maintainer of the Forena module.
> 0 votes

# Answer
An alternative is to use

> Statistics module saves data into the database and for a high traffic site it can make a large number of writes to the database.

You may want to read this thread - https://groups.drupal.org/node/145294

Hope that helps
> -1 votes

---
Tags: nodes
---


# Question
Title: How to give user permissions to edit other user fields except user id & pwd?
Hi i am using drupal 7 website in my site having 3 different role of users 1st role of users need to edit 2nd role of user fields except user id & pwd & email & roles.i have tried with administer user permissions,it is possible to edit user id and pwd.Also i have tried with user protect module no use,Any suggestions on this it will be very helpful.Thanks in advance.

# Answer
I think what you want is Restrict Password Change module.

**Related modules:**
> 0 votes

---
Tags: users
---


# Question
Title: How can authenticated users of a site join a group implemented using Groups module?
### Pre-requisite knowledge:

I am using **Group** module to implement "**Group**" functionality on my drupal site similar to what **Organic Groups** module implements. I have a **user role** *community-leader* whose users have been granted the permission (under **People \> Permissions**) - *Technology : Create New Group* so that they **can create new groups** of type *Technology*, but **normal authenticated users** have not been granted this permission so they **cannot create groups**.
**Group** module provides **separate permissions** on its **configuration/overview page** under **Group Roles**. These **group roles** are for users involved in a particular group. In my case, users who create the group (essentially of *Community-leader* role or a user-role with *higher permissions*) are assigned *Group-leader role* and then there is a *Group-member role* supposed to be assigned to users who will join the group created thereafter.
For these roles (both *Group-leader* and *Group-member*), permissions like *Join Group, Request Group Membership*, etc. are disabled (no checkbox available instead a 'x' sign is present). I believe this is because since a *Group-leader* created a group, he automatically joined the group and there is no meaning of these permissions for him.
**Note:** The above roles (both *Group-leader* and *Group-member*) are *global group roles*, not *group-type specific roles*.

### Problem Statement

An authenticated user on my site is unable to access a particular **group's** page and thus has no way available to join the **group**. There is no granular(specific) permission available for this purpose. Moreover, even *Group-leader* or *Group-member* role users cannot access **groups** other then their own **group**. How to allow that? Could someone please guide me on **Group Access Control** for a better understanding?

# Answer
**Drupal 7**

* Download and activate Group.
* Activate submodules Group add (gadd) and Group node (gnode).
* Click on Group that now appears in your menu bar next to Content (/admin/group). This is the main overview for administering Group, here is where new functionality will appear when you activate more submodules.
* Go to Group Types, in a tab on the page (/admin/group/type)
* Add a group type, you only have to choose a name
* Click "edit permissions" (/admin/group/type/manage/partner/permissions)
* Activate suitable permissions. "Outsider" are logged in users that are not part of the group. Add at least view and add permissions for one content type for members, and "View group" permission.
* Go back to the Groups start page (/admin/group)
* Create a new group
* Click on your group name, then click Add member
* Add some members
* Log in as one of those members, go to your account, click the Group tab, click on "view group"
* Add some content

Now you have the basics of a group. Users, content, permissions and some ways to interact. Look through the rest of the tabs on all pages you visited, go into the detailed settings screens, activate more submodules, group roles, group permission etc. Extend using the group api hooks. Set up a suitable user interface using standard tools (views, VBO, rules, fields on the group).

For other settings you can visit following urls :

**Drupal 8**

Watch this video for a excellent and complete use-case configuration.

Hope this will clear all doubt.
> 0 votes

---
Tags: users
---


title: How do I manage 404s for old paths?

text:
# Question
Title: How do I manage 404s for old paths?
We moved to Drupal from another CMS about a year ago, and we still get 100s of "page not found" log entries each day for paths that were for our old site that don't exist on the new site. By checking IPs, I have concluded that *most* of these are from Google's indexer, but not all.

I add redirects when I can, but most of the links are to some meaningless tokenized path that our old CMS used. I feel like there is probably something I *should* be doing to flag bad paths for Google/SEO/whatever.

Is there a best practice for what to do with old broken links?

# Answer
> Is there a best practice for what to do with old broken links?

1. Redirect as much links as you can to existing pages using URL aliases.
2. Find out what pages are linking to your website on the old URLs, see if you can get them adjusted by contacting the webmaster (using a backlink indexing tool like Open Site Explorer or Majestic SEO).
3. For other links you have the HTTP 404 status code. Sometimes you just can't redirect the links...
> 2 votes

# Answer
If most of the broken links are coming from search engines, I highly recommend installing and XML sitemap module.

> The XML sitemap module creates a sitemap that conforms to the sitemaps.org specification. This helps search engines to more intelligently crawl a website and keep their results up to date. The sitemap created by the module can be automatically submitted to Ask, Google, Bing (formerly Windows Live Search), and Yahoo! search engines.

And if you're not using Redirect for your redirects, I would recommend it, as it simplifies creating the redirects.
> 1 votes

# Answer
Not sure if it is the "*best*", but another practise is to prevent the problem from happening where possible. To do so, use the Rules module, as described in my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?". It includes a sample rule (in Rules export format), which is using Rules Event "Drupal is initializing" (that's the clue to make it work).

That answer also explains how by using the Rules URL Argument module, you can even further enhance such redirects.
> 0 votes

---
Tags: migrations
---


# Question
Title: How to add page restrictions for blocks in frontpage?
I have several blocks in my homepage : 2 statics and 1 with a pager.

I want to hide a static block when paging my homepage (after page "0").

I saw something similar in How can I show a block in a view page, excluding it's paginated pages but I do not know exactly what to put in the PHP code regarding the homepage : '' or '/' (instead of 'news' in this example) ?

```
<?php
$url = request_uri();
$pos = strpos($url, "page");
if ($pos === false && arg(0) =='news') {
return TRUE;
}
?>

```

I tried also this code that I saw on this answser : How to add page restrictions for blocks in drupal? but it does not work for me.

```
<?php
if (arg(0)=='/' && is_numeric(arg(1))) {
return TRUE;
} else {
return FALSE;
}
?>

```

My website is : http://femme.bonsplansdemarc.fr/

# Answer
Your suggestions both involve using the PHP setting for block visibility, which isn't available by default and isn't recommended for security reasons. If you already have PHP filter enabled and want to use it, you can probably use the code:

```
<?php
  if (drupal_is_front_page() && !isset($_GET['page'])) {
      return TRUE;
  }
  return FALSE;
?>

```

The option I would recommend (which avoids using PHP filter) would be to install the context module (with this patch https://drupal.org/node/904416) and position the blocks using that. You can set it to appear in all circumstances except when on the home page with query string '\*shs\_term\_node\_tid\_depth=\*'.

If you don't know how to use context module, there are lots of tutorials and it's fairly simple.
> 1 votes

# Answer
There is another alternative available ... ***which doesn't require the PHP filter to be enabled*** (which you should try to avoid whenever possible) ... Just use the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your homepage but not after page "0").

For an illustration of how to use this module, refer to my answer to "How to show block on pages with URLs containing a question mark ( 'searchquery' )?". If you'd use the sample rule in that answer, you probably want to use a "NOT" (= negate) in the Rules Condition there, and of course you'd have to adapt the "`viewname?`" value in it to match your case.
> 1 votes

---
Tags: blocks
---


# Question
Title: Making File Size visible to anonymous users
I have media installed for file handling, and am displaying download links for my files using display suite. I have the file size being loaded in as a dynamic field loading token \[file:size\].

Everything works fine while I'm logged in as admin, but when I view the page as an anonymous user, the file size no longer shows up. Any thoughts?

# Answer
Permission should be given for that *file type* in case of anonymous user.

Because if size is visible to authenticated user and not to anonymous user, then it must be a permission issue.
> 3 votes

---
Tags: 7, tokens, media, display-suite
---


# Question
Title: Set value on newly created node using Rules
This is what I have now: Content type 123 has a Entity Reference field referencing content type XYZ. If new content is created of type XYZ then Rules creates new content of type 123. So by creating 1 new node (of type XYZ) I get one extra of type 123.

This is what I'm missing: How do I set the Entity Reference field of 123 correctly by using Rules?

# Answer
In the Rules action you need to use the `Set a data value` action. This can be used to enter data in fields and properties. Make sure to set the value of your new 123-entity to refer to the xyz entity.

```
{ "rules_create_new_basic_page_after_saving_article" : {
    "LABEL" : "Create new basic page after saving article",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Basic page to go with [node:title]",
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "page_created" : "Created basic page" } }
        }
      },
      { "data_set" : {
          "data" : [ "page-created:field-reference-to-other-entity-" ],
          "value" : [ "node" ]
        }
      },
      { "entity_save" : { "data" : [ "page-created" ], "immediate" : "1" } }
    ]
  }
}

```
> 1 votes

---
Tags: 7, rules
---


title: Related articles with comments

text:
# Question
Title: Related articles with comments
I've been made module that shows related articles and based on taxonomy tags. My problem is that, it listed related articles where is no comments too.

So I want that shows only these articles where is comments.. At least one comment, but I can't get that working. Thank you

My code:

```
function related_articles($cat, $limit = 10) {

 //$nid = $variables['node']->nid;
 //$variables['num_comments'] = db_result(db_query('SELECT COUNT(cid) AS count FROM {comments} WHERE nid = %d', $nid));

$limit = isset($limit)?  " LIMIT $limit " : ' ';
$row = db_query('
    SELECT nid \'id\',title \'name\', field_category_tid
    FROM {node} n
    LEFT JOIN {field_data_field_category} fdft ON (fdft.entity_id = n.nid AND bundle = :article AND entity_type = :node)
    WHERE type = :article AND status = :status AND fdft.field_category_tid = :cat order by title asc
    '.$limit, array(':cat' => $cat, ':article' => 'article', ':status' => NODE_PUBLISHED, ':node' => 'node'))->fetchAll(PDO::FETCH_OBJ);

return ($row)? $row: array();
}

```

# Answer
You will need to join in the comment table and check the comment count.

```
...
LEFT JOIN {comment} c ON (c.nid = n.nid)
...
HAVING COUNT(c.cid) > 0

```

The whole query would probably become something like this:

```
$row = db_query('
  SELECT nid \'id\',title \'name\', field_category_tid
  FROM {node} n
  LEFT JOIN {field_data_field_category} fdft ON (fdft.entity_id = n.nid AND bundle = :article AND entity_type = :node)
  LEFT JOIN {comment} c ON (c.nid = n.nid)
  WHERE type = :article AND status = :status AND fdft.field_category_tid = :cat
  HAVING COUNT(c.cid) > 0
  ORDER BY title asc
  '.$limit, array(':cat' => $cat, ':article' => 'article', ':status' => NODE_PUBLISHED, ':node' => 'node'))->fetchAll(PDO::FETCH_OBJ);

```

Final note, what you want can be easily achieved with the Views module without having to write a query.

UPDATE:

Count should be checked in HAVING.
> 0 votes

---
Tags: nodes, taxonomy-terms
---


# Question
Title: What is the scope of the drupal session cookie?
I am bootstrapping drupal 7 (using DRUPAL\_BOOTSTRAP\_FULL) so that I can use drupal's authentication/security features in the rapid development of a web app I'm doing a proof of concept for. (And yes I know it is better to use drush to bootstrap drupal.)

If the PHP file that I am bootstrapping drupal from is in the root drupal directory, then the bootstrapping works -- I know this because inspecting the $user global variable will show that I am logged in.

If the PHP file is not in the root drupal directory (whether a subdirectory of the root drupal directory or a sibling of the root drupal directory), then the bootstrapping works -- I can inspect the $user global variable, but the $user variable says I am an anonymous user rather than the logged in user that I am.

Is my suspicion right that this is related to the scope of the drupal session cookie? If so, what is that scope?

# Answer
> 0 votes
Better late than never?

Yes, if you are creating the cookie with a default path. It will use the current page path. So the cookie will be restricted to any path starting with the defined one (if it's /a/b then the cookie will be available for /a/b, a/b/c etc but not /a alone).

(I had a short period of hair-tearing once where I was accessing a site using it's IP address and unable to understand why the cookies weren't available ... they were hardwired to the domain.)

---
Tags: 7, cookies, bootstrapping
---


# Question
Title: How to get node url of selected language?
I have a node with an array of multiple languages.

```
 [19] => Drupal\node\Entity\Node Object
        (
            [in_preview] =>
            [values:protected] => Array
                (
                    [vid] => Array
                        (
                            [x-default] => 19
                        )

                    [langcode] => Array
                        (
                            [x-default] => en
                            [ca] => ca
                        )

```

I'm getting its url as:

```
$options = array('absolute' => TRUE);
$link = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $key], $options);

```

`print($link)` is giving me `http://test-d8.local/en/node/19` where as I want url of "`ca`" language not "`en`" language. i.e. `http://test-d8.local/ca/node/19`

Is there any way that gives node translations of particular langcode?

This line `$language = $entity->get('langcode')->value;` is giving me the value of chosen language from select list.

# Answer
> 6 votes
You want to use toUrl() with the language option.

```
$node->toUrl('canonical', ['language' => $node->language()]);

```

Unfortunately, toUrl() currently doesn't automatically respect the active language.

# Answer
> 3 votes
```
$language = 'ca';
$link = $value->getTranslation($language)->url();
$title =  $value->getTranslation($language)->title->value;

```

this worked for me.

# Answer
> 1 votes
You can get the translation of the node like this:

```
$node = $node->getTranslation('ca');

```

And, depending what you need, you can get the link or url like this:

```
$link = $node->toLink();
$url = $node->toUrl();

```

---
Tags: 8, entities, routes
---


# Question
Title: How to use the Rules module to unset all flags (set x days ago) when cron runs?
**Case**: users set flags on content using Flag module (flags are per user, not global).

**Requirement**: after a period of time the system should automatically unset these flags using Rules module.

The obvious way to do this would seem to be: when cron runs, fetch all instances of flag that have been set, and unset them.

(In actuality, only flags that were created x days ago will be unset; newer flags will be left. But I can't get the basic setup and this will just be a condition.)

```
    Event: Cron maintenance tasks are performed
    Action: ??

```

I can't see a way to **get/fetch all flags of a certain type that have been set**.

(Obviously I could choose the action `Execute custom PHP code` and write some code against the relevant flag table... but surely there's a cleaner way of doing this..?)

Can anyone help?

# Answer
> 1 votes
Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the steps below.

### Step 1: Create a Rules Component to unflag a node

Create a Rules Component to unflag (= unset the flag) of a node that was flagged by a given user. Assume you give it a machine name like `rules_unflag_node_flagged_by_a_user`. Use parameters like `flagged_node` (for the node) and `flagging_user` (for the user who flagged). And assume that the machine name of your flag is `my_special_flag`.

Here is a Rules Component (in Rules export format) you can use for this (using the above mentioned machine names):

```
{ "rules_unflag_node_flagged_by_a_user" : {
    "LABEL" : "Unflag node flagged by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be unflagged", "type" : "node" }
    },
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "my_special_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node unflagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

```

Use the Rules "Import Component" facility (located within `/admin/config/workflow/rules/components`) to import it in your own environment, but make sure the machine name of the flag matches with your own machine name for it.

Consider the Rules Action `drupal_message` as for QA-testing only (remove it in your final version, no need for that Rules Action).

### Step 2: Schedule the execution of the Rules Component

Create a rule like so:

* **Rules Event** = After a node gets flagged (with the flag you're already using).
* **Rules Action** = Schedule the execution of the Rules Component (created in Step 1), for execution within x days.

Here is a Rule (in Rules export format) you can use for this (using the above mentioned machine names):

```
{ "rules_schedule_the_unflag_a_node_flagged_by_a_user" : {
    "LABEL" : "Schedule the unflag a node flagged by a user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "flag" ],
    "ON" : { "flag_flagged_my_special_flag" : [] },
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_unflag_node_flagged_by_a_user",
          "task" : "[flag:name]-[flagged-node:nid]-[flagging-user:uid]"
        }
      },
      { "schedule" : {
          "component" : "rules_unflag_node_flagged_by_a_user",
          "date" : "+7 day",
          "identifier" : "[flag:name]-[flagged-node:nid]-[flagging-user:uid]",
          "param_flagging_user" : [ "flagging-user" ],
          "param_flagged_node" : [ "flagged-node" ]
        }
      }
    ]
  }
}

```

Some more details about the above rule:

* The scheduled date of the Rules Component is within 7 days (cfr. your "x" days).
* The identifier of the scheduled task is `[flag:name]-[flagged-node:nid]-[flagging-user:uid]`, which should ensure the scheduled tasks have unique identifiers.
* The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" reminders will get removed if for whatever reason the same user flags the same node with the same flag (so that it only triggers 1 reminder, and with the most recent date).

Use the Rules "Import" facility (located within `/admin/config/workflow/rules`) to import it in your own environment, but make sure the machine name of the flag matches with your own machine name for it (and review the value of +7 day to fit your value of "X days"). Then use the Rules UI to enable the rule (it's disabled by default).

### Step 3: Run cron periodically

Rules scheduled for execution using `Rules Scheduler`, will actually be executed "next time cron runs" (after the scheduled date/time has arrived). So make sure to (a) actually run cron and (b) schedule the execution a bit before the cron job will actually run them.

Example: if you want the unflagging to happen every night at (say) 2 am, schedule the Rules Component's execution at (say) 1:55 am, and make sure cron runs at 2 am sharp.

**Notes**:

1. The above logic will only apply to nodes flagged by users after the Rule component (Step 1) and Rule (Step 3) was activated.
2. No need for custom PHP code.

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

---
Tags: rules, flags, cron
---


title: How do I change the scrolling speed?

text:
# Question
Title: How do I change the scrolling speed?
I recently installed and enabled the Back To Top module. It gives a button at right bottom of the screen to scroll back to the top of the page.

How can I increase the scrolling speed?

# Answer
> 3 votes
In the file `back_to_top/js/back_to_top.js` you'll find the following on line 23:

```
$('html,body').animate({ scrollTop: 0 }, 1200, 'easeOutQuart', function() {

```

The 1200 is the animation duration in milliseconds. Lower it and the animation will go faster. Optionally you could raise a feature request in the module issue queue to make this a configurable setting.

---
Tags: 7
---


# Question
Title: How add publish config block to a custom entity content
i have a custom entity content : Product. I am looking for a way to give the posibility to change the url of the product like this block :

Block on the right.

It's a screen of article content.

Here my annotation for my entity content :

```
/**
 * Defines the Produits entity.
 *
 * @ingroup boutique
 *
 * @ContentEntityType(
 *   id = "produits_entity",
 *   label = @Translation("Produits"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\boutique\ProduitsEntityListBuilder",
 *     "views_data" = "Drupal\boutique\Entity\ProduitsEntityViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\boutique\Form\ProduitsEntityForm",
 *       "add" = "Drupal\boutique\Form\ProduitsEntityForm",
 *       "edit" = "Drupal\boutique\Form\ProduitsEntityForm",
 *       "delete" = "Drupal\boutique\Form\ProduitsEntityDeleteForm",
 *     },
 *     "access" = "Drupal\boutique\ProduitsEntityAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\boutique\ProduitsEntityHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "produits_entity",
 *   admin_permission = "administer produits entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *
 *   links = {
 *     "canonical" = "/produits/{produits_entity}",
 *     "add-form" = "/admin/boutique/produits/add",
 *     "edit-form" = "/admin/boutique/produits/{produits_entity}/edit",
 *     "delete-form" = "/admin/boutique/produits/{produits_entity}/delete",
 *     "collection" = "/admin/boutique/produits/liste",
 *   },
 *   field_ui_base_route = "produits_entity.settings"
 * )
 */

```

Is there a way for extend my entity content to the node properties ?

# Answer
> 0 votes
This is how i have solve my problem (don't work with pathauto):

I create a custom field in my form for the path :

And in my submit :

i use the

> $path = \Drupal::service('path.alias\_storage')-\>save($system\_path, $path\_alias, $langcode);

```
 public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
    $status = parent::save($form, $form_state);

    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this->t('Created the %label Produits.', [
          '%label' => $entity->label(),
        ]));

        $path = \Drupal::service('path.alias_storage')->save('/produits/'.$entity->id(), $form_state->getValue('path')[0]['value'], 'fr');

        break;

      default:
        drupal_set_message($this->t('Saved the %label Produits.', [
          '%label' => $entity->label(),
        ]));
    }
    $form_state->setRedirect('entity.produits_entity.canonical', ['produits_entity' => $entity->id()]);
  }

```

Now i need to work with the service path.alias\_storage when user modify and delete my product.

---
Tags: 8, entities
---


# Question
Title: How can I remove emoji from all user input?
It looks like iPhone emoji are not currently supported in Drupal 7 on MySQL.

When I try to save a node containing an emoji (I U!) in the database, I get an SQL error:

> PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect string value: '\xF0\x9F\x92\x9BRi...' for column 'body\_value' at row ...

So, to avoid this very unpleasant user-unfriendly error, I would like to automatically clean all user input, including all node textfields and private message module messages.

I found several functions for removing emoji, but which hook can I use to clean all user input?

# Answer
> 4 votes
All user input is a bit much. Only common ground I can see is that all user input goes thorough some kind of forms. And the only thing that for sure happens before anything tries to save, is validation\*.

Functions listed in `#validate` can alter form state. Example definition shows they take form state by reference:

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

```

So the "only" thing you would have to do is to recursively iterate over all `$form_state['values']`, and apply your removal function. It should be pretty safe, because by the very nature your function will not affect numerical inputs in any way.

Other approach might be a bit faster. You can use `#element_validate` \- prepend your removal function to validation array of each and every text field. Sadly, form element types may be added by modules, so you would have to prepend it to every element anyway (forgetting any significant boost due to validation only data that needs it, and paying a price of more function calls), or carefully inspect your modules and make sure you know what else, except textfield and textarea can accept text data (machine\_name element is already safe, I omitted it on purpose).

All in all, I would prefer to just switch my MySQL to utf8mb4 charset, that supports all utf8 as it ought to be supported. You need MySQL 5.5.3 or greater to do this.

* make a backup (obvious, but hey)
* upgrade if needed
* for each database, table and column that has it set already, change to `CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci`
* Set `default-character-set = utf8mb4` for `[client]` and `[mysql]` in my.cnf
* Set (in the same file)

```
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

```
* Hack Drupal to use it. What you want is around line 53 of /includes/database/mysql/database.inc

Hacking Drupal is usually not encouraged, but in this particular case we cannot expect a patch, so this is the only way to give users what they want. Also, it's method way less CPU consuming that altering all inputs.

---

* Of course you may create your own submit handler and make it a first one, but making sure it's always first is hard. Other module developers may try to have their handlers first, too. And if they decide to, for example, log something to MySQL, your fix becomes futile. Using validation is a bit of abuse, but it's an only way I would trust in this scenario.

# Answer
> 2 votes
You could try the Emoji Scrub module.

# Answer
> 1 votes
If you want to **remove**/replace emoji with some other text you can use the Strip 4-byte UTF8 module.

> This module helps in preventing PDO Exceptions caused by MySQL general error of incorrect string value. Enabling this module will have your site reject overly long 2 byte sequences, as well as characters above U+10000, and reject overly long 3 byte sequences and UTF-16.

I've used the Unicode module for one of my project.It deals well with emojis

> Unicode module converts unicode characters to html entities so that drupal may store them correctly in mysql.
>
> This module only does this conversion prior to saving entities by looping over the defined properties of the entity and only converts properties of type text & formatted text.

---
Tags: hooks, database, input-formats
---


# Question
Title: How to remove author name and date created from Simplenews emails?
When I create a newsletter using the Simplenews module and save it, I don't see the author name and date created in the node. However, when I send email, it contains author name as a **link** and date and time of creation + 'html' as shown.

```
rktaxali Thu, 05/19/2016 - 11:42 html

Unsubscribe from this newsletter

```

Any suggestion, how to remove the author name and date row from email?

On a similar note, the email also includes the node title twice in the body of the email, e.g.

# Quarterly News Letter

Quarterly News Letter

This is sample newsletter sent by the simplenews module ...

Any suggestion, how to remove the two repeating lines at the top of the email?

# Answer
> 0 votes
I would suggest you two options:

1. You can put node.tpl.php specific to your simplenews content-type and remove the unnecessary content from it.
2. Add css file specific to the mailing system. I use mimemail system, so I did the following:

`function THEME_NAME_preprocess_mimemail_message(&$variables) {
 drupal_add_css(drupal_get_path('theme', 'THEME_NAME').'/css/mail.css');
}`

In the mail.css, you can hide those fields using `display:none;`

---
Tags: emails
---


# Question
Title: Cannot access responsive image sources from Twig
In Twig I am unable to retrieve the file source for each responsive image style on a ImageItem. How should I be getting this information?

# Answer
> 1 votes
-You can use a theme hook to wire in the responsive image sources (yourtheme.theme)

-You can set your content / (or custom entity) "manage display" / the image field: set responsive display. So it will send to the dom all of the url's when rendering the item.

---
Tags: 8, theming
---


# Question
Title: Using arrays when setting values in defaultConfiguration() of BlockForm in BlockBase
I'm writing a block plugin that allows you to specify certain values for the block in the panel pane editor. I'm able to defined the default values using

```
public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        );
}
public function blockForm($form, FormStateInterface $form_state){
    $form['plugins_string_text'] = array(
      '#type' => 'text_format',
      '#title' => $this->t('Block contents'),
      '#format' => 'full_html',
      '#description' => $this->t('This text will appear in the block.'),
      '#default_value' => $this->configuration['plugins_string'],
    );

    $form['layout'] = array(
        '#type' => 'details',
        '#title' => t('Layout'),
        '#open' => FALSE,
        '#group' => 'layout',
        );
    $form['layout']['pane-type'] = array(
        '#type' => 'select',
        '#title' => t('Pane Type'),
        '#options' => array(
            'standard' => t('Standard Panel Pane'),
            'box' => t('Box Layout'),
            'column' => t('Column Layout'),
        ),
        '#description' => 'Choose what type of pane this is',
        '#default_value' => $this->configuration['layout']['pane-type-submit'],
    );
}

```

I see how to generate the default configuration\['plugins\_string'\] but I'm not sure how to load a default when it is in an array. Like configuration\['layout'\]\['panetype-submit'\]

I have already tried

```
public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        array('layout', 'pane-type-submit') => 1,
        );
}

```

and

```
public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        'layout', 'pane-type-submit' => 1,
        );
}

```

Both of these were not successful

# Answer
Are you looking for this?

```
public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        'layout' => array('pane-type-submit' => 1),
     );
 }

```
> 2 votes

---
Tags: 8, blocks, plugins
---


# Question
Title: I want to change default product variation machine name?
I am working in Drupal Commerce kickstart. It's have default content types like hats,bags\_cases,tops and all. I want to change the machine name also.Is it possible?

I am going to change structure-\>content types -\> edit

But I can't change it...

# Answer
> 1 votes
Yes its possible.

if you want to edit the machine name of your content type name 'pages' then goto 'admin/structure/types/manage/page' --\> click the "edit" button and update with the required value.

Same way you can do it for any content types.

Thanks

# Answer
> 1 votes
Sadly the poster above didn't read your question properly and I wasted quite a bit of time thinking it could be done only I was looking in the wrong place or something.

Anyway, as far as I can see there is no drupal way to change the name of the machine name for a product variation. What I did to get around this was to 'hack' the database directly.

As always, backup you db first!

First of all I changed the variation type title to what it should be, in my case I was changing 'Drinks' to 'Charms'.

I did spend a lot of time trying to figure out which tables I needed to update but in the end the most efficient and error free way was to dump the whole database then open the .sql file into a text editor like Sublime text (I tried Coda but it was too sloooow as the file was 28mb) and do a search and replace, searching for 'drinks' and replacing it with 'charms' in my case.

Once done and saved to a new file I just re-imported it. Job done, so far no side effects. I'll post here if I find any. :-)

---
Tags: nodes, commerce
---


# Question
Title: Menu unserialized warning when using autocomplete in a custom module
I am working on creating a form with Autocomplete feature for the text field. This is the code I have so far..

```
    /**
     * Implementation of hook_menu()
     */
    function suggest_feature_menu() {
      $item['suggest_feature/autocomplete'] = array(
        'page callback' => '_suggest_feature_autocomplete',
        'access arguments' => user_access('access example autocomplete'),
        'type' => MENU_CALLBACK
        );

        return $item;
      }

    /**
     * Implementation of autocomplete
     */

 function suggest_feature_autocomplete($string){

    $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title'))
    ->condition('status', 1) //Published.
    ->condition('type', array('e_hood', 'oranization'))
    ->condition('n.title','%'.db_like($string) . '%', 'LIKE')
    ->orderBy('created', 'DESC') //Most recent first.
    ->range(0,10)
    ->execute();

    $items = array();

    foreach ($query as $node){
       $items[$node->nid] = check_plain($node->title);
    }

    return drupal_json_output($items);

  }

    /**
     * Implementation of hook_form()
     */

    function suggest_feature_form($form_state) {
     $form = array();

       $form['test_item'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'suggest_feature/autocomplete'
        );

      return $form;
    }

```

all my functionality works but i get a warning which says

> Warning: Invalid argument supplied for foreach() in menu\_unserialize() (line 393 of C:\xampp\htdocs\drupal7\includes\menu.inc).

Please let me know how to solve this. Is this an issue with my code ? Also I use superfish menu's in my drupal. Is this related ?

# Answer
This is a bit of a shot in the dark, but the `'title'` property is required for items defined in `hook_menu()`, and it's missing in your code.

I can think of a couple of scenarios where a lack of the `'title'` property might cause this error in `menu_unserialize()` so it's worth adding it to see if that helps. Remember to flush the caches once you make the code change.
> 1 votes

# Answer
There are three functions calling `menu_unserialize()`, the function for which the error is reported:

* `menu_get_item()` uses it in the following code

```
  if ($router_item['access']) {
    $router_item['map'] = $map;
    $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
    $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
  }

```
* `_menu_check_access()` uses it in the following code

```
$arguments = menu_unserialize($item['access_arguments'], $map);

```
* \_menu\_item\_localize() uses it in the following code

```
$item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));

```

The *Invalid argument supplied for `foreach()`* error simply means that `foreach()` is getting a value that is not an array. With the code you are showing, that is happening only for `$arguments = menu_unserialize($item['access_arguments'], $map);` since you are setting `$item['suggest_feature/autocomplete']['access arguments']` to `TRUE` when it should be an array.

In your case, the code should be the following one.

```
/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

```

For Drupal that code would be equivalent to the following one.

```
/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

```

You can understand now why your code is wrong.

It's not the access arguments that you can set to a boolean value, but the access callback. See what the documentation for `hook_menu()` says. (Emphasis is mine.)

> * "access callback": A function returning `TRUE` if the user has access rights to this menu item, and FALSE if not. **It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean).** Defaults to `user_access()` unless a value is inherited from the parent menu item; only `MENU_DEFAULT_LOCAL_TASK` items can inherit access callbacks. To use the `user_access()` default callback, you must specify the permission to check as 'access arguments' (see below).

And for the access arguments, it says:

> * "access arguments": **An array of arguments** to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.
> 2 votes

# Answer
Your "access argument" in hook\_menu must be an array e.g "access argument" =\> array() in your custom module.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How can I get the responsive image style id from a FileFieldItemList
I am trying to get the machine name of the responsive image style attached to a field. I am not able to get this from the settings attached; it seems it is not accessible from the object in any way.

How can I get the responsive image style ID from a FileFieldItemList?

# Answer
> 0 votes
This setting is not a field setting. Because a field can be part of different displays. You have to look for this setting in a view mode. For example if you configure the image field of the article with a responsive image style, your view mode would contain something like this:

```
core.entity_view_display.node.article.default:
  content:
    field_image:
      type: responsive_image
      weight: 0
      settings:
        responsive_image_style: *responsive_image_style_id*

```

---
Tags: 8, media, theming
---


title: Adding image styles path in page.tpl

text:
# Question
Title: Adding image styles path in page.tpl
i have image upload field in my theme-settings.php

```
$form['fsos_settings']['intro']['hero']['heroImage'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array(
    'file_validate_extensions' => array(0 => 'png jpg jpeg gif'),
),
    '#upload_location' => 'public://image/home/',
    '#description' => t("Upload an image."),
    '#default_value' => theme_get_setting('heroImage'),
);

```

I can print this in my page.tpl.php using the following code

```
<img src="<?php print file_create_url(file_load(theme_get_setting('heroImage'))->uri); ?>"/>

```

But i want to use Image Styles (heroimage) for the size. How can i get the image styles URL instead of the original URL

# Answer
> 1 votes
Heres an example using theme\_image\_style()

```
$mypath = (file_load(theme_get_setting('heroImage'))->uri);
print theme_image_style(
  array(
    'style_name' => 'heroimage',
    'path' => $mypath,
    'attributes' => array(
    'class' => 'YOUR_IMAGE_CLASS'
    ),
    'width' => NULL,
    'height' => NULL,
   )
 );
}

```

I'll be honest, I cant remember why I set height and width to NULL, off the top of my head it helped fix some bug! Hope it helps!

# Answer
> 0 votes
You can use this:

```
<img src="<?php print image_style_url('heroimage',$image_link_uri); ?>" />

```

**$image\_link\_uri** would be the URI link of your image

That should work !

---
Tags: theming
---


# Question
Title: How to list page translations next to the original in the same row?
D8's multilingual features are way above average compared to other major competing solutions, but I'm still missing one feature, or I don't know about it being implemented in D8.

When I create transations of the same page, I see them on individual rows, one row per translation like this:

If you have more languages, let's say 5, it's not good for clarity to have it like this. It would be much more clear if it would be possible to display the page (original) in one row and to list all the available translations of the given page on the same row, like this:

Being able to do this in D8 would be a great benefit. Is this possible in D8?

# Answer
Have a look at the Translation Management Tool, considered as the successor of the Translation Overview module, and "the" module to move forward with in D8 also. From its project page:

> ... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.
>
> This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

One of its community pages also contains some related screenprints, such as this one:

### Plan B

Another possible approach that might be worth experimenting with, is to try to tune the View itself, by using "rewrite results" for each of the values in the columns with "Czech", "English", etc. And use these values to rewrite them to shown an image (like "Czech.jpg", "English.jpg", etc) with an "**Edit**" link below it. For the "**Add**"-equivalent you'd have to check what value you get for a 3rd language if you don't have a translation yet: if you do get something for that also, you could using a similar rewrite result, but then with an "Add" link.
> 1 votes

---
Tags: views, 8, i18n-l10n
---


title: Extend Block Class

text:
# Question
Title: Extend Block Class
I created a block plugin that adds the ability to specify style settings by adding a form for configuring the styles.

Is it possible to extend the block class so that all blocks have this capability and not just the specific block plugin I created. Or is there a hook that can perform this action?

# Answer
> 3 votes
In general, you would use hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() in a module to change all forms of a broad type. For all blocks, it looks like the form ID is always "block\_form". So you can easily add elements to all block forms by implementing this function assuming your module is named "MYMODULE"

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

```

Since most blocks are extending BlockBase there is no way to change the class on the fly.

A really heavy-handed alternative to the form alter would be to use the decorator pattern and change all block plugins via the alter hook in discovery to use your class that adds some form elements and delegates most method calls back to an instance of the original class.

# Answer
> 1 votes
The Block Class module allows to add classes to every block.

To that, it uses a form alter and the third party settings support of config entities. The classes are then added through a template preproprocess.

The details can be found in the source code.

---
Tags: 8, blocks
---


# Question
Title: Saving and retrieving value in hook_node_form_alter()
This is in Drupal 7.

I have managed to add a section to the node vertical tab. But I have not found out how to save the value and retrieve the value. After saving the node if i go back to the node edit form it still shows the default value. What am I missing?

```
function myModule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['test_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('test settings'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#group' => 'additional_settings',
   );

   $form['test_settings']['node_uaid'] = array(
    '#type' => 'textfield',
    '#title' => t('uaid'),
    '#default_value' => variable_get('node_uaid', "default"),
    '#size' => 50,
    '#maxlength' => 50,
    '#description' => t('test UAID.'),
    '#required' => FALSE,
    '#group' => 'settingsform'
   );
}

```

The final objective is a field in the node add/edit vertical form that is directly associated with that node. This field should be accessible in relation to the node.

# Answer
> 2 votes
Unlike building a settings form in Drupal using `system_settings_form()`, you need to do more than define the form field so that it's processed. You need to define a submit handler so your custom field can be processed. In your `hook_form_alter()` add a submit handler:

```
$form['#submit'][] = 'myModule_form_node_form_submit';

```

Then define your submit handler to process the form value for saving.

```
function myModule_form_node_form_submit($form, &$form_state) {
  variable_set('node_uaid', $form_state['values']['node_uaid']);
}

```

---
Tags: nodes, forms
---


# Question
Title: How can I create a Drupal/IFTTT trigger or action?
I am looking into the service IFTTT ("IF This Then That"), which is like a trigger/action for the internet. For example, I could tell it that IF I post a new image to flikr, THEN post a link to it on Facebook.

I am wondering if anyone has managed to integrate this into drupal, so, for example, I could automatically post across social media networks when I create new content on a drupal site.

# Answer
> 1 votes
There is a module for that. Rules and/or Gigya

probably more around.

# Answer
> 0 votes
you can use a service like ping.fm to post media to multiple sites. There is a ping.fm Drupal module available.

# Answer
> 0 votes
Take a look here - a quick implementation of rules action and IFTTT maker. https://www.drupal.org/node/2753119 \- https://www.drupal.org/sandbox/ursuvictor/2753083. Simply create a new rule(ie: User logs in) , for actions select IFTTT, fill in the IFTTT key (https://ifttt.com/maker), the event name, and the three variables (you can use tokens) to send over to IFTTT if you want to send any, then Enjoy. I am sending my user logins to a google spreadsheet, sending a slack message on user register, and turning off the light when my personal user logs out from the website.

---
Tags: 7, actions, rules
---


title: JS not work in bootstrap subtheme

text:
# Question
Title: JS not work in bootstrap subtheme
I am using bootstrap 3.6 sub-theme/cdn, I've added `scripts[] = js/custom.js` and I can see it in the source code of the page.

But... javascript is not working. I copied some javascript code modules to test and from my `custom.js` and still does not work.

how I can run my code javascript in my sub?

# Answer
To put a JavaScript in your theme you must do the following steps:

Assuming that your sub-theme name is `example`.

1. Update your `example/example.info` to have this `scripts[] = js/custom.js`. That means the `custom.js` path is `example/js/custom.js`.
2. Clear the cache.

**Troubleshooting:**

If your code in `custom.js` is not working then there is something wrong. First, check if there is a js error using browser console. Second, check the `http response code` make sure that there is no permission issue.

**Alternative way to add Javascript.**

Another way of adding Javascript is by using `drupal_add_js`. With this API you can control which page the js is going to load.
> 0 votes

---
Tags: javascript, theming, cdn
---


# Question
Title: Is it possible to combine contextual filters with regular filters?
I would like to take my standard taxonomy term view and add a "meta" category that would show up in addition to the term selected. The result should be that items in the meta category show up as well as those in the term being viwewed.

I tried adding the meta category as a regular filter or an additional contextual filter, but there's no way to add the "OR" logic needed between the contextual term filter and the specified meta term filter. In spite of using them for many many years, I still don't fully understand the all settings of contextual filters. Perhaps there is a right way to get it to do what I want?

Thanks for any leads or suggestions.

# Answer
You can add "or" conditions to filters -- either regular or exposed -- using Views in Drupal 7 or 8 (in Drupal 6 you need to use the Views Or module).

Add the filters you want -- in your example, a "Has taxonomy term" filter for "meta" and a "Has taxonomy term" exposed filter. Then click the arrow next to the "Add" link to expand the options and select "And/Or, Rearrange".

From there you can add a new group and drag both the "Has taxonomy term" filters into that group and set the operator to "or". (You can also set the operator between groups to "or" for more complicated scenarios.)

To add OR clauses to contextual filters, tick the "Allow multiple values" option and use the "+" or "," characters in the URL to indicate an OR or AND of values.

That should get you what you want.
> 1 votes

---
Tags: 7, taxonomy-terms, views
---


# Question
Title: Change all article text format to basic html
I installed Drupal 8 on my site and used migrate to migrate my old site Drupal 6 to Drupal 8.

The error message pop out.

But when total articles have been all imported to new site Drupal 8.

The content of the article is not displaying. Only title of article shown.

I checked the article, there is content there.

It needs to be change from text format FULL HTML to BASIC HTML to make it appear on the site.

I have more than 20,000 articles. How do I do change it for all?

Is it adding the script here and press "Format"?

# Answer
While you might just need to add/configure the `full_html` text format, you can update the text format for all body fields to `basic_html` via a DB query ( and clear cache )

```
db_update('node__body')
  ->fields(array('body_format' => 'basic_html'))
  ->condition('bundle', 'article')
  ->execute();

db_update('node_revision__body')
  ->fields(array('body_format' => 'basic_html'))
  ->condition('bundle', 'article')
  ->execute();

```

The raw SQL equivalent (e.g for PHPMyAdmin) is:

```
UPDATE node__body set body_format = 'basic_html' where bundle = 'article';
UPDATE node_revision__body set body_format = 'basic_html' where bundle = 'article';

```

Backup your database *first*
> 7 votes

---
Tags: 8, migrations
---


# Question
Title: Views Exposed Filters AND result for multi select field
I'm working with a view with exposed filters for a directory style page.

One of the filters is a multi-select check list, however, we want the results to return AND results only. It is currently returning OR.

For example: Activity open to: \- Men \- Women \- Older People \- Children

So I only want to see results that have both selected.

All the testing I've done returns OR options, so they can have Men OR Women. I want Men AND Women returned.

# Answer
> 0 votes
Views' filters default to an OR between all the options selected. If you pick the "Is all of" option, it will change to an AND operator.

# Answer
> -1 votes
You can modify the query as you like before executing it using hook\_views\_query\_alter.

---
Tags: views
---


title: No layout and menu not working

text:
# Question
Title: No layout and menu not working
I installed latest version of Drupal 8.1.3 on my site. Everything went fine and no error message. But after installation done, my homepage became this. No layout, menu not working.

How can I fix this?

# Answer
> 0 votes
It was disabled cgi execution and make the CSS unable to work properly.

# Answer
> 1 votes
Check that the sites/default/files directory and any directory inside that are writeable from the account used to run Apache. After that, force Drupal to clear its cache.
It happened to me too, and all the times it was because Drupal was not able to write the files it uses for rendering the page in that directory.

---
Tags: 8
---


# Question
Title: How to access field values from a custom block
How do you give a custom block (in a custom module) access to field values produced by the context of page?

eg: If the page has a field, say 'field\_my\_custom\_id' and I want to use it for some purpose in the Build function of a custom block, how to access it from within my module?

# Answer
At the point when you build your block you don't know what other code will put in the page.

As alternative you can use the routing system, because the route is resolved in the bootstrap process (in D8 the symfony framework) before any custom code is run:

```
if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $field_my_custom_id = $node->field_my_custom_id->value;
}

```

Of course you don't know if other code will put this field on the page, but you know that the url of the page will produce the specific node as main content.
> 2 votes

---
Tags: 8, blocks
---


title: Contact form email template

text:
# Question
Title: Contact form email template
Currently, the whole email generated by the Contact module is without a single line break. They look very ugly. Is there a way to edit the email template for specific contact forms?

# Answer
> 1 votes
If you check core.services.yml you can see the service which sends mail (*plugin.manager.mail*). It looks for overrides for default mail plugin starting from message\_id to module name. You can create simple new mail plugin which sends HTML mail and set this in configuration "system.mail".

```
 drush cset system.mail interface.contact your_mail_plugin  // this will change mail plugin for contact module

```

Creating a mail plugin is easy and you can find example here *Drupal\Core\Mail\Plugin\Mail*

MailSystem module does this and it supports advanced options https://www.drupal.org/project/mailsystem

---
Tags: theming, 8, emails
---


title: How Much Time spent on websites of user

text:
# Question
Title: How Much Time spent on websites of user
In website have many AUTHENTICATED USER. I want to how many times spent of each user on site.

I use login history module, it show only every login time of all user.

I use time spent module, but not track all time of every page.

Please suggest how to calculate time spent of each user on every login.

# Answer
Seems the Time Spent module is what you're looking for

> This module tracks, by Ajax, how long a registered user took to read a page and the amount of time he spent on the entire site.
>
> You can configure which content type and role should be tracked and view the report, exhibiting the total hours (or minutes/seconds) a user spent reading a page and at the entire site.

Similar module -Time Tracker

> **Features**
>
> * Track Time on any entity and or comments
> * Activities and Time Entries are now both fieldable entities.
> * Track time using time intervals (start and end times) or durations (admin/settings/time\_tracker)
> * Integrated Timer to track time as you go
> * Time estimating
> * User Time Sheets to display weekly logged time (user/%uid/time\_sheet)
> * View for reporting on tracked time (time/report)
> 3 votes

---
Tags: 7, users
---


title: Views Filter on a subquery custom field

text:
# Question
Title: Views Filter on a subquery custom field
I've defined a global table, like this:

```
  $data['custom_test']['table']['group'] = t('Custom: Test');
  $data['custom_test']['table']['join'] = array(
    // #global is a special flag which let's a table appear all the time.
    '#global' => array(),
  );

```

Next I added a custom field:

```
  $data['custom_test']['test'] = array(
    'title' => t('Test'),
    'help' => t('Show test field'),
    'field' => array(
      'handler' => 'custom_test_handler_test_field',
    ),

```

With this I could now make a field handler; This field handler adds a subquery:

```
$this->query->add_field(NULL, "(QUERY)", '(FIELD)');

```

And with this I can output the result.

However, when I add a filter, (using a default filter handler), the query looks something like:

```
AND (.test BETWEEN '20' AND '30') ))

```

So what it does is that it tries to prefix a table, however there are no tables (since it's a subquery).

Is there someway I can fix this by configuration, without having to say build my own filter?

# Answer
I ended up creating a filter class, since I use a subquery I needed to use `HAVING` rather than `BETWEEN`.
> 0 votes

---
Tags: views
---


# Question
Title: The simplest way of get an emerging modal window
I want to open a modal emerging window, with some HTML on it and a close button. It should open when the user visits the page. What is the simplest way of doing that and what modules should I use? I have tried with CTools and a javascript (jQuery) emulation of click on a hidden link, but that gives me problems and seem so convoluted to me. Is there any simplest way?

# Answer
> -2 votes
You can check one of the module:

1. Splashify
2. Pop-up announcement
3. Popup On Load

---
Tags: 7, javascript, chaos-tool-suite
---


# Question
Title: MySQL query for getting blog records/content Drupal7?
I want to customize the and limit the content from the blog entry. If I want hook the sql query output for blog entry, How can i do it? Please help me.

# Answer
The limit is controlled through a variable called `default_nodes_main`. You can change it by executing the following code:

```
// This would increase the number of nodes on the blog page to 20.
variable_set('default_nodes_main', 20);

```

If you have Devel module installed, you can do this at `/devel/php`.
> 0 votes

# Answer
Not sure what you mean by 'limit the content' of the blog entries but there's a module that limits amount of content (number of chars) on a text field already. That maybe what you're after.

https://www.drupal.org/project/maxlength
> 0 votes

---
Tags: views
---


# Question
Title: How is it possible for CSS code to be in a false directory but still be used?
I am trying to mimic a theme from another website. I pulled the code / database down and now I have a local copy.

The sub-theme this guy is using is fine and correct, all is in order.

```
/var/www/sandbox/sites/all/themes/erc_generic/css/

```

However, when I go to look at where he put his CSS code, its in this directory:

```
/var/www/sandbox/sites/default/files/css/

```

This is no-where near in the sub-theme that is being used by Drupal.

He has about 30-40 CSS files in that folder and they don't have normal names either.. here is a example of one:

css\_0\_-tDmvAnmauKU86ANuyPJMDjn5wjUx4qFEEbOhbr7g.css

Also for whatever reason, maybe for extraction purposes, each CSS file he has, he has them individually zipped up.

I am trying to mimic the theme and I thought just copying and pasting the sub-theme settings would do, but when I right-click on the site to look for what CSS properties are being used.. they are linked to these files instead.

How does one even DO this? I can't find how he can link CSS files to a theme thats not even located in the sub-theme folder.

# Answer
> 1 votes
> I can't find how he can link CSS files to a theme thats not even located in the sub-theme folder.

He's not, the system is doing that part.

When you have CSS aggregation enabled, Drupal concatenates all the relevant files together per-page (bit more complicated than that actually, but for the sake of argument that'll do), and those are served instead of multiple originals. Compressed versions are also created for browsers that support it, yes.

If this is messing with you, just pop to the Performance settings page at admin/config/development/performance, switch off CSS aggregation, reload your page, and check the source again. You'll now see links to the original, un-merged CSS files within the theme.

---
Tags: 7, theming
---