# Question
Title: Get $form_state backup and migrate filter extended class
I have form altered the backup and migrate quick backup screen (admin/config/system/backup\_migrate) and added a text field. I'd like to use the value of the field to create a new node just before the backup is done. I found a way to "hook" backup and migrate just before it performs a backup, which is great. However, I need to get $form\_state\['values'\]\['my\_value'\] and pass that to my function that creates a new node. I can't figure out how to get that passed to the pre\_backup() inside the extended class backup\_migrate\_filter.

# Answer
From your question, I get you altered the form built from the following function.

```
/**
 * The quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form($form, &$form_state, $inline = TRUE) {
  backup_migrate_include('profiles', 'destinations', 'sources');
  drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js');

  $form = array();

  // Theme the form if we want it inline.
  if ($inline) {
    $form['#theme'] = 'backup_migrate_ui_manual_quick_backup_form_inline';
  }

  $form['quickbackup'] = array(
    '#type' => 'fieldset',
    "#title" => t("Quick Backup"),
    "#collapsible" => FALSE,
    "#collapsed" => FALSE,
    "#tree" => FALSE,
  );

  $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));

  $form['quickbackup']['destination'] = _backup_migrate_get_destination_pulldown('manual backup', variable_get('backup_migrate_destination_id', 'download'), variable_get('backup_migrate_copy_destination_id', ''));

  $profile_options = _backup_migrate_get_profile_form_item_options();
  $form['quickbackup']['profile_id'] = array(
    "#type" => "select",
    "#title" => t("Settings Profile"),
    '#default_value' => variable_get('backup_migrate_profile_id', NULL),
    "#options" => $profile_options,
  );

  $form['quickbackup']['description_enabled'] = array(
    '#type' => 'checkbox',
    "#title" => t("Add a note to the backup"),
  );
  $form['quickbackup']['description'] = array(
    '#type' => 'backup_migrate_dependent',
    '#dependencies' => array(
      'description_enabled' => TRUE,
    ),
  );

  $form['quickbackup']['description']['description'] = array(
    '#type' => 'textarea',
    "#title" => t("Note"),
    '#description' => t('This note will be saved with the backup file and shown on the listing page.'),
  );

  $form['advanced'] = array(
    '#type' => 'markup',
    '#markup' => '<div class="clearblock backup-migrate-footer-message">' . t('For more backup options, try the <a href="!advancedurl">advanced backup page</a>.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))) . '</div>',
  );

  $form['quickbackup']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Backup now'),
    '#weight' => 1,
  );

  $form['#validate'] = array('backup_migrate_ui_manual_quick_backup_form_validate');
  $form['#submit'] = array('backup_migrate_ui_manual_quick_backup_form_submit');

  return _backup_migrate_ui_action_form($form, $form_state, 'backup');
}

```

The only way to pass a value submitted in a form to a hook is to save it into a persistent variable, exactly in the same way a submission handler does.

```
/**
 * Submit the quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  backup_migrate_include('profiles', 'destinations');
  if (user_access('perform backup') && !empty($form_state['values']['settings'])) {
    // Save the settings for next time.
    variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
    variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
    variable_set("backup_migrate_copy_destination_id", $form_state['values']['copy_destination_id']);
    variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);

    // Do the backup.
    backup_migrate_ui_manual_backup_perform($form_state['values']['settings']);
  }
  $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
}

```

Your `hook_form_alter()` implementation needs to do two things:

* Add the form element, as you already did
* Add a submission handler to `$form['#submit']` (`$form['#submit'][] = 'mymodule_submission_callback';`)
> 1 votes

---
Tags: hooks, forms
---


# Question
Title: How to block permissions tab for certain users?
Is there a way to block users who are allowed to edit users roles from seeing the "permissions" tab?

Can this be done without code?

# Answer
> 2 votes
# Option 1

Use the RoleAssign module for this. Some details from its project page:

> RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
>
> RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.
>
> RoleAssign is ideal for smaller sites with a system administrator and one assistant administrator role that should be reasonably restricted in what it allows. For larger sites with multiple levels of administrators or whenever you need finer-grained control over which role can assign which other role, check out Role Delegation. See #961682: Does the role delegation module supersede this module? for a short discussion of the relative merits of the two modules.

# Option 2

Use the Role Delegation for this. Some details from its project page:

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
>
> The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions in the Permissions page.
>
> If an administrator has the administer users permission, a role assignment widget gets displayed in the account creation or editing form, and bulk add/remove role operations become available on the user administration page. Otherwise, if s/he has at least the access user profiles permission, the module adds its own Roles tab to the user profile so that roles can be assigned.

# Option 3

Use the Administer Users by Role module for this (only an RC version for D7). Some details from its project page:

> This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

# Answer
> 2 votes
This cannot be done without code. If you take a look at `user_menu()` you'll see that access to both of those pages is determined by the `administer permissions` permission.

To block access to one but not the other will require you to implement `hook_menu_alter()` and change which permission is checked for one of those pages.

# Answer
> 0 votes
this code works

function mymodule\_menu\_alter(&$items){ $items\['admin/people/permissions'\]\['type'\] = MENU\_CALLBACK;

}

---
Tags: 7, users
---


# Question
Title: Create a wrapper div within field groups on node displays
For ease of formatting I would like to add an inner wrapper div inside of field groups displaying on content nodes and node forms. I'm using the Field Group module to display groups in div format.

Currently it's this:

```
<div class="field-group-format group_user field-group-div group-user required-fields  speed-fast effect-none">
…
</div>

```

Would like to output this:

```
<div class="field-group-format group_user field-group-div group-user required-fields  speed-fast effect-none">
<div class="inner">
 …
</div>
</div>

```

# Answer
> 1 votes
You can use the theme\_preprocess\_node hook in your custom theme and add your inner div using the #prefix and #suffix of the fieldgroup. It should be in $variables\['content'\]\['name\_of\_the\_fieldgorup'\]\['#prefix'\] .

# Answer
> 2 votes
Try hook\_field\_group\_build\_pre\_render\_alter() since node content solution seems not longer working.

```
/**
 * Implements hook_field_group_build_pre_render_alter().
 * Adds additional wrappers
 */
function [your_theme_or_module_name]_field_group_build_pre_render_alter(&$element) {
  if (!empty($element['group_tabs'])) {
    $element['group_tabs']['#prefix'] = '<div class="field-group-container">';
    $element['group_tabs']['#prefix'] .= '<div class="field-group-row">';
    $element['group_tabs']['#suffix'] .= '</div></div>';
  }
}

```

Check Field group for developers for more info.

# Answer
> 0 votes
I found that the best way to handle this is to use Views Display Modes from Display Suite.

---
Tags: entities
---


# Question
Title: How to define custom permissions for organic groups?
I would like to define some organic group permissions for a custom entity. The permissions should look like:

```
  $perms += array(
        "create $type content" => array(
          'title' => t('Create %type_name content', array('%type_name' => $name)),
        ),
        "update own $type content" => array(
          'title' => t('Edit own %type_name content', array('%type_name' => $name)),
        ),
        "update any $type content" => array(
          'title' => t('Edit any %type_name content', array('%type_name' => $name)),
        ),
        "delete own $type content" => array(
          'title' => t('Delete own %type_name content', array('%type_name' => $name)),
        ),
        "delete any $type content" => array(
          'title' => t('Delete any %type_name content', array('%type_name' => $name)),
        ),
      );

```

How do I do this? I found the function og\_get\_permissions() to get all set permission, but how to modify this array?

Or may be it should be another way round? You set a normal drupal permission first with:

```
function custom_example_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

```

And then make it eligible on the permission preferences page of OG? But how?

# Answer
> 1 votes
I found the solution here:

```
/**
 * Implements hook_og_permission().
 */
function custom_permissions_og_permission() {
  $name = "taks";
  return array(
    'update own task content' => array(
      'title' => t('Update own %type_name content', array('%type_name' => $name)),
      'description' => t("Edit own %type_name content.", array('%type_name' => $name)),
      // Determine to which role to limit the permission. For example the
      // "subscribe" can't be assigned only to a non-member, as a member doesn't
      // need it.
      'roles' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
      // Determine to which roles the permissions will be enabled by default.
      'default role' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
    ),
    'update any task content' => array(
      'title' => t('Update any %type_name content', array('%type_name' => $name)),
      'description' => t("Edit any %type_name content.", array('%type_name' => $name)),
      'roles' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
    'create new task content' => array(
      'title' => t('Create new %type_name content', array('%type_name' => $name)),
      'description' => t("Create new %type_name content.", array('%type_name' => $name)),
      'roles' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
  );
}

```

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


title: Deadlock on cache table drupal

text:
# Question
Title: Deadlock on cache table drupal
My client site has huge data, which they want to download into CSV through View data export module, when multiple users are trying to download the csv file, its resulting in an error.

In log messages I can see error like-

```
PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction:

```

When I am trying to see my innodb status through: mysqlengine innodb status\G; its showing deadlock for insert into cache table.

Can anyone help in this?

# Answer
https://www.drupal.org/project/apdqc is a pretty good solution for the issue you're describing. Install the module and go to the status report page (`admin/reports/status`); it will then run a gamut of tests and give you advice on things to change in your settings.php, php.ini, and my.cnf files.

The root cause of most of the cache deadlocks is that a truncate query and insert query are in conflict with each other.
> 0 votes

---
Tags: caching, database, importing-exporting
---


title: Schedule node modifications?

text:
# Question
Title: Schedule node modifications?
I use Scheduler when i need to public/unpublish nodes and it works pretty well, but i would like to schedule the modification of an specific node? is there any module or something?

# Answer
> 1 votes
Take a look at Workbench Scheduler. you could make changes as a draft(or any other workbench moderation state) and let Scheduler publish it.

---
Tags: nodes, rules
---


# Question
Title: How to trim view field to height or number of lines?
I have a div with a fixed height and want to display a view field. When the content overflows the div, I'd like an elipsis to click for more.

