# Question
Title: Creating Nodes Programmatically but cannot edit fields using Drupal once created
I have a collection of nodes that are created programmatically after having created the content type using Drupal. This is the creation code:

```
    $node = new stdClass();
    $node->title = $vals->title;
    $node->type = "event_type";
    node_object_prepare($node);
    $node->status                       = 1;
    $node->promote                      = 0;
    $node->comment                      = 0;
    // title
    $node->title = $vals->title;
    // body
    $node->body[$node->language][0]['value']   = $vals->body;
    $node->body[$node->language][0]['summary'] = text_summary($vals->body);
    $node->body[$node->language][0]['format']  = 'filtered_html';
    // intro text
    $node->field_event_type_intro = $vals->field_event_type_intro;
    // teaser
    $node->teaser = $vals->teaser;
    // data
    $node->data = $vals->data;
    // nodewords
    $node->nodewords = $vals->nodewords;

    $node = node_submit($node); // Prepare node for saving

    node_save($node);

```

This seems to be working but when I then click on one of these nodes to edit it it only shows the title in the edit screen. The body and intro are missing.

What am I doing wrong?

# Answer
In your code you have:

```
$node->field_event_type_intro = $vals->field_event_type_intro;

```

But if you want to add values to your fields you can use this:

* if is a text

`$node->field_event_type_intro[LANGUAGE_NONE][0]['value'] = field_event_type_intro;`
* if is a taxonomy

`$node->field_event_type_intro[LANGUAGE_NONE][0]['tid'] = field_event_type_intro;`
* if is a field reference

`$node->field_event_type_intro[LANGUAGE_NONE][0]['target_id'] = field_event_type_intro;`
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Conditional fields for the field type 'managed_file' is not working in Drupal 8
I have two radio buttons

* Enter The Text
* Upload a Text File

If user select the 1st option, a field of type **'textfield'** will appear & if they select the 2nd option, a field of type **'managed\_file'** will appear.
But this code with working fine for **textfield** but not working for **managed\_file**
Now, how to implement conditional fields in Drupal 8 ?

This is my D8 code.

```
    $form['field_type'] = array(
    '#type'    => 'radios',
    '#options' => array_combine( array(t('Enter The Text'), t('Upload a Text File'))
                                 array(t('Enter The Text'), t('Upload a Text File'))
                                ),
    '#title'   => t('Choose entry type.')
  );

  $form['imgurl'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Enter the text'),
    '#states'        => array(
      'visible'      => array(
        ':input[name="field_type"]' => array('value' => t('Enter The Text')),
      ),
    ),
  );

  $form['file'] = array(
    '#title'              => t('Choose Text File'),
    '#type'               => 'managed_file',
    '#progress_indicator' => 'throbber',
    '#progress_message'   => NULL,
    '#upload_location'    => 'public://files/',
    '#states'             => array(
      'visible'           => array(
        ':input[name="field_type"]' => array('value' => t('Upload a Text File')),
      ),
    ),
  );

```

# Answer
> 1 votes
I don't know, if this as anything to do with managed files, but I think `#options` should look like this:

```
'#options' => array(
  'text' => t('Enter The Text'),
  'upload' => t('Upload a Text File'),
),

```

and in `#states` the options key, not the translatable value:

```
'#states' => array(
  'visible' => array(
    ':input[name="field_type"]' => array('value' => 'text'),
  ),
),

```

If it has something to do with managed\_file, then this old issue is back:

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

You can check this by changing temporarily `managed_file` to `file`.

---
Tags: 8, forms, files
---


title: Migrate WordPress blog to Drupal

text:
# Question
Title: Migrate WordPress blog to Drupal
I'm migrating two blogs from WordPress to Drupal 7. How would one handle migrating user subscriptions from the WordPress blogs? I've already used the Migrate module and it looks like that only handles content.

# Answer
> 1 votes
You may try using WordPress Migrate which supports migrating WordPress blog exports (WXR format) into Drupal using Migrate module. Check also Migrate Extras which provides additional support for contrib modules.

For any other extra functionality which is not covered, you've to extend it by writing your own custom class. Check Migrate Example for example of migration data.

See also: What is the most reliable way to migrate a Wordpress site into Drupal?

---
Tags: migrations
---


title: New API version for every release?

text:
# Question
Title: New API version for every release?
Since my company still focuses on D7, I haven't yet had time nor need to use Drupal 8. I am planing to step into it soon, so I browsed around to read up about it. While clicking through current API pages, I figured that there is a new link for every 8.x release.

Since Drupal 7 ended up with over 40 Releases, do we have to expect the same amount on API versions for Drupal 8? Shouldn't it be one link for all 8.x releases like it was on Drupal 6 and Drupal 7?

# Answer
> 4 votes
Drupal 8 has a new versioning system, with the following format:

Major.minor.bugfix

Minor versions are expected every 6 months (8.1.0 was recently released), and will contain backwards compatible enhancements and new features, but will remain compatible with code written for earlier releases of the same major version.

So Drupal 8.1.x contains new features and API enhancements, but remains compatible with modules developed for 8.0.x.

This will allow Drupal to be more agile in future, and new features won't be limited to major releases, but compatibility with modules should be maintained.

---
Tags: 8, community-official-site
---


# Question
Title: How to send an email to a specific user on new account creation using Rules?
I have an alumni association portal. When a new user creates profile on the portal, that account stays blocked until a specific user from that batch/department approves it.

I am trying to make use of Rules, but not able to.

# Answer
> 0 votes
You can do setting "admin/config/people/accounts" to sent notification email on account activation.

# Answer
> 0 votes
Here is a Rule which you can import in your own environment (provided you have the Rules UI enabled, a sub-module of Rules):

```
{"rules_send_mail_about_new_account" : {
    "LABEL" : "Send mail about new account",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "DO" : [
      { "mail" : {
          "to" : "someone@example.com",
          "subject" : "New account created",
          "message" : "A new account got created ..."
        }
      }
    ]
  }
}

```

Adapt the eMail content to fit your needs, eg replace the `someone@example.com` by the appropriate eMail id. You may also want to use any of the available tokens to include it in the subject of message of the eMail.

To refine the above rule, so that you can have a specific user for each department (as in your question), you can use the "Conditional Rules module. Provided you have some user profile field that indicates which department this user relates to (and which you can check via a Rules Condition). If you then create 1 such (similar) rule you'd done, though you might end up with a lot of rules (1 for each department). Soo you may want to group them together using the Rules Conditional module.

For an example using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

# Answer
> 0 votes
Go to admin/config/people/accounts

Under **Registration and cancellation** section see **Who can register accounts?**

Click on the **Visitors, but administrator approval is required** and save

---
Tags: users, rules, emails
---


title: Rendering addressfield

text:
# Question
Title: Rendering addressfield
In my Drupal 7 commerce website, I have my checkout page which will add my billing and shipping profiles. I need to just display my shipping address and billing address, instead of input fields. (Data fed from an ERP backend.)

So I've hidden al the input fields. Now I want to render the addresfield value and add it to my form just for display. But I seem to be unable to do so.

I have the following code in my form alter:

```
  $handlers = array('address' => 'address');
  $context = array('mode' => 'render');
  $address_render_array = addressfield_generate($form['customer_profile_shipping']['customer_profile']['#value']->commerce_customer_address,
                            $handlers, $context);
  dpm($address_render_array, 'render arr');
  dpm(drupal_render($address_render_array), 'rendered');

```

However drupal\_render() returns an empty string and I do not understand why. I've tried to X-debug, and I saw strangely enough that #access vars where FALSE, but I'm not finding out why.

After which I want to display it in my form

Something like

```
$form['my-address'] = array('#markup' => $renderedaddress);

```

# Answer
> 1 votes
I used

```
  $output = field_view_field('commerce_customer_profile', $form['customer_profile_shipping']['customer_profile']['#value'], 'commerce_customer_address');
  $form['customer_profile_shipping']['rendered_address'] = array(
    '#prefix' => '<div class="checkout-address">',
    '#markup' => render($output),
    '#suffix' => '</div>'
  );

```

---
Tags: 7, commerce, entities
---


title: domain with og access issue

text:
# Question
Title: domain with og access issue
My site uses the Domain and OG modules.

I created the following content types: Group and Group Post. I added OG visible field on Group, and OG content visible field on Group Post. Then, I created a group node, set the visibility as private. I created a group post node, and set the visibility as private.

I log out, and verified that anonymous users can see both.

I tried to build a new site with Drupal, and OG. When I follow the above steps, the result is right: Anonymous users can't see the two nodes.

I googled the issue, and found Visibility Access issue and Domain Access.

It seemed that the Domain and OG modules can't work together.

Does anyone have any solution?

# Answer
https://drupal.org/project/domain\_access\_bridge

This module creates a working interplay between the Domain Access suite, one {access control} module (e.g. Organic Groups, Content Access, Taxonomy Access) and eventually the Workflow module.
> 1 votes

# Answer
I ran into this too. I ended up building a module that provides exactly this functionality, to restrict groups by domain. I also identified the need for an easy way to provide

* custom styling (CSS)
* behaviors (JS)
* and templates (template suggestions) per domain.

There are instructions as well as youtube video walkthroughs.

https://github.com/ejanus/og\_domain\_access
> 0 votes

---
Tags: organic-groups, domain-access
---


# Question
Title: How to delete a taxonomy term with a broken URL
I was trying to change the URL pointed to by a taxonomy term so that clicking on it would take the user to a map. However, after changing the URL I am no longer able to go into the term to edit the value. How can I switch the URL back, or delete the term altogether when I can't access it's edit screen?

# Answer
> 1 votes
To solve this I was able to open up the database and view the url\_alias table.

