# Question
Title: Display a message during form submission and prevent multiple submissions
During a form submit I would like to display a message that the server is busy processing the submission. In some cases a user has to wait for several seconds. This message should disappear automatically and submitting the form again should be prevented.

# Answer
This can be achieved by creating an AJAX form. If you fear that the max execution time of the server will be a problem you should look into batch operations as mentioned by Kevin.

An easier alternative is to add a custom JavaScript file and react on the form submission.

Alter the forms you want to behave as requested in a custom module. Use the #attached property to add your custom JavaScript file (in your custom module directory).

```
$form['#attached']['js'][] = drupal_get_path('module', 'MODULE_NAME') . '/MODULE_NAME.js';

```

Then add something like the following to your JavaScript file:

```
(function ($) {
  Drupal.behaviors.formSubmitFeedback = {
    attach: function (context) {
      // Get the forms we want to modify by form ID.
      var $forms = $('#form_id_x, #form_id_y'),
        submitCount = 0;

      // Make sure the form is only submitted once.
      $forms.once('submit-feedback').submit(function(e) {
        if (submitCount) {
          e.preventDefault();
        }
        else {
          var $submits = $forms.find('input[type=submit]');
          // Hide all submit buttons so that they can't be clicked twice.
          $submits.hide();
          // Add a class to the form so we can do some specific styling.
          $forms.addClass('submit-wait');
          // Add a wait message with throbber after the submit buttons.
          $submits.after('<p class="submit-wait-txt ajax-progress-throbber"><span class="throbber"></span>' + Drupal.t('YOUR MESSAGE') + '</p>');
          // Make all input fields (except the submit buttons) readonly.
          $forms.find('input').not($submits).blur().prop('readonly', true);
        }
        submitCount++
      });
    }
  };

})(jQuery);

```

This piece of code hides the submit button and cancels later submits. A message is added to the DOM with a Drupal throbber (depending on your theme). You may need some CSS to make it look nice. There will be a 'submit-wait' class on the form after submission.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: Using the DB API to test against a trimmed value?
I want to use the DB API (Drupal 7) to do a query like:

```
select my_field from table where trim(my_field) <> ''

```

where `my_field` is a text field. My goal is to not get any values in the result that are made up of one or more spaces. (This is a greatly simplified example query, but you get the idea.) Is there any way to get that call to trim() in there? The only thing I could imagine trying was:

```
$query->condition('trim(my_field)', '', '<>');

```

which doesn't work at all. Any thoughts? Thanks!

# Answer
> 1 votes
You can use `SelectQuery::where()` for more complex requirements:

```
$query->where('trim(my_field) <> :val', ['val' => '']);

```

---
Tags: 7, database
---


# Question
Title: Basic Auth working but simple auth not working for create user
I am totally stuck here in Drupal 8 REST API, any help is very appriciate.

**Problem:**

I am using Drupal 8.3.x, simple\_auth module to generate Auth token for REST. When I try to create user by Authorization Bearer then its not working but when I try to create by Basic Auth then it works fine. I also enabled permission for user REST.

See Permission for user resource: URL: admin/config/services/rest/resource/entity%3Auser/edit

**Postman Data:**

Request header:
Authorization:Bearer token\_value
Content-Type:application/hal+json
X-CSRF-TOKEN:OWp4RVNjlQbdjq-s6CMjNRIcfNiYsHp1L7Of87vJH2w

**In Error Log:**
League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in League\OAuth2\Server\Exception\OAuthServerException::accessDenied() (line 165 of /var/www/html/d8/drupal-8-composer/vendor/league/oauth2-server/src/Exception/OAuthServerException.php).

# Answer
I resolved my problem by giving user creation permission to anonymous user. "Access POST on User registration resource"
> 1 votes

---
Tags: 8, authentication-authorization
---


title: Trusted Host Settings Not enabled

text:
# Question
Title: Trusted Host Settings Not enabled
In the settings.php file if the site, I added the following line.

```
$settings['trusted_host_patterns'] = array(
  '^www\.example\.com$',
);

```

I'm using Drupal 8.2.6.

Do I need to add the proxy address too, or my IP? It is a single domain.

# Answer
> 0 votes
Every entry in the array contains a RegEx. So you must escape the dot too.

```
$settings['trusted_host_patterns'] = array( '^www\.example\.com$' );

```

This will match the exact the host "www.example.com".

---
Tags: configuration
---


# Question
Title: Find out which theme is loaded in a given page
I am trying to do some theming for Drupal 8 and I was trying to understand what theme is being used on a given page. I remember using theme developer module in Drupal 7, and using `dpm()` of the page array after theme developer started having issues.

How can I achieve the same with Drupal 8?

# Answer
In Drupal 8, you can do two things from custom code:

```
\Drupal::theme()->getActiveTheme();

\Drupal::theme()->getActiveTheme()->getName();

```

The first will return a theme object, the second will return just the theme name.

See the ThemeManager docs for more details.

You can also install Devel/WebProfiler for more information about the current page request and other variables.
> 8 votes

# Answer
Global theme variables got replaced by an ActiveTheme in Drupal 8.

In Drupal 7 you could access and set the current active theme via global variables like `$GLOBALS['theme_key']` and `$GLOBALS['theme']`.

In Drupal 8 this is replaced by an ActiveTheme object available via the 'theme.manager' service:

Example code in Drupal 7:

```
drupal_set_message(t("Active theme name: @name", array('@name' => $GLOBALS['theme_key'])));

```

Code in Drupal 8:

```
drupal_set_message(t("Active theme name: @name", array('@name' => \Drupal::theme()->getActiveTheme()->getName())));

```

On top of the theme name the ActiveTheme (`\Drupal\Core\Theme\ActiveTheme`) object provides all runtime information needed about the active theme, like the path to the active theme:
> 0 votes

---
Tags: theming, 8
---


title: Using AJAX in blockform

text:
# Question
Title: Using AJAX in blockform
I'm attempting to allow a user to add text fields by clicking a button in a configuration form for a block plugin. I'm currently populating the form like so:

```
public function blockForm($form, FormStateInterface $form_state) {
    for ($i = 0; $i < $this->configuration['linkNum_submit']; $i += 1) {
        $form['link'][$i] = array(
            '#type'          => 'textfield',
            '#title'         => 'Link',
            '#default_value' => '',
        );
    }

```

My form is populated using a for loop that takes into account a configuration field noting the amount of textfields that should be displayed.

I also have a button that's meant to add another $form\['link'\] textfield by doing an ajax callback.

```
$form['add_link'] = array(
    '#type'     => 'button',
    '#value'    => $this->t('Add link'),
    '#ajax'     => [
        'callback' => array($this, 'Drupal\my_module\Plugin\Block\LinkList::addLink'),
        'event'    => 'click',
        'progress' => array(
            'type'    => 'throbber',
            'message' => t('Adding link...'),
        ),
    ],
);

```

Below is the ajax function that is called. It attempts to increase the configuration field the for loop in bockForm is based on.

```
public function addlink(array&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $this->configuration['linkNum_submit'] += 1;

    return $response;
}

```

I believe my issue is that the form isn't being rebuilt, but I'm not sure how to force it to. I found documentation on the rebiuldForm() function here https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!FormBuilder.php/function/FormBuilder%3A%3ArebuildForm/8.2.x but I'm not sure how to implement it in this case.

# Answer
> 2 votes
The issue is not about the form rebuild, the form is being automatically rebuilt on every AJAX call. The issue here is of the wrapper is not being defined in the '#ajax' array and the wrapper attribute should be given to a "container" type of field and then all of the updated fields should be part of the respective "container" field.

or some ajax command should be called on $response object in the ajax callback method above.

e.g.

```
public function blockForm($form, FormStateInterface $form_state) {

$form['link'] = array(
  '#type' => 'container',
  '#attributes' => array('id' => 'link-wrapper'),
);
for ($i = 0; $i < $this->configuration['linkNum_submit']; $i += 1) {
    $form['link'][$i] = array(
        '#type'          => 'textfield',
        '#title'         => 'Link',
        '#default_value' => '',
    );
$form['add_link'] = array(
  '#type'     => 'button',
  '#value'    => $this->t('Add link'),
  '#ajax'     => [
    'callback' => array($this, 'addLink'),
    'event'    => 'click',
    'wrapper' => 'link-wrapper',
    'progress' => array(
        'type'    => 'throbber',
        'message' => t('Adding link...'),
    ),
],

```

);

and then in the ajax callback

```
public function addlink(array&$form, FormStateInterface $form_state) {
  return $form['flipper']['front']['settings']['link'];
}

```

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


# Question
Title: Pass variables from one preprocess function to another in .theme
I am developing a theme in Drupal 8 and I have 2 twig files. One is `page.html.twig` and the other is `status-messages.html.twig`.

The problem is that status-messages has a variable named `message_list` (an array) but this variable is protected, so other files don't have access to it. I have tried to call this variable from `theme_preprocess_page()` like so `$variables['testvar'] = $variables['message_list'];` with result of `$variables['testvar'] = null`.

In the next step I tried to copy the functionality of `status-messages.html.twig` from `Drupal\Core\Render\Element\StatusMessages` to `mythemem.theme` file, like so:

```
use Drupal\Core\Render\Element\StatusMessages;

function MYTHEME_preprocess_page(&$variables) {

  // Create Dynamic path for project root elements (in general files that are in our theme project)
  $variables['theme_path'] = base_path() . $variables['directory'];

  // this here gives us the array of renderMessages() but  '#message_list' has no data in it
  $variables['testvar'] = StatusMessages::renderMessages();
}

function mythemem_preprocess_status_messages(&$variables) {

  // this here dose gives the value but it can be accessed  only in status-messages.html.twig
  $variables['mymessages'][] = $variables['message_list'];

  // same as in mythemem_preprocess.page
  $variables['testvar'] = StatusMessages::renderMessages();
}

```

