# Question
Title: How to insert a block inside the content?
I need to insert a block inside in a specific place of my Drupal posts of only one type.

I understand that would be done through `page.tpl.php` file but can somebody explain how do I actually create that block in the first place and ascribe the right name to it? I tried searching in documentation and I'm a bit confused... Thank you!

```
    <div id="content-wrap">
                <?php print render($title_prefix); ?>
                    <?php if ($title): ?>
                      <h1 class="page-title"><?php print $title;  ?></h1>
                    <?php endif; ?>
                <?php print render($title_suffix); ?>

                <!-- I GUESS THE NEW BLOCK GOES IN HERE BUT WHERE DO I SET IT UP? -->

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

```

# Answer
You render the block in the preprocess function for that template. Each template (with its family of suggestions) has a preprocess function. For instance, if you are rendering page.tpl.php or a suggestion based off that, then the preprocess will be named THEME\_preprocess\_page (template\_preprocess\_page in the docs).

Inside the preprocess function you add a new key to the $vars array, and set it to the html output that you want printed. Then, in the template file (ie page.tpl.php) you print that variable.

**example:**

**template.php file**

```
function MYTHEME_preprocess_page(&$vars) {
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  $vars['my_block'] = render($block['content']);
}

```

**page.tpl file:**

```
<?php print $my_block; ?>

```

You can also just assign the block to a region (below content for instance) and then move it out of there into wherever you want it by using hook\_page\_alter.

Drupal 7 preprocess tutorial adding variable to template

Using hook\_page\_alter to move node render items into blocks

Placing the contents of a block in any location

Drupal 7 - How to Print Blocks in templates
> 2 votes

---
Tags: views, blocks
---


# Question
Title: Problems with SQL Syntax using Left Join and OR
I need some help with my SQL. I've got the following code but it's returning multiples of each item and I don't understand why. When I only include the first Left join it returns results as anticipated...but when I add a second LEFT join and include the 'OR' in the WHERE part of the query it returns multiples of the same resources names. After my query I explain more about the context.

```
$result = db_query("
SELECT rn.field_resource_name_value,
       rn.entity_id,
       el.field_experience_level_value,
       rl.field_role_value,
FROM {field_data_field_resource_name} AS rn
LEFT JOIN {field_data_field_experience_level} AS el ON rn.entity_id=el.entity_id
LEFT JOIN {field_data_field_role} AS rl ON rn.entity_id=rl.entity_id
WHERE el.field_experience_level_value='$level' OR rl.field_role_value='$role');

```

This code is part of a recommendations page where users get resources displayed based on their answers to (we'll say two for now) questions on a form. The questions are radio buttons and ask for their experience level and role. These values are saved in session vars that I've already put in $level and $role respectively so those are values like 'Novice' and 'Writer'.

What I'm trying to accomplish - and what the PHP code that displays results (not shown, but below the query) does - is display a list of resources that match the experience level and role the user selected on their form. Obviously I only want each resource to display once, not five times for each. Also, if a user selected both Novice and Writer, let's say, I'd want any resources returned that had EITHER role set to writer OR exp. level set to novice, not necessarily both (although that's fine too).

I have a resource content type that stores it's values in various tables. So each resource title will store its name in the table field\_data\_field\_resource\_name, and the matching experience levels (each resource can have multiple levels - some are good for both Novices and Experienced users for example - these are set as list fields in the resource content type). The matching experience levels are stored in another table (ref. in the sql above) and the matching roles, likewise, are ref. in a separate table. The only thing all of them have in common is the entity\_id field which matches them all to the resource name...hance the SQL above.

Pfew. So given all that background. Can some knowledgeable SQL expert advise me as to what is going on here?

Thanks!

# Answer
> 0 votes
The answer it appears is to use the GROUP BY statement in my SQL right after the WHERE clauses. So, the following:

```
GROUP BY rn.entity_id, rn.field_resource_name_value

```

The returns just one entry for each field resource name.

---
Tags: database
---


# Question
Title: Is there a module that helps link similar articles together and insert them into each other?
I'm looking for the module that would allow me to manually link related articles together and to then set them to appear within the body of content - as links.

What would be your recommendation?

I tried to find different modules, but I need specifically something that could work by me simply creating links between different articles on a separate module settings page, so I don't have to enter into the EDIT mode for each article to add the connection.

# Answer
> 1 votes
You can set up nodes to be used like taxonomy items. Take a look at this: https://www.drupal.org/project/entityreference

That module will allow you to set a content type as the source for cross-linking nodes.

# Answer
> 0 votes
Besides the above-mentioned Book module you can use References modul to create a node reference field together with Noder Reference URL widget and EVA modules. Here's a tutorial: http://mustardseedmedia.com/podcast/episode37

---
Tags: 7
---


# Question
Title: How can I delete orphaned Product Displays?
Using Commerce Kickstart 2.

We have a number of orphaned nodes we would like to delete, ie Product Displays which reference no Product Variation.

I created a View with VBO which shows me these nodes, but unfortunately, it throws an error when attempting to delete since each orphan is missing certain required fields.

Is there a way to -force- VBO to delete these nodes (bypass the form validation for each delete?)

Or... is there a SQL Query you can recommend which will do the same thing (hopefully safely)?

# Answer
I only post this for any future (noob) travelers as it's probably self-evident to experienced people.

The answer is: You need to assign the View to a Page (its own alias) and execute it there. I was running it from inside the Views editor on the Admin/Overlay theme--which had worked for previous VBO updates I've done.

The error I was getting is a conflict between the Admin/Overlay theme. For some reason, when you're in the overlay, the VBO action to unpublish triggers the field validation for every field on the form on each node.

However, if you execute the View from the Page, it does NOT trigger this form/field validation code and performs the update as expected.
> 0 votes

# Answer
Perhaps a PHP script that mimics creation of that View list and then utilizes a node\_delete\_multiple(). Granted, you will want to test this out very carefully before actually using a method like this.

That said, an Entity Field Query coupled with a node\_delete\_multiple() may be what you're looking for. Again, test very well, look at the DB after a test run, see that everything you want deleted is.
> 0 votes

---
Tags: nodes, commerce
---


title: Page View not showing on path'd page

text:
# Question
Title: Page View not showing on path'd page
I'm using Drupal 6 and I'm pretty sure I'm using Views 3. I created a page called All Events (alias: all-events) and created a view that displays as a page. Under Page Settings for the path option I put all-events.

My problem is that I can see the view results in the preview, but whenever I go to the all-events page it is blank save for the title and the one tag I put on there.

# Answer
If you first created a node whose path is all-events and then created a page view whose path is all-events then the page and the view are competing of the same alias. Just delete your node and your view should display fine.
> 0 votes

---
Tags: views, 6, path-aliases
---


title: How do I collect daily login statistics

text:
# Question
Title: How do I collect daily login statistics
I am trying to add a contest to my website which will be based on how frequently they login into my website. Each user will be assigned one point per day irrespective of how many times the login in a day. A winner will be picked every month, at random, based on the number of times they have logged in. Hence the more times you login, the more odds you have of winning.

Any ideas on what would be the best approach? Would I have to build a module from scratch? Modify a current module? Any help would be appreciated.

Thanks, G

# Answer
I was going to recommend the Login History module to track logins on the site -- then it's just a simple matter of doing some filtering and reporting logic to see how many days a user has a login recorded for.

For instance Views and Views Aggregate could likely help build list of tally's; as @rooby says Rules could then do emailing and other tasks for you.

**EDIT**

views integration seems to be incomplete on the original module in an issue, but there is a small support module that adds the functionality while the issue is worked on the in parent module: https://www.drupal.org/sandbox/mouhammed/2396263
> 2 votes

# Answer
I would say use the User Points module along with the User Points Login add-on module to handle to recording of points for users logging in.

Then you can use the Views module to build reports for yourself to see which users have the most points for a given period.