From there I simply changed the url back to the automatically generated url that I overwrote.

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


# Question
Title: How can you alter the display of Flag confirmation dialog messages?
One of the options for Flags is to have the flag automatically accept when the user clicks the link, or you can have it send the user to a confirmation dialog box where they have to click another button to confirm.

The default text for this dialog message is "Flag confirm", with a button to confirm and then a link for "Cancel".

"Flag confirm" is pretty obtuse, is there any way to alter the display of this dialog box? Thanks!

# Answer
> 1 votes
I figured this out.

When you create a new Flag, at the very bottom of the Flag set up screen is the option to choose if a dialog confirmation box is required for selecting your flag.

If you choose yes, an additional option box becomes available below this were you can set the message to be displayed when a user is either Flagging or Unflagging content with this dialog box.

If you don't enter any values (text string) in these fields, it seems the default text input by the system is "Flag confirm".

# Answer
> 0 votes
In Drupal 8, you can also alter this with hook\_preprocess\_flag function in your custom module:

```
 function mymodule_preprocess_flag(&$variables) {
   if (strpos($variables['attributes']['id'], 'flag-interest') === 0) {
     $variables['title'] = t('hello world');
   }
 }

```

You can use regex to grab the entity id, and then alter the data using information from the entity:

```
function mymodule_preprocess_flag(&$variables) {
   // Change text of button for "interest" flag to taxonomy term label.
   if (preg_match('/flag-interest-id-(\d+)/', $variables['attributes']['id'], $matches)) {
     $tid = $matches[1];
     $entity = \Drupal::entityManager()->getStorage('taxonomy_term')->load($tid);
     $variables['title'] = $entity->label();
   }
 }

```

---
Tags: flags
---


title: Limit caching for a specific page

text:
# Question
Title: Limit caching for a specific page
I'm working on a module, which includes a page that displays a select from a database table. The page content is getting cached for long periods, so is out of date for users.

What's the simplest way to set the cache timeout for this page to a shorter time (or even set that page to never cache)?

(As an aside, I intend to turn this table into an entity and integrate with Views later on, but I need an interim fix).

# Answer
> 7 votes
In case you know exactly when something changes (it is your own code doing it), you can also use a cache tag.

`'tags' => ['my-tag']` within `#cache` and then when it changes, you invalidate it with `\Drupal\Core\Cache\Cache::invalidateTags(['my-tag'])`.

The advantage is that your data is cached as long as possible and also immediately updated when it changes.

If you have constant changes, and that tag would actually result in shorter cache times, then setting a max-age might be more efficient, but that's usually not the case.

# Answer
> 6 votes
```
public function myPageReponse() {
  return [
    'foo' => [
      '#theme' => 'bar',
      '#cache' => [
        'max-age' => 0 // to completely disable cache for this content
      ]
    ]
  ];
}

```

**or** in route definition:

```
my.page:
  ...
  options:
    no_cache: TRUE

```

---
Tags: 8, caching
---


# Question
Title: Is there a way to add custom classes/wrappers to page nodes, similar to pages created with Views?
I'm working on a website where the designer came up with 5 theme colours which I need to associate with specific pages. The theme has 2 regions which need to be affected by the theme colour: sidebar and content. I was hoping to add a field to the Basic Page content type linked to taxonomy vocabulary where the terms would be the colours so I could pick the theme while creating the page. I would need to add a class with the term somewhere height enough to affect all other fields of Page content type. This would be something like row classes in Views where I can use Replacement patterns to call on fields from this node.

The most difficult option would be to be able to affect the content and the sidebar (the object with that class="term/colour" would have to wrap both of the regions) but if anybody knows how to add it to only the content region, that would be great too.

At the moment, I put all the theme rules into the CSS based on node classed in the body tag, but I'm not particularly proud of this solution.

It might be worth adding what themes I use. For the desktop site, I used Omega 4 and for the mobile site, it's Bootstrap3. I'm in the middle of transitioning to Bootstrap.

Any help would be greatly appreciated.

# Answer
(spaghetti code alert!)
It's not the best and perfect way, but you can take advantage of TEMPLACE\_preprocess\_html hook to add a class to body tag.

I used Bootstrap sub-theme. Snippet at follow it's quite simple, before process the page I check if it's a News content type, if so i add a custom class at body tags. Field\_school it's a term reference.

```
file: template.php
/**
  * Implements TEMPLATE_preprocess_html().
  */
function TEMPLATE_preprocess_html(&$variables) {
  $node = menu_get_object();

    // News content type
  if ($node && $node->nid && $node->type === 'news') {
    $schools = $node->field_school['und'];
    foreach ($schools as $school) {
        $variables['body_attributes_array']['class'][] = strtolower('school-' . $school['taxonomy_term']->name);
    }
  }
}

```

This is the link where I got this info: link

I hope to have been helpful.
Nervaccio
> 0 votes

---
Tags: 7, theming
---


title: how do I export permissions?

text:
# Question
Title: how do I export permissions?
I have changed a bunch of permission for certain roles. How do I export them? There doesn't seem to be any yaml file created when I do `drush config-export`.

# Answer
Permissions are stored per user role in roles yaml files.

You'll find the permissions for 'Authenticated User', for example, in user.role.authenticated.yml and for 'Administrator' in user.role.administrator.yml
> 9 votes

---
Tags: 8
---


# Question
Title: Placing content in different regions using a controller
I've defined a route to a custom controller, which returns a render array to define its content. By default, this content gets rendered entirely inside the main content region of the page: what I want is to have different parts of it rendered to different regions.

I've tried specifying the region (e.g. `'#region' => 'content_intro'`) in the relevant sub-arrays for different elements, but they are still output to my main content region.

I've also then tried adding the following to the base definition of the returned render array:

```
$content = array(
  '#type' => 'page',
);

```

This does then allow me to successfully specify the region for placing individual elements. However, other standard elements placed in page regions - specifically, a navigation menu block - are then not output.

How would I best go about having my controller add its content to regions, while still retaining elements placed by other systems?

# Answer
> 1 votes
The normal way to do this is to provide the main content in a controller and the additional content in block plugins.

If you don't want to use blocks and the block layout for this task (what you really should do!), and want to solve this in code, you can use a preprocess hook to add content your module provides in a function (procedural or static, not a controller) to a region.

---
Tags: 8
---


title: Dynamically update views field labels

text:
# Question
Title: Dynamically update views field labels
I have been searching for a while, but cannot find an answer to this. How can I get access to the field name in a view (the label used in the content type)?

I am trying to create an anchor navigation through a view that only displays a link to a field if it has content. I have a custom content type with a number of long text fields and a view, and I would like to rewrite the content of the field with its field label but I cannot figure out how to access the field label. I would like to do it programatically in case the user asks to change the name of a field.

# Answer
> 1 votes
In Drupal 7 the `_field_info_field_cache()` function retrieves the `FieldInfo` which gives you access to various field data.

```
function get_field_label($entity, $bundle, $field) {
  $field_info = _field_info_field_cache();
  $fields = $field_info->getBundleInstances($entity, $bundle);
  return isset($fields[$field]['label']) ? $fields[$field]['label'] : FALSE;
}

//Retrieve the tags label from an article node in a D7 Standard install
get_field_label ('node','article','field_tags');

```

---
Tags: views, entities
---


title: Reload Ajax from the js code

text:
# Question
Title: Reload Ajax from the js code
I am having trouble reloading a page through Ajax from custom JS. There is a form which will change with your choices and this changes are made by Ajax.

How I can change the select list "Leistung" from the code so the price would be updated by Ajax?

As you all know I can't simply write $("select").click(); it doesn't work. Also I tried .trigger() and .mousedown(), actually .mousedown() would work if I use it for the submit button but I wanna change select list value and nothing works there.

What I think is I have two options: I could simulate a REAL click on the select list (which I know I can't), and the other way is to somehow tell the Ajax to reload after changing the select list value.

**To be more clear:** That select list is the target that I wanna change. I mean if I click on the third row of the table, that click function should change the value of the select list and here is the problem! the Ajax won't reload the price!

# Answer
> 0 votes
The event you're looking to trigger is the `onchange` event. JQuery's val() does not trigger onchange automatically. You can either call `change()` or trigger the change event

`$('selector').trigger("change");`.

See Also: https://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery

---
Tags: forms, commerce, javascript, ajax
---


# Question
Title: Should I call a function to query the database in a custom content type template?
I am calling the following function inside a template for a custom content type, but my senior developer suggested that calling a function inside a template file is not Drupal standard.

```
function some_function($AA_tid = 0) {
  $dis_pt = db_select('some_tble', 'v')
    ->fields('v', array('title'))
    ->condition('some_fld', $AA_tid)
    ->distinct();
  $dis_pt->join('another_tble', 'ss', 'v.title = ss.type');
  $dis_pt->fields('ss', array('name'));
  $result = $dis_pt->execute()->fetchAll();
  return $result;
}

```

Should I call the function which will query the database from a content type template? Generally speaking, is it better to avoid such code in a template file?

**Edit: function call is present inside the template & its definition is available in some module file.**

# Answer
I believe that depends on what you're doing with your query. According to this Drupal.org community doc you should "refrain from having complex logic in" .tpl files and "for all the conditional logic and data processing of the output, there is the template.php file". IOW template files are for theming/output manipulation while other functions or logic should go into your custom module. So if your query is part of a theming process, yes it should be in your template file. Otherwise in your custom module.

AFAIK other developers will not be looking for a non-theming function in a template, which is why I think the senior dev suggested that.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Can a theme leverage block config Yaml files when installed for the first time?
In my Drupal 8 contrib theme, when the theme is first enabled, a number of system blocks are dumped into the first region that's in my theme's `info.yml` file. From a UX perspective, this is not really desirable as it makes the theme look ungainly and off balance. The two core blocks in question are "*Powered by Drupal*" and the "*Footer Menu*" blocks.

I've played around with placing these two blocks where I want them (in my theme's case, the `footer_first` and `footer_second` regions), exporting the config for those and then placing the Yaml files in `/mytheme/config/install`. I then try a fresh Drupal 8 Beta 1 install on my local and activate the theme once again but the config files seem to have no effect. The two system blocks in question are yet again placed in the first region that's in my theme which is the top area.