My aim here is to understand how to correctly use `.theme` files, how to pass protected variables from one preprocess function to another.

---

To be more clear I would like to know/understand how to get the same effect for my `custom.html.twig` file as it is here

To achieve this, I want to take `$variables['message_list']` to process it as I want.

# Answer
> 0 votes
well after finking a lot about this problem, i realized that i don't wont to duplicate this variable at all.

lets start from beginning i wanted to copy the `$variables['message_list']` from `status-messages.html.twig` to make my custom layout for different situation.

for example i wanted to have different layout/design of status message on my custom login page and another layout/design for my custom register page. but now i understend that i can have this two in one place (in `status-messages.html.twig`) i can check if my URL is `/login` tean with help of twig `if` condition i can render one layout and if my URL is `/register` then i could have second layout! and in aver situation u would have default layout.

is that correct? how would you solve the problem if you ware in my place

---
Tags: theming, 8, status-messages
---


title: Blocks overlapping in front page

text:
# Question
Title: Blocks overlapping in front page
I have a problem with one block in my website, recently I noticed that it gets overlapped by the others, not allowing to be seen correctly and to click the links in it, it's the partner block at the bottom right of this website: http://www.esnbologna.org/

Any hints on how to solve this problem?

# Answer
The problem is that the `<div>` with id `#views_slideshow_cycle_teaser_section_partners-block` for the browser has an height of 0. Therefor, the most simple solution for you would be to set a static height for this element using CSS (i.e., the largest slide is currently 656px).

If you want the 'view all' link to be right below the slide that is shown to the user, in your situation I think the most easiest solution would be to alter the height of `#views_slideshow_cycle_teaser_section_partners-block` using JavaScript (i.e., jQuery).

For more information on this, see this post: Make absolute positioned div expand parent div height
> 1 votes

---
Tags: blocks
---


# Question
Title: Defining a varibale Node Expire date by custom PHP code in Rules module
I have a content type, Job Offer, and this node type is able to expire thanks to Node Expire module.

When editing a Job Offer, I want to change the expire date by the value of the Duration field that I added to this node.

In order to do this, I made a rule with the help of Rules Module and I am using the custom PHP code below as an action in the light of this post, but it did not work with my field:

```
$node->expire = date('Y-m-d', strtotime("+[node:field-duration:field-value] days"));
return array("node" => $node);

```
* node:field-duration:field-value is an integer field of a taxonomy term

Any help would be appreciated. Thanks

# Answer
> 0 votes
Thanks to @undersound, the code below worked!

```
$duration = [node:field-duration:field-value];
$node->expire = date('Y-m-d', strtotime("+" . $duration . " days"));
return array("node" => $node);

```

---
Tags: rules
---


title: Creating field with multiple properties

text:
# Question
Title: Creating field with multiple properties
I am creating a Field plugin, where I have requirement as below

**Field name :** Question

**Properties:**

Question Text : String

Question Type : integer (0,1,2)

Question Options : Array of Strings

I defined schema like this. I am not sure if I am doing it right for Question Option

```
public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
        'columns' => [
            'question_text' => [
                'type' => 'varchar',
            ],
            'option_type' => [
                'description' => 'Option Type: 0 = radio, 1 = checkbox',
                'type' => 'int',
                'default' => 0,
            ],
            'question_option' => [
                'type' => 'varchar',
                'serialize' => TRUE,
            ],
        ],
    ];

    return $schema;
}

```

And for property definition I have following

```
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {

    $properties['question_text'] = DataDefinition::create('string');
    $properties['option_type'] = DataDefinition::create('integer');

    $properties['question_option'] = DataDefinition::create('string');

    return $properties;
}

```

Please let me know how can I do it for the question\_option.

--

Thanks

# Answer
> 1 votes
If you want an array of strings maybe your should use a blob in you schema:

```
 'question_option' => [
          'type' => 'blob',
          'size' => 'big',
          'not null' => TRUE,
          'serialize' => TRUE
        ],

```

Note that by default 'size' = 'normal' which max storage value is 16KB so if it is enough for you use 'big'; 'big' can handle up to 4GB. And for properties as follow:

```
$properties['question_options'] = MapDataDefinition::create()->setLabel(t('Options'))

```

---
Tags: 8, entities, plugins
---


# Question
Title: Auto Import facebook comments into Drupal website
Using Drupal 7. When i share a node on Facebook, i wish to automatically import Facebook comments made on Facebook for that node into the node's page on Drupal. I've tried a couple of modules including Facebook comments Block

: https://www.drupal.org/project/facebook\_comments\_block and Facebook comments social plugin

but they only help users to comment on your site using their facebook accounts, no way to import comments made by users on the content page when it is shared to facebook.

# Answer
You can fetch comments on a post using graph API. But you must know the Facebook post id of the corresponding node.

```
https://graph.facebook.com/<postedid>/comments

```

Try this - https://stackoverflow.com/questions/11043527/how-to-get-all-comments-and-likes-for-a-facebook-post
> 0 votes

---
Tags: 7, social-network
---


# Question
Title: How to send a webform email to all users of a specific role?
Is it possible send webform data in email to all users of a specific role?

In the webform email settings there is no such option.

I also tried with Rules, but in rules the webform tokens are rendering the webform submitted data.

Here is my rule attached.

```
{ "rules_send_email_to_ce_user_on_webform_submit" : {
    "LABEL" : "Send email to CE user on webform submit",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "[form-id:value]",
          "selected_webform" : { "value" : { "webform-client-form-121" : "webform-client-form-121" } }
        }
      }
    ],
    "DO" : [
      { "webform_submissions_load" : {
          "USING" : { "nid" : "121", "sid" : [ "data:sid" ] },
          "PROVIDE" : { "submissions" : { "submissions" : "Fetched submissions" } }
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "11" : "11" } },
          "subject" : "Form submission from: [node:title]",
          "message" : "DATA\r\n[data:data]\r\n\r\nRAW\r\n[data:data-raw]\r\n\r\nField value\r\n[data:title-value]"
        }
      }
    ]
  }
}

```

Any other method?

# Answer
From the exported rule in your question, it seems you already have the Webform Rules module enabled (a prereq for what follows ...).

You may want to give it a try to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* Load the VBO list that you want to be processed.
* Add a loop to perform a Rules Action, for each row contained in your Views results.

Some more details about the VBO-view you'd have to create for this:

1. Create a list users, using the Views module.
2. It should include an appropriate filter for the role to be processed.
3. It should have exactly 1 result (row) for each user to be eMailed.
4. One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
> 1 votes

# Answer
You can add an additional submit handler for the webform in ***hook\_form\_alter***. Then in the submit handler, you get the list of users with that role. You can try the below code to get list of users. Then send email to these users with the submitted data.

```
// get role data by role name
$role_data = user_role_load_by_name('member');

// get list of users with specific role
$uids = db_select('users_roles', 'ur')
->fields('ur', array('uid'))
->condition('rid', $role_data->rid, '=')
->execute()
->fetchCol();

$users_list = user_load_multiple($uids);

```

There may be better solutions for this. But you can have a try.
> 1 votes

---
Tags: 7, rules, webforms, emails
---


# Question
Title: How to print a field in node.tpl.php without labels or markup?
In Drupal 7, you can render a field in a `tpl.php` file like this:

But that prints it out with it's label and HTML. Is there a way to get just the raw value of the field.

I know you can do the following:

* Override the field markup in the field.tpl.php file (or field--FIELDNAME.tpl.php)
* Turn off labels in the admin interface
* Use a module like Fences to control mark up in the admin interface.

However, all of those involve extra steps. I was wondering if there is a way to do it directly in the node.tpl.php file. That way, all the changes are contained in a single place. (Plus if you change themes to one that requires the labels, you have to go back in the admin interface and turn them back on).

# Answer
wolffer-east's answer satisfies the original question goals of:

* Printing a field
* Doing it in a single file (so everything is in one place).

However, the code is quite complex for a node.tpl.php file which are only supposed to contain simple PHP statements.

So in the end, I reworked it as follows. In my template PHP file, I put the following:

```
function print_field($field_name) {

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);
print $field[0]['value'];
}

```

This is the same as wolffer-east, except it loads the node.

In my node file, I can then use the following:

```
<?php print_field('field_body_text') ?>

```

This renders out the field without any labels and HTML, but still clean.

---

A more advance version is this:

In template.php function print\_field($field\_name, $format = 'safevalue') {

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);

if ($format = 'url') {
    print file_create_url($field[0]['uri']);
} else {

print $field[0][$format];
}
}

```

In node.tpl.php

You can swap 'filename' with any of the following:

* value: Prints field without any extra HTML for paragraphs and line breaks
* safe\_value: Prints field HTML for paragraphs and line breaks
* filename: Prints field's filename uri: Prints field's path in public:// format\[\*\]
* url: Prints field's path in traditional URL format\[\*\]
* alt: Prints field's alt value\[\*\]
* title: Prints field's title value\[\*\]
* width: Prints field's width value\[\*\]
* height: Prints field's height value\[\*\]

\[\*\] only applies to fields that have files/images

The only downside is that it displays the following error message:

> Notice: Undefined index: safevalue in print\_field() (line 16 of template.php)

I am not sure how to fix this error message, but I guess it is a separate question.
> 1 votes

# Answer
If you just want the value of a given field, it will be in the $node object in your node.tpl.php file (or node--type.tpl.php).

Normally it's under something like:

```
$node->field_name['und'][0]['value']