CSS can handle overflow and hide it (and overflow-text can handle a single line) but I have to estimate everyting for number of lines since words can be an arbitrary length. Sure views with or without the smart trim module can handle words or characters, but I need to estimate the number of lines or, ideally, **I'd like the trim based on the max-height of a div**.

The Smart Trim maintainer suggested a CSS library which may help but does not solve the problem.

I imagine that views text overflow based on height is a common problem.

# Answer
> 0 votes
There is no way to handle this with Drupal modules, I suggest you use Ellipsis in your Style( style the result rows items with `Ellipsis` .

You can read below help content :

link1

link2

---
Tags: views, entities
---


# Question
Title: Deny access to URL non-authenticated users
I have a drupal 7 site with an academic paper that should be accessible only to authenticated users. At the moment the paper is set up as a hyperlink in the full text field of a biblio page and only authenticated users can reach the page.

However, if non-authenticated users get their hands on the url that leads to the pdf version of the paper, they can download it. How can i redirect non-authenticated users that use the url to an error page?

# Answer
To control which user can access a download link, you need what is called a "private file system" in Drupal. Public files are directly served to the visitor by the web server; Drupal doesn't even come into play. Private files on the other hand are served by Drupal, so it can check permissions before sending the file.

You do not need additional modules to enable the private file system and upload files to it. The documentation should get you started. If you want to make it easy to create links in the body text to file download URL's, you could try adding the CKeditor and Linkit modules.
> 2 votes

# Answer
Maybe Private files download permission handle what you want.

Some quote form this module page :

> Version 1.x provided "two useful features which Drupal itself is missing: a simple permission to allow downloading of private files by role, plus the ability to combine both public and private downloads".
>
> Version 2.x removes the "global" permission and implements a per-directory by-user and by-role filter instead, to let the administrator better tweak the whole website and increment the overall security.

Also you can use Field Permissions module

some quote form this module page :

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> Features
>
> ```
> Enable field permissions on any entity, not just nodes.
> Role-based field permissions allowing different viewing patterned based on what access the user has.
> Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields
>
> ```
>
> where this feature is needed.
> 0 votes

---
Tags: uri, users, taxonomy-terms
---


title: 403 redirect loop on every page

text:
# Question
Title: 403 redirect loop on every page
I'm not sure what is causing this, but every page of my Drupal site is throwing a 403 error redirect loop.

I was just working on the project this morning, and left and came back to it and can't figure out what has gone wrong.

If anyone could event point me toward a resource for figuring out what has gone wrong it would be a huge help.

# Answer
Looks like you have wrongly configured 403 page, in order to change it back, you can override it by adding following on your settings.php

```
 $conf['site_403'] = '';

```
> 1 votes

---
Tags: redirection
---


# Question
Title: How to modify HTML of specific node in Drupal 7?
I use Drupal 7 with Bootstrap Theme. I have many blocks placed on different nodes and HTML generated is as follows:

```
<div class="region region-content">
  <section id="block-system-main" class="block block-system clearfix col-md-12">
    <div id="node-21" class="node node-pagina clearfix">
      <div class="content">
        [...]
      </div>
    </div>
  </section> <!-- /.block -->

  <section id="block-block-13" class="block block-block contextual-links-region clearfix col-md-4">
    [...]
  </section> <!-- /.block -->

  <section id="block-block-12" class="block block-views contextual-links-region clearfix col-md-6">
    [...]
  </section> <!-- /.block -->

  <section id="block-block-15" class="block block-block contextual-links-region clearfix col-md-12">
    [...]
  </section> <!-- /.block -->

  <section id="block-block-14" class="block block-block contextual-links-region clearfix col-md-12">
    [...]
  </section> <!-- /.block -->
</div>

```

I want to change that HTML for put some `<div class="container">` to enclosing some `<sections>`

Example:

```
<div class="container">
    <section id="block-block-13" class="block block-block contextual-links-region clearfix col-md-4">
      [...]
    </section> <!-- /.block -->

    <section id="block-block-12" class="block block-views contextual-links-region clearfix col-md-6">
      [...]
    </section> <!-- /.block -->
  </div>

```

# Answer
> 2 votes
Short answer: Place a customized template named `node--[nid].tpl.php` or `page--node--[nid].tpl.php` in your themes template folder. (\[nid\] = id of specific node).

Long answer: If you didn't done yet, you should first create a Bootstrap subtheme for your modifications. Then copy either node.tpl.php or page.tpl.php from the Bootstarp theme inside your subtheme folder. Rename the file to either `node--[nid].tpl.php` or `page--node--[nid].tpl.php` (Replace \[nid\] with the node id of the specific node) and customize the file to your liking. Lastly clear the cache at /admin/config/development/performance

For more/other template examples have a look at Drupal 7 Template (Theme Hook) Suggestions

EDIT: To control specific blocks for a specific page, I'd create a dedicated region inside your subtheme's `.info`-file and in your `page.tpl.php` / `page--node--[nid].tpl.php`. And place the blocks inside those regions.

---
Tags: 7, theming
---


# Question
Title: Unable to change date format on node created field
On my article content type, I enabled "Display author and date information" but am unable to change the date format.

I'm using Druapl 8.0.0-beta14 with a sub-theme based on Classy. The field's value is already computed by the time the twig template and hook\_preprocess\_field get to it but was able to chase down the setting of the date format to the defaultSettings method in TimestampFormatter.php using a debugger.

```
    public static function defaultSettings() {
      return array(
        'date_format' => 'medium',
        'custom_date_format' => '',
        'timezone' => '',
      ) + parent::defaultSettings();
    }

```

So far, I haven't found a place in the admin UI or yaml files (or a hook, which I know I probably shouldn't be doing too much of in D8) where the date format can be changed. Interestingly enough, this "field" on the node seems to be some sort of pseudo-field, because the value is actually the timestamp on the revision\_timestamp field in the node\_revision table.

That said, how can I change the date format for this "field"?

# Answer
One way to do this is using a preprocess hook in your .theme file. There you can do pretty much anything with that variable.

Here an example:

```
function [theme_name]_preprocess_node(&$variables) {
  if ($variables['display_submitted']) {

    // Getting the node creation timestamp from the node object.
    $date = $variables['node']->getCreatedTime();

    // Here you can use drupal's format_date() function, or some custom php date formatting.
    $variables['date'] = format_date($date, 'medium');
  }
}

```

In an earlier beta, before being able to alter the 'date' variable, I had to first pass the string through the create() method of the SafeString class like this:

```
$variables['date'] = \Drupal\Core\Render\SafeString::create('your dangerous new date string')

```

This might not be necessary anymore, concidering all the recent fuss around the safe string functions. Edit: I still need to do that in beta15.
> 1 votes

---
Tags: 8
---


title: Views attach block to a field

text:
# Question
Title: Views attach block to a field
I want to create a simple websites listing. I have created a content type named `Sites` and a taxonomy vocab named `Sites` to handle `Sites` nodes categorization. i.e every Site node (a content of type Sites) belongs to one term under `Sites` taxonomy vocab.

In the Views module, I have created a new Page view which has the path `/sites-cats-listing` and it shows `Taxonomy terms` of type `Sites`. The format is `Unformatted list` and it is only has one field `Taxonomy term: Name`

It renders a simple list of Taxonomy vocab Sites terms as expected. However, I want to list all of sites titles that belongs to each taxonomy term, so, I will get two levels list something like the following example:

```
-term1
--Site1
--Site2
--Site3
-term2
--Site4
--SiteA
etc...

```

Also I need to be able to rewrite the site's title field to make it linked directly to the destination website.

So, I need to know is there any way to attach a block to field which the block takes its contextual filter from the field value? Or is there any other workaround to complete this task? I have tried EVA but I could not able to find what I want to get.

# Answer
> 1 votes
this can be done with a bit of code in a tpl file or in a preprocess function.

Views has a function views\_embed\_view that you could use to embed the block into your field output.

```
print views_embed_view('views_name', 'display_id', $fieldvalue);

```

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

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


# Question
Title: Is it possible to implement an express checkout with Drupal commerce?
I'd like to setup a product, where it's just a one page form customers fill out, and a button labelled 'Pay now'.

I don't want a list of products or add to cart functionality or anything like that. Just a simple form and a button. A confirmation page and email is fine.

Is it possible to do this with Drupal Commerce?

# Answer
> 11 votes
Here is a nice tutorial on how to set up an EXPRESS CHECKOUT using Rules to bypass the add to cart stage.

I noticed there is a Commerce Express Checkout module, but I personally rather use rules to do it.

To display this on your home page, using the views module you'll need to create a **block view** of your product and put it in your home page.

---
Tags: commerce
---


# Question
Title: How to make group visible, but content hidden?
Using Organic Groups, I'd like to have three visibility states:

* Group and group content is visible to all, including anonymous users.
* Authenticated users can see the group, but not the content.

+ This would be the same thing as if everyone marked all the content as "private", but the group node was marked as "public."
* Only members of the group can see the group and the group content.

I tried OG Visibility, but it is no longer maintained and did not work. Or at least I couldn't figure out how to get it to work.

Any suggestions?

This is on Drupal 7.

# Answer
## Steps:

1. Go to Configuration \> Organic groups \> OG field settings
2. Under Bundle, select your group content type
3. Under Fields, select **Group visibility** and click Add field
4. Under Fields again, select **Group content visibility** and click Add field

Now these settings will add two fields into your group node which are Group visibility(Public or Private) and Group content visibility(Public or Private).

If I understood your comment requirements right, to achieve requirement:

* No. 1 - Set group visibility to **public** and content visibility to **public**
* No. 2 - Set group visibility to **public** and content visibility to **private**
* No. 3 - Set group visibility to **private** and content visibility to **private**
> 1 votes

---
Tags: organic-groups
---


# Question
Title: Updating / Pushing Changes to a Views from Local to Staging Server?
I'm working on a complex view which is from an existing view that currently just needs a bunch of fields and exposed filters added. I have it working on my local desktop and now I want to make these same changes on the Staging/Dev server. How can I update the server without doing everything from scratch?

# Answer
> 2 votes
If your working on an existing View and not a new one, you can just use the import View option on your server. Once you click into that page just check off the following:

**Replace an existing view if one exists with the same name**

It will update the existing view with what you have done on the local. On your local desktop just click on **export** on the view and copy and paste the code given to the server Views import page.

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


# Question
Title: Can't uninstall "Translation Language capabilities (tmgmt_language_combination)" dissabled ALL translation modules that might be dependant
I've tried drush, I disabled i18, ALL fields, multilingual, entity translation, l10n, everything about translation is disabled.

How can I completely get rid of this module, it's caused nothing but griefwith patches and bugs...

# Answer
> 0 votes
Had to go into Phpmyadmin browse system\>\> search tmgmt\_language\_combination

Click on edit and set status to 0

Then I had to manually delete the modules, refresh, repaste the modules, then refresh, and finally it showed up as red.

---
Tags: views, i18n-l10n, debugging
---


# Question
Title: Panels creates different pane number for any mini-panel inside a panel-node
It's kind of hard to explain this but I'll try in a pragmatic example:

You have a mini-panel in a block, somewhere around a **panel-node** (say node/1, your homepage):

* in the first panel-node (your homepage) this mini-panel has a CSS class named (For example): .pane-1
* in the second panel-node (your "about-us" page) this mini-panel has the CSS class .pane-6
* in the third panel-node (your "customers" page) this mini-panel has the CSS class .pane-11
* in the forth panel-node (your "contact-us" page) this mini-panel has the CSS class .pane 14

And so on and so forth, you get the idea.

I would like to know why Panels creates different pane classes for mini-panels that appear inside panel-nodes?... It makes the CSS development very very hard, forcing me to fill the Style.css file with different classes that all has the same properties. It is also problematic in the sense that we shouldn't and can't adding a class to the Style.CSS each time when creating panel-nodes...

What is your most efficient way to handle with this and to achieve working just with a single general class for this same pane?

Please help,

**Notes:**

---

* This problem doesn't occur in Nodes, it occurs only with Panel-nodes. In regular nodes it uses the same basic panel-pane class (for example **.pane-1**).
* I Could supply direct links for examples in my site.

---

Here is but a **very** gentle example for the inefficacy of this method Panels works with that forces filling of Style.css with repitative lines of code.

# Answer
I recommend using the pane configuration itself under **CSS Properties** to provide semantic class names for each pane. Create some sensible defaults for `.panel-pane` and extend it by adding classes. Eg `users` or `themed-list list-striped`. If necessary extend the concept using CSS ID's. But I think that's taking it a little far.

If that isn't enough then sometimes I create a custom panel layout with additional wrappers, classes and regions.
> 1 votes

# Answer
When we are creating block in drupal then the class are `"block block-block"` which is similar in case of all blocks, But drupal also provide a unique ID to block which differentiate the block and made us easy to write a common css(according to class) or unique css(according to id).

Same thing is happening in case of panel-nodes. Each pane is having a unique class that is something like `.pane-1, .pane-2` but there is also a common class `.panel-pane`. So u can use `.panel-pane`.

You can add css on `.panel-pane` which is followed by the outer region class.
> 1 votes

# Answer
The classes your are seeing .pane-1, .pane-2, etc are generated as a part of the default theme implementation for panels.

The method of how the pane is rendered is controlled by the **panels-pane.tpl.php** file, this file can be copied from the templates folder and pasted into your theme where you can override it.

This would allow you to change the classes that are printed for the pane. You could insert a general class that you could use to identify and alter these panes. Additionally, you could use a preprocess function in your template file. This would be: `THEME-NAME_preprocess_panels_pane`. This function takes a single variable (`$variables` or `$vars` depending on the theme developer), in this is an array of values that can be overridden. One of these is `$variables['classes']`, again you could insert your general purpose class here, and if you would like you could remove the incrementing class that you mentioned in your post.

Adding/altering the template or classes array in this fashion would be more productive as it would avert issues where content entry persons forget to add the general purpose class using the UX interface in Drupal.
> 1 votes

---
Tags: panels, theming
---


# Question
Title: Using Site A to authenticate users of Site B?
Is there a module that will pass the authentication request off to a second Drupal site, ideally to an out-of-the-box services endpoint?

There are some similar questions about login integration with other systems, but I couldn't find a Drupal-to-Drupal question.

# Answer
Have you checked out the Multisite Login module? This allows sharing logins across different domains, and I've had luck with it. They also have a Drupal 7 version available in dev.
> 2 votes

# Answer
Another option might be to set up whichever site you want to be responsible for authentication as an OpenID provider then on the other site enable OpenID (core module) for users to log in. You can set up the first site as an OpenID provider; I've never done this, but it should work in theory.
> 2 votes

# Answer
There are some option to achieve this job

1. Single Sign On Multiple Domain

> Single Sign On Multiple Domain module allows login to multiple drupal websites from a single website. If you have multiple drupal website installed at either on same server or other server, then you just need to login to one and it will login you to other websites as configured in the configuration page. For this you have to install this module in all website and do required settings.
>
> This module also allows to create account for user if user do not exist in other website. It also allows you to synchronize user role while creating account.

2. Multisite Login

> Multisite Login allows a user to login to all sites in a multisite configuration, even though the multisites do not share domain names.
>
> For example: politicker.com politickernj.com politickerny.com
> etc.
>
> NOTE: if you are using several sites on the same domain (ex. politicker.com, nj.politicker.com, ny.politicker.com, etc.), then you do not need this module. The multisite functionality in Drupal core has the ability to share logins for sites like these without additional modules.
>
> This module was designed to be an alternative to the singlesignon module but using a technique that does not block search engines from accessing your websites.

3. OpenID Provider

> This module implements an OpenID Provider in Drupal based on the OpenID Authentication 2.0 specification. It turns your Drupal site into an OpenID provider and allows users of your site to login to any other OpenID-enabled site using their Drupal password and identity.

**According of my experiences I suggest first try Single Sign On Multiple Domain module**
> 0 votes

---
Tags: users
---


# Question
Title: How to create a Content pane view of nodes with common taxonomy terms (creating relared contents))
I need to create a list of related contents to the current node with common taxonomy terms in Panels. I tried Related Articles - a block view of nodes with common taxonomy terms, it works well with blocks but I have problem with moving this idea to a `Content pane` display mode.

After following the above method I add `Term from node` relationships to get the following contexts in the Panels

and it is `Argument input` configuration of the Views pane

**The problem is this View is not available in the `Add content -> Views pane` section of the panels**. But if I remove `Argument input` configuration it will be available.

How can I create a View pane of the above block that works with panels?

# Answer
Found it, I should have select `Multiple terms from node` in *Relationships* to create *Contexts* not the `Term from node`
> 0 votes

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


# Question
Title: User profile fields translated but not showing up on user account modification and registration
I translated my user fields (select list) and they show up fine on:

* Exposed Filters
* In .po files and and translated
* User Display view mode

However, they don't show up translated for users.

Hard to explain...so let me try this way:

A user registers on the site in French, with fr prefixe.

When modifying his account, the drop downs are not shown in French, they are in English. However, even if English selections are selected, the display is indeed translated into French.

# Answer
After you translated the select list options of your (user) field, make sure that you ALSO change the **Format** of that selection list from ***Default*** to ***Default Tanslated***, which you can do via "Manage Display" (located at `/admin/config/people/accounts/display`). Similar to what is explained in this comment also ...

**Note**: same is true for using such fields within a content type.
> 0 votes

# Answer
I got this resolved.

A. Uninstalled EVERY TMGMT modules, deleted all instances of that module in phpmyadmin

B. Disabled ALL translation related modules

C. Enabled ONLY i18, not entity

Now it works, some entity modules and TMGMT had conflicts with i18 I guess.
> 0 votes

---
Tags: i18n-l10n
---


title: Adding cache manifest

text:
# Question
Title: Adding cache manifest
I need to add cache manifest file just like below in my static markup:

```
<html manifest="my.manifest">

```

Is there any module to add this or custom way?

# Answer
> 0 votes
Look at HTML5 tools it enables you to preprocess the HTML element for manifest insertion.

> HTML5 Tools is a module that allows Drupal sites to be built using HTML5 ... smartly.
>
> One of our goals is to provide as much support for HTML5 markup in a set of Tools provided by a module so that you can use this module with any HTML5 theme you'd like.

# Answer
> 0 votes
you can do by adding manifest value in html\_attributes in hook\_preprocess\_html as mentioned below:

```
function ThemeName_preprocess_html(&$variables) {
  $variables['html_attributes_array'] = array(
    'manifest' => 'example.appcache',
  );
}

```

---
Tags: 7
---


# Question
Title: Whenever new user registered, how to make them active based on some condition automatically
I have a cloud driven drupal site. In the site one content type exists named as people it has email field. The content in this content type is around 5000. Whenever new user registered I want to check user email with the people content type email field that is around 5000 content i want to check. If user email matches with any one email in people content type I want to make them active automatically. How to do this.? Can anyone give me suggestions. I tried with rules but its not happening. Can anyone suggest some custom php code for rules module

# Answer
> 0 votes
Using PHP on admin end is not recommended. If you are interested in custom module here are the pointers

1. Implement hook\_user\_presave : Invoked when a user is created or updated.
2. Make sure your code inside presave hook is conditional for new account created but not updated. You can use in\_new property of account object

if ($account-\>is\_new) {...}
3. Use Entity Field query to find a node with email id of current account being created
4. if you found a result then Set $edit\['status'\] as 1.

# Answer
> 0 votes
Try this steps in a custom module..

First load all your content Email values into an array. You can done it using db\_query or db\_select.Then in hook\_user\_insert check `$user->email` with array values. If match is found set `$user->status = 1`.

---
Tags: rules
---


title: How to trim an Aggregator RSS feed?

text:
# Question
Title: How to trim an Aggregator RSS feed?
Drupal core module Aggregator produces feed titles like:

One two three four five six seven, all good children go to heaven.

I want this displayed:

One two three four five six seven, all good children

How to get this done?

Someone hinted that the Smart Trim module offers this option but I can't get it working in combination with Aggregator and Panels. How to do this?