I can fool Drupal by placing the footer regions first in my theme's `info.yml` file but this presents other issues - for example, when users view the block admin page and see those regions come up first when they are actually last.

My guess is, there is no good solution for this but I thought I would ask in case anyone had some ideas.

# Answer
It turns out tim-plunkett was correct in his comment above. I used the config export function at `/config/development/configuration/full/export` to export all the block settings for my theme.

I then took all the generated YAML files and placed them in a new folder within my theme at `/config/install`. I then uninstalled the theme and then reinstalled it as the default. Voila, all my blocks, i.e., menu, help etc... were in their designated regions according to what had been exported in the YAML files.

Some examples of the file names are:

```
block.block.gratis_help.yml
block.block.gratis_main_menu.yml
block.block.gratis_branding.yml

```
> 4 votes

# Answer
I had the same issue, but for an admin theme. To copy blocks from the existing admin theme into a new one:

```
# temporarily set existing_admin to be default theme
drush config-set system.theme default existing_admin -y

# will copy blocks from default theme
drush en -y new_admin_theme

# return to previous default theme
drush config-set system.theme default previous_default_theme -y

# enable new admin theme with copied blocks
drush config-set system.theme admin new_admin_theme -y

```
> 2 votes

# Answer
Had the same issue:

* Place custom blocks in theme using the UI.
* Export config.
* When it came time to import my config in a new environment custom blocks not appearing in proper region despite .yml files for individual blocks being present in my default config directory...
* As described above solution was to disable and uninstall custom theme and then re-enable.

Here are the steps (Where `vcs` is our directory for default config defined in `settings.php` and `my_custom_theme` is our theme name).

After running `drush si`, lets import our config.

`drush cim vcs --partial -y`

At this point although our config has been imported our custom blocks are not appearing in the regions as set in the config .yml files.

Enable a core theme so we are free to uninstall our custom theme.
`drush cset system.theme default seven`
**Important** Rebuild the cache now.
`drush cr`
Uninstall our custom theme.
`drush pm-uninstall my_custom_theme -y`
Enable our custom theme.
`drush en my_custom_theme -y`
Set our Custom theme as default theme.
`drush cset system.theme default rrre_theme -y`
Import our default config.
`drush cim vcs`
Run Server.
`drush rs`

:)
> 0 votes

---
Tags: theming, 8, configuration
---


# Question
Title: Custom theme block position is not importing
Problem:

Making a custom theme with blocks placed in different regions.

* Place custom blocks in theme using the UI.
* Export config. `drush cex vcs`
* When it came time to import my config in a new environment custom blocks not appearing in proper region despite .yml files for individual blocks being present in my default config directory...

How to import configuration so that blocks from my custom theme appear in the correct region?

# Answer
> 0 votes
The solution was to disable and un-install my custom theme and then re-enable.

Here are the steps (Where `vcs` is our directory for default config defined in `settings.php` and `my_custom_theme` is our theme name).

After running drush si, lets import our config.

`drush cim vcs --partial -y`

At this point although our config has been imported our custom blocks are not appearing in the regions as set in the config .yml files.

Enable a core theme so we are free to uninstall our custom theme.

`drush cset system.theme default seven`

Rebuild the cache now.

`drush cr`

Uninstall our custom theme.

`drush pm-uninstall my_custom_theme -y`

Enable our custom theme.

`drush en my_custom_theme -y`

Set our Custom theme as default theme.

`drush cset system.theme default rrre_theme -y`

Import our default config.

`drush cim vcs`

Run Server.

`drush rs`

:)

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


# Question
Title: Do i need to worry about using deprecated functions in Drupal 8?
I'm finding Drupal 8 a pretty steep learning curve, and quite often when I do find a solution that works PhpStorm tells me that the function I'm using is deprecated.

E.g. this answer shows how to list a bundles fields, however entityManager is deprecated and will removed before Drupal 9.

How long before Drupal 9 will this be removed? Like next week, next month, next year or in several years just before D9 is released.

Do I need to worry about using deprecated functions? Is it best practice to avoid them all together?

# Answer
I don't have a reference handy, but I had the conversation about removal with one of the Drupal committers this weekend.

Right now, the committers will not remove any functions from core that are marked as deprecated.

Currently, there is no work being done on Drupal 9. When the 9.0.x branch gets forked from 8.x.y, they will start to accept patches against 9.0.x that remove deprecated functions.

However, there is work to remove *usage* of deprecated functions in core. For example, `format_date()` is marked as deprecated. This function will remain until 9.0.0 is released, and it will never actually be removed from any 8.x.y version. However, patches against 8.x.y will be accepted to replace `format_date()` in core with use of the date formatter service. And, in general, no new usages of deprecated functions are allowed in patches (there are some small exceptions for this for consistency sake, mainly in tests).

Should you use them? In general, no. Typically, a deprecated function was a placeholder from Drupal 7 while Drupal 8 was being developed that didn't get replaced (eg, `format_date()`), or left for backwards compatibility as Drupal 8 got refactored (eg, the Entity Manager service). Nearly all of the docs on deprecated functions describe what should be done instead. In PhpStorm, Command-B will take you to the function definition, and Command-\[ will take you back to where you were.
> 4 votes

---
Tags: 8
---


title: HTML tags are stripped away

text:
# Question
Title: HTML tags are stripped away
I'm new with Drupal but have to use it to develop a web form for my workplace. I have to insert a `form` in a drupal web page and I am allowed to insert it in full HTML.

However, since I must paste code directly in a little editor box, I have to cut all my CSS code and paste it in a `<style>` tag.

After hitting save, Drupal essentially removes the tag and the form looks horrible. Here is my code.