It would also be possible to use the Rules module to automatically email you a report of the winners at the end of every month and then reset all user points to zero (I'm making an assumption that there is a rules action you could use to remove existing user points).
> 2 votes

---
Tags: users
---


title: Disable or hide taxonomy term

text:
# Question
Title: Disable or hide taxonomy term
What is best module to hide or disable or un-publish some terms in taxonomy or vocabulary like the way in the node tab of publishing in the back end

# Answer
> 4 votes
The taxonomy term status module is aimed at this use case.

There is an issue for that module regarding views exposed filters at https://www.drupal.org/node/1805882

Looking at that issue it is a little unclear the status of it. Some users say they have it working and others say they do not. I would try adding your experiences to that issue and someone that has experience with that specific problem may be able to help you get it working.

---
Tags: taxonomy-terms
---


# Question
Title: Display and Modify CSS variable ? (Module)
I'm developing a basic module that allows site admin to have the NavBar for mobile and Administration menu for the desktop view.

This can easily be done by adding this CSS.

```
#navbar-administration {
    display: none;
}

@media only screen and (min-width: 0px) and (max-width: 959px) {

    #navbar-administration {
        display: block;
    }  /* show it on small screens */;
}

#admin-menu {
    display: block;
}

@media (max-width: 960px) {

    #admin-menu {
        display: none;
    }
}

```

I'm using hook\_page\_build() to display it on every page. Now I want user to be able to change on an administration page the `960` width which is the default line break to changes menu to their desired value.

My question how can I display the default variable value (`960`) on a text field and it can be modify the css once the number on the text field is been change.

# Answer
> 1 votes
You have many options:

* Make a system settings form that stores the value to a drupal variable. Read that value from your (themes) css. Then when that form is submitted in your theme form submit handler have code clears the cache: `cache_clear_all("{$theme}:css:*", NULL, TRUE);`. Where `$theme` is your theme name. The CSS should be re-generated on page load.
* I believe the LESS module allows you to easily make CSS variables applied to your files (in Less-3.x or greater for drupal). If you're not currently using LESS, then this is less helpful (pun NOT intended!)

# Answer
> -1 votes
If you make the menu 100% wide inside the div and use jquery resize by dragging it should auto adjust the menu when dragged.

example of div resizing when dragged

---
Tags: theming
---


title: How to alter a custom form

text:
# Question
Title: How to alter a custom form
I am using Drupal 7 to create an registration form, there are: username, email dan password fields, but I want to make an username checking while user leave username field (ajax). I found an module as Username Check

This module is great and working in "myweb/user/register" form, but I need to move this function to my custom form in username field too

The code:

```
function username_check_menu() {
  $items = array();

  $items['username_check/isunique'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'username_check_callback',
    'access arguments' => array('access content'),
    'file' => 'username_check.unique.inc',
  );

  $items['admin/config/system/username_check'] = array(
    'title' => 'Username check',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('username_check_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'username_check.admin.inc',
  );

  return $items;
}

function username_check_form_user_register_form_alter(&$form) {

  $mode     = variable_get('username_check_mode', 'auto');

  if($mode != 'off')
  {
    _username_check_load_resources($mode);
    $form['account']['name']['#field_suffix'] = '<span id="username-check-informer"> </span>';
    $form['account']['name']['#suffix'] = '<div id="username-check-message"></div>';
  }

}

/**
 * Load username_check resources.
 */
function _username_check_load_resources($mode) {
  $module_path = drupal_get_path('module', 'username_check');
  drupal_add_css($module_path . '/username_check.css');
  drupal_add_js($module_path . '/username_check.js');

  drupal_add_js(array(
    'usernameCheck' => array(
      'ajaxUrl' => url('username_check/isunique', array('absolute' => TRUE)),
      'delay'   => variable_get('username_check_delay', 1),
    ),
  ), 'setting');
}

```

and my form as `userregis_form` How to apply this to my custom form?

# Answer
> 0 votes
you need to add a validation to your form via

```
    $form['#validate'][] = 'yourFunction';

  function yourFunction($form, &$form_state) {
        //to show the form values
        dpm($form_state);
        //do validation
  }

```

---
Tags: forms
---


title: Remove users with no created nodes D7

text:
# Question
Title: Remove users with no created nodes D7
I have a site setup where users create a node as soon as they login from the activation link sent via email. I've recently been getting tons of people signing up but not creating any nodes because the emails they register with are obviously fake so I would like to remove all the users with the role listing user that hasn't created a node withing a day of registration.

I need help doing this with Rules if at all possible please. If you have any other methods that doesn't involve complex php that would help as well.

Thanks

# Answer
You can create a View that shows the users who haven't authored any nodes, and then use VBO https://www.drupal.org/project/views\_bulk\_operations to delete those users.
> 6 votes

# Answer
You can hook to the cron that runs daily that check and delete those users.
> -1 votes

---
Tags: rules, users
---


# Question
Title: Disable click event on Next button on checkout form's first step if all cart products are removed
I am new to learning jQuery and JavaScript. I have small task that is becoming hard to solve.

On step one of a checkout form `#ps-cart-checkout-form`, I have to disable `<div class="button">Next</div>` when cart table is empty or emptied by clicking an "X" image in cart table row So that user does not go forward. Button's location and HTML is:

```
<div class="small-right">
<span class="page">Side <span class="current">1</span>/2</span>
<div class="button">Next</div>
</div>

```

Cart table `(.table-cart)` when having one or more products it contains `<thead>` tag but when empty the `<thead>` becomes `<tbody>` with one row `<th>` in it.

My approach:

I have tried to create a module that add js on hook\_form\_alter. and in js file. I have created :

```
(function ($) {
Drupal.behaviors.myModule = {
  attach: function (context, settings) {
      var $form = $("#cart-checkout-form");
      if($($form.find("thead").lenght == 0) {
        $(".button").unbind( "click" );
        }

      });
   }
}(jQuery));

```

With above code I am trying to find out if there is no `<thead>` that means table is empty and therefore above code should disable the click next button. There already having a jQuery code that handles click event on Next div.

# Answer
What module are you using for the cart?

you can also use preventDefault() function to stop the page from loading to the next page.
> 0 votes

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


# Question
Title: How can we apply filter in view for a content type by start date-time and end date-time?
I want to show the latest exam on a tablet based notice board. I am using Drupal 7.

For this I need to show an item from a content type called **Exams** which has a start date and end date with time. After the time ends I need to show the next item if there any.

We can apply start date and end date filter, but I want to check the time also.

For e.g.

> An exam starts on `28/01/2015 10:00 am and ends on 28/01/2015 11:30 am`. If I will add another exam starts at 12:30 pm at the same day after the first exam I need to show the second one automatically.

How can I accomplish this condition ? Seeking the help from Drupal experts.

# Answer
Try the Scheduler module, then just create a view with published exams.

> This module allows nodes to be published and unpublished on specified dates.
>
> Dates can be entered either as plain text or with calendar popups. To use calendar popups you need to install the Date Popup module, which is part of the Date module.
> 0 votes

---
Tags: views
---


# Question
Title: How do I remove the revision information from a node edit form?
I'm hoping someone can help a Drupal beginner removing a view from my page. The purpose of it is a for data collection.

This is the section I am trying to remove:

# Answer
In your `MODULE_form_alter` hook add:

```
$form['revision_information']['#access'] = FALSE;

```
> 10 votes

# Answer
The best solution would be to **bind it to a permission** which can then be tied to a role.

use this code in a custom module:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['#access'] = user_access('view revisions');
}

```

Then only roles with 'view revisions' permission can see this tab.
> 4 votes

# Answer
Take a look at Jammer.

The best description for what that module does can be found in the project page:

> This module is intended to be a dumping ground for removing things from the user interface that might not be appropriate in all cases or just plain confuses certain audiences.

The revision information that you mentioned is one of the many things that are considered "confusing" and that you can remove with jammer.

P.S: An extra plus is that Jammer has a stable D7 version.
> 2 votes

# Answer
This can done by using following code in hook\_form\_alter function.

```
$form['revision_information']['#access'] = FALSE;
          OR
$form['revision_information']['#disabled'] = TRUE;