# Answer
I managed to do it using the Views module. I create a View of "Aggregator item" type.

In my view, I display each field I want to see, and for the "Aggregator:Title" field configuration, in the "Rewrite results" section, I checked "Trim this field to a maximum length". There are options to set the maximum length, to add or not an ellipsis (...), to add or not a "Read more" link... See the picture for more details (it refers to the "Aggregator:Body" field, but it works the same way).

Hope that helps,
> 1 votes

---
Tags: feeds
---


title: Update custom fields on hook_user_login

text:
# Question
Title: Update custom fields on hook_user_login
I have implemented hook\_user\_login(&$edit, $account) and some of custom fields from $account should be updated. I am doing this with user\_save(). These changes are not visible in Simpletest. I have tried user\_load() in Simpletest before login and after, no changes. The Values are being saved to the db but are not visible in Simpletest. Any Idea?

# Answer
Simpletest assertions are working on user created in Simpletest with $this-\>drupalCreateUser().
> 0 votes

---
Tags: testing
---


title: sending mail for select list field

text:
# Question
Title: sending mail for select list field
I have created a content type in which I have a field as *field\_result* of type *select list* with options as;

1. pass
2. fail
3. hold
4. postpone

When user selects the *pass* from select list and update or create a content, email should be sent to all admin users and other users stating that result is pass. Following same thing to other select list options ie for fail,hold and postpone. So what exactly I need to do using rules?

Here event can be both like; user can save the new content also can update using this select list field. Whenever user selects, it should send an email according to corresponding select list option.

Can anyone help me please? I will be thankful to you. My problem is similar to sending mail after checking a selected list in field but it didn't work for me.

# Answer
> 1 votes
Following rule should help you

```
{ "rules_send_email" : {
    "LABEL" : "Send Email After Save",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--send_email" : { "bundle" : "send_email" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "Subject Test",
          "message" : "submittted value for Result field is [node:field-result]"
        }
      }
    ]
  }
}

```

The above rule will trigger email when a new content will be added For update also clone this rule and change the event to "After updating existing content"

---
Tags: rules, emails
---


title: Apply condition on particular template

text:
# Question
Title: Apply condition on particular template
I have a template name `page--catalogue.tpl.php`, I need to add style sheet only for this template. Below is my snippet in my `html.tpl.php` which only adds class to a particular node whereas I need to add to a whole template. Is there any way?

```
<?php
if (strtolower ($_GET['q']) == "node/287")
{
?>
<link rel="stylesheet" type="text/css" href="sites/default/files/engine1/style.css" />
<?php
}
?>

```

# Answer
> 2 votes
**OPTION 1:**

If it's a small amount of CSS, maybe considering making your CSS selectors based on the node and including the css in your theme's CSS? Drupal 7 provides the body.page-node-NODEID selector.

**OPTION 2:**

You could have a look at the Code per Node module. It is also featured in this blog post.

> Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.

**OPTION 3:**

For adding css file to specific content type, you may use this snippet;

```
function MYTHEME_preprocess_node(&$variables) {
  if(!empty($variables['node'])) {
    if($variables['node']->type == 'my_custom_content_type')
      {
       drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
      }
  }

}

```

**OPTION 4:**

If you want to add css to specific node then you may use this;

```
MYTHEME_preprocess_node(&$variables) {
  if ($variables['node']->nid == 3) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/foo.css");
   }
}

```

# Answer
> 0 votes
Yyou can use drupal\_add\_css()

in your page--catalogue.tpl.php

# Answer
> 0 votes
I think you need to use node class where you can set you own class to particular node using that class hierarchy you can apply your css. Which would convenient for further use.

---
Tags: 7
---


# Question
Title: Why do images rendered with image_style_url disappear on iPhone?
I use "image\_style\_url" to render images in node template. Everything works fine on web browsers. However, these images disappear on iPhone.

Here is my code:

```
<div class="porDetCarousel">
    <div class="carousel-content">
        <?php
            foreach($node->field_project_pics[LANGUAGE_NONE] as $project_pics){
        ?>
                <img class="carousel-item" src="<?php print image_style_url('eve_project_page_detail__700x476_', $project_pics['uri']);?>" alt="">
        <?php
            }
        ?>
    </div>
</div>

```

Link: http://tvphong.x10host.com/node/62

Any suggestions?

# Answer
The problem is with jcarousel. The images are rendered fine, but width and height is set to 0 on mobile.

You should be able to set widht and height in CSS.

See possible solution here: https://www.drupal.org/node/576016#comment-6041834

Attached is iphone rendering:
> 1 votes

---
Tags: 7, media
---


title: styling submit form button for mobile

text:
# Question
Title: styling submit form button for mobile
I have styling done for the submit form buttons on web, and when i maually resize my browser, the stying stays the same in smaller widths. But, when i videw on my Iphone 6, the stying looks like default drupal button.

Is there something is the base theme Bartik that is causing an override on true mobile?

I'm using Drupal 7 and only have 2 themes installed, My custome theme, and Seven for admin use.

```
.button,
input[type="button"],
input[type="submit"] {
  padding: 7px 14px;
  display: inline-block;
  border: 0;
  font-weight: 500;
  outline: none;
  font-size: 14px;
  cursor: pointer;
  width: auto;
  -webkit-transition: all 0.2s ease-in-out;
  -moz-transition: all 0.2s ease-in-out;
  -o-transition: all 0.2s ease-in-out;
  -ms-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
  border-radius: 3px;
  box-shadow: inset 0px -1px 0px 0px rgba(0,0,0, 0.1);
}

.button i {
  margin: 0 2px 0 0;
}

.button.gray {
  color: #fff;
  background: #aaa;
}

.button.gray:hover {
  background: #a0a0a0;
}

.button.light {
  color:#999;
  background:#f2f2f2;
  box-shadow: inset 0px -1px 0px 0px rgba(0,0,0, 0.05);
}

.button.light:hover {
  color: #fff;
  background: #a0a0a0;
  box-shadow: inset 0px -1px 0px 0px rgba(0,0,0, 0.1);
}

.button.color {
  color:#fff; background: #a0a0a0;
}

.button.color:hover {
  background: #a0a0a0;
}

/* Input Button */
input[type="button"],
input[type="submit"],
input[type="button"]:focus,
input[type="submit"]:focus {
  color:#fff;
  background: #a0a0a0;
  padding: 8px 14px;
  border: none !important;
}

input[type="button"],
input[type="submit"] {
  /*float: left;*/
}

input[type="button"]:hover,
input[type="submit"]:hover {
  background: #a0a0a0;
}

```

My Responsive Media Queries are in two sections

```
/* Standard 1180 (devices and browsers) */
@media only screen and (min-width: 1200px){
  .caption.text { margin-left: 0 !important; }
  .caption h2,
  .caption h3,
  .caption p {margin:0;}
}

/* Smaller than standard 1180 (devices and browsers) */
@media only screen and (min-width: 959px) and (max-width: 1199px) {
  .caption.text { margin-left: 50px !important; }
  .caption h2,
  .caption h3,
  .caption p { margin:0; }

  #navigation ul > li > a { padding-left: 15px; padding-right: 15px; }

  ol li ol.childlist .comment-des {
    float:right;
    width:78%;
  }

  .comment-des {
    float:right;
    width: 81%;
  }

  .add-comment textarea,
  #contact textarea { min-width: 97%; }

  .flickr-widget-blog a {
    width: 57px;
    height: 57px;
  }

  #not-found { margin: 50px 0 75px 0; }

  #not-found h2 {
    font-size: 210px;
    line-height: 210px;
  }

  #not-found p {
    font-size: 28px;
    line-height: 36px;
  }

  #not-found i {
    font-size: 200px;
    top: -5px;
  }

}

/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {
  .caption.text { margin-left: 30px !important; }
  .caption h2 { margin-top: -8px;}
  .caption p { margin-top: 8px;}
  .img-1 {margin-left: 0 !important;}

  #navigation ul > li > a { padding-left: 14px; padding-right: 14px; }

  #search-form {
    position: absolute;
    right:0;
  }

  .search-container { margin-left: 50px !important; }
  .the-icons { font-size: 13px; }

  ol li ol.childlist .comment-des {
    float:right;
    width:71%;
  }
  .comment-des {
    float:right;
    width: 75%;
  }

  .add-comment textarea,
  #contact textarea { min-width: 96%; }

  .flickr-widget-blog a {
    width: 69px;
    height: 69px;
  }

  #not-found {margin: 35px 0 60px 0;}

  #not-found h2 {
    font-size: 160px;
    line-height: 160px;
  }

  #not-found i {
    font-size: 155px;
    top: -4px;
  }

  #not-found p {
    font-size: 22px;
    line-height: 32px;
  }
    #footer, #footer-bottom {text-align: center;}
  .get-in-touch li i, .get-in-touch li p strong {float: none}
  .get-in-touch p {margin: 0;}

}

/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {

  .caption.text {margin-left: 30px !important;}
  .caption h2 {font-size: 32px; margin-top: 10px;}
  .caption h3 {font-size: 20px; margin-top: 15px;}
  .caption p {display: none;}
  .img-1 {margin-left: 0 !important;}

  .fullwidthbanner-container { top: 0; }

  .showbiz.our-clients ul li img { margin: 0 auto; }

  #breadcrumbs ul {
    float: left;
    margin-top: 0;
    padding: 0 0 24px 0;
  }

  #titlebar {
    top: 0;
    margin-bottom: 40px;
  }

  #titlebar h2 {
    margin-top: 3px;
  }

  #googlemaps { padding-bottom: 40%; }
  .plan-features { margin-bottom: 25px; }
  .medium .post-img { margin-bottom: 20px; }

  #filters { margin: 10px 0 30px 0; }
  #filters a { margin: 0 5px 5px 0; }
  .line.filters { display: none; }

  .line.showing {
    display: inline-block;
    margin: -11px 0 0 0;
    z-index: 5;
  }

  .social-icons-footer {
    margin-top: 5px;
    float: left;
  }

  #footer { padding-top: 10px; }
  #footer h3, #footer h2 { margin-top: 30px; }

  .featured-boxes { margin: 40px 0 5px 0; }
  .featured-box { margin: 0 0 25px 0; }

  a.button.launch { margin: 0 0 30px 0; }
  #related-work figure {margin-bottom: 20px;}

  .search-form {
    margin-top: 40px;
    padding-top: 40px;
    border-top: 1px solid #f0f0f0;
  }

  #contact input[type="submit"] {
    margin: 0 0 30px 0;
  }

  #not-found {margin: 15px 0 25px 0;}

  #not-found h2 {
    font-size: 110px;
    line-height: 120px;
  }

  #not-found i {
    font-size: 105px;
    top: -2px;
  }

  #not-found p {
    font-size: 22px;
    line-height: 32px;
  }

  #footer, #footer-bottom {text-align: center;}
  .get-in-touch li i, .get-in-touch li p strong {float: none}
  .get-in-touch p {margin: 0;}

}

/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {

  ol li ol.childlist .comment-des {
    float:right;
    width:63%;
  }

  .comment-des {
    float:right;
    width: 68%;
  }

  .add-comment textarea,
  #contact textarea { min-width: 95%; }

  .flickr-widget-blog a {
    width: 87px;
    height: 87px;
  }

  #footer, #footer-bottom {text-align: center;}
  .get-in-touch li i, .get-in-touch li p strong {float: none}
  .get-in-touch p {margin: 0;}

}

/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {

  .caption h2 {font-size: 32px; margin-top: 0;}
  .caption h3 {font-size: 18px; margin-top: 10px;}
  .caption p {display: none}

  ol li ol.childlist .comment-des {
    float:right;
    width:49%;
  }

  .comment-des {
    float:right;
    width: 56%;
  }

  .add-comment textarea,
  #contact textarea { width: 90%; }

  .flickr-widget-blog a {
    width: 82px;
    height: 82px;
  }

  .dropcap {font-size: 52px;}

  #footer, #footer-bottom {text-align: center;}
  .get-in-touch li i, .get-in-touch li p strong {float: none}
  .get-in-touch p {margin: 0;}
}

```