```
> 3 votes

# Answer
You're on the right track!

Rather than a node template file though, the individual markup of a field is controlled by its field.tpl.php file. You can control the display of a field in a very granular way by making a custom one - copy your theme's default implementation of it, name the copy field--field-name.tpl.php, and remove all the excess markup.
> 2 votes

# Answer
You might want to try

```
<?php print render($content['field_your_field']); ?>

```

in node.tpl.php combined with context and entity view modes modules or simply modify the display settings of the field in the content type configuration
> 2 votes

# Answer
If you are in the node template you can load the field, then get the content from the loaded field. Check out the field\_get\_items documentation for more info. In short it returns the values you want in the current language.

```
$field_name = 'your_field_here';
$field= field_get_items('node', $node, $field_name);
print $field[0]['value']

```

should do it. It will return an element for each item if it is a multi value field. They can be accessed via `$field[$key]['value']`
> 1 votes

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


title: Proper way to create custom tables

text:
# Question
Title: Proper way to create custom tables
I have tried to create custom tables for a module in Drupal via `hook_install()` and `hook_schema()` in module.install, and it works fine after disabling and enabling module using `drush dre module_name`. Is that the proper way to create tables in custom module ?

Can I use config/schema/module\_name.schema.yml for creating tables? If not, what is the use of schema files in Drupal 8?

# Answer
> 9 votes
`hook_schema()` is not used differently from how it was used on Drupal 7, the only difference is that it is not used to create database tables for entities. See, for example, `node_schema()`, which doesn't define the table used for the Node entity (the *node* table).
In particular, you don't need to call `drupal_install_schema()`) in `hook_install()` to create custom database tables, which was instead necessary in Drupal 6.

.schema.yml files (for example, user.schema.yml) are used to define the schema for the module configuration files. Their purpose is different from defining a database table schema, and they cannot be used for that.

# Answer
> 3 votes
For a database table, you use `hook_schema` to define it and if the module already exists, you can use `hook_update` to create the table manually as it hook\_schema is only triggered during installation.

This is all like you describe.

The schema config is not used to create database tables, instead it's use to define the schema of configs. Basically you use it to explain the structure of configs your module will save, data types etc. I don't know what actually uses this as most things will work without it.

# Answer
> 2 votes
The two 'schema' have different contexts.

Your assertion of creating database tables is correct.

schema.yml files serve another purpose. From the docs:

> Using the knowledge embedded in the configuration schemas about what is stored of a configuration entity, the default persistence implementation for configuration entities requires a configuration schema for the configuration entity, so the right properties are exported with the types defined. Although it is better to provide configuration schemas, if you really don't want, implement the toArray() method in your configuration entity implementation to not require schema for saving configuration entities of your type.

And that is just one reason. See: https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata#use

---
Tags: 8, database
---


# Question
Title: How do I remove the active class in the main menu?
One item in the menu has sub-items that point to the same page (just with different arguments) ex:

Products \- List item 1 \products?pid=1 \- List item 2 \products?pid=2 \- List item 3 \products?pid=3

Drupal assigns the "active" class in the

- and tag of the menu items since all the items have the same page url (\products)

I'm overwriting the menu\_link function in template.php to remove the active class but the class remains in the tag

```
function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {

    if (strtolower($element['#title']) == 'Products') {

      if (isset($_GET['pid'])) {
        $currID = $_GET['pid'];

        foreach ($element['#below'] as $Taxonomy) {

          if ($currTaxonomyID != $Taxonomy['#localized_options']['query']['pid']) {
            $mlid = $Taxonomy['#original_link']['mlid'];
            $key = array_search('active', $Taxonomy['#attributes']['class'], TRUE);
            if ($key) {
              unset($element['#below'][$mlid]['#attributes']['class'][$key]);
              $element['#below'][$mlid]['#localized_options']['attributes']['class'][$key] = '';
            }
            // remove active-trail class
            $key = array_search('active-trail', $Taxonomy['#attributes']['class'], TRUE);
            if ($key) {
              $element['#below'][$mlid]['#attributes']['class'][$key] = '';
            }
          }
        }
      }
    }
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

Final Result:

```
<ul class="menu nav">
   <li class="first leaf menu-mlid-44253">
      <a href="/products?pid=1" title="Best Practices" class="active">Best Practices</a>
    </li>
    <li class="leaf menu-mlid-44254">
      <a href="/products?pid=2" title="Checklists" class=" active">Checklists</a>
    </li>
....

```

How can I remove the class "active" from the tag?

My menu Structure:

```
-Clients
-Products
  -prod1 (url:\\products?pid=1)
  -prod2 (url:\\products?pid=2)
  -prod3 (url:\\products?pid=3)
  -prod4 (url:\\products?pid=4)
-About

```

# Answer
> 0 votes
I had the same problem: the l() function automatically assigns an `active` class when a link is pointing to the current page.

I got around this using an (ugly) hack:

As noted in the documentation, `$options['language']` is additionally compared with `$language_url->language` before assigning the `active` class.

So, the hack is to supply a *deliberately incorrect* language when calling `l()`.

You can find out what the current language of your site is using dpm():

```
global $language_url;
dpm($language_url->language);

```

In my case, I know that the language of the site is *definitely not* `und`, so I appended `array('language' => 'und')` to my call to `l()`:

`l('link text', 'path/to/page', array('language' => 'und'))`

After this, the `a` element no longer had the `active` class.

---
Tags: 7
---


title: How can use session

text:
# Question
Title: How can use session
I created a html page and create form on it . I want send data of my form to a form that I create . I use session but when I use session and refresh page , other session was delete or when i use `session_unset();` the sessions in 4 or 5 time refresh age was show .

What is the right way for save session for anonymous users?

I use `$_SESSION['test']` but I think that it's not good way .

# Answer
> 0 votes
If you get form content that is outdated since 4 or 5 refreshes this could be a caching issue. You can try to add a cache context to the form:

```
$form['#cache']['contexts'][] = 'session';

```

Or if this doesn't help disable the render cache for the form:

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

```

---
Tags: 8, sessions
---


title: How to fix "Clickjacking"?

text:
# Question
Title: How to fix "Clickjacking"?
I have got this vulnerability "#150124 Clickjacking - Framable Page". Can anyone suggest how to fix this vulnerability for a Drupal 6 site?

# Answer
> 2 votes
You could use this module which is available for Drupal 6 to make your site more secure and tackle Clickjacking especially.

Clickjacking can also be tackled on the webserver level directly, do some research on X-Frame-Options, i. e. check this https://geekflare.com/secure-apache-from-clickjacking-with-x-frame-options/

---
Tags: csrf
---


# Question
Title: Add an additional custom submit handler to default search api Solr view filter?
I would like to run an additional submit handler every time a user searches a term with the default view filter provided by the `search_api_solr module`.

Here is my form altering code:

```
/**
 * Implements hook_form_FORM_ID_alter.
 */
function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-solr-search-content-page-1') {
    $form['#submit'][] = 'my_module_handler';
  }
}

**
 * Custom submit handler.
 */
function my_module_handler(array $form, FormStateInterface $form_state) {
  drupal_set_message($form_state->getValue('keys'));
}

```

The problem is the that submit handler executes twice. It executes when the page loads (I think) and when the 'Search' button is clicked. Any ideas why this would be?

(I am trying to write all the terms searched by users (strings) to a database table.)

Thanks.

# Answer
The solution was to enable AJAX on the view. This stopped the page refreshing and the double form submission.
> 0 votes

---
Tags: 8, search
---


title: $_POST empty in custom callback

text:
# Question
Title: $_POST empty in custom callback
I'm trying to write a custom listener for PayPal Instant Payment Notifications. I've defined a page callback in `hook_menu` as

```
$items['paypal-listener'] = array(
    'title' => 'PayPal IPN Listener',
    'description' => 'Simple test for receiving PayPal notifications',
    'page callback' => 'ipn_test',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

```

and my custom callback is

```
function ipn_test() {
    var_dump($_POST);
    watchdog('paypal_ipn', print_r($_POST, TRUE));
}

```

but it's always empty. When testing with postman the response is always

```
array(0) {}

```

Is there something I'm missing? Something that empties out the $\_POST array?

The $\_POST from PayPal is `Content-Type: application/x-www-form-urlencoded` in case that matters.

I have already checked this question, this question and this one but none seem to have the answer to why the data is gone.

This doesn't work either

```
$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);