```
> 1 votes

# Answer
Also use :

```
$form['revision_information']['#type'] = 'hidden';

```
> 1 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Change drupal admin password for 100 sites using drush
I've a requirement to change admin password for drupal 7 sites which are over 100 and i would like to do it with drush. I know one method of doing it is updating user table with a shell script listing databases in a queue, but i want to achieve this with drush. Would be great if anyone can put me in some reference if they have any idea.

## Cheers,

Swaroop.

# Answer
> 1 votes
**Recover password with Drush**

Drush offers several ways of recovering the administrator's password. Generate login-link

Drush can generate a one-time login link.

```
drush uli

```

Reset password

```
drush upwd --password="givememypasswordback" admin

```

(where "admin" is the user name)

For more info visit here

---
Tags: drush, users
---


title: Disable opcache.use_cwd for Drupal

text:
# Question
Title: Disable opcache.use_cwd for Drupal
In PHP Opcache there is an option `opcache.use_cwd`. Disabling it improves performance, but in documentation mentioned that this may break existing applications:

> If enabled, OPcache appends the current working directory to the script key, thereby eliminating possible collisions between files with the same base name. Disabling this directive improves performance, but may break existing applications.

I would like know will Drupal break by disabling `opcache.use_cwd`? I know Drupal has a lot of files with same base name.

# Answer
> 2 votes
It really depends on your server and Drupal sites setup.

**opcache.use\_cwd=0 can *ONLY* be used if you can ensure that there is no duplicate filenames in the PHP files that the server PHP engine may run.**

Note that PHP files are not only those with .php extension, but any of them that begin with the php symbol, like .module, .inc, .install, .tpl.php and so on (whatever extension could be used really).

There are a lot of Drupal setups where these duplicate filenames exists, so opcache.use\_cwd=0 must not be used, like:

* Overriden core tpl files from your custom theme or sub-theme.
* Multisite configurations, or multiple drupal installations running in the same PHP engine.

Note that **in a single PHP engine, OpCache (if active) is shared between ALL the PHP files that are running on it**, so name collisions will happen if any filename is duplicated, if the subdirectory info is not appended.

---
Tags: 7, performance
---


title: How to add module to admin/config page?

text:
# Question
Title: How to add module to admin/config page?
I'm working on a module in Drupal 7. I've added a hook\_menu implementation:

```
$items['admin/config/content/mymodule'] = [
  'title'            => 'MyModule',
  'description'      => 'Configure MyModule settings.',
  'page callback'    => 'mymodule_get_form',
  'page arguments'   => ['mymodule_admin_settings'],
  'file'             => 'mymodule.admin.inc',
  'access arguments' => ['administer mymodule'],
  'menu_name'        => 'mymodule',
];

```

...and a configure line to mymodule.info:

```
configure = admin/config/content/mymodule

```

A *Configure* link for MyModule now appears the **admin/modules** page, but how can I also have the module listed on the **admin/config** page? Or is the **admin/config** page reserved for only core modules?

# Answer
> 9 votes
Looking at the code of system\_admin\_config\_page(), which is page callback for admin/config, I notice it contains the following lines:

```
if ($admin = db_query("SELECT menu_name, mlid FROM {menu_links} WHERE link_path = 'admin/config' AND module = 'system'")->fetchAssoc()) {
  $result = db_query("
    SELECT m.*, ml.*
    FROM {menu_links} ml
    INNER JOIN {menu_router} m ON ml.router_path = m.path
    WHERE ml.link_path != 'admin/help' AND menu_name = :menu_name AND ml.plid = :mlid AND hidden = 0", $admin, array('fetch' => PDO::FETCH_ASSOC));
  foreach ($result as $item) {
    _menu_link_translate($item);
    if (!$item['access']) {
      continue;
    }
    // ...
  }
  // ...
}

```

The first query select the menu\_name field for the menu associated with the path admin/config, which by default is management; the second query select all the menus that have the same value for menu\_name, and whose parent is admin/config.

As your menu uses a different value for menu\_name, it is not selected from the second query, and it is not show in the admin/config page.

# Answer
> 24 votes
If you do it like this, with the system.module callback for the parent item, you get the nice listing page when you visit 'admin/config/mymodule'

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items = [];

  $items['admin/config/mymodule'] = [
    'title'            => 'My configuration section',
    'description'      => 'This is the parent item',
    'position'         => 'left',
    'weight'           => -100,
    'page callback'    => 'system_admin_menu_block_page',
    'access arguments' => ['administer site configuration'],
    'file'             => 'system.admin.inc',
    'file path'        => drupal_get_path('module', 'system'),
  ];

  // Need at least one child item before your section will appear.
  $items['admin/config/mymodule/item'] = [
    'title'            => 'First item',
    'description'      => 'This is the first child item in the section',
    'page callback'    => 'mymodule_item_callback',
    'access arguments' => ['administer site configuration'],
  ];

  return $items;
}

```

# Answer
> 3 votes
Remove the 'menu\_name' part, that is not necessary.

# Answer
> 1 votes
I had trouble with this too on the config page. The only way I was able to do add the link to the config page was to declare two menu items like so, with the parent link at 'admin/config/module' and a child link at 'admin/config/module/manage'.

```
  $items['admin/config/whh-maps'] = array(
    'title' => 'World Hiphop configuration',
    'description' => 'Allows administrators to configure maps for WHH.',
    'position' => 'left',
    'weight' => -30,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('whh_maps_form'),
    'access arguments' => array('administer whh maps'),
    'file' => 'whh_maps.admin.inc',
  );
  $items['admin/config/whh-maps/manage'] = array(
    'title' => 'Manage countries',
    'description' => 'Allows admins to edit country information',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('whh_maps_form'),
    'access arguments' => array('administer whh maps'),
    'file' => 'whh_maps.admin.inc',
    'weight' => -10,
  );

```

# Answer
> 1 votes
```
$items['admin/config/user-interface/mymodule'] = array(
    'title' => 'My Module',
    'description' => 'description',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_admin_function'),
    'access arguments' => array('administer site configuration'),
);

$items['admin/config/user-interface/mymodule/manage'] = array(
    'title' => 'My Module',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'description' => 'description',
    'weight' => -10,
);
return $items;

```

this worked for me.
I was actually struggling for about half an hour until I realized I wasn't returning $items....I always seem to do that.

# Answer
> 0 votes
```
/**
 * Implements hook_menu().
 */
function notification_menu() {

  $items = [];

  $items['admin/customize'] = [
    'title'            => 'Send Comment notifications',
    'discription'      => 'Admin will send notification to user about updates',
    'type'             => MENU_NORMAL_ITEM,
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['notification_form'],
    'access arguments' => ['access adminstration page'],
    'access callback'  => TRUE,
  ];

  return $items;
}

/**
 * Custom form.
 */
function notification_form($form, &$form_state) {

  $form['send_mail_to'] = [
    '#title'         => 'Send Mail To',
    '#discription'   => 'To whom you want to send form',
    '#size'          => 40,
    '#type'          => 'textfield',
    '#required'      => TRUE,
    '#default_value' => variable_get('send_mail_to'),
  ];

  //here the admin can wite subject for the mail.
  $form['mail_subject'] = [
    '#title'         => 'Subject',
    '#discription'   => 'the purpous of this mail',
    '#type'          => 'textfield',
    '#size'          => 40,
    '#maxlenght'     => 120,
    '#required'      => TRUE,
    '#default_value' => variable_get('mail_subject'),
  ];

  $form['mail_body'] = [
    '#title'         => 'Body',
    '#discription'   => 'the body of your mail.',
    '#type'          => 'textarea',
    '#row'           => 10,
    '#columns'       => 40,
    '#required'      => TRUE,
    '#default_value' => variable_get('mail_body'),
  ];

  $form['mail_bcc'] = [
    '#title' => 'BCC this mail to all',
    '#type'  => 'checkbox',

  ];

  return system_settings_form($form);
}

```

---
Tags: 7, routes, navigation
---


# Question
Title: How to add extra field after caption and title on images
Is there a way with Drupal that I can add more fields on the one of caption and title when uploading images?

# Answer
The file entity module will allow you to add fields to your files (including images) like you would with nodes.

You can then add whatever fieds you like and configure how those fields display use them in views etc.
> 0 votes

---
Tags: media
---


title: Redirect to referrer, confirm_form

text:
# Question
Title: Redirect to referrer, confirm_form
I have few `confirm_forms` which could be invoked from different places. I would like to redirect user to proper place after cancelation. `Referrer` Header is not good way to do it so I'm looking for good idea to do it in drupal. Maybe something with `current_path`?

Menu for deletion is defined like so:

```
$menu['module/entity/%/delete'] = array(
    'title' => 'Delete directory',
    'description' => 'Remove directory from ITC Backup',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_entity_delete_form', 2),
    'access arguments' => array('Entity administer'),
    'type' => MENU_LOCAL_TASK
);

```

Form creation function is (at the moment) defined this way:

```
function module_entity_delete_form($form, &$form_state, $did) {
    $form['Id'] = array(
        '#type' => 'hidden',
        '#value' => $did
    );

    return confirm_form($form, t('Are you sure you want to delete selected entity?'), 'module/entity/list');
}

```

# Answer
> 0 votes
I think you answered yourself :). If you want to redirect back to the page the user invoked it from, set `$path` to `current_path()` when calling `confirm_form`. Otherwise set `$path` to wherever you want them to go on cancel.