The Second Media Queries CSS is only for layout purposes and shouldn't effect anything but column widths.

Picture 1 is from Firefox on my desktop

Picture 2 is from my iphone 6 Safari

My Page code shows this for the viewport code: meta name="viewport" content="width=device-width, initial-scale=1"

My PHP is not rendering the final maximum-scale=1

Here is my PHP that is in my template.php file"

```
  function your_theme_name_preprocess_html(&$vars) {
$viewport = array(
  '#tag' => 'meta',
  '#attributes' => array(
    'name' => 'viewport',
    'content' => 'width=device-width, initial-scale=1, maximum-scale=1',
  ),
);

drupal_add_html_head($viewport, 'viewport');
}

```

# Answer
> 0 votes
After a lot of searching with different terms i found the answer. Simple but effective.

-webkit-appearance: none;

Simple CSS value that stops any strange webkit CSS from rendering, and will then use the sites CSS as normal.

---
Tags: forms, theming
---


# Question
Title: Letting anonymous users vote in a poll when using Varnish
I have a poll on my front page that I want users to be able to vote on, but anonymous users always just see the results and are never able to vote. I've been trying just about everything I can think of to fix this and nothing works.

I'll start by saying that I can access my web server directly through an alternate port. When I do this I see the poll when I'm not logged in; so I know that anonymous users can vote.

I've tried using ESI and the Drupal 7 ESI module. I got it set up and working so that the poll block is being loaded via an ESI tag (obviously accessing it directly through the alternate port stopped working when I did this since browsers don't parse ESI tags). No dice.

I tried using the AJAX Blocks module, I set a delay on loading the block just so I could visibly make sure the block was loading via AJAX, it was and it was still just displaying the results.

I tried voting from the same IP address using the alternate port, thinking that since someone has voted going through Varnish before the server wont allow it again, but I can vote twice from the same IP address through the alternate port.

I tried logging into the server via ssh and using Links to view the site, thinking that maybe it's the local IP address that is making the web server serve the results page for some other reason, but when I use Links I can see the voting form.

Clearly there's something that's causing Drupal to serve the results instead of the form when Varnish requests the page, but what is it?!?

# Answer
https://drupal.org/project/pollanon This lets anonymous users vote in a poll more than once, and here's an article on using ESI to allow parts of your page to remain cached while other parts remain dynamic.

```
Accepting votes from anonymous users on Drupal polls is complicated when you use caching. By using Edge Side Includes (ESI), you can dynamically load some parts of a Drupal page while caching the rest of it. The addition of the Poll Enhancements module allows multiple anonymous users to vote on polls by using cookies to track who has voted.

Edge Side Includes integration
The ESI module includes two Varnish VCL files (located in the docs directory of the module:

docs/esi_blocks.vcl - custom sub-routines to handle ESI-block integration.
Copy this file to the Varnish config directory, /usr/local/etc/varnish/
docs/default.vcl - example code showing how to include the ESI blocks VCL in your Varnish config. Portions of this should be added to appropriate places your Varnish config file. We'll do it by creating a copy, /usr/local/etc/varnish/default-esi.vcl, that has the portions we want:
include "/usr/local/etc/varnish/esi_blocks.vcl";
sub vcl_recv {
  call esi_block__recv;
}

sub vcl_hash {
  call esi_block__hash;
}

sub vcl_fetch {
  # don't ESI anything with a 3/4 letter extension
  # (e.g. don't try to ESI images, css, etc).
  if (! req.url ~ "\..{3,4}$") {
    esi;
  }

  call esi_block__fetch;
}

Then, edit /usr/local/etc/varnish/drupal.vcl and add a line near the beginning:

include "/usr/local/etc/varnish/default-esi.vcl";
Restart the Varnishcache:

svc -t /service/varnish
With the module enabled in your Drupal site, block configuration pages now have an ESI Settings section with two options: Enable ESI, and a TTL value.

Poll Enhancements
Installing this module allows anonymous users to vote on polls. By using cookies to track who has voted, multiple users who are behind a firewall will be able vote on polls. There's a threshold setting for how many votes from a single IP in a time period. The module also provides a Use AJAH option - I needed to enable this to have the ESI-enabled Poll block work properly.

Configure Varnish to ignore the poll cookie ( pa-[nid] ) by editing the vcl_recv section of /usr/local/etc/varnish/drupal.vcl and inserting a line to remove the cookie:

// Remove pollanon cookies.
set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(pa(.*))=[^;]*", "");
Restart Varnish:

svc -t /service/varnish

```

Source: http://www.productionmonkeys.net/guides/drupal/performance/pressflow/varnish/varnishing-polls
> 1 votes

# Answer
I know this is old but it ranks well in Google so others may still stumble upon this.

If you don't want to use blocks (in my case we have hundreds of polls, a block for each has overhead) then you can simply not cache the page that the poll is on;

```
/**
 * Implements hook_node_view().
 */
function your_module_node_view($node, $view_mode, $langcode) {
  // Don't cache pages with polls. This needs to be changed to an ESI solution.
  if ($node->type == 'poll') {
    if (in_array($view_mode, array('full', 'default', 'embedded'))) {
      drupal_page_is_cacheable(FALSE);
    }
  }
}

```

This just avoids the page cache. Performance on our production server is still good, the polls make up only a small part of the content so the other pages are still cached with Varnish.

I have a comment in there for ESI - we're going to investigate using ESI on a Paragraph or a Field Group as thats what we use.
> 0 votes

# Answer
I stumbled upon this question because I wanted to see how well my new (sort of.. it has been a sandbox project for ages) contrib module ranks for a search on this issue. This is the top result, so I'll link to the module here: http://drupal.org/project/cached\_poll. It addresses exactly this problem.

A benefit of the module over Christian's solution includes that pages with Polls still are cached (depending on where exactly you show the Poll, this may be an important consideration; you don't really want your frontpage excluded from caching just because it shows a poll). The module prevents the version of the poll showing results getting cached, but it still allows the non-voted version (i.e. the voting form) into the cache.

ESI is something that I researched a long time ago. At least back then, it didn't make the cut and was too complicated to set up and get working reliably with Drupal. It also led directly to the development of this module.
> 0 votes

---
Tags: caching, proxies
---


# Question
Title: How to log custom entries in 'Recent log entries'?
I am developing a custom module, and I'd like to log my own log entries with their own ***type***, so that they can be accessed and filtered at `admin/reports/dblog`.

But I can't find the appropiate function or script. Any suggestions?

# Answer
> 8 votes
`watchdog()` is what you are looking for. See the description of its parameters, in particular these:

> `$type`: The category to which this message belongs. Can be any string, but the general practice is to use the name of the module calling `watchdog()`. The `$type` parameter is limited to 16 characters; anything longer is truncated.
>
> `$severity`: The severity of the message; one of the following values as defined in RFC 3164:
>
> * `WATCHDOG_EMERGENCY`: Emergency, system is unusable.
> * `WATCHDOG_ALERT`: Alert, action must be taken immediately.
> * `WATCHDOG_CRITICAL`: Critical conditions.
> * `WATCHDOG_ERROR`: Error conditions.
> * `WATCHDOG_WARNING`: Warning conditions.
> * `WATCHDOG_NOTICE`: (default) Normal but significant conditions.
> * `WATCHDOG_INFO`: Informational messages.
> * `WATCHDOG_DEBUG`: Debug-level messages.
>
> `$link`: A link to associate with the message.

# Answer
> 0 votes
A possibly alternative for logging custom log entries, is to use the Rules module:

* The Drupal 6 version of Rules has the ability to create a watchdog entry.
* This functionality is not (yet) present in an official D7 release, but there is a patch available to do so in D7 also.

For D7, you can also use the Better Watchdog UI module, which comes with Rules Watchdog Integration. Some more details about this module (from its project page):