```
<style type="text/css">
            .column,.columns,.container,.u-full-width{width:100%;box-sizing:border-box}h1,h2,h3{letter-spacing:-.1rem}body,h6{line-height:1.6}.container{position:relative;max-width:960px;margin:0 auto;padding:0 20px}ol,p,ul{margin-top:0}.column,.columns{float:left}@media (min-width:400px){.container{width:85%;padding:0}}html{font-size:62.5%}body{font-size:1.5em;font-weight:400;font-family:Raleway,HelveticaNeue,"Helvetica Neue",Helvetica,Arial,sans-serif;color:#222}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:2rem;font-weight:300}h1{font-size:4rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:3rem;line-height:1.3}h4{font-size:2.4rem;line-height:1.35;letter-spacing:-.08rem}h5{font-size:1.8rem;line-height:1.5;letter-spacing:-.05rem}h6{font-size:1.5rem;letter-spacing:0}@media (min-width:550px){.container{width:80%}.column,.columns{margin-left:4%}.column:first-child,.columns:first-child{margin-left:0}.one.column,.one.columns{width:4.66666666667%}.two.columns{width:13.3333333333%}.three.columns{width:22%}.four.columns{width:30.6666666667%}.five.columns{width:39.3333333333%}.six.columns{width:48%}.seven.columns{width:56.6666666667%}.eight.columns{width:65.3333333333%}.nine.columns{width:74%}.ten.columns{width:82.6666666667%}.eleven.columns{width:91.3333333333%}.twelve.columns{width:100%;margin-left:0}.one-third.column{width:30.6666666667%}.two-thirds.column{width:65.3333333333%}.one-half.column{width:48%}.offset-by-one.column,.offset-by-one.columns{margin-left:8.66666666667%}.offset-by-two.column,.offset-by-two.columns{margin-left:17.3333333333%}.offset-by-three.column,.offset-by-three.columns{margin-left:26%}.offset-by-four.column,.offset-by-four.columns{margin-left:34.6666666667%}.offset-by-five.column,.offset-by-five.columns{margin-left:43.3333333333%}.offset-by-six.column,.offset-by-six.columns{margin-left:52%}.offset-by-seven.column,.offset-by-seven.columns{margin-left:60.6666666667%}.offset-by-eight.column,.offset-by-eight.columns{margin-left:69.3333333333%}.offset-by-nine.column,.offset-by-nine.columns{margin-left:78%}.offset-by-ten.column,.offset-by-ten.columns{margin-left:86.6666666667%}.offset-by-eleven.column,.offset-by-eleven.columns{margin-left:95.3333333333%}.offset-by-one-third.column,.offset-by-one-third.columns{margin-left:34.6666666667%}.offset-by-two-thirds.column,.offset-by-two-thirds.columns{margin-left:69.3333333333%}.offset-by-one-half.column,.offset-by-one-half.columns{margin-left:52%}h1{font-size:5rem}h2{font-size:4.2rem}h3{font-size:3.6rem}h4{font-size:3rem}h5{font-size:2.4rem}h6{font-size:1.5rem}}a{color:#5B0000}a:hover{color:#0FA0CE}.button,button,input[type=submit],input[type=reset],input[type=button]{display:inline-block;height:38px;padding:0 30px;color:#555;text-align:center;font-size:11px;font-weight:600;line-height:38px;letter-spacing:.1rem;text-transform:uppercase;text-decoration:none;white-space:nowrap;background-color:transparent;border-radius:4px;border:1px solid #bbb;cursor:pointer;box-sizing:border-box}.button:focus,.button:hover,button:focus,button:hover,input[type=submit]:focus,input[type=submit]:hover,input[type=reset]:focus,input[type=reset]:hover,input[type=button]:focus,input[type=button]:hover{color:#333;border-color:#888;outline:0}.button.button-primary,button.button-primary,input[type=submit].button-primary,input[type=reset].button-primary,input[type=button].button-primary{color:#FFF;background-color:#660000;border-color:#660000}.button.button-primary:focus,.button.button-primary:hover,button.button-primary:focus,button.button-primary:hover,input[type=submit].button-primary:focus,input[type=submit].button-primary:hover,input[type=reset].button-primary:focus,input[type=reset].button-primary:hover,input[type=button].button-primary:focus,input[type=button].button-primary:hover{color:#FFF;background-color:#5B0000;border-color:#5B0000}input[type=tel],input[type=url],input[type=password],input[type=email],input[type=number],input[type=search],input[type=text],select,textarea{height:38px;padding:6px 10px;background-color:#fff;border:1px solid #D1D1D1;border-radius:4px;box-shadow:none;box-sizing:border-box}input[type=tel],input[type=url],input[type=password],input[type=email],input[type=number],input[type=search],input[type=text],textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none}textarea{min-height:65px;padding-top:6px;padding-bottom:6px}input[type=tel]:focus,input[type=url]:focus,input[type=password]:focus,input[type=email]:focus,input[type=number]:focus,input[type=search]:focus,input[type=text]:focus,select:focus,textarea:focus{border:1px solid #660000;outline:0}label,legend{display:block;margin-bottom:.5rem;font-weight:600}fieldset{padding:0;border-width:0}input[type=checkbox],input[type=radio]{display:inline}label>.label-body{display:inline-block;margin-left:.5rem;font-weight:400}ul{list-style:circle inside}ol{list-style:decimal inside}ol,ul{padding-left:0}ol ol,ol ul,ul ol,ul ul{margin:1.5rem 0 1.5rem 3rem;font-size:90%}.button,button,li{margin-bottom:1rem}code{padding:.2rem .5rem;margin:0 .2rem;font-size:90%;white-space:nowrap;background:#F1F1F1;border:1px solid #E1E1E1;border-radius:4px}pre>code{display:block;padding:1rem 1.5rem;white-space:pre}td,th{padding:12px 15px;text-align:left;border-bottom:1px solid #E1E1E1}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}.u-max-full-width{max-width:100%;box-sizing:border-box}.u-pull-right{float:right}.u-pull-left{float:left}hr{margin-top:3rem;margin-bottom:3.5rem;border-width:0;border-top:1px solid #E1E1E1}.container:after,.row:after,.u-cf{content:"";display:table;clear:both}</style>
            <form action="" method="post">
                <div class="row">
                    <div class="eleven columns">
                        <label>Your Name</label>
                        <input class="u-full-width" name="user_name" id="user_name" placeholder="John Doe" type="text"></input>
                    </div>
                </div>
                <div class="row">
                    <div class="eleven columns">
                        <label>Your E-mail</label>
                        <input class="u-full-width" name="email" id="email" placeholder="example@mail.com" type="email"></input>
                    </div>
                </div>
                <div class="row">
                    <div class="eleven columns">
                        <label>Request Description</label>
                        <textarea class="u-full-width" name="job_description" id="job_description" placeholder="Description of your job here" style="height:200px"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="eleven columns">
                        <label>Request Support For</label>
                        <select class="u-full-width" name="purpose" id="purpose">
                            <option value="simulation">Simulation</option>
                            <option value="detector_development">Detector Development</option>
                            <option value="detector_electronics">Detector Electronics</option>
                            <option value="electronics_development">Electronics Development</option>
                            <option value="data_acquisition">Data Aquisition</option>
                        </select>
                    </div>
                    <div class="row">
                        <div class="eleven columns">
                            <input type="checkbox" name="sub_support" value="sub_support">Mechanical</input>
                            <input style="margin-left:10%;" type="checkbox" name="sub_support" value="sub_support">PCB</input>
                            <input style="margin-left:10%;"  type="checkbox" name="sub_support" value="sub_support">Firmware</input>
                            <input style="margin-left:10%;"  type="checkbox" name="sub_support" value="sub_support">DAQ Hardware</input>
                        </div>
                    </div>
                </div>
                <input class="button-primary" value="Submit" type="submit" name="submit" id="submit">
            </form>

```

Also, is there any way I can include PHP code as well? I'd be grateful if anyone could point me in the right direction.

Thanks in advance.

# Answer
> 2 votes
There are several answers to this. I am assuming that you are using Drupal 7.

1) If this is really what you want to do (not recommended), you'll need to do some work with your text filters (Configuration-\>Content Authoring-\>Text Formats). I could go into greater detail here, however..

2) You could simply use the Webform module. You will need to download it to your modules folder (probably sites/all/modules/contrib) and then enable it. Then you can construct your webform using the webform's UI editor. Finally, you would want to apply your CSS in your theme, not paste it into the editor textarea.

As for the PHP Filter, this is a module you can just turn on and then configure like the other Text Formats (the module is just called "php"). However, I would STRONGLY recommend against it! Certainly do not do this on a production site, it's a pretty big security risk. It also makes it very easy to put code someplace in your content that you later forget about, causing all kinds of headaches when you go to troubleshoot issues. Instead, create your own module. Learn how to use Drupal's function hooks instead. They are one of the reasons Drupal is such a powerful platform.

Good luck!

---
Tags: forms
---


# Question
Title: 500 error when deleting node with 300,000 comments
I have a node which has been spammed and has 300,000 comments. Whenever I try to delete it I get a 500 internal server error.

Deleting all comments via database is not an option because I need to retain a large number of legitimate comments on OTHER nodes. However, this specific node has been spammed and I wish to delete the node and all associated comments, But I can't. I have disabled commenting on the node, but how can I remove these comments? Any ideas?

# Answer
I think you *could* delete the comments via database, limiting the deletion to those attached to the involved node.

It might be a simple as this:

```
DELETE FROM comment
WHERE nid = <the involved node id>

```

To ensure avoiding any issue (or in case there is something subtle I missed) you can first execute the equivalent `SELECT` and control its results:

```
SELECT * FROM comment
WHERE nid = <the involved node id>

```

And obviously you shouldn't execute the `DELETE` query without previously getting a backup.

---

EDIT: as a non-expert, I only proposed what seemed obvious when examining the `comment` table.
But thanks to @MPD comment, I realize that there are some linked data to also consider.

Regarding fields, after looking at the tables definition I think that an additional `DELETE` query should be executed *first* (before deleting comments themselves), something like:

```
DELETE FROM field_data_comment_body
WHERE entity_type = "comment"
AND entity_id IN (
  SELECT cid
  FROM comment
  WHERE nid = <the involved node id>
)

```

If unfortunately supplemental comments had been added, a similar query should be executed also for each of them.

Regarding "The node won't be reindexed." and "Node statistics won't be updated.", I'm not expert enough to understand what is involved.
So I hope @MPD will be able to bring its own complementary information.
> 3 votes

# Answer
Likely you are running out of time or memory in your PHP setup. If you can temporarily allow PHP to have a great deal more of both you might be able to solve the problem just by changing values in php.ini and then trying again to delete the node.

To tell which is your limiting factor review the web server error log if you have access.

If you are comfortable writing a script, you could also write a simple drush script that would delete the one node using node\_delete(). PHP Cli is not time limited so if that's the limit you're fighting you will not run into a time out.
> 1 votes

# Answer
If you have drush access to your server, you can use the `drush php-script` command (or `drush scr` for short) to run a script on top of a full Drupal bootstrap. This allows you to run any Drupal functions or access information you'd customarily have available in a Drupal module on your server, without the overhead of writing an entire custom module for a one-time operation.

Using comment\_delete\_multiple() to delete comments will ensure that additional field data is removed and statistics get updated during the deletion process. This script should get the job done. **Back up your database before running!**

```
<?php

// Change this to the nid you want to clear comments from
$nid = 12345;

// Queries the database for all comment IDs associated with the nid, max 1000
$cids = db_select('comment', 'c')
  ->fields('c', array('cid'))
  ->condition('c.nid', $nid)
  ->range(0, 1000)
  ->execute()
  ->fetchCol();

if (!count($cids)) {
  drush_print("No more comments found. Aborting.");

  // Abort with an error code (so a bash script can key off that)
  exit(1);
}

// Delete the comments with comment IDs we got from the DB
comment_delete_multiple($cids);
drush_print(count($cids) . " comments deleted");

```

Upload this script to the web server and you can execute it from your local machine (with a properly configured drush alias), or the server itself, using `drush @your-server-alias scr`. Since you'll need to run it multiple times (it only deletes 1000 comments at a time to avoid timeouts or out-of-memory errors), you'll probably want to use a cron job, or a bash script with a while loop, to keep running it until all the comments are deleted. Here's a bash script that should do it:

```
#!/bin/bash

while drush @your-server-alias scr /path/to/script/on/server/so.php; do
    sleep 1
done

```