---
Tags: 7, forms
---


title: Advertisement block changing

text:
# Question
Title: Advertisement block changing
I have a Drupal 7 site, where there is a normal static block at the top of my content region. This is basically an advertisement with some full html content. Now I want to have a second similar block, and I'd like to keep them switching periodically somehow.

Before jumping on to coding something with javascript, I'd like to ask around to see if there is any easy solution for this, maybe a module for rotating ads?

(I know there are some themes that come with this feature out-of-the box, but I like my theme, so would not switch that for this minor thing)

Thanks!

# Answer
> 0 votes
Ok, looks like the right approach is not looking for something that changes blocks. I needed to define a content type, then create a view that lists my ads, and apply one of the numerous view-based carousels, like https://www.drupal.org/project/views\_slideshow

---
Tags: blocks
---


# Question
Title: using jquery updated version in user edit page
With jquery update module I can use newer JQUERY version in my pages and also in admin pages I use another version, `1.9` for pages and `1.5` for admin pages,my question is DRUPAL know user edit page ( `user/uid/edit`) as admin page, how can I use updated version of JQUERY in user edit page?

I did something like

```
function mymodule_js_alter(&$js) {
  //$javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';

  if(preg_match('/user\/\d*\/edit/', current_path())){
    //ym($js);
    //there is exist 1.9.1 jquery file
     $path = libraries_get_path('jquery').'/jquery-1.9.1.min.js';
  // Copy the current jQuery file settings and change
  $js[$path] = $js['misc/jquery.js'];

  // Update necessary settings
  $js[$path]['version'] = 1.9;
  $js[$path]['data'] = $path;
  // Finally remove the original jQuery
  unset($js['misc/jquery.js']);
  }
}

```

also

```
function mymodule_js_alter(&$js) {

  if(preg_match('/user\/\d*\/edit/', current_path())){
     $path = libraries_get_path('jquery').'/jquery-1.9.1.min.js';
  // Copy the current jQuery file settings and change
  $js['sites/all/modules/jquery_update/replace/jquery/1.5/jquery.min.js'] = $path;
  }
}

```

but not worked

# Answer
> 0 votes
I found a solution: First check the path, and then replace the JavaScript file.

```
function mymodule_js_alter(&$js) {
  if (preg_match('/user\/\d*\/edit/', current_path())) {
    $js['sites/all/modules/jquery_update/replace/jquery/1.5/jquery.min.js']['data'] = 'sites/all/modules/jquery_update/replace/jquery/1.7/jquery.min.js';
  }
}

```

---
Tags: javascript
---


# Question
Title: Why do I get the "Maximum function nesting level of 100 reached" error?
On all Drupal 8 beta sites, I have this error:

> Maximum function nesting level of '100' reached

Is this a problem with Drupal 8 or my server? How can I fix this error?

# Answer
> 5 votes
It is probably caused by xdebug. Increase nesting level in php.ini

`xdebug.max_nesting_level = 200`

---
Tags: 8
---


# Question
Title: How do I organize webforms in admin panel
I want to customize the Webforms Admin view. Place all the related webforms in a groups and control who can access the groups.

For example I have many departments. I create a group to each department and allow group members to access the webforms and not other departments.

Can anybody direct me how to achieve this?

# Answer
How many Webforms do you have? I have worked on huge sites, and I have never had enough forms to even fill one page.

As for filtering, you can already go to `/admin/content` and filter by Content type = webform, or just go to `/admin/content/webform`.

If you need even more control over filtering, then you need to create a custom administrative View. With that, you can add filters for whatever you need, and pagination.

Group level access permissions are more difficult, but not impossible. Start here: https://www.drupal.org/project/permissions\_per\_webform. If that is not what you need, then look at the many other modules available for controlling access/permissions.

Last, I think your question was voted down because of several things. First, it is not helpful to make general negative comments like "not well organized". Second, this is not the place to make demands for new features. Third, is the fact that you don't seem to have done even basic searches for the functionality you need.

Last, is your presumption that webforms need to be changed to suit your use-case. Drupal is very powerful because it is modular. Just because you need a certain set of features does not mean that those very specific features would be helpful to anyone else. You should be able to build the functionality you need, but the key word here is "build". Drupal gives you the power to add a GPS to a lawnmower, but that doesn't mean you can demand that every lawnmower sold has a GPS.
> 1 votes

---
Tags: webforms
---


title: Web form integrate with views

text:
# Question
Title: Web form integrate with views
I working on project where user search for nearest shop. so configured view and output result user get list of shops. in that result I want to provide a button **Email us** and when user click on that button have to one form will appear and user fill up the data and click on **SEND**, Then that mail should be send to the shopkeeper\`s mail id and also to the user who sent it. **I want to display a button on every single result with fetching mail field according to user into webform** I used profil2 for user profile and webform modules.

# Answer
> 0 votes
we have a webform views module which may help you I suppose

---
Tags: views, webforms
---


title: Add payment method to Billy PDF?

text:
# Question
Title: Add payment method to Billy PDF?
Is there a way to add a billing method/status line to invoice, generated by module Commerce Billy PDF?

I've been looking for a way for days and still cannot figure it out......

# Answer
Go to the template directory of Billy PDF (commerce\_billy/modules/commerce\_billy\_pdf/templates) and copy the file

```
commerce_order--commerce_order--pdf.tpl.php

```

to your theme directory. Thats the template of the generated pdf. You can simply edit this template and add the billing method i think.

You can access the order object via

```
$order = commerce_order_load($variables['elements']['#entity']->order_id);

```

inside of the template.
> 2 votes

---
Tags: files, commerce
---


# Question
Title: Hide comments on a node type for standard users
I'm using the 'comment permissions' module to restrict standard 'authenticated' users from commenting on a particular node type. However I do not want them to bee able to see comments on that node either.

I want to use the commenting system as tool for discussing posts internally. So admins can discuss posts by standard users. I DO want standard users to be able to comment on some other node types.

Obviously it is very important that the author never sees these comments. 'Comment permissions' doesn't have a way to handle this part so I have overridden the node.tpl.php file and only show comments if a certain role is present (see below)

My question is; how bullet proof is this method? Can anyone suggest a better way to achieve this? Obviously a change in theme would reveal comments but are there other issues I'm not thinking of?

```
<?php if ( (in_array('staff', $user->roles)) || (in_array('administrator', $user->roles)) ){ ?>

// show comments

<?php } ?>