> Upgrade watchdog entries to entities and replace default database log listing with a view, which grants advanced filtering options and filtered deletion as a bulk operation.
>
> The module creates an entity wrapper around database log entries and enhances the watchdog listing by replacing it with a view. Beside type and severity, additional filter options were introduced such as date and author.
>
> The possibility to change the number of listed entries per page has also been added.
>
> Database clearing has also been customized, now admins can clear only the filtered entries, if needed.
>
> The provided view is accessible to the admins and can be fully customized as any view, to fit one's needs.

---
Tags: log-messages
---


title: Show content type form to block

text:
# Question
Title: Show content type form to block
I've created one content type named Newsletter. And I want to display that content type form to block. I've tried with this code but failure. Your suggestions will be appreciated.

```
$my_module_form = drupal_get_form('blog-node-form');
$my_module_form = drupal_render($my_module_form);

```

# Answer
You can also use Advance form block which supports ajax submission and multiple form with same content type.

**FORM BLOCK:**

1. **Create** any number of blocks with a particular **node edit form**.
2. **Create** any number of blocks with a particular **node add form** of a content type.
3. **Create** as **many blocks** as you like of **each kind**.
4. From the content type **choose which fields to display on a per block basis**.However required fields will be automatically displayed.
5. All forms will be **saved through ajax**. So **multiple node forms** can be independently placed on a single page and **worked with simultaneously**.
> 0 votes

# Answer
Using contrib modules will certainly help for this. There are at least two I can think of:

To answer your question, however, you need to instantiate a new (or existing) node object to set as your `form_state` (Assuming the machine readable name of your content type is "newsletter").

```
global $user;
$node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'newsletter', 'language' => LANGUAGE_NONE);
$form_state['build_info']['args'] = array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('newsletter_node_form', $form_state);

```

If you want the form to edit an existing node, the you can replace the `$node = (object)` part with a `node_load([nid])` function.
> 1 votes

# Answer
Try Form Block module. It allows to embed a contact/registration/node form as block.

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.
> 0 votes

---
Tags: blocks
---


# Question
Title: How do I get rid of the node title on a specific view mode?
I'm using Drupal 7 with *Omega subtheme* and Display Suite module.

I have a content type and the nodes are displayed as default (Full Content). But I have two or three nodes of this content type which must be displayed in slightly different way (just a few fields hidden, some others perhaps).

So using Display Suite I've created a new *view mode* for these specific nodes and on the *content edit* page I've selected new *view mode* rather than *Default*.

Now the problem with this new mode is that node's title is rendered twice, once as the *page title* and second as the *node title*. This is different from the *Default/Full Content* mode, which seems to just have a *page title* and no node title.

How to get a rid of the *node title* on the new view mode so it's the same as the way *Default/Full Content* displays are shown (without using Views)?

Maybe there's some way to clone the *Full Content* view mode and then just edit that clone. So the new *view mode* also only shows a *page title* not the node title?

# Answer
Since already using Display Suite you can enable Extras module in orde to hide page title

DS config
admin/structure/ds/extras

Tab "Other"
Check "Page title options"

Node Manage Display
admin/structure/types/manage/article/display/full

Tab "Layout for article full"
select Hide "Page title"
> 11 votes

# Answer
sounds to me like a theming error. you probably have forgotten to check in the `node.tpl.php` if the node is being viewed or not.
regularly there is no title set

```
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
    <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
  </h2>
<?php endif; ?>

```

you can check for the $view\_mode in the node template file and depending on that, set the titel (or dont set it). dont forget, that on the full view\_mode, the page variable is set to true.
> 2 votes

# Answer
If anybody wants to solve this problem programmatically from template.php or a custom module:

```
/**
 * Implements template/hook_preprocess_node().
 */
function MYTEMPLATE/MYMODULE_preprocess_node(&$vars) {

  if ($vars['view_mode'] != 'full') {

    $vars['title'] = FALSE; // hides second title
  }
}

```
> 1 votes

---
Tags: 7, display-suite, entities
---


# Question
Title: How to create a custom header with print module and tcpdf
I'm using print module to generate pdf files of the articles. I'm using tcpdf library, I couldn't find the header options in the settings page. I can see options for Logo and footer, but no header options.

When I tried to get the pdf file. In the header section, there appears logo in the left corner and title of the article on the right corner. I was looking for the header settings in such a way to fix header with an image and nothing else.

I tried to google it but ended with empty hands. This article, suggests to create sub-class of tcpdf - I don't know where to create, I mean where to integrate the code??. I also found `views PDF` module to set header - I don't think it will be a better option.

Is there any better way to set custom header (as image).

# Answer
Since there's not an option for that, you'll need to work on the code, and you have two different options there.

First, work on your theme's print.css file and add something like

```
.article-name{display:none}

```

If it has none, add on to its .info file with

```
stylesheets[print][] = 'css/print.css';

```

Second, if you need "bigger" changes not achievable trough css (or just need too many), copy the print template from the print module to your theme template's folder and edit at wish.

---

consider however that the cas changes will be applied to every page you will print, and the template changes to every page printed trough the print module, both pdf and all the others.
> 0 votes

# Answer
```
<?php

class PrintTCPDF_No_Headers extends PrintTCPDF {
  public function Header() {
    if ($this->page > 1){
      return;
    }
    parent::Header();
  }
}

```

you try out this more detials for idea
> 0 votes

---
Tags: files
---


# Question
Title: Option for auto Masspay in ubercart marketplace
Is there any auto Masspay option in ubercart marketplace module. Now working with manual payment method.

# Answer
> 0 votes
Automatic mass payment (with paypal only)

Explanation: When a user makes an order and pays with PayPal or does ExpressCheckout with PayPal and the system redirects him to "checkout/complete" the added code starts to work and makes masspay for all the orders done before that one. (Newest order not included)

**Another Method :**

* Go to Test Accounts, select "Create Account: Preconfigured", Choose account type "Seller", use given data
* Go to API Credentials, copy API Username, Password, and Signature to Drupal Enable uc\_paypal module
* Setup PayPal Website Payment Pro settings at: "Store Administration
> > Configuration \>\> Payment Settings \>\> Edit \>\> Payment Gateways" or directly via /admin/store/settings/payment/edit/gateways
* Enable this payment gateway for use API server: Sandbox
* Now enter your API credentials
* If IPN is setup you may now make payments at "Store administration \>\> reports \>\> Seller reports"

---
Tags: ubercart
---


# Question
Title: How to call function in mail which is configured using Rules in drupal
I want to call function in mail body. I am using Rules modules for sending mail on some event triggers.

anyone have idea, how can i achieve this?

# Answer
You can alter the mail content using hook\_mail\_alter

> hook\_mail\_alter() allows modification of email messages created and sent with drupal\_mail(). Usage examples include adding and/or changing message text, message fields, and message headers.
> 1 votes

---
Tags: rules, emails, tokens
---


# Question
Title: preprocess_field() not working - what am I doing wrong?
I am trying to alter how a field is displayed with `hook_preprocess_field()`. This is the code I added to the theme's template.php.

```
function creative_responsive_theme_preprocess_field(&$vars) {
  $element = &$vars['element'];
  if ($element['#field_name'] == 'field_myfield') {
    $element['#items'][0]=[];
    $element['#items'][0]['value'] = 'replaced value';
    $element['#items'][0]['format'] = 'filtered_html';
    $element['#items'][0]['safe_value'] ='';
    $element['#items'][0]['#markup'] = 'replaced value';
  }
}

```

The code is executed, but the page does not show what I added. The field is being displayed as usual. I am using the Display Suite module.

I am not sure if that effects anything, but searching online, I see no indication that above should not work. I added the #markup part because I read that is truly what one has to do.

Do you have ideas?

# Answer
I think it was the # in front of items that was messing things up. I have this working now.

```
function creative_responsive_theme_preprocess_field(&$variables) {
  if (user_is_logged_in()) {
    return $variables;
  }
  if (($variables['element']['#field_name'] == 'field_audio_fast_') OR ($variables['element']['#field_name'] == 'field_audio_slow_')) {
    $variables['items'][0]=[];
    $variables['items'][0]['value'] = '<a href='.'"/user/register?destination=[path]"> <img src="/images/play.gif"></a>';
    $variables['items'][0]['format'] = 'full_html';
    $variables['items'][0]['safe_value'] ='';
    $variables['items'][0]['#markup'] = '<a href='.'"/user/register?destination=[path]"> <img src="/images/play.gif"></a>';
    return $variables;
  }
}

```

At first, `$variables['items'][0]=[];` was producing a bunch of warnings about invalid arguments to core functions regarding children and parents and rendering. Then I cleared the cache. The thing is, the field I am replacing is an audio file field. So I think there must be a cleaner way to do this than above.
> 1 votes

---
Tags: entities, theming
---


title: Show View's title

text:
# Question
Title: Show View's title
Block - Move the view to content. It shows it's title. The Insert view module doesn't show any view's title. I need insert view module as well as it can display title. May I know how to solve this?

Many Thanks

# Answer
To remove View Title, you have to edit the `Title` field of the view and provide `<none>` or leave it blank.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to remove mymodule configurations on uninstall
I have created a custom module and created a yml file to create a menu

```
system.menu.custom_menu.yml

id: custom_menu
label: 'Custom menu'
description: 'Custom menu.'
langcode: en
locked: true
dependencies:
  - mymod

```

When I installed my module it creates the the custom menu. But then When I uninstall the module and try to install it again I get the following exception

```
exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects (system.menu.custom_menu) provided by mymod already exist in active configuration' in
/var/www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70

```

What I am doing wrong? Is there any way to remove my configuration (system.menu.custom\_menu) from the configurations when I uninstall my module?

# Answer
> 46 votes
The easiest way is to ensure that the config has a dependency on your module.

```
dependencies:
  module:
    - yourmodule
  enforced:
    module:
      - yourmodule

```

Then Drupal will automatically remove that configuration and also warn in the UI that it will be removed.

Note that this only works for new installations, it won't fix existing ones.

An alternative is to put the configuration in config/optional instead of config/install, then it will only be created if it doesn't exist yet and the dependencies are met.

---
Tags: 8, configuration
---


title: How can I cache pages indefinitely?