The bash script can be run on the server itself, or your local machine if you have drush configured to talk to your server from your local. If you get 500 errors or other failures while the script is running, you may need to decrease the second value on the `->range(0, 1000)` line. (You will see one error at the end when there are no comments left, by the design of the PHP script, so don't worry about that)
> 1 votes

---
Tags: 7, comments
---


# Question
Title: Display the method of payment of an order on the invoice pdf comerce billy
I installed Commerce Billy.

How can I display the payment method on my bill?

```
<?php

/**
 * @file
 * Template for invoiced orders.
 */

?>
<?php
//The code to get payment type

$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}
?>
<div class="invoice-invoiced">
  <div class="header">
    <img src="<?php print $content['invoice_logo']['#value']; ?>"/>
    <div class="invoice-header">
        <p><?php print render($content['invoice_header']); ?></p>
    </div>
  </div>

  <hr/>

  <div class="customer-billing"><?php print render($content['commerce_customer_billing']); ?></div>
  <div class="customer-shipping"><?php print render($content['commerce_customer_shipping']); ?></div>
  <h1 class="credit-memo"><?php print render($content['invoice_title']); ?></h1>
  <div class="invoice-header-date"><?php print render($content['invoice_header_date']); ?></div>
  <div class="order-id"><?php print render($content['order_id']); ?></div>

  <?php print($payment_method); // Use this PHP Code where you want to print the payment type, you can style it any way, adding div, span, whatever you want ?>

  <div class="line-items">
    <div class="line-items-view"><?php print render($content['commerce_line_items']); ?></div>
    <div class="order-total"><?php print render($content['commerce_order_total']); ?></div>
  </div>
  <div class="invoice-text"><?php print render($content['invoice_text']); ?></div>

  <div class="invoice-footer"><?php print render($content['invoice_footer']); ?></div>
</div>

```

Here are the contents of my file "commerce\_order--commerce\_order--pdf.tpl.php". Where do I put the code ?

# Answer
> 1 votes
You can use code below to get the payment method of an order by passing order id to the function. The order id on Commerce billy template file can be easily found in this variable *$content\['commerce\_customer\_billing'\]\['#object'\]-\>order\_id* and some other variables as well:

```
$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}

```

After using this function, you can print the payment method on your bill by printing *$payment\_method* variable.

---
Tags: 7, commerce
---


# Question
Title: using {{ twig variables }} inside external jquery
Developing a D8 theme, I am loading an external .js file containing some jQuery code (so it is not inside the TWIG template).

Is it possible to access and modify TWIG variables like `{{ myvariable }}` inside the external jQuery?

# Answer
> 2 votes
It's not possible to access Twig variables in jQuery directly. Instead access the content of PHP variables inside of an external jQuery code by attaching them to drupalSettings. See the documentation:

> Attaching configurable JavaScript
>
> In some cases, you may want to add JavaScript to a page that depends on some computed PHP information.
>
> In this case, create a JavaScript file, define and attach a library just like before, but also attach JavaScript settings and have that JavaScript file read those settings, via drupalSettings (the successor to Drupal 7's Drupal.settings). However, to make drupalSettings available to our JavaScript file, we have to do the same work as we had to do to make jQuery available: we have to declare a dependency on it.
>
> ```
> cuddly-slider:
>   version: 1.x
>   js:
>     js/cuddly-slider.js: {}
>   dependencies:
>     - core/jquery
>     - core/drupalSettings
>
> ```
>
> and
>
> ```
> $build['#attached']['library'][] = 'fluffiness/cuddly-slider';
> $build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';
>
> ```
>
> Where 'bar' is some calculated value.
>
> Then cuddly-slider.js will be able to access
>
> `drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').`

https://www.drupal.org/developing/api/8/assets

---
Tags: theming, 8, javascript
---


# Question
Title: How to configure the Total Subscription module?
I'm taking a look at the Total Subscription module and have done the basic installation and configuration. But it's not evident how to get it to show up on any given node/page. I've been working from its documentation at https://www.drupal.org/node/2170825.

Any other suggestions about how to configure it?

# Answer
> 1 votes
The Total Subscription module has indeed some challenges related to finding out how to get it configured as it should be. Apart from its Community documentation (which you seem to have found already), the best I have found to far is a video tutorial (without sound though ...) that takes you through various admin screens. E.g. to show you some of the blocks related to this module.

Apart from that, to understand what this module is about, I find its readme.txt a bit helpful, as well as the module's project page. Here is a quote from it:

> Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.

---
Tags: 7, notifications
---


# Question
Title: How do I enable the Views Contact Form module?
I cannot install the Views Contact Form module because it depends from the Email module, which is said to be missing, in the module page. The Email module is not a Drupal 8 core module.

How do I install that module?

# Answer
> 2 votes
The Views Contact Form module doesn't actually works for Drupal 8, since it puts its class files in \[module directory\]/lib/Drupal/views\_contact\_form (PSR0), when Drupal 8 now requires them to be in \[module directory\]/src (PSR4), inside the module directory. Looking at the code, I notice the module has not been updated to work with the official releases of Drupal 8.0, nor 8.1.

For this reason, not even removing the dependency on the *Email Field* module from the views\_contact\_form.info.yml file would work. Otherwise, I would have suggested to change the views\_contact\_form.info.yml file as follows.

```
name: Views Contact Form
description: Views Contact Form
core: 8.x
type: module
dependencies:
 - views

```

To add more details about the dependecies, the *Views Contact Form* module declares its dependency from the Email Field module, which is only for Drupal 7. In the project page of the latter module, it's clearly stated:

> The basic email field type is in core now: #1668332: Add an E-mail field type into core, making this contrib module obsolete. Specific formatters (like the contact form) can live in separate contrib modules.

It seems the *Views Contact Form* module implements one of those formatters, so it would just require the email field already present in core. Unfortunately, the module has not been updated to work with the latest releases of Drupal 8.

# Answer
> 1 votes
It looks to me like that module needs an update. The email field is a field type plugin, not a module in latest 8.1.x branch. I think the dependency could be safely removed from the module, but I have not tested myself.

---
Tags: views, 8
---


# Question
Title: How can I insert block content between page fields?
My page content type has two entity reference types that reference other content types.

* Hero
* Quotes

The hero displays at the top of the page and I want the Quotes at the bottom of the page.

In between these two pieces of content I have custom blocks and views that I wanted displayed. How can I have the Hero and the Quotes nodes below other custom content?

# Answer
### Using Template files

You can create a template file .html.twig for your content type or specific node.

Download and enable Twig tweak module:

> Twig Tweak module provides a Twig extension with some useful functions and filters that can improve developer experience.

And then on your twig template put:

```
{{ content.field_refhero }}
<dd>{{ drupal_view('view_name', 'block_1') }}</dd>
<dd>{{ drupal_block('block_id') }}</dd>
{{ content.field_refquotes }}

```

---

Alternatively, you could use the following modules

### Display Suite

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.

### Panels

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.
> 6 votes

# Answer
The content is itself a block in Drupal 8.

You should be able to achieve what you want by creating a view to display the second entity reference.

In your content type, change the display settings so the Quotes field is not visible.

Now create a new Block view. Set it to display the Quotes field, and under Advanced add a Contextual Filter for the Node ID, and select a default value of Content ID from URL.

Now you can display this block below your other blocks, and it will display the quotes for the current node.
> 2 votes

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


# Question
Title: Where is the code of a new view i've created?
i'm using drupal 7 with starter theme of zen. i've created a view on a block, now i need to customize some parts of `html / css` in order to add just media query (css part) and add a `<a>` tag with `display:none` for desktop version and `display:block` for mobile. SO i need to modify html AND css of this view. I'm searching for the php file of this view and i didn't find it.

Any help please ?

# Answer
If you click on the Theming link in the Advanced tab, you will get a list of possible template files that you can use. See here:

Next, you can click on "Display Output" to get a copy of the PHP that is powering the view. See here:

Copy that PHP into a file and save it using the naming pattern of your choice from the list beside "Display Output".

Click on "Rescan template files" to make your theme aware of the new template.

Now, any changes you make to that template - add CSS classes, etc - will automatically be picked up.

If you wish to edit HTML for the style or row, just click on the relevant "Style Output" or "Row Style Output" link instead of "Display Output".

I hope this helps you.
> 0 votes

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


# Question
Title: display html result via form builder in d8
i am building a form in d8 using form builder , what i need to display the html results along with the form .But unlike we display the result using html markup in controller, its not displaying the result however .

in **`module_name.routing.yml`**

```
module_name.findAllUsers:
  path: '/module_name/findusersgroup'
  defaults:
    _form:  '\Drupal\module_name\Form\UserLookUp'
    _title: 'Find users of a Group'
  requirements:
    _permission: 'access admin menus

```

and in **`module_name/src/Form/UserLookUp.php`**

```
<?php

namespace Drupal\module_name\Form;

use Drupal\Core\Form\FormState;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class UserLookUp extends ConfigFormBase {

  public function getFormId() {
    return 'user_lookup';
  }
/**
 * General form for switching all nodes from one user to another.
 */
  public function buildForm(array $form, FormStateInterface $form_state) {
   $operation = select_usergroup_dropdown_options();

    // two ways to transfer the nid
    $form['operation'] = array(
        '#type' => 'select',
        '#title' => t('Select User group:'),
        '#options' => select_usergroup_dropdown_options(),
        '#description' => t(''),
        '#required' => TRUE,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Find Users'),
    );
    return $form;
}
/**
 * #submit callback for node_adoption_transfer_form().
 */
  public function submitForm(array &$form, FormStateInterface $form_state) {
//   $form_state = new FormState();
   $form_state->setRebuild();
   //get the dropdown values selected
    $operation = $form_state->getValue('operation');
    $res = '';
   //query the db to get all the users under this group
        $query =  "SELECT vid,uid,init as email,u.name,ctu.field_p_group_name_value as group_name FROM {content_type_usergroup} ctu"
            . " INNER JOIN usergroup_user_map um ON ctu.vid = um.group_id"
            . " LEFT JOIN users_field_data u ON u.uid = um.user_id"
            . " WHERE ctu.vid=$operation"
            . " ORDER BY name";

   if(count(db_query($query)->fetchObject())==0){
       $res='<p style=""> No users found for this group </p>';
   }
   else {
        $res .= page_1_maketable_3($query);
        #print $res;exit();
        #$form['result'] = array( '#value' => $res, '#type' => 'markup' );
        $build = array(
          '#markup' => $res
        );
       return $build;
   }

  }

  protected function getEditableConfigNames() {
    return "user_lookup";
  }
}

```

and in function page\_1\_maketable\_3() am making the html table from the query as

```
 function page_1_maketable_3($query) {
        $buf = '<form method="post" action="module_name/batchdelete"><table class="inline">';
           $result = db_query($query);
          // Body
          $rowcount = 0;
          while ($row = $result->fetchObject()) {
              $id = $row->vid;
              unset($row->vid);
          if ($rowcount == 0) {
              $width = sizeof($row);
              // Header
              $buf .= '<tr>';
              foreach($row as $key => $value) {
                $buf .= '<th>' . $key . '</th>';
              }
              if($isedit) {
                  $buf .= '<th>Edit</th>';
                  $buf .= '<th>Delete</th>';
                if($batchop)$buf .= '<th>Select items</th>';
              }
              if($isaha)$buf .= '<th>Delete</th>';
              $buf .= '</tr>';
            }
            ++$rowcount;;
            $buf .= '<tr>';
            foreach($row as $key => $value) {
              $buf .= '<td>' . $value . '</td>';
            }
            //adding one more td with edit button if needed
           if($isedit) {
               $buf .= '<td><a href='.$url.$id.'>edit</a></td>';
               $buf .= '<td><a href='.$urlDelete.$id.'>delete</a></td>';
               $buf .= '<td><input type="checkbox" name="chkbox[]" value='.$id.' ></td>';
           }
           if($isaha) $buf .= '<td><a href='.$urlAhaDelete.$id.'/user/'.$row['uid'].'>delete</a></td>';
           $buf .= '</tr>';
          }

          $buf .= '</table>';
          if($batchop)$buf .= '<input type="submit" name="btchDelete" value="Delete Selected Items" id="batchDelete"></input>';
          $buf .= '</form><br/>';
          return "($rowcount rows)" . $buf;
    }

```

# Answer
> 2 votes
The naming `module_name/src/Controller/Form/UserLookUp.php` looks like you want to mix form and controller. That's not possible.

What you can do is to rebuild the form in submit and put the additional html in buildForm(). There you check $form\_state. If it is empty you have a new form and if it is filled with data you have a rebuild. Then you can react on the user input to generate the html that should be displayed along the form.

---
Tags: forms, 8
---


# Question
Title: Where to put dpm (Devel) to see comment elements?
Where to put `dpm` or `dsm` (Devel) to see comment elements?

# Answer
> 3 votes
You would put it in comment.tpl.php

```
dpm($content);

```

or in templates.php (located in sites/all/themes/yourtheme) inside a preprocess function

```
function MYTHEME_preprocess_comment(&$vars) {
  dpm($vars);
}

```

Upon reading your comment and trying this out myself, looks like devel dpm() doesn't work for comments. As an alternative, you can always use `var_dump($content);` or `print_r($content);` php function.

# Answer
> 2 votes
If you can't get `dpm` to work, have a look at the Devel Debug Log module as a possible alternative, which provide the `ddl()` function. Some more details about it (from its project page):

> Devel Debug Log is a developer module that provides a way for developers to save and display debug messages on a separate page in the web browser. It serves as an alternative to using drupal\_set\_message() or watchdog() for debugging, and a complementary module to Devel for those who find viewing messages in the browser easier than looking for them, say, in a file.
>
> The module provides the ddl($message) function, which the developer can use to save a debug message. If an object or array is supplied as $message, it will be displayed using the Krumo debugging tool. Messages can be viewed at Reports \> Debug Messages.

# Answer
> 0 votes
If you need dpm() to view all comment properties and then change something before it renders, you can use hook\_comment\_view().

```
function YOUR_MODULE_comment_view($comment, $view_mode, $langcode) {
  // How old is the comment.
  $comment->time_ago = time() - $comment->changed;
}

```

More infor here: https://api.drupal.org/api/drupal/modules%21comment%21comment.api.php/function/hook\_comment\_view/7.x

---
Tags: comments, debugging
---


# Question
Title: Views: add (link to file field) to image field
In D7, I have an *event* content type containing an *image* field ("Featured image") and a *file* field ("Document"). I have a view of events containing documents, and would like to wrap a link around the image, leading to the document. Here's a sample link.

**How can I rewrite the image (or use another technique) to get the desired link around the image?** Looking at available tokens (I did add a second, hidden Document field above the image to define tokens), nothing seems suitable. Thanks for your help.

# Answer
> 3 votes
* First add the "Content:File" field
* Check "Exclude from display" (hidden)
* Under "Formatter" select "URL to file"
* Then add your Image field and uncheck "Link this field to the original piece of content" or something similar
* Click on "Rewrite Results" and check "Output this field as a link"
* In the "Link path" textbox add "Replacement Pattern" from the file field (\[field\_file\] == Content: File, for example)

# Answer
> 0 votes
You can simply write

\['imag-tag'\]

in view select "Global custom" field.

---
Tags: 7, views, navigation, tokens, files
---


# Question
Title: Update commerce cart block when product added through ajax
Hii How can I update **commerce\_cart\_block** when my product is added through **ajax**. Any suggestion will be helpfull.

# Answer
> 0 votes
You need to extend your custom ajax call (or how is your setup ?) with an update cart ajax command, there's a module for it named: commerce\_ajax\_cart

If you want it all out of the box, then use the dc\_ajax\_add\_cart module.

---
Tags: views, ajax
---


# Question
Title: How to send an email notification when a subcription renewal is due?
When a subscriber’s monthly subscription is due for renewal, an automatic email should go to that user stating that the renewal is due. There will be two possibilities:

1. If there is no response to the notification, automatically the CC will be charged as per the current package selected.
2. The automatic eMail notification will have a link to upgrade to a different package if the subscriber wants to.

How to achieve this?

# Answer
# Part 1 - Sending eMail notifications

Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate renewal date of a specific package. To support multiple packages, just create similar date fields (1 for each package type).

### Step 1: Create a field to store the renewal date

Add a field to the "user" entity with machine name (say) `field_next_renewal`. Allow only 1 date (to store the "next" renewal).

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your upcoming renewal",
          "message" : "This is a reminder about the upcoming renewal  on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Message*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID. The Message-part of it is also where you can add the "*link to upgrade to a different package*" (as in your question).

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_on_user_renewal" : {
    "LABEL" : "On user renewal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 259200 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

```

Note that the above rule refers to the *Rules Component* from the previous step. It gets triggered any time a user profile is updated (feel free to replace that Rules Event with any other event that might fit).

The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

### Step 4: additional refinements

* The ***date\_offset*** (=259200) in the above rule corresponds to "3 days in advance", which may need review / tuning.
* If needed, you could also use the Field Permissions module to set field-level permissions to edit, view and create this renewal field.
* Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

> ... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

# Part 2 - Tracking possible responses

If you'd also use the Flag module, you could enhance the above Rules logic to also "flag" the user (to indicate that you're waiting for some kind of response to the renewal eMail. By creating a view (using the Views module), you could then simply list the flagged users for which you do not have some desired response (those are the users who didn't perform a renewal).

***Happy Rules-ing!***
> 0 votes

---
Tags: 7, emails, notifications
---


# Question
Title: Programatically save node fields if fields is autocomplete?
I have created a content type with 3 fields and my one field is node\_refrence in this filed I am filling title of other node using node\_refrence.

I am using this code.

```
> $node = new stdClass();
 $node->type = 'application';
> node_object_prepare($node);
> $node->title = "test title";
 $node->language = LANGUAGE_NONE;
> $node->field_application_school[$node->language][]['target_id']  =
> 1373;
> $node->field_application_school[$node->language][]['target_type'] =
"node";
 node_save($node);

```

I need to fill the entry for `$node->field_application_school[$node->language][]['target_id']`, its not working.

# Answer
@jsh I'd suggest to create a test node through the admin menu (i.e. node/add/content\_type) then dpm/debug the $node object in that content type template and finally view the node and look through the object's output and see where your code differs from the object constructed by Drupal.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: drupal_is_front_page can't recognize arguments
I have a view display as a drupal site's front page. And that view has a path (like **"/myview"**. Also that view takes several arguments from url (like **"/myview/arg1/arg2"**). I also have some extra code to be called on the front page only. But it seams that drupal\_is\_front\_page function can't recognize a view page with arguments as a front page. For example, drupal\_is\_front\_page returns:

* 1) "mysite.com/" - \>true
* 2) "mysite.com/myview/" - \>true
* 3) "mysite.com/myview/arg1" - \>**false**
* 4) "mysite.com/myview/any-text-here" -\>**false**

In any of these cases a view display returns correct data, but drupal\_is\_front\_page - not. Is there any way to check if its a frontpage in my case?

# Answer
When looking at the drupal\_is\_front\_page function you see it performs a check on

```
($_GET['q'] == variable_get('site_frontpage', 'node'));

```

So it only returns true if there is an exact match.

You can recreate the function and use something this instead, to check if the frontpage url is a part of the request url:

```
(strpos($_GET['q'], variable_get('site_frontpage', 'node')) !== false)

```

All other code in drupal\_is\_front\_page is for static caching. You want to copy that if you intend to call this function often. If it is for one check you can do with this simple function:

```
function drupal_is_front_page2() {
  $is_front_page = (strpos($_GET['q'], variable_get('site_frontpage', 'node')) !== false);
  return $is_front_page;
}

```
> 0 votes

---
Tags: views
---


title: How to promote nodes/pages into blocks?

text:
# Question
Title: How to promote nodes/pages into blocks?
Standard Drupal comes with a "promote to front page" when creating new content. But I want know how to promote, let's say `News` flow to the block located to the right?

As far as I know there is no "url" for blocks so I can't really use view to assign my news flow to the blocks url. So how do I do this the easiest way?

# Answer
I complete the previous answer about Drupal 8.

In Drupal 8 with Views (include in core) it's exactly the same way.

Add a 'Promote to block' checkbox field on your `News` content type.

Then in Views you can create a new View or you can go in the "Content" View. Then create a new "Block". Describing all Views functionalities would take a long time, but in this block you can filter all your content, particularly in the Filter Criteria sections where you can filter in order to take only News content type with only the 'Promote to block' option checked.

If needed, search for some Views tutorials. It's quite easy and very powerful.

Then call this new block instead the old one.
> 1 votes

# Answer
Just use the Views module to create a block display. And within the block settings specify that you only want to show it on the "front page". The fields to be shown are probably only the title of the nodes you want to see included in that block. with that you've reduced your question (challenge) to selecting the appropriate Views "filter" and "sorting".

To filter your nodes, you could add an extra field to the content types (like your "News"?) you want to see included, whereas that field is just a boolean to yes/no indicate if it should be shown in that block.

If you'd want to make it a little more flexible (dynamic), you could also use the Flag module, and allow authorized users (with appropriate roles to set such flags) to flag whatever should be included in that block. Your view would then become a similar list of nodes that were "flagged".

Enough options to pick from?

PS 1: I'm assuming this question is about Drupal 7 ...

PS 2: for D8, Views is in core ... and for Flag there is a 8.x-4.x-dev release, for which the current status is "Under active development, but not yet ready for production."
> 0 votes

---
Tags: blocks
---


title: Why NOT to use Clean URLs?

text:
# Question
Title: Why NOT to use Clean URLs?
I have a theoretical question: why is there option to enable clean URLs? And I don't mean that they are not useful - on the contrary, I don't see the point of **not** using them. Why would anyone use URLs like `www.drupal.stackexchange.com/?q=questions/ask` if they can get rid of this `?q=`?

And why are they not at least a default option?

# Answer
My unconfirmed hypothesis is that this setting was still available through Drupal 7, even on servers that properly support rewrites, was to provide backward compatibility.

There are scenarios where you do something (upgrade from Drupal 6 to Drupal 7, move a site to a new server, etc) and want to retain your URL structure for SEO / ranking purposes. In the case where you weren't able to use clean URLs on the old site, but can on the new site, means that you may not want to enable them. You may also have the case where the un-clean URL is baked into body fields, so these URLs will still get out into the wild.

That said, there is little need for this given the state of contrib. The Redirect and Global Redirect can handle inbound mapping with proper response codes so that search engines know the proper URL to update and serve back the updated one. Pathologic can rewrite old URLs on the fly to updated ones, to prevent the old URLs from getting out into the wild again.
> 0 votes

# Answer
There are web-servers not supporting url rewriting.
> 0 votes

---
Tags: uri
---


# Question
Title: What is the intended use of drupal_static?
I understand Drupal static cache is used to store static values in the memory for the length of the request to faster access them. However throughout Drupal and contributed modules I tend to see two different versions:

Example from drupal\_is\_front\_page:

```
function drupal_is_front_page() {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['is_front_page'] = &drupal_static(__FUNCTION__);
  }
  $is_front_page = &$drupal_static_fast['is_front_page'];

  if (!isset($is_front_page)) {
    // As drupal_path_initialize updates $_GET['q'] with the 'site_frontpage' path,
    // we can check it against the 'site_frontpage' variable.
    $is_front_page = ($_GET['q'] == variable_get('site_frontpage', 'node'));
  }

  return $is_front_page;
}

```

They way I read (and used) it from some tutorial I once found:

```
$static_cache = &drupal_static(__FUNCTION__);
if (!isset($static_cache[$key])) {
  // Obtain value
  $static_cache[$key] = $obtained_value;
}

return $static_cache[$key];

```

So I skipped the static declaration of the local variable, and to be honest I don't see why I should be adding it, it is in the first line of drupal\_static:

```
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();
  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }
  ...
}