```

**Update**:

OK, it seems as if the chrome app postman can't send POST varibale to a local server properly. I created a simple php script with just `var_dump($_POST)` and while it works fine on an online server, it is empty on my local server.

# Answer
There must have been some kind of bug or I set it up wrong because the next day it started working fine.
> 0 votes

---
Tags: 7
---


title: Hide form behind PayPal payment

text:
# Question
Title: Hide form behind PayPal payment
The site I'm working on at the moment has a competition that requires the following workflow:

1. User creates an account
2. User pays fee with PayPal (ideally a button)
3. User enters multi step/page form

I'm at a loss as how to best implement this:

The **Webform Paypal** module allows me to include a button but when I put it on the first page of my form it doesn't redirect me back to continuing the rest of the submission after payment.

The **Payment for Webform** module has too many steps:

1. First you have to click 'add payment' which opens a new window
2. Then you have to select a quantity
3. Then you have to select a payment method
4. Then you're taken off site

The **Webform Paymethod Select** module has the same issue as the first module except I get a 404 after completing a payment.

I'm wondering if payment should be part of the form at all? Is it possible to hide the webform until a successful payment has been received? I guess I'd have to write something custom for that.

# Answer
What I ended up doing was creating a separate page with a generated PayPal button. You can include a hidden field called 'custom' that you can use to pass in your own data so I included the current user's UID. After a successful payment you can get PayPal to send a POST with the details to a URL of your choosing. I set up a custom page with a listener then updated the user account specified by the UID.
> 0 votes

---
Tags: 7, webforms, payment-gateways
---


title: Private folder issues with NGINX

text:
# Question
Title: Private folder issues with NGINX
So I have been setting up my Drupal 8 installation and I'm having troubles with my private folder setup.

I went on to `settings.php` and specified the path which I wanted for my private folder as `sites/default/files/private`. It seemed to be working well for a while, but now it isn't.

I have configured Drupal to use the private folder as default location for file uploads and it shows the `sites/default/files/private`path as the private folder path.

Now my issue is that I created a custom content-type with a private folder file upload field. This is for a restricted area I have in the website which I only want authorized (logged in) users to be able to access - both that area, and the files linked there.

The area was successfully blocked via role permissions and works great. The files attached to content - even though the content-type settings are explicitly and correctly set to use the private folder for upload - result in the following behavior:

* files served by direct HTTP in `sites/default/files`are accessible, regardless of Drupal login state - **as intended**
* files served by direct HTTP in `sites/default/files/private` are blocked with a 403 forbidden by NGINX regardless of Drupal login state - **as intended**
* restricted files served by Drupal in the restricted area with an URI similar to `system/files/YEAR-MONTH` don't show Drupal's access denied 403 page (**the intended effect**), **BUT INSTEAD**:
    + if they are images, I get an NGINX 404 NOT FOUND error page
    + if they are other file-types, they are accessible without restriction (**exactly what I'm trying to prevent**).

Right now I'm lost as I've been searching around for answers on these issues, but I can't seem to find them.

I'm using a shared web server setup in which I don't have direct access to NGINX's `.conf` files. I'm also using the IMCE File Manager module. I think that the images issue is related to some NGINX conf and as such I'll have to contact the web server maintainer to fix it, but I'd like to have some insight to share with them about this. Also, what can possibly explain the files being uploaded to the private folder being accessible without any restriction?

Any help would be very welcome, thanks!

# Answer
It has been a while since I created this question, and as such I might be missing quite a few details, but I eventually did find a solution.

> **TL;DR** It should probably relate to NGINX, so cover all the bases related to it. NGINX's official Drupal recipe helped me a lot, you might want to check that first. Although, if you're using Drupal 8, you'll need to update/change some settings for it. You might find some of them here.

Can't recall much about my specific case, but this checklist might be worth checking out in your setup:

* **settings.php** be careful and mindful of the options you have setup in your settings file. IIRC, I think the private folder path value was all I changed regarding this issue.
* **Drupal configuration** \- in Drupal's admin backend, go to `Configuration > Media > File System` and make sure you have the correct option selected for your use case, either public/private. This will setup your default file upload location, but can be overridden in the content type's definition, if I'm not mistaken.
* **Content type definition** \- make sure that your content type using the file field is setup properly and also according to your needs. I think at some point I even re-created my content-types just to make sure there wasn't stale info in the DB.
* **Drupal role permissions** \- this was probably one of my biggest headaches with this issue. Make sure they are properly setup and test them thoroughly. In this process I discovered the Masquerade module, which has helped me a lot ever since.
* **Folder permissions** \- The folders you want to use for both private and public uploads should be writable by Drupal/NGINX, but NGINX should not enable HTTP access to them.
* **NGINX** \- this is definitely the most important part. What you basically need to absolutely make sure of is that Drupal handles it's own URLs, and everything else is handled by NGINX accordingly. This can get confusing really fast, so here are some more tips:
    + Drupal will have it's own file URL being generated internally and saved to the DB. This should make Drupal respond and take over HTTP requests to a `system/files/YEAR-MONTH`-type URL.
    + NGINX on the other hand, must let Drupal handle those requests, while intercepting and preventing direct access to `sites/default/files/private`, or whatever folder you have setup for private files.
    + This should be fixed by setting up the correct NGINX directive regarding the path you want/need it to handle. This might help. Also, go read about Perusio's NGINX setup, as there are a lot of valuable nuggets of information there (D8's setup is equivalent to D7).
    + I think some specific NGINX directives may target certain file-types differently (maybe something related to MIME types, not sure). This could explain if your issue happens with, ie, JPG, but not PDF or vice-versa. Couldn't find info on this, though.

@GokulNK I'm sorry if this isn't enough help, but I really can't recall what I did to fix it. Hopefully it'll point you in the right direction, though.

**EDIT:** I found an old email with the webserver's maintainer discussing some NGINX directives that has some info that might be relevant:

```
# handled by NGINX
location ~ ^/sites/default/files/private/ {
    return 403;
}

# Handle private files through Drupal.
location ~ ^/system/files/ { # For Drupal >= 7
    try_files $uri /index.php?$query_string;
}

```
> 6 votes

---
Tags: files, 8
---


title: Easychart with views cache

text:
# Question
Title: Easychart with views cache
I have installed easy chart plugin with Drupal 7 website.

My pages are generated with views using nodehierarchy and quick tabs plugin. To speed up page load, I have enabled views cache.

I noticed easy chart displays while page loads for the first time after cache is cleared. But as soon page speeds up(cached) charts are not displaying.

We have APC cache installed on our website.

Can anyone help with?

Thanks!!!

# Answer
> 0 votes
Found a solution the other way.

Created views for chart separately and inserted into my existing view through "Global view" Field. It increased page load time a bit so for cached page from 2-3 seconds to 3-4 seconds but that is better than 30 seconds(sometimes even more based on content) without cache

---
Tags: 7, views, caching, charts
---


title: Using hook_form_alter to Hide a field

text:
# Question
Title: Using hook_form_alter to Hide a field
```
function custom_form_alter(&$form, &$form_state, $form_id) {

global $user;
$node = node_load(arg(1));
$num  = $node->field_node_reference['und'][0]['nid'];
$val  = node_load($num);
$event_noderef_uid = $val->uid;

if($form_id == 'regester_node_form'){

if($user->uid == $event_noderef_uid){
 $form['field_NAME']['#access'] = FALSE;
 }

```

How to hide `field_NAME` only if `($user->uid == $val->uid)`

# Answer
> 1 votes
You can clean up the code a bit by using hook\_form\_FORM\_ID\_alter:

```
function mymodule_form_regester_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $node = node_load(arg(1));
  $num  = $node->field_node_reference['und'][0]['nid'];
  $val  = node_load($num);
  $event_noderef_uid = $val->uid;

  if($user->uid == $event_noderef_uid){
    $form['field_NAME']['#access'] = FALSE;
  }
}

```

Other than that, if `field_NAME` exists in the form and the condition is true, `access` will be set to FALSE. If you are testing this as user 1, you may not be seeing the results you desire as that is the superuser. It would help if you posted the form you are trying to alter and what its structure is for `field_NAME`. Probably a really good case to write an automated test for as well.

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


# Question
Title: How to get Media entity image (Entity Reference Field) URL in TWIG theme
Apologies if this question has already been asked. However, in my research I found the answers have been for simple image fields which are in default install of Drupal 8. However, in order to have reusable media, I am using Media Entity and associated modules. The problem is I am not able to access image or its URL in TWIG template, where simple image fields work just fine.

While the code below works as expected if field\_image is a simple Image type, but doesn't work if it is Entity Reference field.

```
<div class="header-title white overlay" style="background-image:url({{content.field_image.0}});">

```

In case of Entity Reference field, the output is fully escaped and breaks the structure of my theme. How can I get raw image or URL? I am not a programmer so I don't know how to write preprocessor code.

I am attaching configuration images for the Media Bundle I am using and the node configuration in which I'm using the two types of image fields.

*Media Bundle configuration*

*Node configuration. Note, **'field\_image'** is default drupal image type, while **'field\_image2'** is an entity reference field as configured in the Media bundle above.*

Please advice how to get this working. Thanks.

**Drupal Configuration**

* Drupal 8.3
* media\_entity\_browser-8.x-1.0-beta2
* media\_entity-8.x-1.6
* media\_entity\_image-8.x-1.2
* embed-8.x-1.0-rc3
* entity-8.x-1.0-beta2
* inline\_entity\_form-8.x-1.0-beta1
* file\_entity-8.x-2.0-beta3
* file-8.2.6
* field\_formatter-8.x-1.0
* image\_raw\_formatter-8.x-1.x-dev
* image\_url\_formatter-image\_url\_formatter

# Answer
> 8 votes
If this entity referenced image is controlled by Media, then you should let normal rendering occur:

```
{{ content.field_image2 }}

```

The rendering is then controlled by the field formatter, which will look to a display mode in Media, which is not dissimilar from Node display modes (default, teaser, etc).

Your filename would be something like:

```
media--media-bundle--display-mode.html.twig
media--media-bundle.html.twig

```

The first one is most specific, the second one would be the base for that media entity wherever it is used. I usually opt for the first one.

It is in this specific twig template where that code should live. The markup should be sourced there, instead of the referencing entity, in my opinion.

You could also do some preprocessing to solve this as well. Here is an example:

```
/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle == 'landing_page' && $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node->get('field_hero_image')->getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('landing_page_hero')->buildUrl($entity->field_image->entity->getFileUri());
    }
  }
}

```

Then in my respective template...

```
<div{{ attributes.addClass(classes) }} style="background-image: url('{{ hero_image }}');"></div>