text:
# Question
Title: How can I cache pages indefinitely?
I'm upgrading a small site currently in Drupal 6 to Drupal 8, it's for a non-profit and doesn't receive all that much traffic. It's a relatively static site, content will be added regularly, but certainly not every day. While the amount of traffic is easily handled even on shared hosting, I'd like to keep the page loading times low. I used Boost for that on Drupal 6, but now with Drupal 8 I want to use the internal page cache.

From what I understand, Drupal 8 should be able to automatically invalidate the cache when nodes are edited. So what I'd like to do is to cache all pages of my site indefinitely until the data behind them actually changed. But the cache dialog on the performance admin page only allows a page cache maximum age of 1 day.

Is there a way to configure a stock Drupal 8 to cache pages forever? The cache should only be invalidated if nodes are edited and the page actually changes content. Ideally I'd like to automatically pre-warm the cache as well.

# Answer
The setting on the performance page, unlike D6/7, does **not** affect the page cache module at all. The page\_cache module always caches indefinitely, you can not configure it otherwise. Invalidation happens through cache tags, as you said.

The setting that you can see only affects external caching through the HTTP Cache-Control header, for example Varnish and in browsers. There are ways to invalidate caches in varnish using cache tags, but there is none to invalidate pages that are cached client-side in browsers, so I would recommend to not set that value too high.
> 3 votes

---
Tags: 8, caching
---


# Question
Title: How to set views configurations settings on custom module install?
I have a custom module. On its installation I want to set some configuration settings of views like:

```
ui.show.master_display
ui.show.sql_query.enabled

```

to `TRUE`.

For this I have added a file `mymod_views.settings.yml` to `modules/mymod/config/install/`. the content of the file is:

```
ui:
  show:
    additional_queries: true
    advanced_column: true
    master_display: true
    performance_statistics: true
    preview_information: true
    sql_query:
      enabled: true
      where: above
    display_embed: false
  always_live_preview: false

```

But on the installation of the module I am getting the following exception.

```
exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects (mymod_views.settings) provided by mymod already
exist in active configuration' in
/var/www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70

```

Can someone tells me how I will set these options through my module?

# Answer
It is not possible to change or override configuration from other modules like that, you can only provide new, not yet existing configuration in `config/install`. The only exception to that rule are install profiles.

Instead, you need to implement `hook_install()` and alter the configuration there. See `locale_install()` for example:

```
\Drupal::configFactory()
  ->getEditable('views_ui.settings')
  ->set('ui.show.master_display', TRUE)
  ->save();

```
> 0 votes

---
Tags: views, 8, configuration
---


title: sync drupal users to open ldap

text:
# Question
Title: sync drupal users to open ldap
We can find many discutions on how to sync ldap to drupal, or use ldap to auth drupal users, but my goal is totally different :

My goal is this : Use drupal to manage user accounts (add/edit/delete users), then use LDAP to share drupal users with an other website (redmine)

So the idea is that drupal send users to LDAP then redmine website use LDAP for login.

Drupal users don't have to ssh login into my server of course...

I've found no doc, no tuto on how to setup drupal LDAP module to match with my use case. So here i am.

Considering : I have installed openldap on my debian server, and also ldap authentification module in drupal. More over i have setted up drupal and can querry my ldap server from drupal admin panel.

**Questions :**

1) Is there a doc or tuto somewhere explaining how to sync drupal users to LDAP?

if no

By default posix user template contains useless attributes for me, like homedirectory or loginshell

2) So, do i have to define LDAP templates to match with drupal?

3) i've made some tests to sync users, but drupal display no info, what is going wrong? how to debug?

# Answer
> 0 votes
after one day, i finnaly figured out how to :)

I've first found some help on those both discutions :

a)https://www.drupal.org/node/1920682 (see kenorb answer)

b)Create a new user in LDAP, not wherever Drupal normally creates it (see kernorb answer again)

**HOW TO :**

1) from LDAP server create manually an inetOrgPerson account (in phpldapadmin it is called a "Courier Mail Account") , let's call it 'myuser'

next steps will be done in drupal admin=\>configuration=\>people=\>LDAP configuration

2) setup LDAP server, and test it (see links above for further details)

3) again in server test page, set myuser into 'Testing Drupal Username' field. Start the test, then copy somewhere 'testing\_drupal\_user\_dn' value from test result.

4) now 2 things must be done :

a) choose a user schema, inetOrgPerson is a good schema for drupal as it contains email, username, and password fields

b) find witch fields are requiered by your LDAP server for this schema

so search on google \[NameOfTheSchema\] \[NameOfYourLdapServer\] attributes

(e.g : "inetorgperson openldap attributes")

then note witch fields are marked as requiered.

for example i found this : http://www.openldap.org/lists/openldap-software/200001/msg00079.html

there we see that

objectClass, sn, and cn are marked as required

To resume, you have now noted somewhere: the dn (step 3) and the required field (this step)

c) now, how to set objectclass? get back to phpldapadmin, display 'myuser' account that you have manually created, then click on export =\>LDIF

as example here my result :

```
# Entry 1: uid=myuser,ou=drupal,dc=mydomain,dc=lan
dn: uid=test1,ou=drupal,dc=mydomain,dc=lan
cn: myuser
description: my description
mail: email@email.com
objectclass: inetOrgPerson
objectclass: top
sn: myuser
uid: myuser
userpassword: mypassword

```

it is important to respect the order of objectclass fields. In my case i'll have to set in drupal : UserToken =\> inetOrgPerson=\> \[objectclass:0\] UserToken =\> top =\> \[objectclass:1\]

5) go to admin=\>configuration =\> LDAP configuration =\> user then "Basic Provisioning to LDAP Settings" section

Check all checkbox into "LDAP Entry Provisioning Events "

Now fill the table bellow

For each line created, you'll have to check both "ON LDAP ENTRY CREATION" and "ON SYNC TO LDAP ENTRY" collumns

a) You MUST have a line with \[dn\] as target, this is here that you use the dn retreived in step 3.

Example : i had this : testing\_drupal\_user\_dn = uid=myuser,ou=drupal,dc=mydomain,dc=lan

so i add this line :

```
--user tokens-- => uid=[property.name],ou=drupal,dc=mydomain,dc=lan => [dn]

```

b) You MUST set objectclass lines . If we refere to my result in step 4) c) , i have to add 2 lines :

```
--user tokens-- => inetOrgPerson => [objectclass:0]
--user tokens-- => top => [objectclass:1]

```

c) you MUST add as many lines as there is required fields in the schema. If we refere to my case step 4) b) i have to setup objectclass , sn and cn, so i have to add two more lines :

Property:UserName =\> =\> \[cn\] Property:UserName =\> =\> \[sn\]

**To Resume :**

## 3 steps to follow :

* Setup connection to LDAP server then test it
* Give a correct path to user entries (path is called DN with lpda)
* Choose a user schema (inetOrgPerson is a good one) and fill all fields required by this schema (this is specific of your LDAP server so refere to its doc)

**How to test :**

in admin=\>configuration=\>people=\>LDAP configuration=\>Settings , check " Enabled Detailed LDAP Watchdog logging.", then edit a user in drupal to trigger the sync with LDAP (assuming you followed my howto). when you save an user in drupal, you'll see an LDAP error message if something goes wrong.

---
Tags: authentication-authorization
---


title: How to use Drupal.behaviors?

text:
# Question
Title: How to use Drupal.behaviors?
I am trying to do a simple ajax request when the document is ready. Along with that, I also want to provide a function that is an onclick event.

Here is my code:

```
(function ($) {

  Drupal.behaviors.user_alert_get_message = {
    attach: function(context, settings) {

            $.ajax({
               type: "GET",
               url: "/admin/user-alert/get-message",
               success: function(data){
                   $('div#block-user-alert-user-alert').html(data);
               }
             });

        $('div.user-alert-close a', context).click(function() {
          alert(1);
        });
    }
  };
}(jQuery));

```

The click function does not fire. The ajax does. What can I wrap the ajax in so it only does this on page load, or, is that assumed through attach?

I also tried an onclick on the a tag, but Firebug said the function was undefined, even when it was defined as function (function name) in the .js file.

Edit:

If you have a click event that accepts an argument, how can I pass that in?

# Answer
As I understood it, Drupal.behaviors attach would allow the .click to fire on an element created at anytime. But just in case, I would try using `.delegate()`, as in

```
$('body').delegate('div.user-alert-close a', 'click', function() {
  alert(1);
});

```
> 5 votes

# Answer
**What are Drupal Behaviors?**

In short, Drupal.behaviors is a more modular and better way to implement jQuery.ready. Unlike jQuery.ready which only runs once when the DOM is ready for manipulation, Drupal.behaviors can be ran multiple times during page execution. Even better, they can be ran whenever new DOM elements are inserted into the document (i.e. AJAX driven content).

Drupal.behaviors can also override or even extend an existing behavior. So for instance, if a module behavior adds a bounce effect on all links, another module could replace that behavior with a different bounce effect.

Another added bonus of Drupal.behaviors (starting in Drupal 7), is the ability to use the drupal\_add\_js (PHP) or Drupal.settings.modulename (JS) and pass settings as a second parameter (the first being the context) to the behavior.

**Have a look at the following resources for more information:**
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Authenticated user can't download audio, even though has permission
I have an embedded audio player using HTML5 which is displayed on my guitar lessons site. I have a private file system set up. When I am logged in I can play the audio files fine. If I register as a regular user and go to the same page, it shows the embedded audio player, but no audio plays. This is because drupal is not serving the audio via the media module because for some reason drupal thinks the user is not authorized, even though I specifically set up the roles.

Any ideas how to troubleshoot this?

Thanks!

# Answer
Ok, I didn't realize beyond administering the user roles that I also had to go under Configuration » Media and under private file downloads add a directory '/' under sites/default/files/private... Now it works.
> 1 votes

---
Tags: users, files
---


# Question
Title: arg() dependent hidden field in AJAX form
Basically, I have a hidden field I set using `arg()`.

```
$form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => arg(2)
);

$form['fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#default_value' => "",
    '#size' => 40,
    '#description' => t("Image should be less than xxxxxxxxxxxx."),
    '#upload_location' => 'public://',
    '#prefix' => '<div id="things">',
    '#suffix' => '</div>',
);

```