```

Is is even faster if I declare another static variable in my module to hold a function that manages a static variable? (The name drupal\_static\_fast implies this.) Is this some old Drupal 6 convention where there was no drupal\_static and it had to be declared locally? Or am I missing something else?

# Answer
The code in `drupal_is_front_page()` makes the page rendering faster because it calls `drupal_static()` once for each page request; how much faster it makes it depends from how many times `drupal_is_front_page()` is called. The fact it is using that code means the core maintainers know the function is called enough times to need that code.
The `drupal_static()` documentation explains this with the following paragraph:

> In a few cases, a function needs a resettable static variable, but the function is called many times (100+) during a single page request, so every microsecond of execution time that can be removed from the function counts. These functions can use a more cumbersome, but faster variant of calling `drupal_static()`. It works by storing the reference returned by `drupal_static()` in the calling function's own static variable, thereby removing the need to call `drupal_static()` for each iteration of the function. Conceptually, it replaces:
>
> ```
> $foo = &drupal_static(__FUNCTION__);
>
> ```
>
> with:
>
> ```
> // Unfortunately, this does not work.
> static $foo = &drupal_static(__FUNCTION__);
>
> ```
>
> However, the above line of code does not work, because PHP only allows static variables to be initialized by literal values, and does not allow static variables to be assigned to references.
>
> The example below shows the syntax needed to work around both limitations. For benchmarks and more information, see http://drupal.org/node/619666.
>
> ```
> function user_access($string, $account = NULL) {
>   // Use the advanced drupal_static() pattern, since this is called very often.
>   static $drupal_static_fast;
>   if (!isset($drupal_static_fast)) {
>     $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
>   }
>   $perm = &$drupal_static_fast['perm'];
>   // ...
> }
>
> ```

Your code calls `drupal_static()` every time, and essentially is the same code as the following one, which in Drupal documentation is not considered the fast version.

```
  $added = &drupal_static(__FUNCTION__);

  // User-uploaded files cannot set any response headers, so a custom header is
  // used to indicate to ajax.js that this response is safe. Note that most
  // Ajax requests bound using the Form API will be protected by having the URL
  // flagged as trusted in Drupal.settings, so this header is used only for
  // things like custom markup that gets Ajax behaviors attached.
  if (empty($added)) {
    drupal_add_http_header('X-Drupal-Ajax-Token', '1');
    // Avoid sending the header twice.
    $added = TRUE;
  }