```

Alternatively, you can preprocess the media entity:

```
/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  /** @var \Drupal\media_entity\MediaInterface $media */
  $media = $variables['elements']['#media'];

  $variables['media'] = $media;
  $variables['name'] = $media->label();

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  $variables['attributes']['class'][] = 'media';
  $variables['attributes']['class'][] = Html::getClass('media-' . $media->bundle());

  if (!$media->isPublished()) {
    $variables['attributes']['class'][] = 'unpublished';
  }

  if ($variables['elements']['#view_mode']) {
    $variables['attributes']['class'][] = Html::getClass('view-mode-' . $variables['elements']['#view_mode']);

    if ($variables['elements']['#view_mode'] == 'hero') {
      $variables['hero_image'] = ImageStyle::load('hero')->buildUrl($media->field_image->entity->getFileUri());
    }
  }
}

```

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


# Question
Title: Calendar view: Making year+month exposed filter go to the right URL
Using the calendar module, I've created a monthly calendar:

> >

The built-in navigation using \<\< Prev and Next \>\> links works great, and correctly navigate to the previous and next month, using URLs like: http://example.com/calendar?field\_event\_date\_value\[value\]\[year\]=&field\_event\_date\_value\[value\]\[month\]=&date=2014-07

The 2nd navigation is the year + month select lists. I got a requirement to navigate directly to a specific year and month using a dropdown selection. So I've added an exposed filter on the "Event: start date" field (see screen below), which tries to do it but the URL gets broken on the way. I get: http://example.com/calendar?field\_event\_date\_value%5Bvalue%5D%5Byear%5D=2014&field\_event\_date\_value%5Bvalue%5D%5Bmonth%5D=7. However, even if I manually fix the URLs displays empty data.

I tried to put a custom date selection form using this tip, but the form doesn't print. I also tried to create a custom submit handler like this in order to create a custom redirect but views behavior doesn't change. Also, changing the form action doesn't work since the target of the redirect depends on the user's selection and it still appends the extra query parameters.

Any idea on how to fix it?

# Answer
> 1 votes
I dunno but I ended up just doing it all manually with markup and JS, probably is an easier way but yeh:

```
<select id="month" name="month">
  <option id="01" value="January">January</option>
  <option id="02" value="February">February</option>
  <option id="03" value="March">March</option>
  <option id="04" value="April">April</option>
  <option id="05" value="May">May</option>
  <option id="06" value="June">June</option>
  <option id="07" value="July">July</option>
  <option id="08" value="August">August</option>
  <option id="09" value="September">September</option>
  <option id="10" value="October">October</option>
  <option id="11" value="November">November</option>
  <option id="12" value="December">December</option>
</select>

<select id="year" name="year">
</select>

<button id="gotomonth">Go</button>

$('#gotomonth').click(function() {
  var month = $("#month option:selected").attr('id');
  var year = $("#year option:selected").attr('id');
  location.href = year + '-' + month;
});

var currentMonth = ("0" + (new Date().getMonth() + 1)).slice(-2);
var currentYear = new Date().getFullYear();
for (i = (currentYear - 3); i < (currentYear + 3); i++) {
  $('#year').append('<option id="' + i + '" value="' + i + '">' + i + '</option>');
}
$('#month #' + currentMonth).attr("selected", "selected");
$('#year #' + currentYear).attr("selected", "selected");

```

---
Tags: uri, views, datetime
---


# Question
Title: preprocess views view field find view block name
I need the to find the block view name so I can add it to the if statement in hook\_preprocess\_views\_view\_field in Drupal 8. How would I do this? When I use kint($variables\['field'\]) to find the variables Drupal explodes so I don't even know if the variables exists

```
/**
 * Implements hook_preprocess_views_view_field()
 *
 */
function mytheme_preprocess_views_view_field(&$variables) {
    //-- I need the to find the view name
    //-- so I can add it to the if statement
    if ($variables['field']->field == 'nid') {
    }
}

```

# Answer
Try the following

```
//gives you views current display - "block_1" or "page_1"
$variables['view']->current_display;

//gives you views id - "recent"
$variables['view']->id();

```
> 5 votes

---
Tags: views, theming, hooks
---


# Question
Title: How to prevent a site from ever using experimental core modules?
Quote from Experimental modules in Drupal 8:

> Drupal 8 core introduces the concept of experimental modules. These are modules that are provided with Drupal core for testing purposes, but that are not yet fully supported. Experimental modules are included in the Core (Experimental) package on the Extend page of a Drupal site (`/admin/modules`).

I do understand what "testing purposes" means, and I'm aware of best practices like having a ***Dev / Staging / QA / Prod*** configuration.

But when using Drupal 8 in a ***Prod*** environment, I'm looking for a way to ensure to a site owner something like "***`You can be 100% that there is no way that any of these experimental modules can ever be enabled in the prod version of your site.`***". Imagine it's about a business critical Drupal site where "testing in production" is not ever allowed.

So what options do I have in Drupal, apart from hacking core (which is not an option), to be 100% sure of this? And so that:

* It applies for "everybody" (any user), so even `user/1` should not be able to do so if (s)he'd be tempted to do so.
* It doesn't matter if you're using the Admin UI, Drush, Console or anything similar

**Update**

There are some D8 core issues about these experimental modules, which IMO are either related, or contains some inspiring comments for finding a possible solution (work around?):

# Answer
This is by far not as black and white as you make it in regards to experimental modules.

First, on a mission critical production site, you don't want to do *anything* directly on production. Completely irrelevant then if it's an experimental module or not. Any configuration change or module should be tested first. There are modules to enforce a read only configuration system for example, that's one way to approach that. One example is Configuration Read-only mode, note that I have no personal experience with it.

Second, there are experimental modules and there are experimental modules. The first experimental module apart from migrate, wich is a special case anyway, was big\_pipe. Which is now officially stable in 8.3. It is a module that has zero data, zero API, zero configuration, zero UI. You just enabled it and it does its thing. As such, it was perfectly fine to use it on production already and people have been doing that, myself included. **After testing it first**, like any other module/functionality. If you found a bug, you could disable it from one minute to the other, without loosing any data or critical functionality.

On the other side of that spectrum is content\_moderation and anything around that. Once you start using it, it is a critical and central part of your content creation workflow, and getting rid of it again is much harder. We specifically made it so you could uninstall it, and your content that was published was still published and same for unpublished. But your workflows and metadata around that would be gone. Also upgrading is likely going to be tough from 8.2 to 8.3. That's also why we're working hard to get media\_entity into core as a non-experimental module, so people have a stable API and data storage that they can rely on.

Third, the concept of experimental modules is pretty new and there's a bunch of modules in core that we would have made experimental if we could have back when they were added. rest.module and the related modules is one example there.

And last, lots of contrib modules are at least as experimental as experimental core modules, they just don't warn you about that in such an obvious way. Especially development/pre-beta versions. They just don't warn you about themself in such an obvious way.

To summarize, as with many other things, you need to do your research about an experimental module before using it, and for example check if it's big\_pipe-like or content\_moderation-like. And then decide what that means for your site.
> 5 votes

# Answer
I am not 100% sure about this, but I think the only bulletproof way is to

* Extend `ModuleHandler` or implement your own `ModuleHandlerInterface` class, and exclude experimental modules from the methods. Then replace the `@module_hander` in the service container.
* Extend `ModuleInstaller` or implement your own `ModuleInstallerInterface` class, and exclude experimental modules from the methods. Then replace the `@module_installer` in the service container.
* Implement a `hook_system_info()` to remove experimental modules from the discovery list.
> 2 votes

# Answer
**Wanted to delete this, but going to leave this undeleted for the comments sake.**

Option 1)

Don't give client the `Administer modules` permission and don't give them user 1.

Option 2)

Custom module with hook\_form\_alter that loads the CSS or JS file which hides those rows.

EX:

jQuery to hide the table row that belongs to a experimental module.

```
(function ($) {

    $('tr').each(function() {

       var module_attr = $(this).attr('data-drupal-selector');

       if (module_attr == 'edit-modules-content-moderation' || 'edit-modules-datetime-range' || ...) {

         $(this).hide();

       }
    });

}(jQuery));

```

Or you can hide them all with

`$('#edit-modules-core-experimental').hide();`

or

CSS `#edit-modules-core-experimental { display: none; }`

Also add a validate function in case the client strips the CSS/JS or checkmarks the value via inspect element.
> 0 votes

---
Tags: 8, security
---


# Question
Title: Rebuild form AFTER ajax callback has run
I have a form with a button that when pressed re-builds a different part of the form via an ajax request.

Upon clicking the button the form is rebuilt, then my ajax callback is called which saves the values from the form, and then returns part of the form.

The problem is the form is rebuilt BEFORE my callback which saves the values, and therefor alters how the form is built.

If I click the ajax button a second time then it works correctly as has the values from the previous ajax request when the form is build.

How can I get my callback function to run before the form is rebuilt?

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

    ddl('build'); // log that this function is being called

    $form['save'] = array(
        '#type' => 'button',
        '#submit' => array('emtr_shift_plan_form_ajax_submit'),
        '#value' => 'Save',
        '#ajax' => array(
            'callback' => 'emtr_shift_plan_form_ajax_submit',
            'wrapper' => 'postions',
        ),
        '#id' => 'ajax-save-form-values',
    );

    $form['postions'] = array(
        '#type' => ' container',
        '#prefix' => '<div id="postions">',
        '#suffix' => '</div>',
    );

    // code here to populate the positions container

}

function emtr_shift_plan_form_ajax_submit($form, &$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt

    return $form['positions'];

}