This value is set correctly once the form loads, but after a call to a AJAX field (managed\_file), the form is refreshed and I get the wrong value in `arg(2)`.

I have found arg(1) changed when doing AJAX, which doesn't give me any solution.

Is there any alternative that can be used, or can we skip the hidden field in the AJAX re-build? Is it possible to use a managed\_file element without the AJAX submit?

# Answer
As suggested by @AyeshK, I checked the `$form_state` in the `hook_form` before i set the value from arg()

```
 $form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => (!empty($form_state['input']['slideid']) ? $form_state['input']['slideid'] : arg(2))
);

```

This could also be done in the `hook_form_submit` ...

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

    if($form_state['values']['slideid'] != $form_state['input']['slideid']){
        $form_state['values']['slideid'] = (int)$form_state['input']['slideid'];
    }
   //====save the form data...

}

```

It looks like a crude fix, but it works for me.

Thank you for your help @AyeshK & @kiamlaluno
> 1 votes

# Answer
If you want to use ajax submit you need to set callback path using #ajax\['path'\] otherwise it will automatically set to **system/ajax**.
> 0 votes

---
Tags: forms, ajax, files
---


# Question
Title: Node registration form - redirect after submit
short question. I'm using node registration module. Can i use hook\_form\_alter to redirect to some custom page after form submit?

# Answer
> 2 votes
To redirect user to a particular page after the form is submitted you can use `$form_state['redirect']`

eg:

```
//Implementation of hook_form_alter()
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    switch($form_id) {
        case 'form_id_of_the_form_to_alter':
            $form['#submit'][] = 'custommade_custom_submit';
    }
}
//Custom submit handler
function custommade_custom_submit($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    $form_state['redirect'] = 'whatever/link/to/redirect';
}

```

Hope this helps.

---
Tags: forms, nodes
---


# Question
Title: Listing first name, last name at Users listing page
I have installed and configured User Profile module, which allows me to add fields like First Name, Last Name for users.

As of now, when I go to users list at /admin/user/user I see username column. How can I can add these extra fields in the column?

# Answer
I suggest using Administration views module which will replace all administration overviews, e.g. the list of users, with actual views. You will then be able to add any field you have attached to user profiles to your overview as well. This will work for both Drupal 6 and 7.
> 1 votes

# Answer
You have to add fields in profile.

You have to create profile type and add fields at admin/structure/profile path.
> 0 votes

# Answer
if you want to change in your administrative view then all hooks are available here for content modification of admin user.. Content administration and module settings UI.

i hope this helps you..
> 0 votes

---
Tags: users
---


# Question
Title: Remove white spaces from inline form-inputs
If there is a form generated by drupal form api in template file, is there a way how to remove whitespaces between `.form-input` html elements?

My template looks like this:

```
            <form action="" method="post" id="activit-grant-filter-form" accept-charset="UTF-8">
                <div class="cont"><!--
             --><?php echo render($form['organisation_type']); ?><!--
             --><?php echo render($form['locality']); ?><!--
             --><?php echo render($form['support_type']); ?><!--
             --><?php echo render($form['thematic_objective']); ?><!--
        --></div>
                <div class="submit-wrapper">
                    <?php echo render($form['submit']); ?>
                    <?php echo drupal_render_children($form); ?>
                </div>
            </form>

```

As you can see I'm using comments between form elements, but they're still keeping whitespaces in between.

# Answer
Set form font size 0 and increase font size of input

```
form {
    font-size: 0;
}

form input {
    font-size: 12px;

```
> 0 votes

---
Tags: forms, theming
---


# Question
Title: How to create drop down while the menu structure is in array type?
I have created menus with sub-menus in the header.

It is supported by some themes .

But some themes don't support this. e.g Bartik, fontfolio etc.

I want to use the drop down as customized in the main-menu region, so as to display in these themes also.

How can I edit this in the drupal page.tpl?

As I am new to drupal, please suggest me.

E.g Dropdown not Supported in this format:

```
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'menu',
        'class' => array('links', 'inline', 'clearfix', 'menu'),
      ),
      'heading' => array(
        'text' => t('Menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      )));
    ?>

```

# Answer
> 1 votes
I have found some possible answers related to your solution.

**SOLUTION 1:**

The main menu in Bartik only displays the first level. Since it's hardcoded in `page.tpl.php` there's nothing you can do about it.

Here's how to get the menu to work properly:

1. In your theme settings (admin/appearance/settings/bartik) disable "Main menu".
2. Go to admin/structure/block and add the "Main Menu" block to the header region (or wherever you want it).

Alternatively, you can also check out the excellent Menu Block module, which generates extra customizable blocks (1st level, 2nd level, etc) for each menu.

**SOLUTION 2:**

There are some useful resources that may help you to solve your problem.

---
Tags: theming, routes
---


title: Internal link to menu item not working

text:
# Question
Title: Internal link to menu item not working
I have several rows with elements and I created the delete operation for each row. When I clicked the delete link, nothing happens (it seems that don't calling the delete function).

Code of the menu item (delete function):

```
$items['node/%webform_menu/webform-factors/factors/%factor_component/delete'] = array(
  'page callback' => 'drupal_get_form',
  'page arguments' => array('forms_grade_factors_delete_factor', 1, 4),
  'access callback' => 'user_access',
  'access arguments' => array('access administration pages'),
  'type' => MENU_LOCAL_TASK,
);

```

Code of the deletion function:

```
function forms_grade_factors_delete_factor($form_state, $node, $component) {
    $form = array();
    $form['node'] = array(
      '#type' => 'value',
      '#value' => $node,
    );
    $form['component'] = array(
      '#type' => 'value',
      '#value' => $component,
    );
    $question = t('Are you sure you want to delete this component?');
    $description = t('Description');
    return confirm_form($form, $question, 'node/'.$node.'/webform/components');
}

```

Code of the table (with the deletion links):

```
foreach($all_factors as $factor) {
  $delete_link = l(t('Delete'), '/node/'.$nid.'/webform-factors/factors/'.$factor->fid.'/delete',
                                  array('query' => drupal_get_destination()));
  $factors[] = array($factor->factor_name, $factor->factor_formula, $delete_link);
}
$form['factors'] = array(
  '#tree' => TRUE,
  '#theme' => 'table',
  '#header' => array(t('Factor'), t('Formula'), t('Operations')),
  '#rows' => $factors,
);

```

Thanks for your help! :)

# Answer
Just saw the your form callback, seems like you are missing argument $form. Small Change as following

From:

```
function forms_grade_factors_delete_factor($form_state, $node, $component) {

```

To:

```
function forms_grade_factors_delete_factor($form, &$form_state, $node, $component) {

```
> 0 votes

---
Tags: 7
---


# Question
Title: How do I convert code implementing hook_init()?
Looking on Drupal.org API, I noticed that `hook_init()` is not documented for Drupal 8. Looking at the change records, I found Bootstrap hooks no longer exist, which points to Get rid of all 'bootstrap' hooks, where the bootstrap hooks are said to be `hook_boot()` and `hook_exit()`; nothing is said about `hook_init()`.

I searched for *hook\_init* in Drupal 8 source, and I found the following code. The first one is a reference to `hook_init()` made in a comment; the other two seem a `hook_init()` implementation, but they both get a parameter I am not expecting.

```
function overlay_enable() {
  if (strpos(current_path(), 'admin/modules') === 0) {
    // Flag for a redirect to <front>#overlay=admin/modules on hook_init().
    $_SESSION['overlay_enable_redirect'] = 1;
  }
}

```

```
/**
 * Implements hook_init().
 */
function phptemplate_init($template) {
  $file = dirname($template->filename) . '/' . $template->name . '.theme';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

```

```
/**
 * Implements hook_init().
 */
function twig_init($template) {
  $file = dirname($template->filename) . '/' . $template->name . '.theme';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

```

I also looked for any function invoking `hook_init()` but I didn't find any.

How do I convert Drupal 7 code implementing `hook_init()` to code running on Drupal 8/9?

# Answer
> 7 votes
Perhaps this has changed since this question was last answered. But I think the preferred approach to replacing what is going on in `hook_init` is to create an event subscriber, and adding to the 'request'. Here is how you do that for those that may find it useful.

Example services.yml

```
services:
  init_subscriber:
    class:   Drupal\mymodule\EventSubscriber\MyModuleSubscriber
    arguments: ['@current_user'] // <- optional args
    tags:
      - {name: event_subscriber} // <- Required Tag

```

Then you would implement the `EventSubscriberInterface` (new file in the `src/EventSubscriber` directory) and in the implemented method `getSubscribedEvents` you can do something like...

```
/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = array('initializeMyModule');
  return $events;
}

```

And add the method accordingly

```
/**
 * MyModule
 *
 * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
 *   The event to process.
 */
public function initializeMyModule(GetResponseEvent $event) {
  $request = $event->getRequest();
  ...
}

```

# Answer
> 5 votes
Yes, `hook_init()` is not used in Drupal 8. If you need `drupal_add_js()` or `drupal_add_css()` you can use `hook_page_build()` instead, which is also useful for that in Drupal 7.

For example, CSS styles and JavaScript code can be added to `hook_page_build()` using `$page['#attached']`.

```
$path = drupal_get_path('module', 'MY_MODULE');
$page['#attached']['js'][$path . '/my_module.js'] = array('scope' => 'footer');
$page['#attached']['css'][$path . '/my_module.base.css'] = array('every_page' => TRUE);

```

If you need to do more complex listening on the request/response, you can define an event listener as documented on hook\_init() removed.

# Answer
> 5 votes
`hook_page_build()` has been deprecated in favor of `hook_page_attachments()` as documented on Added hook\_page\_attachments(\_alter)() and removed hook\_page\_build/alter().

For example, to attach a library to every page, the hook implementation would be similar to the following one.

```
function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'modulename/libraryname';
}

```

`libraryname` is the name of the library, defined in your module's mymodule.libraries.yml.

---
Tags: hooks
---