```

@Clive explained the reason `drupal_static()` was added to Drupal: The idea behind its implementation was to use a static variable that at the same time could be reset (or changed) from other functions as well. In fact, the `drupal_static()` documentation says:

> All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables.
> 8 votes

---
Tags: 7
---


# Question
Title: Accessing custom block fields from a template file
I have a sidebar region "Sidebar Ad" and placed in that region is the custom block "Sidebar Ad" of type "Image" which has two fields "Image" and "Link".

When I output the block on my page using `{{ page.sidebar_ad }}`, I get the image and the link separate from each other, which is to be expected. What I can't figure out, and I've been trying for around 5 hours now, is how to reference the fields separately so I can wrap the link around the image.

Does anyone know how to reference those fields? Am I going about this the wrong way?

I've successfully pulled the link URL by overriding the specific block template and referencing:

```
{% block content %}
        <a href="{{ content.field_link.0['#url'].uri }}"></a>
{% endblock %}

```

Referencing the image URL still eludes me.

# Answer
This was the final solution.

```
{% block content %}
    <a href="{{ content.field_link.0['#url'].uri }}">
        <img src="{{ file_url(content.field_image.0['#item'].entity.fileuri) }}" alt="{{ content.field_image.0['#item'].alt }}">
    </a>
{% endblock %}