```

EDIT:

As a workaround I found it is possible to manually rebuild the form a second time in the ajax callback with `$form = drupal_rebuild_form('emtr_shift_plan_form', $form_state);`, but is seems inefficient building the form twice. Can I just swap the order of these events over as opposed to having the build the form twice per ajax request?

# Answer
> 2 votes
I know this question is 3 years old, but I came upon it while searching for a similar issue.

You'll need to modify your approach to get this working. The order of operations when you submit the AJAX request is this:

1. AJAX submit callback is fired. In your AJAX submit callback you'll want to save the data. Flag it in your `$form_state` variable.
2. Form is rebuilt.
3. AJAX callback is fired.

I've re-worked your code a little bit to demonstrate.

```
// AJAX FLOW: 2. Form rebuild is fired.
function emtr_shift_plan_form($form, &$form_state) {

    ddl('build'); // log that this function is being called

    $form['save'] = array(
        '#type' => 'button',
        '#submit' => array('emtr_shift_plan_form_button_submit'),
        '#value' => 'Save',
        '#ajax' => array(
            'callback' => 'emtr_shift_plan_form_ajax',
            'wrapper' => 'postions',
        ),
        '#id' => 'ajax-save-form-values',
    );

    $form['postions'] = array(
        '#type' => ' container',
        '#prefix' => '<div id="postions">',
        '#suffix' => '</div>',
    );

    // code here to populate the positions container
    if (isset($form_state['saved_values'])) {
      // do stuff.
    }
}

// AJAX FLOW: 1. Button submit is fired.
function emtr_shift_plan_form_button_submit($form, &$form_state) {

  // log the ajax callback is being called
  ddl('ajax submit');

  // save the values. Make sure the data is stored somehow so your form can get at it.
  $form_state['saved_values'] = emtr_shift_plan_form_save($form, $form_state);

  // rebuild flag here will trigger emtr_shift_plan_form() to be run
  $form_state['rebuild'] = TRUE;
}

// AJAX FLOW: 3. Button callback is fired.
function emtr_shift_plan_form_ajax($form, &$form_state) {
    return $form['positions'];
}

```

Hope that sheds some light for someone.

# Answer
> 2 votes
You could try like this making submit different and callback different and see if it helps.

```
$form['save'] = array(
    '#type' => 'button',
    '#submit' => array('emtr_shift_plan_form_ajax_submit'),
    '#value' => 'Save',
    '#ajax' => array(
        'callback' => 'emtr_shift_plan_form_ajax',
        'wrapper' => 'postions',
    ),
    '#id' => 'ajax-save-form-values',
);

function emtr_shift_plan_form_ajax($form, &$form_state){
  return $form['positions'];
}
function emtr_shift_plan_form_ajax_submit($form, &$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt
}