```

# Answer
> 0 votes
You could make a module that uses hook\_comment\_load() to do that user role check.

https://api.drupal.org/api/drupal/modules%21comment%21comment.api.php/function/hook\_comment\_load/7

---
Tags: users, comments
---


# Question
Title: What is the best practice for showing a specific node within a specific page?
I'm using the boostrap\_carousel module which creates a custom content type for a slideshow. I'd like to have a block for one of these carousels to show on the home page. I'd also like to have a carousel embedded on most of the interior pages. What's the best practice to render a specific node that would be created using that content type within the front page and within another node?

# Answer
> 1 votes
You could try creating a new block view, which selects a specific carousel node, and then choose where you want the block to appear.

Views Slideshow does something similar, where you can create a slideshow in a block from a number of existing images.

# Answer
> 0 votes
Not positive if it will render correctly in your situation, but you could try the Node Block module and then limit the block to whichever pages you want it to show.

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

---
Tags: nodes, theming
---


title: Change behaviour of Date at 00:00

text:
# Question
Title: Change behaviour of Date at 00:00
Is there a way to change how Date works when saving dates with the time in 00:00:00? I have a calendar view, and I would like to avoid having events showing as all-day when the are saved with a time of 00:00. Is this possible? I have a content type that cousd either start at 00:00 or end at 00:00, but those are not all day events.

# Answer
You could (a) try changing the granularity of the date field in your content type (b) override the theme function. (ref)
> 0 votes

---
Tags: 7, datetime
---


title: Display corresponding menu

text:
# Question
Title: Display corresponding menu
I've several content types configured to add links in several menus other than the main one and navigation, and I'd like Drupal to show in a left sidebar the corresponding menu it belongs and its siblings and children.

How could I achieve that?

# Answer
Using blocks!

Create your new menu, and assign it to your left sidebar block. then, configure that menu's block settings to only appear on certain content types.
> 1 votes

---
Tags: routes, nodes, navigation
---


# Question
Title: How to add a custom field to views block
I have a view (block) created. When I modify the view block, I have only the field "block title" in the form. However they are 3 fields (block title, block description et block body) in a block of drupal (which I can create via /structure/block/add).

So my question is how can I add a custom field (like a textfield) to the form of views block? Is it possible to add it programmatically?

Thanks in advance.

# Answer
Views is used to pull in existing data/content from other nodes so that you can customise and display it either in new a page or block. There is no body field on the blocks page for a views block is because the contents of that block is controlled by the view and can change dynamically. So if you want to change the body text displayed in the view you can edit the body field of one of the content nodes your view is collecting from.

When I want to add extra custom text to a view I usually add a random field to the view and then inside that fields settings enable rewriting to allow rewrite the fields output with custom values, if you want to go a bit deeper you can use the module Views Custom Fields as another alternative: https://www.drupal.org/project/views\_customfield, but as far as I know editing the body of a views block directly from the blocks admin page is not possible without writing some custom programming.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: file_managed not working when i try to save permanently
First of all, i want to say that i tried everything, i have coded since 10:30 am and i cannot get the solution, i looked in forums, combined code and many other things and nothing seems to work. What i want to achieve is to save permanently an uploaded image to a carrousel but in one minute (default is six hours but i changed it) the image dissapear. I would appreciate any help you can do.

This is the code.

```
function participacionciudadana_form_system_theme_settings_alter(&$form, &$form_state) {
  $form['participacionciudadana_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('participacionciudadana Theme Settings'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['participacionciudadana_settings']['show_front_content'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show content and sidebar on front page'),
    '#default_value' => theme_get_setting('show_front_content','participacionciudadana'),
    '#description' => t('Check this option to show content and sidebar on the front page.'),
  );
  $form['participacionciudadana_settings']['breadcrumbs'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show breadcrumbs in a page'),
    '#default_value' => theme_get_setting('breadcrumbs','participacionciudadana'),
    '#description'   => t("Check this option to show breadcrumbs in page. Uncheck to hide."),
  );
  $form['participacionciudadana_settings']['slideshow'] = array(
    '#type' => 'fieldset',
    '#title' => t('Front Page Slideshow'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['participacionciudadana_settings']['slideshow']['slideshow_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show slideshow'),
    '#default_value' => theme_get_setting('slideshow_display','participacionciudadana'),
    '#description'   => t("Check this option to show Slideshow in front page. Uncheck to hide."),
  );
    $form['participacionciudadana_settings']['slideshow']['slide'] = array(
    '#markup' => t('You can change the description and URL of each slide in the following Slide Setting fieldsets.'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Slide 1'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['participacionciudadana_settings']['slideshow']['slide1']['slide1_desc'] = array(
    '#type' => 'textfield',
    '#title' => t('Slide Description'),
    '#default_value' => theme_get_setting('slide1_desc','participacionciudadana'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide1']['slide1_url'] = array(
    '#title'        => t('Custom Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom image for your site.'),
    '#default_value' => theme_get_setting('slide1_url'),
    '#upload_location' => 'public://imagessliders',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
    );

  $form['participacionciudadana_settings']['slideshow']['slide2'] = array(
    '#type' => 'fieldset',
    '#title' => t('Slide 2'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['participacionciudadana_settings']['slideshow']['slide2']['slide2_desc'] = array(
    '#type' => 'textfield',
    '#title' => t('Slide Description'),
    '#default_value' => theme_get_setting('slide2_desc','participacionciudadana'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide2']['slide2_url'] = array(
    '#title'        => t('Custom Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom image for your site.'),
    '#default_value' => theme_get_setting('slide2_url'),
    '#upload_location' => 'public://imagessliders',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
    );

  $form['participacionciudadana_settings']['slideshow']['slide3'] = array(
    '#type' => 'fieldset',
    '#title' => t('Slide 3'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['participacionciudadana_settings']['slideshow']['slide3']['slide3_desc'] = array(
    '#type' => 'textfield',
    '#title' => t('Slide Description'),
    '#default_value' => theme_get_setting('slide3_desc','participacionciudadana'),
  );
  $form['participacionciudadana_settings']['slideshow']['slide3']['slide3_url'] = array(
    '#title'        => t('Custom Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom image for your site.'),
    '#default_value' => theme_get_setting('slide3_url','participacionciudadana'),
    '#upload_location' => 'public://imagessliders',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
    );

    $form['participacionciudadana_settings']['slideshow']['slideimage'] = array(
    '#markup' => t('Los nombres tienen que ser foto1, foto2 y foto3 sino no funcionará. Las medidas tienen que ser 930 x 320'),
  );
  $form['participacionciudadana_settings']['footer'] = array(
    '#type' => 'fieldset',
    '#title' => t('Footer'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['participacionciudadana_settings']['footer']['footer_copyright'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show copyright text in footer'),
    '#default_value' => theme_get_setting('footer_copyright','participacionciudadana'),
    '#description'   => t("Check this option to show copyright text in footer. Uncheck to hide."),
  );
  $form['participacionciudadana_settings']['footer']['footer_credits'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show theme credits in footer'),
    '#default_value' => theme_get_setting('footer_credits','participacionciudadana'),
    '#description'   => t("Check this option to show copyright text in footer. Uncheck to hide."),
  );

$form['#submit'][] = 'participacionciudadana_form_system_theme_settings_submit';

}

function participacionciudadana_form_system_theme_settings_submit(&$form, &$form_state) {
      $image_fid = $form_state['values']['slide3_url'];
      $image = file_load($image_fid);
      if (is_object($image)) {
      // Check to make sure that the file is set to be permanent.
      if ($image->status == 0) {
      // Update the status.
      $image->status = FILE_STATUS_PERMANENT;
      // Save the update.
      file_save($image);
      // Add a reference to prevent warnings.
      file_usage_add($image, 'participacionciudadana', 'slide3_url', 1);
     }
  }
}

```

# Answer
> 0 votes
Your code is specifically deleting the file after it has been uploaded.

A good example to follow is the image example. Check out the form and submit functions of that.

You start of the same where you load the image, set it to permanent and then save it, although maybe

```
    if ($image->status != FILE_STATUS_PERMANENT) {

```

would be better than

```
    if ($image->status == 0) {

```

Then you add file usage, which is also good.

But then you remove the file usage and delete the file. I'm not sure why seeing as that kind of defeats the purpose of uploading it in the first place.

I would say that is your problem. Try not deleting it.

**Edit:**

Oh I see another issue. Your use of

```
$image_fid = $form_state['slideshow']['slide3']['slide3_url'];

```

seems wrong.

If you interrogate the $form\_state array and reference with the image example you can see there is a `$form_state['values']`, which is where you should be getting your image fid from.

It probably should be this:

```
   $image_fid = $form_state['values']['slide3_url'];

```

---
Tags: forms, files
---


# Question
Title: Search facet user entered date field display
I've recently started working on an existing Drupal site that uses Apache Solr search & have come across a problem when configuring facets.

The search index just indexes one type of content & one of the facets it displays from this is a year field, this is set as a date select field where the user can select a month & year. If I set this to only allow one entry it works fine and the facet links have the years that are available with the number of results it'll return in brackets.

When I set the field to allow an unlimited number of values instead of getting a list of years as links I get what seems to be a random number "1414800000 (1)," timestamp maybe? It also seems to group them by the month & year entered rather than just the year as it did when only one field entry was allowed.

# Answer
If anyone else has this same problem, there is a patch on drupal.org. If you've not used to patches, See this beginner's guide.
> -1 votes

---
Tags: 7, search
---


# Question
Title: Will Drupal & Drupal Commerce run under php-cgi?
For some specific reasons (experimental setup - not Apache nor nginx) want run Drupal under `php-cgi` (not fast-cgi). The site should serve an very-small e-commerce site - probably Drupal Commerce.

Based on my googling Drupal can run under `php-cgi`, but the found links are pretty old (2009 and such), so looking for some answers for both of current main versions - for the `v7` and for the upcoming `v8`.

The questions are:

* Will Drupal (v7 and/or v8) run under `php-cgi`?
* Will run Drupal Commerce under `php-cgi`?
* are here some **major** limitations (other than speed!) caused using Drupal (and Drupal Commerce) with `php-cgi`?

# Answer
Core in particular, but also Commerce, is extensively covered by automated tests.

Many of those are also run in a style that simulates a users journey, not only unit tests. So if you run those, you will have exercised essentially all relevant code.

There are some things that are not covered though, such as CSS and JS, although I strongly doubt those are affected by how you run the php interpreter.

Setup a Drupal instance, enable the `testing` module, and execute all the tests. Go read a book (as that will take a long time), and hope that you come back to all green. :)
> 5 votes

---
Tags: commerce, installation
---


# Question
Title: How to delete duplicate comments using sql?
In order to clean up an old large site from spam, I'd like to delete all duplicate comments from mysql. By duplicate I mean, the comments which are posted by the same user across all nodes of a certain type where content of the comments are exactly the same.

# Answer
> 1 votes
For toying things on the backend in SQL. The best place to start would be to look to see how the API does something in Drupal. For this you want to look at comment\_delete\_multiple which you can call to delete mass comments. You will need to know the comment IDs of the comments that you want to delete.

This is where this gets complicated. You have to find the CIDs you need before you can start deleting. Your criteria for finding the comments is going to depend on what you want to do. If you just want to delete any and all comments that are dupes then you could run a query like this to find dupes and generate the CIDs you want to delete.

Once you ahve the CIDs, it is very easy.You write a delete statement against the comment table. Using the Drupal API where it would iterate through the list of CIDs

```
$cids = array( , , , .....)
db_delete('comment')->condition('cid', $cids, 'IN')->execute();

```

With the amount of comments you are trying to delete doing this strictly in SQL is going to be hard because you will need to write a statement with a gigantic list in a LIKE clause.

**In my humble opinion:** when I have had to do massive data changes like this in Drupal I write a PHP CLI script to do it so I can handle the data. I've migrated a website that had 150k users, 2000 blogs, and 110k comments, I did it all with PHP CLI scripts.

---
Tags: 7, comments
---


# Question
Title: How to get View display label for field?
I'm trying to enable grouping for the Views Datasource module. I'm looping through the `$rows` array, which is where output is stored by the module before it's formatted into JSON. Problem is, the grouping field is stored in `$options` as its machine name, but `$rows` uses the user-defined label for field names. Basically, I just need a function to take the machine name for a field and return the display-set label for it.

I already tried field\_views\_field\_label, but it returns an array of the labels for fields defined in the **content type**, where I need the label defined in the **view display**.

```
$group = $options["grouping"][0]["field"];
// Get grouping field as defined by the field options in the view display
$root = $options["root_object"];
$top_child = $options["top_child_object"];
if ($group) {
  $grouped = array();
    foreach ($rows[$root] as $key => $array) { // Values are numeric
      // Grab the grouping field value from inside the 3rd-level array.
      // Creating a label for grouping field will break everything
      $groupnode = $array[$top_child][$group];
      foreach ($array[$top_child] as $prop => $value) {
        if ($prop != $group) { // Ignore grouped field
          $grouped[$root][$groupnode][$prop][$key] = $value;
        }
      }
    }
  $rows = $grouped;
}

```

# Answer
> 1 votes
I finally learned of the Search Krumo module, which let me search for the variable I was looking for. It was `$view->query->pager->display->handler->handlers['field'][$group]->options['label']`, where `$group` is the machine name of the grouped field. No function was necessary.

# Answer
> 1 votes
I recommend to take a look at this answer which provides lots of information on how to change the output produced by Views Datasource. This should give you a starter.

---
Tags: 7, views
---


# Question
Title: Removing potentially malicious code from template
Our drupal site was hacked at some point recently, and I've been tasked to clean it up because nobody knows much about drupal here. I think I've taken care of most of the glaring security holes, and updated all the modules I could, but I've discovered there's still some gibberish/potentially malicious code on the site that I can't seem to track down.

At the top of every page drupal includes the site's CSS files, and then there's the three IE conditional blocks that are included in the `seven_preprocess_html()` function in `themes/templates/seven/template.php`. Immediately below those conditionals is the following block (I can't actually include the code because SE won't allow the characters in the textbox):

Then there are a series of legitimate .js script tags immediately below. The code in that block is throwing illegal token errors, and appears to be breaking other things in the page. I don't know if it's actually malicious or a corrupted file/db, but I obviously want it gone. Unfortunately I can't find it anywhere in any of the template files and I'm running out of places to look.

Anybody have any ideas on where this block might exist or how I can remove it?

# Answer
> 1 votes
Turns out that it wasn't actually malicious code, it was a GZIP'd javascript file that was getting served onto the page, instead of the uncompressed version.

I disabled "Aggregate Javascript Files" in the Performance menu, and that fixed the problem.

Not sure exactly why this suddenly became an issue, but it's possible our host or a sysadmin made changes to Apache that broke something.

# Answer
> 3 votes
The script may be included from any of the files involved in the build and render pipeline of Drupal as it outputs a page so it's tough, as you say, to pinpoint the single file (it may also affect multiple files). It may also be stored in the database via something included on every page.

So, instead of spot cleaning it's recommended that you start fresh with known-to-be safe Drupal files by importing your database and custom code over a new Drupal install. Drupal provides documentation for handling a hacked site that details why this is a better strategy.

You may have been hacked via the SA-CORE-2014-005 Drupal core vulnerability but even if not this detailed rollback blog post may also help http://befused.com/drupal/drupalgeddon

---
Tags: 7, theming, security
---


# Question
Title: Centering pager for view using Bootstrap 3
I am using Drupal 7 and Bootstrap Business, which is a theme that utilizes Bootstrap 3. I have found that my pager in my views pages is not centered. I know that Bootstrap 3 for non CMS work has a particular css markup that you use to center pagers, but in Drupal 7 there is no UI in the view that allows you to alter the css for the pager that the view uses.

Here is the non changeable html for the pager for a view in Drupal 7

```
<div class="item-list"><ul class="pager"><li class="pager-current first">1</li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=1" title="Go to page 2">2</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=2" title="Go to page 3">3</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=3" title="Go to page 4">4</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=4" title="Go to page 5">5</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=5" title="Go to page 6">6</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=6" title="Go to page 7">7</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=7" title="Go to page 8">8</a></li>
  <li class="pager-item"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=8" title="Go to page 9">9</a></li>
  <li class="pager-ellipsis">…</li>
  <li class="pager-next"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=1" title="Go to next page">next ›</a></li>
  <li class="pager-last last"><a href="/resource-multi-category-search?&&field_resourcecategory_value=All&&page=154" title="Go to last page">last »</a></li>
</ul></div>

```

# Answer
Bootstrap centers the pagination by wrapping it in a `<div class="text-center"></div>` There are definitely a few ways of doing something like this, only going to list the main two.

At the theme level you would want to override theme\_pager in your template.php with special attention being paid on the `return` statement.

Original theme\_pager() return (see link above):

```
return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
  'items' => $items,
  'attributes' => array('class' => array('pager')),
));

```

Modified theme\_pager() return to center pagination (taken from Bootstrap Theme):

```
return '<div class="text-center">' . theme('item_list', array(
  'items' => $items,
  'attributes' => array('class' => array('pagination')),
)) . '</div>';

```

Looking at the code between these you can see that all that is added is the text-center wrap, plus the Bootstrap theme actually uses the pagination class from Bootstrap unlike Bootstrap Business (seems like a weird thing to say when I said it out loud).

I couldn't actually get the other CSS answer to work with the demo of the Bootstrap Business theme but that doesn't mean that it won't or is wrong per say. Just incase you have an issue with that one here is one that I got to work with the demo site:

```
ul.pager li a, ul.pager li.pager-current {
  display: inline-block;
}
.item-list ul.pager li {
  float: none;
}

```

That being said I would go with the way Bootstrap does this, it's already proven and holds up better than changing those lines of CSS I believe.
> 1 votes

# Answer
This should do it:

```
.item-list ul.pager {list-style-type: none;text-align: center;}
.item-list ul.pager li { display: inline}

```

Demo via jsfiddle. I use CSS Injector to easily add the markup.
> 0 votes

---
Tags: 7, paging, theming
---


# Question
Title: Where do pending drush database updates live?
I'm using drush to update the modules on our drupal site. I updated the video\_embed\_field module to the latest version.

This update required 3 database updates to occur, 7006, 7007, and 7008. For some reason 7006 failed as documented here. That link includes a patch which should fix the problem, the only issue is I have no idea where the patch needs to be applied. i've applied patches to drupal modules before, but video\_embed\_field does not appear to have a directory in sites/all/modules which is where I think the patch ought to go.

When I run `drush updb` it wants to apply those three database updates, but I can't find them stored anywhere in the file system (or any references to video\_embed\_field at all). Are these database updates stored in a table in the database, is their a folder somewhere I'm not looking at? Is there another folder where modules get placed?

# Answer
> 3 votes
Drupal will look in /modules and /sites/\*/modules if the site was installed on top of the default profile. If you're using a distribution or other contrib/custom profile then it'll also look under /profiles/\[name-of-profile\].

```
SELECT filename FROM system WHERE name = 'video_embed_field'

```

will tell you exactly where Drupal is looking for the module you're trying to find.

> Are these database updates stored in a table in the database\[?\]

I haven't looked at Drush, but as far as core's update.php goes, no. The .install file of each enabled module is checked to see if it has any update functions with a schema greater than the currently installed schema. I'd imagine Drush does the same thing, no real reason for it to do things differently.

If that assumption holds, then you basically couldn't be seeing those updates as options unless the module is somewhere in the file system (or at least a PHP file that will be included in a normal bootstrap containing a function called `video_embed_field_update_7123()` or similar).

So keep looking, it's likely to be there somewhere!

---
Tags: 7, drush, updating
---


# Question
Title: Flexslider field: number of thumbs, number photos and thumb slider
I just installed the module Flexslider. I want to create an image gallery similar to this one: http://flexslider.woothemes.com/thumbnail-slider.html, with a main big photo slider and thumbs sliders (carousel).

I'm using Flexslider field (that means it will create a gallery with the images of the node) instead of Views. I'm not sure how to show **all** thumbs (all the images I uploaded to the node) in the strip.

I was playing around with the settings in the section "Edit optionset" of the Flexslider module, specially with Item width, Minumum items and Max items. When I change the values, sometimes it shows 2 thumbnails, sometimes 3, etc, depending of the quantity I put in the values.

The weird thing is, when displaying the node if it shows only 3 thumbnails, the main big slider just will have 3 photos, even if the node have a lot of more photos.

What I need is simple, create a gallery that shows all the images in the slider and per each image it should shows one thumb. How I do that? And what means the fields **Item width**, **Minumum items** and **Max items**

Thanks in advance.

# Answer
> 1 votes
I ended up doing it from scratch. I created a custom node.tpl.php, got all the pictures with

```
$photos = field_get_items('node', $node, 'field_photos');

```

Then looping through all items and creating for each item the options

```
$photos_slide = array(
    'style_name'    => 'large',
    'path'          => $photo['uri'],
    'width'         => '',
    'height'        => '',
    'alt'           => '',
    'title'         => $title,
);

```

and then print the image:

```
print theme('image_style', $photos_slide);

```

You can follow this example http://flexslider.woothemes.com/thumbnail-slider.html in order to know how to set the HTML.

---
Tags: media, javascript
---


# Question
Title: How do I find and alter the Views field markup in Drupal 8?
Below is a twig template: *core/modules/views/templates/views-view-unformatted.html.twig*:

```
{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  <div{{ row.attributes }}>
    {{ row.content }}
  </div>
{% endfor %}

```

How do I alter the markup (and add some php logic) in `row.content`? - which outputs markup such as:

```
<div class="views-field views-field-body">
  <div class="field-content">
    <p>Hello world!</p>
  </div>
</div>

```

Presumably, there is another twig template for this markup? I cannot find it. I have the twig debugger turned on, but there are no notes above the markup that renders each content field.

I've looked at the template preprocess functions in *views.theme.inc* too - can't see any markup being generated in those things.

Thanks

# Answer
`theme_views_view_field()` is one of the 17 currently remaining theme functions in Drupal 8. This is a special case that is both a theme function and a template, like `theme_field()` and `field.tpl.php` in Drupal 7. The fact that there is a still a theme function and that's where the output comes from by default is why you aren't seeing it in the `twig_debug` output, which only shows output from template files. The issue to fully convert `theme_views_view_field()` to a template is https://www.drupal.org/node/2348729.
> 0 votes

# Answer
First, enable twig debugging in sites/default/services.yml.

Then that should print a wrapper around each template that tells you which template it is exactly using for that piece of marking. In this case, it is probably views-field.html.twig or so.

Twig also reports what kind of suggestions you can use (e.g. a node type specific template for node.html.twig), but that doesn't work for views because views uses a different approach for that, and twig debug doesn't understand that yet.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: SQL query for phpMyAdmin to delete authenticated users
Question 1: I would like an sql statement to use in phpMyAdmin to delete the users with the role: authenticated user. Looks like rid = 2.

Related Question 2: I show thousands of users in admin/people but the query: SELECT * FROM `drup_users` WHERE 1
only shows 30 users. Shouldn't they all be there?

Related Question 3: I created several roles but only the three standard roles appear using: SELECT * FROM `drup_role` WHERE 1 Where are all the roles I created?

I think I'm having some gross conceptual error. I would appreciate any guidance :) Thanks!

# Answer
As mentioned in the comments, directly modifying the tables could be disastrous. If you need to get rid of large numbers of users I would suggestion Using Views with Views Bulk Operations:

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.
> 0 votes

# Answer
To answer your second related question, showing records with 30 per page is phpMyAdmin's default behaviour and you can always increase this number or have it show all records.
> 0 votes

---
Tags: database
---


# Question
Title: How to remove delete link from admin manage fields ui
I have created a new entity type and progamatically added the fields it requires. My issues is that on the Manage Fields UI (the same interfaced used for managing fields for basic pages/articles), in the operations column there is an option to delete the field. How do I remove prevent the delete link from appearing?

I have googled and looked at the FAPI documentation but don't see an option for this. Anyone know how to do this?

# Answer
> 1 votes
this function will do one of two things - remove the link from the screen, or limit it's effect to doing nothing, depending on what you want to accomplish.

This will work on the Body of an Article - you will need to adjust names appropriately for the content type and field names.

Keep in mind however this will not prevent them from accessing the delete functionality using the url: example.com/admin/structure/types/manage/article/fields/body/delete - you would need to either override the menu, use an access restriction module or something like Rules to prevent users from manually deleting the field.

```
function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'field_ui_field_overview_form' && $form['#bundle'] == 'article')
  {
    unset($form['fields']['body']['delete']);  // remove the link

    $form['fields']['body']['delete']['#href'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '#';  // make the link have no effect
  }
}

```

---
Tags: 7, forms, entities
---


title: Adding Placeholders for PHP variables

text:
# Question
Title: Adding Placeholders for PHP variables
When creating a query using db\_query in my module I want to make sure it's as secure as possible. So I'd like to use placeholders in my 'WHERE' clauses. The problem I'm having is how to use placeholders when the array values to be used are PHP variables. So for example:

```
WHERE el.field_experience_level_value='$level'

```

Is what I'm normally using and it works fine. But then I changed it to the following and added the array part at the end like so:

```
WHERE el.field_experience_level_value=':level'
...some more code
array(':level' => '$level')

```

I get no error but it doesn't return those results. So my main question is, how do I add a php variable such as $level above (already defined in previous code, not here) to a placeholder?

# Answer
Ok so I solved this already. You just have to NOT put quotes around the placeholder in the SQL query, so like this works:

```
WHERE el.field_experience_level_value=:level

```
> 0 votes

# Answer
Better to use PDO for DB related operations in Drupal like db\_select(), db\_insert(), db\_update() and db\_delete().

Here you no need to worry about place holder and other injections.

Ex: `$result = db_select('node', 'n')
 ->fields('n')
 ->condition('nid', $node->nid,'=')
 ->condition('status', 0,'>')
 ->condition('uid', array(1,5,7),'IN')
 ->execute()
 ->fetchAssoc();`

Note from db\_query() API page : *Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db\_select() instead.*

*Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db\_insert(), db\_update() and db\_delete() respectively.*
> 1 votes

---
Tags: database
---


title: Taxonomy term block linked to a view

text:
# Question
Title: Taxonomy term block linked to a view
I have a list of Authors listed as taxonomy terms . I also have a view list of Contents named Topics

I need to display the taxonomy terms of Authors in a View block (lets say in the home page). and then link each term to its related content view page (displayed as List).

Thanks in advance.

# Answer
You need to have 2 views:

**First view: Author's content:**

1. View should be a page.
2. Add all the required field.
3. set path to be like `author/%/content`.
4. Add a contextual filter for the content taxonomy term field (author).

**Second view: Authors list**

1. View should be a block.
2. Add field with term ID (author ID) and mark it to be excluded.
3. Add field with term name (author name).
4. Mark the term name output field to be overridden as a link.
5. Set author name as link text
6. Set `author/[tid]/content` as link path. (You can find correct value for term id in token replacements)

P.S. If you use panels it will be a bit different.

P.P.S. You can use standard `taxonomy/term/%` for the "First view: Author's content" view.
> 0 votes

---
Tags: taxonomy-terms, views, navigation
---


# Question
Title: Rules condition: check for a product with particular value for a field in the cart
I have to aplly a custom fee if in the cart there's a product with a certain value for a field (producs with particular kind of battery). I use Commerce fees for applying the fee.

Every time the cart is updated I have to check: if there is at least one of those products the fee is applyed; if there's not (or there's not anymore) I have to not apply or remove the fee.

Removing a fee is a problem, as the module doesn't allow this. But the bigger problem is whith rules: in conditions I can look for a particular SKU (only one) or a particular content type; instead I have to check something like this: "if there's in cart at least one product whith the value 1 for the field\_battery,..."

Field\_battery is a boolean field thath allow to the store's owner to flag products whith particulr battery, that require the extra fee.

I'm trying with the event "After updating an existing ordine commerce" btu I need help for conditions...

Thanks.

# Answer
Not sure if this is the best way, but its the only way I can think of to do it.

You can do this by adding 3 different rules as well as adding a new field to "order" at admin/commerce/config/order/fields. We will call the field "Apply Fee" (apply\_fee) and it is of the field type "integer"

Rule # 1, Event: when product added to cart
Condition: Entity has field: Entity=order Field=Apply\_Fee
Action: Set Data Value: (use the data selecter to slect the "apply\_fee" field) add offset "1"

Rule # 2, Event: when product removed from cart
Condition: Entity has field: Entity=order Field=Apply\_Fee
Action: Set Data Value: (use the data selecter to slect the "apply\_fee" field) add offset "-1"

Rule # 3, Event: Apply fee to order
Condition: Entity has field: Entity=order Field=Apply Fee
Condition: Data Comparison: order's field Apply Fee is Greater than 0
Action: Apply a Fee to order
> 1 votes

# Answer
You can have a Rule that looks for a SKU, a partial SKU or a Product Type using the module Commerce Rules Extra.
> 0 votes

---
Tags: 7, commerce, rules
---


# Question
Title: How to add cancel button while clicking the Edit link in View?
I created a content type and a view; when I click the edit link shown in the view, it redirects to the filled content type page, which contains only the *Save*, *Preview*, and *Delete* buttons. I need to have a *Cancel* button too.

How do I add the *Cancel* button?

# Answer
> 2 votes
You can make use of the Content type extras module

* label on manage field forms Add a 'Cancel' button to node edit forms
* Ability to set node title visibility when viewing node Ability to
* hide title of front page (takes precedence over content type setting)
* Ability to add form submission buttons to top of 'Manage fields'

Or you could use the more buttons module

> MB provides a additional Create new action.
>
> This action can used as tab in addition to the node View or node Edit tab. This action can used as action link on the node edit forms.

MB allows to use own values for:

> Cancel button, Save and continue button, Save and create new button Create new tab

---
Tags: views, nodes
---


# Question
Title: Does "drush dl" allow to download a module from a site that is not drupal.org?
I have created a Drupal test site on Openshift, and I got Drush 6.2.0 installed. Reading the online help for `drush dl`, I see the following:

> Download Drupal core or projects from drupal.org (Drupal core, modules, themes or profiles) **and other sources**.

Looking at the rest of the help text, I don't see any option to say to the command the module I want to install is not hosted on drupal.org.

Can `drush dl` really download a module from a site that is not drupal.org, e.g. my git repository on github.com?

# Answer
> 1 votes
It looks like the `source url` for project downloads is context-specific - so you can set, for example, `cli.source` to something other than the default Drupal server, and Drush will look there for new releases.

I can't see anything in the code that would suggest that this can be done per-project though, just globally/per context (it's in \[drush\]/commands/pm/downloads.pm.inc if you're interested).

It is possible per-module using core functionality, i.e. adding this to your module's install file:

```
project status url

```

which:

> Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

But it looks like Drush is expecting the remote server to provide data in Drupal's update XML format regardless of the source, so I don't think you'll be able to integrate this with Github without implementing some middleware.

---
Tags: drush
---


# Question
Title: How to add Clear button for views exposed filter?
I created a content type and View with Filter Criteria for my project, when I click the Search it shows the appropriate results.

But there is no option to clear the Search Fields and redirected to previous page (View).

In my requirement I need to keep a \[clear/cancel\] button with \[search\] button.

How to add \[clear/cancel\] button with \[search\] button in View?

# Answer
> 36 votes
Go to you view and Exposed form style settings. (You can find it right side Advanced settings of the view)

and check the 'Include reset button' option . You can also change the Reset button label. Find below.

---
Tags: 7, views
---