```
> 1 votes

---
Tags: theming, blocks
---


# Question
Title: How to subscribe to any or all taxonomy terms on one page?
I'm wondering about the best way to set up "subscribe to get email alerts"

I have a content type which is "tagged" with various terms from various taxonomies and I want to set up a simple "subscribe to get email alerts" page, where users can subscribe to whichever 'terms' they like, so that emails are sent to them when a new item of the content type is created with the associated tags.

I have installed the notifications and messaging modules which have enabled me to create a "subscriptions block", which is presented on the content pages with links like "Subscribe to: Content tagged with: XXXXX", which allows users to subscribe to a specific tag.

But what I really want is a page, which lists ALL available tags (terms) a user could subscribe to, with check boxes, so the user can skim the list and subscribe to any / all the tags they are interested in, in one go

I am struggling to work out how I might do that using the notifications and messaging modules… perhaps I would be better off allowing users to 'tag' themselves with the same terms used on Content Type… and then set up a rule which fires an email to the user if new content (of the specific content type) is created with the same terms as they have tagged themselves with?

But I'm not entirely sure how I would go about that… or if there is a better / simpler plan?

I don't think this is a very complicated task - and am surprised I can't find links to similar requests / solutions online…

Any advice appreciated!

# Answer
> 1 votes
# Subscriptions

The Subscriptions module (with over 5K reported installs) is a typical solution used to setup such Subscriptions. Some details about it (from its project page):

> This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

# Total Subscription

The Total Subscription module (only a bit over 100 reported installs) seems like a possible alternative for such subscriptions. Some details about it (from its project page):

> Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.
>
> ... provides users the ability to:
>
> * Subscribe to a specific content type through the node page.
> * Subscribe to the related taxonomy terms associated with the node on the node page.
> * Subscribe to a specific taxonomy term from the term page.
> * Unsubscribe from any previous subscription.
> * Add a separate ctools content type - "subscription", which could be integrated with any panel page.
> * Add a "subscription" block to the any region.

Refer to its Community documentation for more details about it, or this video tutorial (without sound ...) that takes you through various admin screens.

Apart from that, to understand what this module is about, the readme.txt might be helpful also.

# Module comparison

Some more details about how both modules compare (from the Total Subscription project page):

> Subscriptions provides the following features which are not there in Total Subscription, namely it allows subscription to new comments in specific forums, or additions to some category of blog. More control on subscription management for user. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made which can be turned off by admin. But the biggest disadvantage of Subscriptions is it does not allow anonymous users to subscribe, which Total Subscription provide. Total Subscription also has Views and Token integration.

---
Tags: 7, taxonomy-terms, notifications
---


# Question
Title: How to show a user login form on a completely separate page?
I am developing a application where I want to restrict everything from anonymous users. If anyone tries to access any page from url directly they will be redirected to login page. How to do this?

Also I want show the login page in a completely separate page where there should be no menu or any other links, just the login form (like for example: google login page). What is the best way to do this.

# Answer
> 0 votes
As lynbermt suggests, you can easily remove permission to do anything at all from the anonymous user at `admin/people/permissions`. There are a few other great add-ons to this:

* Create a 403 page in the Panels module and add a login form, making it visible only to anonymous users
* Activate the login block at `admin/structure/block` so that it's always visible to anonymous users no matter what page they're on
* Remove anything else from the main page, or make everything invisible to anonymous users (panels panes, blocks, etc.)

It will basically just take a lot of testing, browsing around as an anonymous user to see what's visible and then go hide it. And beware! Every time you add a new module or bit of functionality you should re-test as much of it as possible to make sure that an anonymous user can't get at anything. Vigilance. Each module will have its own new permissions to configure, security risks to watch out for, etc.

# Answer
> 0 votes
Easiest way would be to remove all permissions from the anonymous user at /admin/people/permissions and then set the 403 page on /admin/config/system/site-information to /user.

# Answer
> 0 votes
> If anyone tries to access any page from url directly they will be redirected to login page.

Create a rule using the Rules module, which looks like so:

* **Event:** Drupal is initializing
* **Conditions:**

1. *User has role(s)* \- `Parameter: User: [site:current-user], Roles: anonymous user`
    2. *NOT Text comparison* \- `Parameter: Text: [site:current-page:url], Matching text: user/login`
* **Actions:** *Page redirect* \- `Parameter: URL: user/login`

> ... login page in a completely separate page where there should be no menu or any other links.

For any blocks shown on the login page (eg related to menu blocks for primary menu, navigation menu, etc), set the block visibility settings so that these blocks are not shown for anonymous users.

# Answer
> 0 votes
> If anyone tries to access any page from url directly they will be redirected to login page.

You could use:

### Require Login

> Require user authentication (login) on all pages, regardless of user role permission settings.
>
> **Features**
>
> * Ability to make all pages require user login.
> * Easily exclude paths from requiring user login.
> * Customize require login user message.

---

> Also I want show the login page in a completely separate page where there should be no menu or any other links

You can create a custom module with a custom path Ex: `/login` use Drupal render login form programatically or Print registration and login forms on same page to display the form.

Make a copy of page.tpl.php and rename the copy to Ex: page--login.tpl.php. Edit the file and delete the print menu part.

# Answer
> 0 votes
Thanks all for all your suggestions. I find the answer after doing some google.

1) restrict everything from anonymous users.

I added the following code in my custom module init hook

```
function mymodule_init(){
$login_path =  'user/login';
if (user_is_anonymous() && current_path() != $login_path) {
  $path = $_GET['destination'];
  $destination = array('destination' => $path);
  header('Location: ' . url($login_path, array('query' => $destination, 'absolute' => TRUE)), TRUE);
 drupal_exit();
 }
}

```

2) show the login page in a completely separate page

For this I added "page--user--login.tpl.php" in my theme folder and rendered the login form with the following code-

```
<?php
 print(drupal_render(drupal_get_form('user_login_block')));
?>

```

Thats it. Any more suggestion greatly appreciated.

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


# Question
Title: How to replace text about [node:url] within a Rules Action?
I'm using the Rules module and have a Rule created that, upon saving of new content, an email is sent out containing the node title, as well as the URL of the node. Pretty straightforward. That said, I want to replace text in the URL before the message that's sent out. I'm using str\_replace() but it isn't working.

Any suggestions?

**Update**:

The path currently look like this: domain.com/cron.php/newsroom/press-release/\[path-to-content\] However, I would need to replace out the "cron.php" from the URL, as that doesn't actually exist. So the new URL should look like this: domain.com/newsroom/press-release/\[path-to-content\]

Here's an export of the rule. I've removed any sensitive information:

```
{ "rules_press_release_notification_test" : {
    "LABEL" : "Press Release Notification Test",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "press_release" : "press_release" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "[node:title]",
          "message" : "We've added a new press release to our Newsroom:\r\n\r\n[node:title]\r\n\r\n\u003C?php\r\n$releaseurl = \u0022[node:url]\u0022;\r\n$releaseurl = str_replace(\u0022newsroom\/\u0022, \u0022\u0022, $releaseurl);\r\n\r\necho $releaseurl;\r\n?\u003E\r\n\r\n[node:url]\r\n",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
I would transform your existing rule into 2 separated rules like so:

* Create a Rules Component that only performs a Rules Action which is to send an eMail, similar to what you already have in your current Rules Action. But replace the `node:title` and the `node:url` by corresponding parameters to execute this Rules Component.
* Replace the Rules Action of the rule you already have by the execution of your newly created Rules Component, in which you pass as parameter values:
    + the title of the node
    + the appropriate string that matches your `domain.com/newsroom/press-release/[path-to-content]`

With that, you don't need any PHP, so no `str_replace()` either.

---
Tags: 7, rules
---


# Question
Title: 8 - Node::load is generating an object with circular reference which is crashing kint() and var_export()
I have a content type with a Taxonomy term which has fields. When I try and load a node (or possibly nodes) of this type I get unexpected results. While debugging with kint() and var\_export() I get errors about "circular references". Is this normal in Drupal 8 node structures?

Or is there an underlying misconfig in the content type or taxonomy causing this problem?

# Answer
> 1 votes
Yes, this is normal and by design.

When you want to dump it, just use $node-\>toArray(). Then you get an array with the plain values. You can use those field names and properties again to access the values on the node object, e.g. `$node->yourfield->value`.

---
Tags: 8, debugging
---


title: Customize commerce cart form page

text:
# Question
Title: Customize commerce cart form page
# Task

I have been issued to alter the cart form view `Shopping cart form (Commerce Order)` on the `site.com/cart` page of the Drupal 7's commerce module. This includes adding extra choices such as sizes together with simply updating the quantity of each product.

# My attempts so far

I've tried overriding `commerce_cart_block` just realise it was `commerce_cart_form` that was in charge of the content. Now I've tried a module that's called Commerce Cart View Override and it helps me have a template file called `views-view--commerce-cart-form.tpl.php` inside my template to display the content.

However I'm not really sure what I'm supposed to do now. In my mind I would override the table that show the items and the form surrounding it. I echo'ed `get_defined_vars()` in the template just to realise that there are quite many variables passed.

# Question

What I desire is an elegant solution that allows me to append more forms to modify existing cart session, all in the /cart page, and also be able to have full control of the current cart table.

What is the ideal way for me to customize the /cart page? Am I on the right path, or there some simplier alternatives that I have missed? Personally I want a coded solution and not a database saved one.

# Answer
## Editing the /cart page in Views

I think this is the expected approach. Note: this assumes you know your way around Views.

1. Install Commerce Cart View Override, as you've done.
2. Edit the view named Shopping Cart Form, clone it, change the machine name to something starting with `commerce_cart_form` like `commerce_cart_form_custom`
3. Select this in the dropdown on the admin page `admin/commerce/config/cart-overrides` (Administer \>\> Store \>\> Configuration \>\> Cart Overrides), then save.
4. You can now edit the view that appears on the `/cart` page by editing this new view. A few non-intuitive tips:
    * To see a preview in the Views preview, you'll need to enter a shopping cart ID number into the "Preview with contextual filters" box above the preview. You can see some shopping cart ID numbers at `/admin/commerce/orders/carts`. You just enter the ID number, no other text needed.
    * To add any views fields from the products, for example **product images**, you'll need to add a new relationship from Line Items to Products. Under Advanced in the Views UI, under Relationships, click Add, then choose **Commerce Line item: Referenced products**. Product fields like images and taxonomy tags will then become available under Fields.
    * A common Commerce Cart configuration confusion: If no "Checkout" button appears for customers who aren't logged in, you need to go to `admin/people/permissions` and tick the "Anonymous user" box next to "Access checkout"
    * If you want to change the labels of buttons, for example the "Remove" buttons... that's a whole different story. Form elements are generated in a whole different part of the Drupal ecosystem and put into a View like this pre-rendered, all you can edit in Views is the labels that appear alongside or above the button. To edit the buttons themselves has to be PHP code:

## Editing form elements like buttons

In a custom module or your theme's template.php file (remember that if you use a seperate admin theme, your template.php won't have any effect in the views preview, only the customer-facing pages), add something like this (credit):

```
function yourthemename_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id)  {
  case 'views_form_commerce_cart_form_custom_default':
  //               ^ from here on should match the view machine name from earlier
  //                                         ^ from here, the particular view display, which you can see at the end of the Views UI URL while editting that display
      foreach ($form['edit_delete'] as $row_id => $row) {
        if(isset($form['edit_delete'][$row_id]['#value'])){
            $form['edit_delete'][$row_id]['#value'] = 'New delete button label';
            }
        }

    $form['actions']['checkout']['#value'] = 'New checkout button label';
    $form['actions']['submit']['#value'] = 'New update button label';

  break;
  }
}

```
> 4 votes

---
Tags: 7, views, commerce
---