```

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


# Question
Title: How do I change the "Access Denied" message?
I have a need to temporarily unpublish some pages on our website, but when anonymous users try to access an unpublished page, say they had it bookmarked, they get the message:

Access Denied

Which may sound too harsh. I thought about changing it to 'Page Not Found.'

However, I searched the entire site and I can't find any template that controls this particular message. Using Theme Developer, I can see that the Access Denied page is using the standard page.tpl.php, which I don't believe has anything pertaining to the Access Denied page. What am I missing?

# Answer
> 4 votes
For Drupal 7 & 8, you can set your access denied page and your page not found page easily. Go to `/admin/config/system/site-information` and review the error page section.

# Answer
> 0 votes
Assuming you are using Drupal 7. To find where the string comes from, you can go to your docroot and run `grep -rnw . -e 'You are not authorized to access this page.'` (You might need sudo permission).

I found it inside includes/common.inc at line 2729, under function drupal\_deliver\_html\_page. That tells me I can try something like hook\_page\_delivery\_callback\_alter to modify the output in a custom module.

# Answer
> 0 votes
you can use the hook\_preprocess\_page to alter your page. the code example below will help you. add it it to your template.php or custom module.

```
    function Hook_preprocess_page(&$vars) {
   global $user;
     if ($vars['title'] == 'Access denied') {

            $normal_path = $_GET['q'];
            $parts=explode('/', $normal_path);
            $nid_part = $parts[1];
            $node = node_load($nid_part);
            if (!isset($node)) {
              return;
            }
            if (($node->status == 0) &&
              ($node->nid == $nid_part) &&
              ($user->uid == 0)) {
              drupal_not_found();
               drupal_exit();
            }
    }

```

simlar question : check this link

---
Tags: users
---


# Question
Title: Views 3, contextual filter on language - allow for multiple languages
So for this site I'm building I need to be able to do the following.

1. When user views the site in English show all English articles
2. When the user views the site in Dutch, show all Dutch articles - but also the untranslated English ones
3. When the user views the site in German, show all German articles - but also the untranslated English ones.

The contextual filter, 'Content translation: Language' only allows to put in one value. That is either a language specified, or all.

But in my case it would be required to be able to set for instance "en+nl" or "en+de". Like one can do with taxonomy 'Has Taxonomy', I would like something like 'Has Language'.

# Answer
> 3 votes
I solved this task like so:

* For "When the filter value is not available", select option "Provide default value".
* then use "PHP Code" as the value for "Type"
* the actual PHP code I added is as shown in the screenshot below:

# Answer
> 2 votes
One solution would be to use field translation:

1. Set "Enable language fallback" to active in the entity translation configuration page.
2. Set the view to use the current user language (Advanced\>Other\>Field Language).

Done.

# Answer
> 1 votes
I guess you need this module: https://www.drupal.org/project/select\_translation

> it provides language fallback functionality for nodes translated with Content Translation (not Entity translation) inside views listings. This is an alternative to the Views "Field Language" option which would not work for nodes translated with Content Translation.

# Answer
> 1 votes
To have a View with a **default language fallback if a node translation doesn't exist and then show the default language one**, just ensure UNCHECK:

*X When needed, add the field language condition to the query*

---
Tags: 7, views, i18n-l10n
---


# Question
Title: Language fallback to site default in internationalization
This should be simple enough; but, I'm trying it since a day now with no success.

My site contains listing pages or different content types. By default all the content is of language "English".
When a user (author) translates a content in the listing to other language (say Spanish), and switches to that language using "language switcher"; only nodes of that language are being listed.
This is because I've added `Content: Language (= Current user's language)` filter to the view.

What I require is when a node does not have a Spanish translation, it should show that node in English. In short I want "English" as a fallback language to all the views (and site). I've tried ORing the filters so that I could list "current language" OR "English", but it shows the both the translated nodes and their corresponding nodes in "English", which is obvious.

**Note** I've made it compulsory for a user to select content for every content type.

I've tried Language Fallback module, but it did not work.

# Answer
> 1 votes
I think what you need is this module: Select translation

> The options are : Use current language ; if not available use original language

I've used it before and it works pretty well.

# Answer
> 0 votes
You can use this method to have a View with a default language fallback: https://drupal.stackexchange.com/a/229445/55122

---
Tags: 7, i18n-l10n
---


title: How to add confirmation to ajax link?

text:
# Question
Title: How to add confirmation to ajax link?
I am rendering ajax link as follows:

```
l(t('Click here'), 'mypath', array('attributes' => array('id' => 'my-id', 'class' => array('use-ajax'))));

```

How to display confirmation dialog before ajax request is called?

I do it as follows in javascript, like I have found on this thread:

```
  Drupal.behaviors.module = {
attach: function() {

 Drupal.ajax['my-id'].beforeSerialize = function () {

      if(confirm('Are you sure?'))
          return true;
      else
          return false;

  }
 }
}

```

When I click on link, ajax request is not called but the dialog appears. It is ok. The problem is, that after I click "Cancel" in confirmation dialog, Ajax request is then called after closing the confirmation dialog.

Can anybody help, how to get the confirmation dialog work?

# Answer
> 4 votes
I don't think this is the best way to go about it as you are messing directly with Drupal's Ajax object.

The best way to do this, is to basically write your own click handler and handle the confirmation yourself, then trigger a Drupal AJAX call yourself.

Here is an example:

```
l(t('Click here'), 'mypath', array('attributes' => array('id' => 'my-id', 'class' => array('toms-ajax'))));

```

In your js file:

```
(function($) {

Drupal.behaviors.tomsAjaxLinks = {
  attach: function(context, settings) {
    $('.toms-ajax',context).once('toms-ajax').on('click', this.handleAjax);
  },
  handleAjax: function(e) {
    // Cache the anchor link
    var $element = $(this);

    // We need some unique id, either ID of link or create our own
    var nowStamp = new Date().getTime() + Math.floor(Math.random() * (1000 - 0) + 0);
    var base = $element.attr('id') || 'toms-ajax-'+ nowStamp;

    // Change the event type to load, so we can trigger it ourselves
    var drupal_ajax_settings = {
      url : $element.attr('href'),
      event : 'load',
      progress : {
        type: 'throbber',
        message : '',
      }
    };

    // Create the ajax object
    Drupal.ajax[base] = new Drupal.ajax(base, this, drupal_ajax_settings);

    // Your confirmation code e.g. Jquery UI Dialog or something
    // Open dialog
    if(yes) {
      $element.trigger('load');
    } else {
      // Dont trigger ajax
    }
  }
};

})(jQuery);

```

Essentially what this does is:

1. Attaches the handleAjax function to your ".toms-ajax" links once to ensure we do not attach multiple event handlers
2. On click, the handleAjax function is called
3. A corresponding Drupal Ajax object is created with it's own unique ID. It is attached to the link and triggered on the event 'load'. You then handle the confirmation box.
4. If the confirmation box confirms the ajaxcall, we simply trigger the 'load' event on the link object and therefore make the Drupal AJAX object do it's thing.

# Answer
> 3 votes
Based on @jnpWebDeveloper answer, but with some changes:

* Support for re-attaching events to content loaded via ajax.
* Support for custom message from `data` attribute of the element.
* Code is production-ready (no need to change any variables etc.).

`ajax-confirm-link.js`

```
/**
 * @file
 * Handling of AJAX links with a confirmation message.
 *
 * @code
 * <a href="custom/nojs/path" class="use-ajax-confirm">Link with default message</a>
 * <a href="custom/nojs/path" class="use-ajax-confirm" data-use-ajax-confirm-message="Please confirm your action">Link with custom message</a>
 * @endcode
 */

/*global jQuery, Drupal*/

(function ($) {
  'use strict';
  Drupal.behaviors.ajaxConfirmLink = {
    attach: function (context, settings) {
      $('.use-ajax-confirm').filter('a').once('use-ajax-confirm').on('click', function (event) {
        var $this = $(this);
        // Allow to provide confirmation message in
        // data-use-ajax-confirm-message element attribute.
        var message = $this.data('use-ajax-confirm-message') || Drupal.t('Are you sure you want to do this?');

        if (confirm(message)) {
          // Create ajax event only if action was confirmed.
          var id = $this.attr('id');
          // Generate unique id, if the element does not already have one.
          if (!id || id.trim() == '') {
            id = 'use-ajax-confirm' + new Date().getTime() + Math.floor(Math.random() * 1000);
            $this.attr('id', id);
          }

          Drupal.ajax[id] = new Drupal.ajax(id, this, {
            // 'nojs' to 'ajax' replacement in path performed by Drupal.ajax().
            url: $this.attr('href'),
            event: 'load.use-ajax-confirm'
          });

          $this.trigger('load.use-ajax-confirm');
        }

        return false;
      });
    }
  };
}(jQuery));

```

# Answer
> 0 votes
If you check Drupal "ajax.js" file, link process is a special case.

Comment on "Drupal.ajax.prototype.beforeSerialize" says that function will never be called if it's not a form.

In that case, "options.beforeSerialize" is used before jQuery ajax call. So if you perform your confirmation here, you can click ok or cancel, ajax call will be always triggered.

But if you overload the "options.beforeSend" function instead, maybe your confirmation box should work because if that function return false, Ajax call is cancelled (jQuery Doc : http://api.jquery.com/jQuery.ajax/).

Here is the snippet used in "ajax.js" file

```
beforeSend: function (xmlhttprequest, options) {
  ajax.ajaxing = true;
  return ajax.beforeSend(xmlhttprequest, options);
}

```

The updated version, you can try it:

```
Drupal.ajax['my-id'].beforeSend: function (xmlhttprequest, options) {
  if(confirm('Are you sure?')){
      ajax.ajaxing = true;
      return ajax.beforeSend(xmlhttprequest, options);
  }
  return false;
}

```

I didn't have the time to test this snippet, upgrades and comment are welcome :)

---
Tags: 7, ajax, navigation
---


title: Export content view to HTML

text:
# Question
Title: Export content view to HTML
As I'm not quite happy with the Simplenews module I want to use phplist instead. The newsletter should contain the teasers of the articles I want to send. Is there a way to export specific articles teasers to HTML (using a custom template), so that I don't have to copy and paste every single teaser to my newsletter?

# Answer
> 1 votes
If you want to make a View of node teasers, all you have to do is set the view format to Rendered Content, and select the teaser display mode.

From here, you can customize `node--node-type--teaser.html.twig` template to your exact specifications to satisfy phplist.

After this change, all the nodes that the View returns will be rendered in the teaser display mode using that template.

You can also create new modes under Admin \> Structure \> Display Modes if you want to create new ones for this purpose, especially if you are already using teaser display mode elsewhere on the site. You can still provide the markup and theme it with the pattern `node--node-type--display-mode.html.twig`.

If for some reason this is not enough, you may have to resort to creating a custom Views plugin to render your result rows. I think this should suffice based on what you asked, though.

---
Tags: views, theming, 8
---


# Question
Title: Form element's #required set to FALSE, but form submission still consider it as required
I am trying to theme Contact form with template file, manipulating the contact form with form API, trying to hide the subject field and make it optional for submission.

```
$form['subject']['#required'] = FALSE;
hide($form['subject']);

```

I used `dsm()` to confirm that the `#required` is successfully set to `FALSE`.

However, when I submit the form, it still ask me to fill in Subject field. (The cache has been cleared.)

These are the steps that I have followed:

* In the template.php file I added the following code

```
function mytheme_theme() {
  return array(
    'contact_site_form' => array(
      'render element' => 'form',
      'path' => drupal_get_path('theme', 'mytheme') . '/templates',
      'template' => 'contact-site-form',
    ),
 );

```
* I created the contact-site-form.tpl.php file with the following code

```
$form['subject']['#required'] = FALSE;
hide($form['subject']);
print drupal_render_children($form);

```
* I cleared the cache

# Answer
Yes, theming the form only changes its markup. If you want to change the form you have to hook\_form\_alter.

I once wondered how to add required styles to elements that weren't actually required. Your question just gave me the answer.
> 6 votes

# Answer
I see that its an old post but still... try to use this via `hook_alter()`

```
$form['subject'][und]['#required'] = FALSE;

```

well worked in my case:

```
$form['field_client']['und']['#required'] = FALSE;
hide($form['field_client']);

```

interesting that for 'title' field its just:

```
$form['title']['#required'] = FALSE;

```
> 4 votes

# Answer
I don't know why your form field is still failing on validation, but try `$form['subject']['#access'] = FALSE;` to achieve what you want.
> 2 votes

# Answer
In drupal 8

`$form['field_first_name']['#access'] = FALSE;
$form['field_last_name']['#access'] = FALSE;
$form['field_gender']['#access'] = FALSE;`

works fine for me.
> 2 votes

---
Tags: forms
---


# Question
Title: Can we fire database query while flagging the node?
Can we fire database query on flagging the flag(**pick\_this\_bid**) I want to update the database table column in which boolen value is saved true and false.

By default it shows **true** status in database but when someone flagged(**pick\_this\_bid**) the status should change to false in the database.

I want something like this on clicking flag how to achieve this?

```
if(status==1)
 $status=0;
 else
  $status=1;

UPDATE  `my_table`.`node` SET  `status` =  0 WHERE  ` node`.`nid`    =1059;

```

# Answer
According to The Flag 3.x API (PHP)

> ```
> mymodule_flag_flag($flag, $content_id, $account, $flagging) {
>   // Do something in response to the flagging.
> }
>
> mymodule_flag_unflag($flag, $content_id, $account, $flagging) {
>   // Do something in response to the unflagging.
> }
>
> ```

In your case

```
mymodule_flag_flag($flag, $content_id, $account, $flagging) {

  if ($flag->name == 'pick_this_bid'){

     $nid = $content_id;
     db_update('my_table')
       ->expression('status', '0')
       ->condition('nid', $nid)
       ->execute();
  }

}

```
> 2 votes

---
Tags: 7
---


# Question
Title: Disable user language setting in user-edit page
I want to unset this specific part of the settings form in template php. I found some code example for Drupal 6, but can't figure out how to do it in Drupal 7.

I tried this without result:

```
if ($form_id == 'user_profile_form') {
  unset($form['language']);
}

```

(There is a module "user tweaks" but I want it to do it in the preprocess)

# Answer
I created both the mentioned projects and I have maintained them for a while. (I stopped maintaining Drupal 6 and 7 modules.)

The code used in the Disable user language module is not correct: `unset()` should never be used for form elements, as this would cause problems to modules that try to access the form element.

The correct code is the following one. It would preferable if the code would be executed after other modules execute their own code.

```
/**
 * Implements hook_form_alter().
 */
function mytheme_form_alter(&$form, $form_state, $form_id) {
  // The language selector is only displayed if there is more than one language.
  if (drupal_multilingual()) {
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      if (count(element_children($form['locale'])) > 1) {
        $form['locale']['language']['#access'] = FALSE;
      }
      else {
        $form['locale']['#access'] = FALSE;
      }
    }
  }
}

```

In my module I also used `hook_init()` to change `$user->language` to a default value; differently `$user->language` would have the last value saved.

```
/**
 * Implements hook_init().
 */
function dul_init() {
  if (!user_access('change own user language')) {
    global $user;

    $user->language = language_default('language');
  }
}

```

Clearly, the Disable user language module has its own permission, which allows to select which users have the permission to select their own language, but that part is not strictly necessary.

I used `hook_init()` because the documentation for `hook_user_load()` has the following warning:

> Due to the static cache in `user_load_multiple()` you should not use this hook to modify the user properties returned by the {users} table itself since this may result in unreliable results when loading from cache.

The code is also changing *on the fly* a property for the currently logged-in user, without making any changes in the database. `hook_user_load()` would not serve this purpose, since it is invoked any time a module calls `user_load()`.
> 14 votes

# Answer
I took a look at the "Disable user language" module.

This part of the code is indeed enough for me:

```
function template_form_user_profile_form_alter(&$form, $form_state) {
   unset($form['locale']);
}

```
> 5 votes

# Answer
For those who, for whatever reason don't/can't do PHP, a simple way to hide the language settings block in Drupal 7 is to add the following CSS to the user-edit page:

```
#user-profile-form fieldset#edit-locale
{
    display: none;
}

```

Having tried several methods of adding CSS to pages, my preferred method is the CSS Injector module (https://www.drupal.org/project/css\_injector). I find it easy to use, effective, and a convenient place to maintain all of my injected CSS.

P.S. I realize this is an old post, but I read it looking for an answer, so I figure others will too.
> 1 votes

# Answer
In drupal 8 we can disable the language setting using the following code:

```
function digicare_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === "user_register_form" || $form_id === "user_profile_form"){
    $form['language']['#access'] = FALSE;
  }
}

```
> 0 votes

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


# Question
Title: Does hitting 'recreate' recreate the feature from the site's elements, or vice versa?
Does hitting 'recreate' recreate the feature from the site's elements, or vice versa?

I tried hard looking to this in the documentation, but I couldn't find a clear explanation.

# Answer
> 0 votes
When you recreate a feature via the UI (`admin/config/development/features/`) or even by using drush (`drush fua -y` or `drush fu feature_name -y`) all your configuration changes regarding nodes, modules, blocks, themes etc are being extracted to the corresponding feature directory. Configurations from different modules are saved to different files. In order to apply your changes to another Drupal instance you have to do it the other way around `drush fra -y` or `drush fr feature_name -y` and your changes will be stored to the database.

In case that you want to revert some settings back to their initial state, before you move them to another Drupal instance you can do the following: edit and save the appropriate file that you want to revert and then use drush to apply the changes from your files to the database. Thus you'll have your site back to its former state.

---
Tags: 7, features
---


# Question
Title: What's difference between "attributes", "title_attributes", and "content_attributes"?
Is there any difference between writing CSS classes directly to Html tags and using the `Attribute` class?

Is there any difference between `attributes`, `title_attributes`, and `content_attributes`? What is the usage of each of them?

I read Using attributes in templates, but it doesn't explain that clearly.

# Answer
> 5 votes
This depends on the template you use. If you use for example the node template

*node.html.twig*

```
<article{{ attributes }}>

  {{ title_prefix }}
  {% if not page %}
    <h2{{ title_attributes }}>
      <a href="{{ url }}" rel="bookmark">{{ label }}</a>
    </h2>
  {% endif %}
  {{ title_suffix }}

  {% if display_submitted %}
    <footer>
      {{ author_picture }}
      <div{{ author_attributes }}>
        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}
      </div>
    </footer>
  {% endif %}

  <div{{ content_attributes }}>
    {{ content }}
  </div>

</article>

```

You have four attributes variables

1. attributes
2. title\_attributes
3. author\_attributes
4. content\_attributes

The difference between them is that they have different targets in the html markup of the template. The main `attributes` variable in a node is for the `<article>` tag, in a form for the `<form>` tag or in other templates often a simple wrapper `<div>`. If a template defines additional attributes variables they are for that specific part of the template, in a node for the title, author and content.

Always add attributes to the existing variable like explained in the linked documentation. Never replace it with your own attributes, because a lot of code depends on that the template is actually using the attributes variables.

---
Tags: theming, 8
---


title: Adding html attributes for block

text:
# Question
Title: Adding html attributes for block
I want to add HTML attributes for my block by using `hook_block_view_alter`. Any suggestions/code snippets for this?

# Answer
> 2 votes
If you need for D7, Block Attributes module or if you just need class Block Class

# Answer
> 1 votes
Instead use Markup module. it easily integrates with the form. I am guessing u use D7...

> This module adds the ability for site admins to add "Markup" widgets to the form. These essentially let designers of cck content-types insert additional markup into the node/edit form to display to content-authors. This is the equivalent of adding additional elements to $form of the type '#markup'.
>
> The module does not add anything to the $node object for the content being created, and utilizes form\_alter to remove unnecessary fields from the '\_content\_admin\_field' form when this widget is being created.

---
Tags: 7, blocks
---


# Question
Title: Multiple Sticky Items within using 2 separate views
I have 10 nodes and 2 views, one view named **highlighted nodes**, the other - **other nodes**

I created the concept that if a user sets one of their nodes to appear "sticky at the top of lists" then it would appear in the **highlighted nodes** view.

My second view outputs the rest of the nodes with an offset of 1 i.e. skipping the first node that I assumed "there will only be one" node that was set to sticky at the top of lists

My question is, how do I cater if two nodes are set to "sticky at the top of lists". Could you offer a solution?

Thanks in advance

# Answer
> 3 votes
You have to add a filter, for the view **highlighted nodes**:

```
Content: Sticky at top of lists (= Yes)

```

and for the view **other nodes**:

```
Content: Sticky at top of lists (= No)

```

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


title: Get the real path of a file

text:
# Question
Title: Get the real path of a file
I am creating an Excel reading module in Drupal 8. I want to get the real path of a file for reading it from a path like public://2016-03/Places.xls.

What function should I call for getting the real path of a file?

# Answer
> 33 votes
Finally I got the solution by digging Drupal code.
We can get the real path or absolute path by using the *file\_system* service.

```
$absolute_path = \Drupal::service('file_system')->realpath('public://2016-03/Places_2.xlsx');

```

# Answer
> 19 votes
@Nisam answer was right but now it's deprecated: function drupal\_realpath

> Deprecated
>
> in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::realpath().

So you should use FileSystem::realpath. In Drupal 9 is the way to go because `drupal_realpath` has been removed.

Example:

```
$file = File::load($file_id);
$uri = $file->getFileUri();
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager')->getViaUri($uri);
$file_path = $stream_wrapper_manager->realpath();

```

---
Tags: 8, files
---


# Question
Title: How to filter articles that are in front page with taxonomy
i have made quick moqup of the site to explain it better :

At this moment i made site in drupal 8 that has some articles in it and thous articles are shown in front page (landing Page).

I have made new taxonomy -\> vocabulary -\> and Add 4 term as shown in picture.

I have created new region and placed it in the front page and from views i call all articles that i have...

My problem is that, how to filter thous articles accordingly to the taxonomy and if there is possible not to refresh page (if Can't than there is no problem)...

Thanks in advance

# Answer
> 0 votes
You could just create a views filter using the taxonomy field of your article and expose it.

If you don't want the page to refresh then turn on "Use Ajax":

I think that should do it.

---
Tags: theming, 8, taxonomy-terms, views
---


title: Map does not show up

text:
# Question
Title: Map does not show up
I am creating a new custom block; when I put HTML into the body and select *Full HTML* as text format, it gives me only the source code back. What might be the problem? This is a full HTML link I get from http://maps-website.com/.

```
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&key= AIzaSyADwz5L6rGV82W_Iom2uMxbyP_mR2ZPEVw '></script><div style='overflow:hidden;height:425px;width:1920px;'><div id='gmap_canvas' style='height:425px;width:1920px;'></div><style>#gmap_canvas img{max-width:none!important;background:none!important}</style></div> <a href='https://embedmaps.net'>embed a google map</a> <script type='text/javascript' src='https://embedmaps.com/google-maps-authorization/script.js?id=ac49ccff700b1b72264816987089dabdd343ea85'></script><script type='text/javascript'>function init_map(){var myOptions = {zoom:12,center:new google.maps.LatLng(55.68811213574507,12.744411111718822),mapTypeId: google.maps.MapTypeId.ROADMAP};map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);marker = new google.maps.Marker({map: map,position: new google.maps.LatLng(55.68811213574507,12.744411111718822)});infowindow = new google.maps.InfoWindow({content:'<strong>Vento Maritime</strong><br>Toldbodgade 35<br> Copenhagen<br>'});google.maps.event.addListener(marker, 'click', function(){infowindow.open(map,marker);});infowindow.open(map,marker);}google.maps.event.addDomListener(window, 'load', init_map);</script>

```

EDIT: While looking at developer's tools console, I noticed there is 403 forbidden error.

# Answer
> 0 votes
Before paste the code you need to click on "Source" option.

See the screen shot

# Answer
> 0 votes
use Markup module which helps with custom html maps.. if it doesnt work ping me up... I will provide you the code...See the image below for limitations...

---
Tags: 8, blocks, google-maps
---


# Question
Title: Disable translation of watchdog messages
i have problem with drupal. I'm using the watchdog function to save some log messages, but when i go to read them in the admin panel (admin/reports/dblog) they get detected by the T function and so i have a lot of unnecessary log entries inside the translate content page. Is there a way to disable the detection for that page? Thanks

# Answer
> 0 votes
Yes. The watchdog report page is driven by `dblog_overview()` which utilizes the theme function `theme_dblog_message()` to render the message columns.

If you override the function, you can alter the arguments for `t()` so that `$options = array('langcode' => 'en')` which will make `t()` ignore it for translation.

For example, if you defined a `mytheme_dblog_message()` within your theme's **template.php**:

```
function mytheme_dblog_message($variables) {
  $output = '';
  $event = $variables['event'];
  // Check for required properties.
  if (isset($event->message) && isset($event->variables)) {
    // Messages without variables or user specified text.
    if ($event->variables === 'N;') {
      $output = $event->message;
    }
    // Message to translate with injected variables.
    else {
      // Add langcode = 'en' to prevent translation
      $output = t($event->message, unserialize($event->variables), array('langcode' => 'en'));

    }
    if ($variables['link'] && isset($event->wid)) {
      // Truncate message to 56 chars.
      $output = truncate_utf8(filter_xss($output, array()), 56, TRUE, TRUE);
      $output = l($output, 'admin/reports/event/' . $event->wid, array('html' => TRUE));
    }
  }
  return $output;
}

```

# Answer
> 1 votes
I made it like this:

```
function MYADMINTHEME_dblog_message($variables) {
  $output = '';
  $event = $variables['event'];
  // Check for required properties.
  if (isset($event->message) && isset($event->variables)) {
    // Messages without variables or user specified text.
    if ($event->variables === 'N;') {
      $output = $event->message;
    }
    // Message to translate with injected variables.
    else {
      $output = format_string($event->message, unserialize($event->variables));
    }
    if ($variables['link'] && isset($event->wid)) {
      // Truncate message to 56 chars.
      $output = truncate_utf8(filter_xss($output, array()), 56, TRUE, TRUE);
      $output = l($output, 'admin/reports/event/' . $event->wid, array('html' => TRUE));
    }
  }
  return $output;
}

```

---
Tags: i18n-l10n, log-messages
---