# Question
Title: Problem with image width in views/ block
I have a problem to set image dimension on various position. I want a 300x100px in top, 100x75px for thumbnail and other dimensions on other place. In WordPress I can just add "width" attribute to set image width, also class. Example: //img src="location" width="100" class="myclass" alt="". In drupal I can't found how to set this.

I know, I can set in image style with various dimension but too many dimensions. I think, it will increase my hosting disk.

**How to set width attribute on image in Drupal block/views** like \[img src="location" width="value"\]?

# Answer
You can try `hook_preprocess_image` in `template.php`

```
function <THEMENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'thumbnail' then assign additional classes to it:
    if ($variables['style_name'] == 'thumbnail') {
        $variables['attributes']['class'][] = 'myclass';
        $variables['attributes']['class'][] = 'yourclass';
        $variables['attributes']['width'] = 'yourclass';
    }
}

```

OR

```
function <THEMENAME>_image_style($variables) {
  $style_name = $variables['style_name'];
  //print_r($variables);
  $path = $variables['path'];
  $style_path = image_style_path($style_name, $path);
  if (!file_exists($style_path)) {
    $style_path = image_style_url($style_name, $path);
  }
  $variables['path'] = $style_path;
  if (is_file($style_path)) {
    if (list($width, $height, $type, $attributes) = @getimagesize($style_path)) {
      $variables['attributes'] = array('class' => 'fullwidth');
      $variables['width'] = '400px';
      $variables['height'] = '400px';
    }
  }
  return theme('image', $variables);
}

```
> 0 votes

# Answer
Hi create custom image style in admin section for the following url

http://www.example.com/admin/config/media/image-styles

then you will set in views section, after adding image field in views you need to find **image style** drop down option to select your created custom style

hope fully help this.
> 0 votes

---
Tags: media
---


# Question
Title: Multiupload widget - create more items inside single node
I am looking for a solution - I want to upload multiple images (media module) into one node, so each image would be separate item. Is there any module out there? I found multiupload module that creates multiple nodes but that is not what I need. Thank you for any ideas.

# Answer
> 0 votes
You can try out the `Plup Upload` module https://www.drupal.org/project/plup which gives a Plup upload widget for images where you can upload multiple images at once to a content.

You can follow the tutorial here: https://www.ostraining.com/blog/drupal/multiple-image-uploads/

```
NB: To fix the missing thumbnail bug add $conf['image_allow_insecure_derivatives'] = TRUE; to your settings.php

```

# Answer
> 0 votes
You can do using custom module development :

1. Implement hook\_field\_schema() in your module's .install file to define what columns are going to be held in your field table (probably file ID (fid), alternative text for the image, title text for the image and the contents of the text area in your case).
2. Implement hook\_field\_info() to define your field type.
3. Implement hook\_field\_is\_empty() to provide a way for Drupal to know that a particular instance of a field is empty and can be removed when the entity is saved.
4. Implement hook\_field\_formatter\_info() to tell Drupal the different ways the content of your field can be displayed.
5. Implement hook\_field\_formatter\_view to define exactly how those field formatters defined in step 4 will be outputted.
6. Implement hook\_field\_widget\_info to define the different input widgets for your field.
7. Implement hook\_field\_widget\_form to define the elements that will make up the widget for your field.

---
Tags: 7, media
---


# Question
Title: call javascript function after ajax form submit
How do I call a javascript function after a successful ajax form submit? I want to call a function in a file that I added with `drupal_add_js()` in `my_form_name_form($form, &$form_state)`.

# Answer
Have a look at the Ajax framework and Ajax framework commands topics in the API documentation.

Basically, instead of simply returning a single render array, you can return a number of so called ajax commands, which will be translated to javascript and executed on the client side. Replacing the specified wrapper with the returned content is just the default command that is done when nothing else is specified.

There doesn't seem to be a provided command that allows to execute any javascript method (only an invoke command that allows to execute an jQuery command on a defined selector) though. However, you can either define your own command (just have a look at what these helper functions return and the corresponding JS functions in misc/ajax.js (look for `Drupal.ajax.prototype.commands = {...`).

Or you might be able to replace your custom JS function with a number of the provided default ajax commands. They're pretty flexible and I'm for example using them to update the page title in userpoints.module.
> 3 votes

# Answer
Maybe this can work for you as well. It worked for me on Ajax Views Exposed Filters.

```
jQuery(document).ajaxComplete(function(e, xhr, settings) {
  // Call your function here
});

```
> 1 votes

# Answer
The case that worked for me. I have created MYMODULE.js file and included it in MYMODULE.info

```
scripts[] = PATH/TO/MYMODULE.js

```

In MYMODULE.js I inserted following code

```
(function ($) { $(document).ready(function(){
$("#ID_OF_SUBMIT_BUTTON").click(function(event){

// DO SOMETHING

});
})(jQuery);

```

Also made following settings for form

```
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Continue'),

'#id' => drupal_html_id('ID_OF_SUBMIT_BUTTON'),
'#ajax' => array(
  'callback' => 'ajax_form_submit_callback',
  'wrapper' => '',
  'event' => 'click',
),

);

```

`#id` was used to make sure that jquery function will be associated with this form only.
> 0 votes

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


# Question
Title: Use the value of node author's field as CSS class
I have a user profile field which gets populated by the Rules module. I want to add that value to the body class of nodes that user creates.

Which hook should I use to achieve this? What code do I exactly need?

# Answer
> 0 votes
Classes are added to the body element in `template_preprocess_html()`, so in your `MYMODULE_preprocess_html()` or `MYTHEME_preprocess_html()` you would need code similar to the following one.

```
function MYMODULE_preprocess_html(&$variables) {
  if ($node = menu_get_object() && $node->uid && $account = user_load($node->uid)) {
    $user_field = field_get_items('user', $account, $field_name);

   // Use $user_field[0] to access the field data.
 }
}

```

Replace `$field_name` with the field machine name, including the field\_ part if present in the field name. Note I used a variable as placeholder, but you should use a literal string.

Notice that the structure of `$user_field` depends from the field being used; you need to know it to write the correct code.

---
Tags: 7, theming, hooks
---


# Question
Title: Avoid access denied page after user logout
I am using Drupal 7. It is good that when user is logged out and again he access the

```
user/logout

```

link he is redirected to **Access denied** page.

Now I want that instead of **Access denied** page, i want to redirect to the specific page.

Can i achieve it using rules module or i have to write the code for that

# Answer
> -2 votes
In Site `Configuration > System > Site information` you can specify the Access denied path.

Simply give the path to your front page and you will be redirected to front page of the site.

# Answer
> 1 votes
What you want is something called 403 redirect to Login: https://drupal.org/project/r4032login

403 access denied messages will get redirected to the login page. I've used this before and it works nicely.

# Answer
> 1 votes
Use Rule Module Event Operations: User has logged out

Actions Elements Click add action Select the action to add "page redirect"

Here in url specify path where you want user after logout.e.g if you want to redirect to your site front page enter. http://www.example.com Note:replace example with your site name.

# Answer
> 0 votes
For redirect choose "Page Redirect" in "System" options group

# Answer
> 0 votes
If you are generating this logout link use the following to generate it and redirect the user.

```
l(t('Logout'), 'user/logout',array('query' => array('destination' => 'node/any')));

```

# Answer
> 0 votes
The redirect\_after\_logout module deals with it.

---
Tags: 7, redirection
---


# Question
Title: email address not appearing in user profile
I am using drupal 7 default `user_register` module, when a user registers with all the required fields, it successfully registers but when I click that user in `people>` tab his/her profile is displayed in which email is not appearing as you can see in the screen shot. Whereas when I clicked on edit link on the right side of that user email address exists.

# Answer
1. copy the default profile template into your theme directory (the default template I copied is /modules/user/user-profile.tpl.php)
2. just after the initial insert this code:

```
$profile_user = user_load(array('uid' => arg(1)));

 if($profile_user) {

   print '<h3>Contact Information</h3>';
   print '<dl><dt class="profile-profile_email">Email</dt>';
   print '<dd class="profile-profile_email"><a href="mailto:' . $profile_user->mail . '">' . $profile_user->mail . '</a></dd></dl>';
 }

```
3. That's it, all your profiles should have email addresses.
> 1 votes

# Answer
By default Drupal **does not show the Registration email in the User profile**. But you can override the default template of the User page with your own template and display the email field.

Alternatively you can use Panels to change the layout and show the `Email Field`.

One more solution is to add a field `email` in the `User Profile` so that users will have a registration email and profile email. Users have more flexibility - they can use the same email or two different addresses. Because in some cases there might be some security issues when the Registration Email is exposed.

Else if you have thought about the consequences of forcing users to reveal their registration email then using `Panels` is the best and easiest way to show it.

Hope this helps.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Adding conditions to the template file of a view
I'm setting up a webshop in drupal and I bought a template.

The tempate has a compare products function embedded, that works with a button on the product pages, however, I would only like that button to show up at certain types of products, like TVs and phones etc., but not for the rest.

The compare button, however, is hardcoded into the template file and not manageable from views, so I have to add the conditions to it there, in PHP - to only appear on the node pages of products that have a certain taxonomy term attached to them.

```
 <div class="actions">
    <?php print flag_create_link('wishlist', $node->nid); ?>
    <?php print flag_create_link('compare', $node->nid); ?>
  </div><!-- .actions -->
</div>

```

This is the section in the code of the node--product.tpl.php file that puts out the action buttons. I need the second one, the compare button to only appear for nodes that have a certain taxonomy term.

I don't really know php, except for very very basic syntax, so I would be really grateful, if someone could describe in detail how to implement a solution, perhaps even provide a snippet of code that I can customize and paste there!

Thank you in advance!

Huba

# Answer
To add a variable in template files you first need to create it in your template.php of the theme folder using template\_preprocess\_node function.

```

/**
* Implements template_preprocess_node.
*/
function theme_preprocess_node(&$variables){
  foreach($variables['field_taxonomy_field'] as $values){  //field_taxonomy_field is the machine name of the taxonomy term field of your content type.
    if($values['tid'] == $term_id){  //$term_id if the id of the term you want to compare.
      $variables['compare_products'] = l("Compare Button", 'node/compare');
      //@todo your stuff here.
    }
  }
}

```

This will create a variable named `$compare_products` which you can use in the template file as a variable.

In `node--product.tpl.php` you can add `<?php print $compare_products; ?>` and the data from the variable will be shown whenever the variable is available.
> 1 votes

---
Tags: theming, views
---


title: How to specify type of script

text:
# Question
Title: How to specify type of script
I need to specify the type of script in my **theme.info** I add the script in my **theme.info** like this `scripts[] = js/file.js` In the head it look like this

`<script type="text/javascript" src="..."></script>`

but i need to change the type to

`type="application/ld+json"`

Can someone help me please

# Answer
Drupal core adds the text/javascript as default type.

You may include the file using drupal\_add\_js

```
drupal_add_js('file.js', array('attributes' => array('id' => 'my-template', 'type' => 'application/ld+json')));

```
> 3 votes

---
Tags: theming
---


title: Migration of Users very slow with d2d

text:
# Question
Title: Migration of Users very slow with d2d
I'm wondering what could be causing my migration to run so slowly. I'm using dev versions of migrate and d2d as I always have without issue. There are over 120,000 users and the first 2000-9000 import within a few seconds.

After that it only processes 2 at a time (about every 30 seconds).

d2d code:

```
  $common_arguments = array(
    'source_connection' => 'legacy',
    'source_version' => 6,
  );

  $arguments = $common_arguments + array(
    'description' => t('Migration of users from Drupal 6'),
    'machine_name' => 'User',
  );

  Migration::registerMigration('DrupalUser6Migration', $arguments['machine_name'], $arguments);

```

include file:

```
class User extends DrupalUser6Migration {
  public function __construct(array $arguemnts) {
    parent::__construct($arguemnts);

    $this->addFieldMapping('roles', 'roles')
      ->sourceMigration('Roles');
  }
}

```

The legacy database the data is coming from is on my local machine on the same SSD the new site is on. Any ideas on why this is running so slow? At the rate it's going out it will take over a month to import all of the users...

# Answer
> 1 votes
In settings.php set:

> $conf\['password\_count\_log2'\] = 1;

You will speed up how drupal handles user passwords: The problems reported here: https://www.drupal.org/node/2200181 ... seem to match yours, first 2000 in X seconds second 2000 in X.Y seconds etc...

Also, in php.ini set:

> max\_execution\_time to 0 (for unlimited) or a high number like 3000 rather than the default 30.

NB. Be sure to return the execution time to its default setting after the migration.

# Answer
> 0 votes
CR47. I had same problem, I had to migrate 300 000 of users and batch migration became very slow. I used drush migrate commands and migration was rather fast (approximately 1000 of users per minute). I used

```
drush migrate-import User

```

where User is a machine name of my migration.

Also you can use

```
drush migrate-import User --feedback="1000 items"

```

In this case you will get feedback when 1000 of users will be migrated.

---
Tags: users, migrations
---


# Question
Title: Leaflet Map disappears when selecting term in views exposed filter
I'm using leaflet in a content view with a page having an exposed filter on taxonomy terms.

Problem is whenever a term/filter is selected and applied the map disappears and turns grey. I'm using Leaflet More Maps and this seems to happens with any map.

# Answer
> -1 votes
You must use global area views from other block with generic map, should not have results always show you the map.

---
Tags: views, taxonomy-terms, javascript
---


# Question
Title: How to add slideshow plugin for CKEditor?
I want add slideshow plugin for CKEditor on Drupal 7. I've tried several ways but without success.

Any suggestions?

# Answer
> 0 votes
You can install a plugin by adding the plugin to: sites\all\modules\ckeditor\plugins

Once the plugin is unpacked correctly, it will automatically appear on the plugins list in your CKEditor profiles along with its toolbar buttons.

See these instructions.

# Answer
> 0 votes
> I have tried to do so but failed. It does not display icon slideshow in "editor appearance" – Lê Quang Tú

The problem is in the "editor.ui.addButton" in "plugin.js": No icon is defined.

```
// Create a toolbar button that executes the above command.
editor.ui.addButton( 'Slideshow', {
    // The text part of the button (if available) and tooptip.
    label: lang.insertSlideShow,
    command: 'slideshow',
    // The button placement in the toolbar (toolbar group name).
    toolbar: 'insert',
    icon: this.path + 'icons/slideshow.png'
});

```

You have to add `icon: this.path + 'icons/slideshow.png'`.

---
Tags: 7, wysiwyg
---


# Question
Title: Login to external server from Drupal site
Is there any way to customize Drupal login to use authentication from an external server?

I'd like to know about any modules or if Drupal core can implement this function.

Source code:

```
// Include FirePHP for debug

function authdave_form_alter(&$form, &$form_state, $form_id) {
    // Authentication based on username and password
    if ( ($form_id == 'user_login' || $form_id == 'user_login_block') ) {
        $form['#validate'][] = 'authdave_user_form_validate';
    }
}
/**
* Custom form validation function
*/
function authdave_user_form_validate($form, &$form_state) {
    if( !authdave_authenticate($form_state) ) {
        form_set_error('name', t('Unrecognize username.'));
    }
}
/**
* Custom user authentication function
*/
function authdave_authenticate($form_state) {
    // get first four characters from user name
    $complete_username = $form_state['input']['name'];
    $password = $form_state['input']['pass'];

    // retrieve users credentials from DB
    $credential = get_all_credentials();

    while($row = $credential->fetch_assoc()) {
        // check if there are any match
        if ( $row["username"] ==  $complete_username && $row["password"] == $password) {
            user_external_login_register($complete_username, 'custom_athentication');
            return TRUE;
        }
    }

    return FALSE;

}

function get_all_credentials() {

    //credenziali di accesso al dbms
    $server = "****";
    $username = "***";
    $password = "***";

    //nome db
    $db_name = "credenziali_db";

    //creo una connessione con il dbms
    $conn = new mysqli($server, $username, $password, $db_name);

    if ($conn -> connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    echo "Connection successfully";

    //sql query
    $sql = "SELECT username, password FROM credenziali";
    $result = $conn -> query($sql); //risultato della query

    return $result;

}

```

?\>

# Answer
> 1 votes
This depends what you mean by external server? There's a tonne of contribution modules at the moment that support a variety of external logins.

You can implement Open Auth 2 to allow a single sign on:

```
https://www.drupal.org/project/oauth2_authentication

```

Or you can use Facebooks Oauth authentication:

```
https://www.drupal.org/project/fboauth

```

---
Tags: redirection, users
---


title: Edit token template

text:
# Question
Title: Edit token template
I am using "Send mail with Variable" module and my variable contains the token \[commerce-order:commerce-email-order-items\], which returns me `<table style="width: 50%;border: 1px solid #ddd;">`. I need other CSS styles. Because it is a body of a e-mail, I can use only inline styles. Where I can find a template of this token?

# Answer
There isn't any template used to populate that token. The function that is called to generate the content of that token is `commerce_email_order_items()`, which then calls `theme_commerce_email_order_items()`.

To alter the content of the token, you have two options:

* Override the theme function. It's easier, but it could change the output also in other contexts.
* Implement `hook_tokens_alter()` to alter the output of that token. It's not as easier as the previous solution, but it's more specific, and you are sure you are not going to alter the output of `theme('commerce_email_order_items')` done from other modules and in other circumstances.

This is the involved code used by the module.

```
/**
 * Implements hook_tokens().
 */
function commerce_email_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $url_options = array('absolute' => TRUE);

  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
    $language_code = $options['language']->language;
  }
  else {
    $language_code = NULL;
  }

  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'commerce-order' && !empty($data['commerce-order'])) {
    $order = $data['commerce-order'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'commerce-email-order-items':
          $order_items = commerce_email_order_items($order);
          $replacements[$original] = $order_items;
          break;
      }
    }
  }
  return $replacements;
}

/**
 * Returns a rendered email of the commerce order
 * or an array of the table details
 *
 * @param $order
 *   The commerce order object
 *
 * @param $theme
 * (optional) Defaults to TRUE
 *   Flag to return the contents of the order
 *   as a themed html table or an array suitable for theme('table' ...)
 *
 * @return
 *   String containing the rendered order table
 *   or an array suitable for theme('table' ...)
 */
function commerce_email_order_items($order, $theme = TRUE) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);

  if ($theme) {
    return theme('commerce_email_order_items', array('commerce_order_wrapper' => $wrapper));
  }
  else {
    return commerce_email_prepare_table($wrapper);
  }
}

/**
 * Theme function for the commerce order.
 */
function theme_commerce_email_order_items($variables) {
  $table = commerce_email_prepare_table($variables['commerce_order_wrapper']);
  return theme('table', $table);
}

/**
 * Returns a table header and rows for theming.
 *
 * @param $wrapper
 *   A metadata-wrapped commerce_order entity
 *
 * @return array
 *   Array suitable for use by theme('table' ...)
 */
function commerce_email_prepare_table($wrapper) {
  $currency_code = $wrapper->commerce_order_total->currency_code->value();
  $amount = number_format(commerce_currency_amount_to_decimal($wrapper->commerce_order_total->amount->value(), $currency_code), 2);

  $header = array(
    array('data' => t('Product'), 'style' => array('text-align: left;')),
    array('data' => t('Qty'), 'style' => array('text-align: left;')),
    array('data' => t('Price (@currency_code)', array('@currency_code' => $currency_code)), 'style' => array('text-align: left;'))
  );

  $rows = array();
  foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {

    switch ($line_item_wrapper->type->value()) {
      case 'product':
        // Special treatment for a product, since we want to get the title from
        // from the product entity instead of the line item.
        $title = htmlentities($line_item_wrapper->commerce_product->title->value(), ENT_QUOTES, "UTF-8");
        $title .= commerce_email_order_item_attributes($line_item_wrapper->commerce_product->product_id->value());

        $rows[] = array(
          'data' => array(
            array('data' => $title, 'style' => array('text-align: left;')),
            array('data' => $line_item_wrapper->quantity->value(), 'style' => array('text-align: left;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($line_item_wrapper->commerce_unit_price->amount->value(), $currency_code), 2), 'style' => array('text-align: left;')),
          )
        );
        break;
      default:
        // Use this for any other line item.
        $rows[] = array(
          'data' => array(
            array('data' => htmlentities($line_item_wrapper->line_item_label->value(), ENT_QUOTES, "UTF-8"), 'style' => array('text-align: left;')),
            array('data' => 1, 'style' => array('text-align: left;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($line_item_wrapper->commerce_unit_price->amount->value(), $currency_code), 2), 'style' => array('text-align: left;')),
          )
        );
        break;
    }
  }

  $data = $wrapper->commerce_order_total->data->value();
  if (!empty($data['components'])) {

    foreach ($data['components'] as $key => &$component) {

      if ($data['components'][$key]['name'] == 'base_price') {
        $rows[] = array(
          'data' => array(
            ' ',
            array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
          )
        );
      }
      elseif (preg_match('/^tax\|/', $data['components'][$key]['name'])) {
        $rows[] = array(
          'data' => array(
            ' ',
            array('data' => $data['components'][$key]['price']['data']['tax_rate']['display_title'] . ':', 'style' => array('font-weight: bold; text-align: right;')),
            array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
          )
        );
      }
    }
  }

  $rows[] = array(
    'data' => array(
      ' ',
      array('data' => t('Total:'), 'style' => array('font-weight: bold; text-align: right;')),
      array('data' => $amount, 'style' => array('font-weight: bold; text-align: left;')),
    )
  );

  return array('header' => $header, 'rows' => $rows, 'attributes' => array('style' => array('width: 50%; border: 1px solid #ddd;')));
}

```
> 0 votes

---
Tags: tokens
---


# Question
Title: Fatal error: Call to a member function difference() on string in error on tpl file
I'm trying to calculate the value between two fields in my custom node.tpl file. I am trying to convert the code show on http://drupal.org/node/1364744, and I wrote the following one.

```
$birthday = format_date(strtotime($content['field_date_de_naissance']['#items'][0]['value']), 'custom', 'd/m/Y');
$today = date('m/d/Y');
$age = $birthday->difference($today,'years');
print $age;

```

I get this error.

> Fatal error: Call to a member function difference() on string in

What is wrong in my code?

# Answer
> 2 votes
I modified my code by converting the $birthday to dateObject, so it works now.

```
$birthday = new DateObject($content['field_date_de_naissance']['#items'][0]['value']);
$today = date_now();
$age = $birthday->difference($today,'years');
print $age;

```

# Answer
> 4 votes
The error is calling a method (`difference()`) on a string, while just PHP objects and classes implements methods. `format_date()` is documented to return a string, not a `DateObject`.

> ### Return value
>
> A translated date string in the requested format.

The code I would use depends from what modules you have installed, and which PHP version you are using.

* If you have the Date module installed, and you enabled the Date API module, I would use the following one.

```
$birthday = new DateObject($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday->difference(date_now(), 'years');

```
* If you don't have the Date module installed, but you have a recent version of PHP 5 (which means higher than 5.2.0), then I would use code similar to the following one.

```
$birthday = new DateTime($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday->diff(new DateTime())->format('y');

```
* If you are still using a PHP version lower than 5.2.0, or you just want code you can use without to worry about the PHP version, I would use the following code.

```
$birthday = strtotime($content['field_date_de_naissance']['#items'][0]['value']);
$age = format_interval(time() - $birthday, 1);

```

I am not using `format_date()` since it returns a translated string, which is not necessary to `strtotime()` (and probably, it would confuse it).
`format_interval()` consider a month made of 30 days; for this reason, the code shown above is probably giving a different value than the other methods.

### Reference

---
Tags: 7, datetime
---


title: Flags with image instead of link

text:
# Question
Title: Flags with image instead of link
I have two flags defined in my site (`false_negative_flag` and `false_negative_flag_passed`). Each flag has different Flag link text.

In views, I have two displays. I have a flag link in each of these views, one with the first flag, the other with the second one. The link text shows correctly on both displays. I wanted to have images instead of the link text so I added the following css:

```
.flag-wrapper.{false_negative_flag} a.flag-action {
    background: url(http://.../files/failed.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}
.flag-wrapper.{false_negative_flag} a.unflag-action {
    background: url(http://.../files/passed.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}
.flag-wrapper.{false_negative_flag_passed} a.flag-action {
    background: url(http://.../files/passed.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}
.flag-wrapper.{false_negative_flag_passed} a.unflag-action {
    background: url(http://.../files/warning.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}

```

There are 3 different images I use but in my views I always see the `passed` and `warning` ones (the last two entries of the css). Is there any error in my css?

NOTE: I'm using the displays in Panels, don't know if it's relevant.

EDIT after first answer: I got the css I'm using from the link in this answer. I simply duplicated and in the second part I added the second flag machine name. The problem is that now it ignores the first two blocks of the css.

Thanks!

# Answer
> 2 votes
Working with flags u should use "-", not underscores and there are should be class names started with flag-: **flag-false-negative-flag-passed**

---
Tags: views, panels, theming, flags
---


# Question
Title: X-Drupal-Cache header not always appearing on page
I have a site which uses Drupal core anonymous caching. However, I have noticed a very strange behavior. Sometimes I will load the home page and in the response headers will be the 'X-Drupal-Cache' header. But if I reload the page again, the 'X-Drupal-Cache' header disappears. I cannot understand how this could happen.

What might be the cause?

The response headers also containL `Cache-Control:no-cache, must-revalidate, post-check=0, pre-check=0`, which I understand will force the browser not to use a cached version of the page.

Strange thing is that if I access the same page using curl (e.g. `curl -I http://example.com/`), the X-Drupal-Cache header appears each and every time.

# Answer
The behavior you're seeing is the result of having a browser cache. After the first request, your browser caches the document and keeps track of its signature through the `Etag`/`Last-Modified` headers.

Upon subsequent requests, the browser makes a request to the server with the `If-None-Match`/ `If-Modified-Since` headers. If the document hasn't changed, the server returns a HTTP `304 Not Modified` which tells the browser it's okay to serve its cached version of the page.

Because cURL doesn't have a caching mechanism, `X-Drupal-Cache` always appears; it needs to go directly to Drupal each time for the document.
> 0 votes

---
Tags: caching
---


title: Php in "regions" without php filter

text:
# Question
Title: Php in "regions" without php filter
I've heard that using the php filter is dangerous. Something about having php in databases being a bad practice. I use it in blocks quite a bit and want to move away from that.

I have a lot of page template files so I need a replacement for regions/module\_invoke blocks. I tried using an include but dealing with paths was tedious. Is that the only option or is there something easier?

# Answer
Includes or requires is likely your best bet here, why are they tedious? If the includes are within the same theme/template files directory you needn't use absolute paths.

If you cannot use relative paths then you can use `getcwd()` to get the current path/working directory of a file, or use `drupal_get_path()` to get the path to a theme or module file.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: ckeditor loads all the page html while editing not only the body field
I have strange issue with ckeditor that it loads all page source including (header, menu, body, footer ...) not the node body field itself.

the problem may have relation with default search module as it disappears when I re-index the site till the index built again.

I tried many links and that question but nothing works for me.

I tried jquery\_update but didn't make any change BTW I see the body field content before the ckeditor loads after that the field content becomes all page source

CKEditor: 7.x-1.16, CKEditor Media: 7.x-1.x-dev, jQuery\_update module loading jquery 1.8

I checked ajax requests and found that /ckeditor/xss returns the whole page content.

Please help me fix that issue

Answer:

The solution in my case was based on zhilevan answer solution 2

just added checking for the $view\_mode like:

```
function my_module_node_view($node, $view_mode, $langcode){
 if ($node->type=="webform" && $view_mode != 'search_index'){
 //Do some stuff here
}

```

solved the issue without the need to disable the search module

Also solution 1 :Switch of "Plugin for inserting Drupal teaser and page breaks" didn't make sense and I think it have no impact here

# Answer
> 3 votes
I had this problem some month ago, one solution with disabling search module was good, but now i've needed search-box working, so i've made a research and found another thing.

In my case the problem was Plugin for inserting drupal teaser and page breaks. I've had this plugin switched off, but button "DrupalBreak" was added to Used button list.

**solution 1:**

Go to CKEditor profile settings page at '/admin/config/content/ckeditor/edit/\[profile\_name\]'
Switch of "Plugin for inserting Drupal teaser and page breaks" in appearance settings.
Make sure, that "DrupalBreak" button is not in use.

**solution 2:**

The problem most likely lies within the search-module's cronjob to index the page. This cronjob kind of views the nodes it wants to index. If you use hook\_node\_view() anywhere in your modules and the cron-user gets an error or gets lead anywhere by a drupal\_goto(), the behaviour you described is the result.
Solution: Disable the search-module if you don't need it. If you need it though, check the $view\_mode in your `hook_node_view()`-implementations. If it says "search\_index", no redirects should be made. (the easiest way is to just return $node if($view\_mode == "search\_index")

# Answer
> 1 votes
This might help:

* Check the version of jQuery required by your donwload of CKEditor
* Install the jquery\_update module
* Choose a vesion of jQuery that will work with CKEditor from that module's configuration page.

(I find 1.8 works well with most contrib modules)

# Answer
> 1 votes
The solution in my case was based on zhilevan answer solution 2

just added checking for the $view\_mode like:

```
function my_module_node_view($node, $view_mode, $langcode){
 if ($node->type=="webform" && $view_mode != 'search_index'){
  //Do some stuff here
}

```

solved the issue without the need to disable the search module

Also solution 1 :Switch of "Plugin for inserting Drupal teaser and page breaks" didn't make sense and I think it have no impact here

---
Tags: search, wysiwyg
---


# Question
Title: Trying to get a property of a non-object in 'mymodule_node_access()'
In a custom module, I try to make this code work :

```
function mymodule_node_access($node, $op, $account) {
  if ($node->type = 'devis' and $op = 'view') {
    $field_language = field_language('node', $node, 'field_project');
    $project_node = node_load($node->fields->field_project[$field_language][0]['value']);
    if ($project_node->uid == $account->uid) {
      return NODE_ACCESS_IGNORE;
    }
    else {
      return NODE_ACCESS_DENIED;
    }
  }
}

```

I get the following notice:

> Trying to get a property of a non-object in `mymodule_node_access()`

I don't know where the problem is.

# Answer
`$node` in `hook_node_access()` can be either a string for the content-type or a node object. I had to test if it was a string or an object.

```
if (is_string($node)) {
  return NODE_ACCESS_IGNORE;
}
else {
  // ...
}

```
> 2 votes

# Answer
Fields are directly on the node object, you're currently trying to find them in another object called `fields`.

Change this:

```
$project_node = node_load($node->fields->field_project[$field_language][0]['value']);

```

To this:

```
$project_node = node_load($node->field_project[$field_language][0]['value']);

```

And it should work.
> 1 votes

---
Tags: nodes
---


# Question
Title: EntityFieldQuery BETWEEN condition is not working
```
$query->join('field_data_field_amountpaid', 'amt', 'n.nid = amt.entity_id and amt.field_amountpaid_value >=500 and amt.field_amountpaid_value <=5000 '); //JOIN node with Body

```

This is my normal query how can I call this in entity query?

I tried this way;

```
$query->fieldCondition('field_amountpaid', 'value', array('501','5000'),'BETWEEN');

```

But it's not working. Any idea?

# Answer
I had the same problem than you, and was able to fix it. The real problem here is that the documentation does not provide any example.

As it was already mentioned, the BETWEEN will only work if you are using the same data types that are being stored.

In my case, the field i was searching was a date field that has a specific format. So instead of passing a timestamp i had to format that date and then pass it.

```
//something like
start_date = (isset($_GET['startDate'])) ?  date('Y-m-d/T00:00:00',strtotime($_GET['startDate'])) : null;
        $end_date = (isset($_GET['endDate'])) ? date('Y-m-d/T00:00:00',strtotime($_GET['endDate'])) : null;

        if (isset($start_date) && isset($end_date)) {
           $query->fieldCondition('field_publication_date', 'value', array($start_date,$end_date), 'BETWEEN');
        }

```

Hope this helps you!
> 1 votes

# Answer
Try also different *type format* like this: array(501,5000).

Try also with small letters 'between'.

Make sure there is some data in that table.
> 0 votes

# Answer
`'BETWEEN': This operator expects $value to be an array of two literals of the same type as the column`.

DId you make sure that your "value" and your array types were the same?
> 0 votes

---
Tags: 7, database
---


# Question
Title: Where are the watchdog logs located or how do I view the errors created?
How do I view the watchdog logs that are created? Is there an interface to view them with, or are the logs stored somewhere on the filesystem?

# Answer
> 14 votes
Both Drupal 6 and Drupal 7 put the viewable version of watchdog logs at `/admin/reports/dblog`. The core database logging module needs to be enabled, and users who want to view them need the `access site reports` permission. The actual database table is `watchdog`.

# Answer
> 5 votes
You can use the Drush `watchdog-show` e.g.:

```
drush watchdog-show --tail

```

More info: http://drushcommands.com/drush-5x/watchdog/watchdog-show

---
Tags: 6
---


title: do not optimize/remove html

text:
# Question
Title: do not optimize/remove html
I would like to have a page with some html content in it that CK Editor does not seem to support, in particular: I want to have a little `<form` tag with a couple of `<input` fields. I can enter it in `Switch to plain text editor` mode and save from there and it will keep the elements but when I want to `edit` the page, it'll go back to the `Switch to rich text editor` and remove my `<form` html items. How can i set CD Editor to not remove any `html` it may not be able to render? Thank you!

# Answer
Depending on which one you are using (filter or full html) You need to go to

/admin/config/content/formats/filtered\_html

OR

/admin/config/content/formats/full\_html

Then under Limit Allowed html Tags add `<form> <input>` into the list.

If that does not do it, try unchecking the correct faulty and chopped off html box.

**Edit:**

If you want to switch between text formats and not have your code erased go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.
> 2 votes

---
Tags: wysiwyg, theming
---


# Question
Title: Ajax is not working for Drupal comments form
I have created two content types slideshow and slides. I am assigning slides to slideshow with the help of node references. One slideshow can contain n number of slides. When I am showing slideshow I am using ajax to show the slides on the slideshow page there are two buttons one is Previous and second one is Next so that user can navigate to the next or previous slides and user can comment on slides means while navigating to the slides user can comment on slides. I have altered the comment form with the help of hook\_form\_alter so that page get not refreshed at the time when user comments on the form( I am using ajax api for this ). Everything is working for the first slide means ajax is working fine for the first slide and page is not getting refreshed and for the other slides it is not working. There is one more problem when I was on the second slide and clicks on the previous slide first slide will be displayed and on this page when submits the comment page is getting refreshed.

I searched on the google and other forums I am getting some information related to the Drupal.attachBehaviors() function but I dont know how to use this function.

```
function lcl_ajax_comment_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'comment_node_article_form') {
     $form['actions']['submit']['#ajax'] = array(
      'callback' => 'lcl_ajax_comment_callback',
      'wrapper' => $form['#id'],
     );
   }
 }
function lcl_ajax_comment_callback($form, $form_state) {
  // Return the actual form if it contains errors.
  if (form_get_errors()) {
    return $form;
  }
  lcl_comments_remove_status($_SESSION);
  $comment = $form_state['comment'];
  $node = $form['#node'];
  $comment_build = comment_view($comment, $node);
  $notify_text = variable_get('lcl_ajax_comments_notify', '') ? theme('lcl_ajax_comments_notify_text') : '';
  // Append comment to root comment wrapper.
  $comment_output = drupal_render($comment_build);
  $commands[] = ajax_command_append('#comment-wrapper', $notify_text . $comment_output);

  // echo "<pre>"; print_r($form_state['values']); echo "</pre>";exit;
  $node = $form['#node'];
  $new_form_state = array();
  $new_form_state['build_info']['args'][] = (object) array('nid' => $node->nid);
  // Don't pull from cache.
  $new_form_state['input'] = array();
  $new_form_build = drupal_build_form($form['#form_id'], $new_form_state);
  $new_form_output = drupal_render($new_form_build);

  $commands[] = ajax_command_replace('#' . $form['#id'], $new_form_output);
  // $commands[] = ajax_command_replace('#comments', $new_form_output);

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 1 votes
I had a similar issue with ajax pagination provided by views. I was equalising the heights of the columns using javascript but it was only working on the first page. Any columns loaded via ajax weren't having equal heights calculated. The solution to my problem was to stop using jQuery's once plugin in my behaviour. This was making it execute only once but I needed it to execute infinitely.

Usually a behaviour looks like this:

```
Drupal.behaviors.ajax = {
    attach: function(context, settings) {
      $('.your-target-element', context).once('ajax', function(){
       var $this = $(this);
       // do stuff with $this
      });
    }
  }

```

But you want to drop the once plugin like this:

```
Drupal.behaviors.ajax = {
    attach: function(context, settings) {
       // do stuff
    }
  }

```

---
Tags: ajax, javascript, comments, forms
---


# Question
Title: How to use values from a referencing node (parent) in a referenced node (child)
On a Drupal 7 site, we have two node types, one called "Collection" (parent node type) and one called "Fabric" (child node type). Collections and Fabrics are connected through an entityreference field.

We want to have a pair of values defined on the Collection node, which is then selected in various combinations for each Fabric node. These are "Colorway" and "Design". We'll define for example 3 Colorways and 8 designs for a given Collection. And when we create each Fabric for that Collection, we will choose one Colorway and one Design - there is always one value from each as a pair.

Most of the time, these values will be defined when creating the Collection node. But occasionally, we will want to add a Fabric node independently. If the needed value (e.g., the new Fabric's colorway) does not already exist, we want to be able to add it via the Fabric node/add form and have it saved back to the Collection so that the value collection's value list remains in sync.

We're wondering what the most future-proof and scalable way to build this would be. We couldn't find any ready-to-go modules to do this. We considered using taxonomy, but it doesn't seem like a good fit (though it does feel like it should be some kind of node-centered taxonomy). It feels like this should be done with fields (and some custom code to do the synching), but maybe a different approach is better?

# Answer
> 0 votes
Have you considered looking at how commerce kickstart solves this same issue? Collections are taxonomy terms and Fabrics are products.

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


# Question
Title: Wrap html in link based on uri component of other field
I need to wrap a div in a template file in an a tag whose href comes from a file field. My markup would be something like this:

```
<a href="/path/to/file">
  <h1>Title</h1>
</a>

```

Sounds easy enough but the uri that I'm given looks like this `"public://newsletter/downloads/Issue 95_0.pdf"` which renders but when clicked doesn't go anywhere. How can I turn that link into a valid link?

# Answer
I needed to use the drupal function file\_create\_url and PHP parse\_url to accomplish this.

```
function newsletter_preprocess_node(&$variables) {

  if ($variables['type'] === 'newsletter' && $variables['view_mode']) {
    // Generate a path to the file based on the download uri
    $path = $variables['field_download'][0]['uri'];
    $path = file_create_url($path);
    $path = parse_url($path);
    $path = $path['path'];
    $variables['download_link'] = $path;
  }
}

```
> 0 votes

---
Tags: theming, navigation
---


# Question
Title: How to fetch/load a node form using jquery/ajax?
In my previous question, I asked on how to fetch views blocks, now I would like to do the same with the node form but somehow this is the code that almost worked for me:

```
setTimeout(function(){
  $('.custom-form').load('?q=node/add/custom #custom-node-form', function() {
    Drupal.attachBehaviors();
  });
}, 1000);

```

The ajax/jquery of the form doesn't work anymore, for example: date field - popup calendar, unlimited field.

I also tried this:

```
setTimeout(function(){
    $('.custom-form').load('?q=node/add/custom #custom-node-form', function() {
         Drupal.attachBehaviors($('#custom-node-form'));

      });
    }, 1000);

```

still not working.

Are there other ways to load the node form with all it's ajax/jquery settings?

I'm using this kind of approach because I have a super long form. When I try to print it on the template or on the regions/blocks, it affects the load speed. I don't want this to be part of the page load.

UPDATE: I'm also trying to load the formblock module using the method I used on the ajax views as an alternative, I also can't get it to work.

Thank you.

# Answer
I don't think you've got the right parameters on the jQuery "load" method. The jQuery API page has this for the signature:

```
.load( url [, data ] [, complete ] )

```

This might be a working revision (not tested):

```
$('.custom-form').load('?q=node/add/custom', {}, function() {
     Drupal.attachBehaviors($('.custom-form'));
});

```

However, your strategy will load the entire Drupal page, not just the form. The AJAX-loaded page and form will not be in the expected request context - I'm not sure that the form can be successfully submitted in this circumstance.

You might try looking into implementing CTools Modal API instead, which is designed to allow the loading forms into modal windows via AJAX.
> 0 votes

---
Tags: forms, blocks, ajax, javascript
---


# Question
Title: Fatal error: Call to undefined function lock_initialize()
I am getting this error on a Drupal 7 site on Ubuntu 12.10. I downgraded PHP from 5.4 to 5.3, but am still getting it.

Does anyone recognize this error?

> Fatal error: Call to undefined function lock\_initialize() in /home/buck/drupal/cms/includes/bootstrap.inc on line 2366

# Answer
The function is called using code similar to the following, from Drupal.

```
  // Initialize the lock system.
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
  lock_initialize();

```

\_drupal\_bootstrap\_variables() is the only Drupal function that calls `lock_initialize()`.

That code could fail if the file whose name is contained in lock\_inc doesn't exist, but in that case I would expect another warning/error message, or it doesn't contain a function called `lock_initialize()`.

I would check if there is code that sets `$conf['lock_inc']`, and which value is used. I would also check if there is code calling `variable_set('lock_inc', ...)`.
> 1 votes

# Answer
I ran into this problem too. It occurred when I mysqldump'd my drupal db from my local dev machine and dumped it into my production db. I believe one of the cache tables had an entry that was referencing a file path that doesn't exist on my production server.

My fix: truncate all cache tables

I also restarted apache after that, but restarting apache was likely unnecessary. If you're running on linux, here's an easy command to truncate all your cache tables:

```
echo "show tables" | mysql yourdb | fgrep cache | xargs -I {} echo "truncate {};" | mysql yourdb

```
> 0 votes

---
Tags: 7
---


# Question
Title: Show audio file but require registration - suggestions for approach?
I am converting my guitar lessons site to drupal. On my previous site, I displayed an audio link, and upon clicking it, one could play the audio if they were registered. If not registered they were taken to a page asking them to register, then redirected to the lesson. The audio was in a protected folder. I am trying to do similarly in drupal. Any tips on how to get started? I am new to drupal...

Here is what I think would be ideal:

* For the lesson page, use selection rule (via panels, views, or whatever) to display the embedded audio for the registered user
* For guest user, display the embedded audio player but via guest class use javascript so when they press play they are redirected to register page, then have them register with captcha then redirect to lesson page. Or simpler, for guest user, just display a "play" icon that takes them to register page.

Ideas?

Regards

# Answer
> 1 votes
You could create a views block for the anonymous user.

1) add a **content path** field

2) Under Rewrite results, rewrite the content path field and use it's token.

Ex: `<a href="/user/register?destination=[path]"> <img src="/images/playbutton.jpg"></a>`

*Note: (the `?destination=` tag, will send them to that page after registration).*

3) Change the view **access** from permission to role and select anonymous user.

4) Add a **contextual** filter of **nid**(node ID), select provide default value, select content ID from url.

Then you could use panels, a block, or a view block, then just give it a role of authenticated and put your player there.

---
Tags: javascript, users, media
---


title: Show search results in block

text:
# Question
Title: Show search results in block
When you click on a search result, you navigate to that node or user. I would like to show the search results in a block when a user navigates to one of the search results, so the other results are always quickly available. Any idea if this is possible?

I was thinking... Make search result variable ($search\_results) global, and show this in a php block. But maybe there are better ways to solve this issue?

# Answer
Override search-result.tpl.php with below code

```
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url . '?search_keyword=' . arg(2); ?>"><?php print $title; ?></a>
  </h3>
  <?php print render($title_suffix); ?>
  <div class="search-snippet-info">
    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
    <?php endif; ?>
    <?php if ($info): ?>
      <p class="search-info"><?php print $info; ?></p>
    <?php endif; ?>
  </div>
</li>

```

Then create a view that displays search results using views module and add a contextual filter saying search term, which is returned using PHP Code.

You can read the value in views contextual filter using `$_GET['search_keyword']` and return the same.

Once view block is built, enable it in the pages you want !
> 0 votes

# Answer
At this moment I don't know any contrib module that fit this use-case but I know a module that may interest you in some way.

The module is the Search API Page Block. Here goes a summary of the module description:

> This module exposes Search API Pages as blocks and uses the node's title as keywords. This allows you to use your existing search results page to direct users to related content.
>
> Currently, this module is only useful when placing search result blocks on node pages, since it currently only uses $node-\>title as the search keywords. Future development can lead to other uses, including using Taxonomy terms, Context module, or custom fields to set the keywords.

To achieve your goal I think you will need to implement a cutom module that stores the result of the user's search and uses the result list as the content of a block implemented by your custom module.

Maybe you can try another approach by using the views module with exposed filters then use the Views filters populate to merge them in a single text field and using a block to show the view result. This approach will let you easily store the keyword in a variable using the hook\_form\_alter in conjunction with the variable\_set and so on.

Here goes a question about the Views Filter Populate that may be useful:

How to combine 2 exposed filters (String and Taxonomy field)
> 0 votes

# Answer
In addition to Anil's answer:

Use Page Manager (part of Chaos Tools) to collect the arguments from the URL and Panels to render the page with the search results visible.
> 0 votes

# Answer
Piggy backing on Anil's search result template with an alternative to the views search block, it's not too bad to implement a block displaying search results in a custom module:

```
function MYMODULE_block_info() {
    $blocks['search-results'] = array(
        'info' => t('Search Results'),
        'cache' => DRUPAL_NO_CACHE
    );

    return $blocks;
}

function MYMODULE_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'search-results':
            if (array_key_exists('search_keyword', $_GET)) {
                $element = PagerDefault::$maxElement;
                $block['subject'] = NULL; // search data renders with a header
                $block['content']['results'] = search_data(check_plain($_GET['search_keyword']), 'node');
                $block['content']['pager'] = array('#theme' => 'pager', '#element' => $element);
            }
            break;
    }

    return $block;
}

```

Granted the results didn't seem to know which pager element to render so I declared it explicitly.
> 0 votes

# Answer
search\_api\_page\_block

> The Search API Page module already exposes the search forms as block. This takes that functionality one step further. This module exposes Search API Pages as blocks and uses the node's title as keywords. This allows you to use your existing search results page to direct users to related content.
> 0 votes

---
Tags: 7, blocks, search
---


# Question
Title: How to use pager_default_initialize with entity field query?
In order to apply pagination on nodes which get rendered into block, I am using pager\_default\_initialize method. Basically I have written a query, execute that query and after that write pager\_default\_initialize() function. **But it is not applying limit to content per page.** i.e. **"paging" is not working.**

```
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', $content_type)
          ->propertyCondition('status',1);
  $results = $query->execute();
pager_default_initialize(count($results['node']), 2);

```

here, the count of nodes is 4 and I want to display only 2 nodes with pagination.

```
return theme('calender', array('calender' => $output)).theme('pager');

```

Here I'm using theme('pager') for pagination interface.

**Pagination UI is displayed, but I'm not able to put limit "2" to the no. of count of nodes. Any suggestion where I went wrong?**

# Answer
If your motive is to create a pager for those results, I suggest you to use `->pager()` on your EntityFieldQuery.

See this question EntityFieldQuery display pager

```
if ($type == 21) {
  $query = new EntityFieldQuery();

  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->fieldCondition('field_razred', 'tid', array (607,608,609,610), 'IN')
    ->pager(10) // this is the bit you're missing
    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));
  print render(node_view_multiple($nodes, 'teaser')) . theme('pager');
}

```

If you necessarily want to use pager\_default\_initialize(), see this post Creating pager in Drupal (without db\_select() and PagerDefault)

```
$per_page = 10;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));

```

Hope these examples will help you.
> 3 votes

---
Tags: paging
---


# Question
Title: How to create a new seller (store) under administrator using drupal commerce marketplace
I am using drupal commerce kickstart to create an eCommerce portal. I need to create sellers, re-sellers and sub-re sellers with in the site. i had installed commerce marketplace, but not aware of creating the new seller. Please help.

The hierarchy will be

The Service Provider has multiple resellers, each reseller can have multiple sub-resellers and finally end-users

# Answer
First you add role like seller then just add a user with role of seller and set permission for seller.
> 2 votes

---
Tags: commerce
---


# Question
Title: setting checkbox Checked in user_registration_form
```
Array
(
[account]
   [notify] => Array
                (
                    [#type] => checkbox
                    [#title] => Notify user of new account
                    [#access] => 1
                )

)

```

I want to checkbox on user\_registration\_form must be checked by default. I did `$form['account']['notify']['#default_value'] = array(1);` but it does't work.Suggest something.

# Answer
> 0 votes
Please Try this

```
$form['account']['notify']['#default_value'] = TRUE;

```

Thank You.

---
Tags: forms
---


# Question
Title: Forms display label elements as placeholder
Do you have any solution for this?

I know I can hide labels via `template.php` but how to add placeholders to some inputs?

# Answer
**SOLUTION 1:**

There is a function through which you can add placeholder to every text field based on its title.

```
function MYMODULE_auto_placeholders(&$element) {
  if ($element['#type'] == 'textfield') {
    $element['#attributes']['placeholder'] = $element['#title'];
  }
  foreach (element_children($element) as $key) {
    MYMODULE_auto_placeholders($element[$key]);
  }
}

```

Now in your form\_alter() function just call this function;

```
MYMODULE_auto_placeholders($form);

```

**SOLUTION 2:**

To add placeholder to inputs of individual from you can use `hook_form_alter` .

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'id_of_form') {
    $form['your_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

```

**SOLUTION 3:**

There is also a module to add placeholder to form input.

**Placaeholder:**

> This project adds an extra FAPI attribute called '#placeholder' to textfield field elements. Often textfields should have some text in them like "Enter your text here" until the user clicks on (or tabs to) the element in question. At that point, the text should disappear and the user can enter his or her desired input.
> 2 votes

---
Tags: forms
---


title: Field Taxonomy Reference full view

text:
# Question
Title: Field Taxonomy Reference full view
is this possible to create full view formatter for taxonomy reference field? I've tried default formatters but it only prints title of the term and nothing else...

# Answer
> 0 votes
I see.

Try this, create a view of fields of content type (ie: Articles)

In your view, under Advanced, RELATIONSHIPS, add taxonomy terms on node.

Now under FIELDS add a field, and now you should have access to the tax term fields now.

---
Tags: taxonomy-terms
---


title: Create View for a Content Type

text:
# Question
Title: Create View for a Content Type
it is a simple question. Probably the answer is simple too but it stole my 2 hours.

I have a contenty type: Article. When i create a content from it normally it shown a default display.

I want to create a view and control this display from it. How can i do that.. what should i write to url part in my view?

# Answer
> 2 votes
It's pretty simple.

1 - Go to **admin/structure/views/add**
2 - write view's name & (auto)machine name.
3 - select Content as of your content view from select list.. second select list choose YOUR content type you want to filter the result of.
4 - Select **Create a page** .. you'd have to write the title of the page .. then the path to this page example: my\_player // example.com/my\_player

other options would be up to you!

hope this helps

# Answer
> 2 votes
I find the way after two hour waste of time;

1. Create your view.
2. Add node/% to url.. or for specific content type create a pattern with pathouto and write this down instead of node.
3. Go to Contextual filters.. select "Provide default value".. and select content id from url
4. Select fields as format and add fields wish you want

It is simple but not a clear answer in site.. I hope this not steal anyone time anymore..

# Answer
> 1 votes
Views might not be a good match for what you want to do -- normally they are meant for lists of items, not just one item.

Have you tried Display Suite, in combination with Fences? It might be a better fit, depending on what you are trying to accomplish.

---
Tags: nodes, views
---


# Question
Title: How to send mail after selecting text from select list using rules?
In my content I have a select list text field. I have four options for that. While clicking only particular one in select list and giving click save. Then I want to generate mail to users.For example: I have select list fields like born, dead, live, none... while user selects born and goes to click save. I want to send a mail for administrator.

# Answer
**(UPDATED)**

go to /admin/config/workflow/rules/reaction/add

1) **Name:** Give the rule whatever name you want.

2) **React on even:** (Under Node) Select **After Saving New Content**

**Restrict by type**: select **Cage Card Info**

Now you're taken to a new page

3) Under **Conditions**, click on Add Condition.

4) In the drop down, **select TEXT COMPARISON**

5) Click on the Blue Link that says **(DATA SELECTORS)**

6) **Look for your field**, if you named it "warnings", then look for **node:field-warnings**

then **highlight it, copy and paste it under Data Selector\***

7) Under **Matching Text** put **New litter**

Then click SAVE

8) Under **Actions**, click add action

scroll all the way down, under system, select mail

9) Under **TO**, put **\[site:mail\]** OR **yourname@gmail.com** (if you don't have access to your websites e-mail inbox)

Then fill out the subject and message fields, click save.

You're done, now go and test it.

**Side Note 1**: I figured why the e-mail was not being set. I was trying namehere@gmail.com instead of putting admin@yourdomain.com as the websites admin e-mail in `/admin/config/system/site-information`

> "under Configuration/Site Information under "Site Details" you MUST insert an email address from your domain, and then the email works."

**Side Note 2**: seems like e-mails get sent after running cron. So you wont see the e-mail until cron runs. See Mail is sending after a cron run
> 2 votes

---
Tags: rules
---


title: How to db_insert into users?

text:
# Question
Title: How to db_insert into users?
I'm inserting new users into tables users (using a webservice that insert), but how to make `uid` being automatically inserted and it would be always the next value of the current maximal value on table users (and auto-increment too) ?

Thank you

# Answer
The `users` table doesn't have an auto-increment constraint on the primary key (or any field).

The recommended way to add users is using the API (`user_save()` etc), that will handle the ID for you.

Failing that, just query for the maximum ID in the table before you perform the insert; after the first insert, assuming you have exclusivity on this database while you're developing, you can maintain the increment in your code (no need to check the table each time).

Drupal does exactly the same thing in `user_save()`:

```
$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

```
> 7 votes

# Answer
Use user\_save()

and try to avoid direct db\_insert for new user creation. With direct db\_insert you cut off the whole functionality of Drupal and other Modules
> 3 votes

# Answer
you can enter new user using user\_save()

```
$account = (object) array ();
$options['name'] = $username;
$options['mail'] = $email;
$options['pass'] = md5($passwd);
$result = user_save($account, $options);
if ($result === FALSE) {
   //take some action
} else {
   //$result is the loaded user object
}

```
> 2 votes

---
Tags: database
---


# Question
Title: No delete button for a content reference
I have a custom block type in Drupal 8 where I reference an unlimited amount of content nodes. Now that I want to delete a reference, there’s no delete button available or label that mentions any kind of operation at all.

If you look at the "image reference field" there’s an operation to delete one image reference after another:

Where can I find this delete option for content references? Simply leaving the field blank and pressing save will raise a validation error.

# Answer
> 1 votes
To delete a value from your "Content Reference" field, simply leave the textfield of the desired row-to-delete blank (the multi-field widget for autocomplete fields doesn't have a delete button, it infers which rows should be maintained/deleted based on the presence of a value).

You've marked that field as required (notice the red asterisk at the top), so it must contain at least one value for the form to pass validation. If that's undesirable, just visit the manage fields page, edit the field, and remove the required constraint.

---
Tags: blocks, 8, nodes
---


# Question
Title: Custom template - How to find out whether a user has permission to access a content?
The case is as following:

* User A has access to content X and Y
* User A adds a reference field to link from content X to content Y
* User A is able to access content X and see the link to content Y and also is allowed to click on it to get forwareded to content Y
* User B is just allowed to access content X but NOT content Y
* User B should be able to see that there is a link to content Y but not be able to click on it!

The last list item is what I want to do. When I use `print_r(get_defined_vars());` for User A and B I do get different outputs but cannot really see the needed difference. In some lines of my output the link to content Y is just shown in a different line or the structure ist just a bit different. To give an example: User A's output:

```
[field_referenced_strategy] => Array
            (
                [0] => Array
                    (
                        [target_id] => 69
                        [entity] => stdClass Object
                            (
                                [vid] => 69
                                [uid] => 1
                                [title] => Strategy abc
                                [log] =>
                                [status] => 1
                                [comment] => 2
                                [promote] => 1
                                [sticky] => 0
                                [nid] => 69
                                [type] => ct_strategy
                                [language] => en
                                [created] => 1439297478
                                [changed] => 1441705417
                                [tnid] => 0
                                [translate] => 0
                                [revision_timestamp] => 1441705417
                                [revision_uid] => 1
                                [body] => Array

```

User B's output:

```
[field_referenced_strategy] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 69
                                [entity] => stdClass Object
                                    (
                                        [vid] => 69
                                        [uid] => 1
                                        [title] => Strategy abc
                                        [log] =>
                                        [status] => 1
                                        [comment] => 2
                                        [promote] => 1
                                        [sticky] => 0
                                        [nid] => 69
                                        [type] => ct_strategy
                                        [language] => en
                                        [created] => 1439297478
                                        [changed] => 1441705417
                                        [tnid] => 0
                                        [translate] => 0
                                        [revision_timestamp] => 1441705417
                                        [revision_uid] => 1
                                        [body] => Array

```

This is just a part of my output. But as you can see the structure is even different but there is not flag or anything like that that distinguishs the accessibility of the user.

I hope my point is clear.

# Answer
> -2 votes
You can use the user\_access() funtion

---
Tags: 7, users
---


# Question
Title: Drupal simplenews doesn't subscribe the users registed via social networks
I'm using Simplenews module for sending newsletter to the registered users. When a user creates a new account he/she will be automatically subscribed to a newsletter which can be seen in **admin/people/simplenews**.

However, when user registers via social network he/she is not subscribed to newsletter. When I visit **admin/people/simplenews** I can see only the users registered in normal way; users registered through a social network cannot be seen.

I'm using HybridAuth for Twitter & Google+ login and Fboauth for Facebook login. In simplenews configuration, I've used **silent** setting. What can I do to make users sign up to a newsletter on social network registration?

# Answer
> 1 votes
The reason users aren't signed up is due to how simplenews works. It does the work of newsletter signup by modifying the Drupal core registration form to capture the newsletters (or setting them automatically in case of the silent option) then takes that data to sign users up following account creation.

For both HybridAuth & FBOauth, they subvert this process with their own forms to do authentication with a 3rd party. Both HybridAuth & FBOauth however, provide their own API hooks to take action upon user registration (`hook_hybridauth_user_insert()` & `hook_fboauth_user_save()` respectively). You can implement their hooks in a custom module to do the same work HybridAuth does to signup users automatically.

# Answer
> 1 votes
Finally got the solution with help of instructions given in the above answer. I just simply called the `simplenews_subscribe_user()` inside hook\_hybridauth\_user\_save().

```
function my_module_fboauth_user_save($account, $fbuser) {
  simplenews_subscribe_user($account->mail, 15, $confirm = FALSE, $source = 'automatically', NULL);
}

```

I don't whether this method is a correct procedure to solve above problem. But it works for me.

---
Tags: emails, social-network
---


# Question
Title: Show profile2 fields only to specific user register path
I am interested in showing profile2 fields only to specific user register path (I have 2 user register path). How can I do this without using the Profile2 registration path module as another module creates the paths? thanks

# Answer
You could apply that patch to **profile2\_regpath.module** which simply show all profile fields to its registeration patch posted here
> 0 votes

---
Tags: users
---


# Question
Title: How do I get the file URI from an EntityMetadataWrapper object?
Getting hold of file objects related to nodes through a field is easy using an `EntityMetadataWrapper`:

```
$wrapper = entity_metadata_wrapper('node', $node);
$images = $wrapper->field_images;

```

So that's great. However, I want to use some of the properties of the standard file object, and they're not available. When I look at the properties available on `$images[0]->file` using the above code, I see these:

* fid
* name
* mime
* size
* url
* timestamp
* owner

Most notably, `uri` is missing, and in its place there's a `url` property, which is the full external URL to the image file. I want to manipulate these images via their URI (create thumbs, etc), so I'm left doing this:

```
$fid = $images[0]->file->fid->value();
$uri = file_load($fid)->uri;

```

Which seems to negate the whole point of using an `EntityMetadataWrapper` in the first place.

What am I missing? Where is the URI on the wrapped file object? If it's not available, for the love of all things good and pure, why not?!

I'm aware I could deconstruct the URL back to a URI, but that also feels very unnecessary.

# Answer
Big thanks to MPD for pointing me in the right direction. In short, without the File Entity module, files aren't entities, so they don't naturally have the 'properties' I was expecting.

The Entity module provides some on their behalf, but URI isn't one of them. Fortunately it's very simple to make it available using `hook_entity_property_info_alter()` and a custom property callback:

```
function MYMODULE_entity_property_info_alter(&$info) {
  $info['file']['properties']['uri'] = array(
    'label' => t("URI"),
    'description' => t("The URI of the file."),
    'getter callback' => 'MYMODULE_entity_get_file_properties',
    'schema field' => 'uri',
  );
}

function MYMODULE_entity_get_file_properties($file, array $options, $name) {
  switch ($name) {
    case 'uri':
      return $file->uri;
      break;
  }
}

```

After that, `$images[0]->file->uri->value()` is available as expected.
> 9 votes

# Answer
Below works without the hack:

```
 $node_wrapper->field_media[0]->value()['uri'];

```
> 8 votes

# Answer
This is what works for me to get the full path of a single image...

```
// wrap it
$wrapper = entity_metadata_wrapper('node', node_load(16));
// get the value
$image = $wrapper->field_image->value();
// check it
if ($image) {
   // get the full path
   $path = file_create_url($image['uri']);
}
print_r($path);

```

Alternatively...

```
  $image = $wrapper->field_image->value();
  $image_path = $image ? file_create_url($image['uri']) : '';

```
> 3 votes

---
Tags: 7, entities
---


title: Entity Registration special form

text:
# Question
Title: Entity Registration special form
How to make Entity registration form with my fields + list of all events available?

# Answer
> -1 votes
You need a module called entityform. There you can create a webform using all of your existing fields.

---
Tags: entities, nodes
---


title: load a class in hook_install

text:
# Question
Title: load a class in hook_install
In my custom module I have created a class in `mymod/src/Controller/TestClass.php`.

In hook\_install I want to call a function of that class

```
function mymod_install() {
Drupal\mymod\TestClass::testfunction();
}

```

and the TestClass.php contains the following code

```
namespace Drupal\mymod
  class TestClass {
    public static function testfunction() {
     // do some stuff
    }
 }

```

But whe I try to enable the module It gives me the following error.

```
Error: Class 'Drupal\mymod\TestClass' not found in
/var/www/drupal8/modules/custom/mymod/mymod.install, line 16

```

Is the hook\_install executes first from autoloading the class of this module?

How will I call that function from hook\_install?

# Answer
> 3 votes
If your class is here:

> mymod/src/Controller/TestClass.php

Then your namespace is wrong. It should be:

```
Drupal\mymod\Controller\TestClass::testfunction();

```

You'll also need to update the namespace in the class file itself:

```
namespace Drupal\mymod\Controller

```

Or, instead of making those changes, you could just move TestClass.php to mymod/src.

---
Tags: 8, installation
---


title: Deleting content types programmatically

text:
# Question
Title: Deleting content types programmatically
I'm trying to delete some content types which are no longer used but are still active.

I'm going to deploy the update using `hook_update_N` and have this so far (Code taken from `node_type_delete_confirm_submit`:

```
function hook_update_N(&$sandbox) {
  node_type_delete('mynodetype');
  variable_del('node_preview_mynodetype');
  node_types_rebuild();
  menu_rebuild();
}

```

The problem I'm having is that the node type is deleted, but the nodes of that type are still there in the database. Running cron hasn't deleted those nodes (I'm not even sure if that's the default behavior when deleting content types through the admin UI)

My question is:

* Are the nodes deleted automatically after a certain time through Cron or some other method? If not then doing it manually, would it be best to do it before deleting the content type or after?

# Answer
> Are the nodes deleted automatically after a certain time through Cron or some other method?

They are not; IIRC, the `type` property for these nodes will be set to an empty string. No content will be deleted, though.

> would it be best to do it before deleting the content type or after?

It probably doesn't matter, hugely, but conventional wisdom would be to sever the connection from the node to the content type *before* deleting the type (whether that's deleting the nodes or moving them to another content type).

That way you're not stepping on the implied (but of course not enforced) referential integrity between those data types, and you're decreasing the potential surface area for while-we're-updating errors.
> 3 votes

# Answer
```
$ournewtype = 'voucher';
$sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
  $nodeids[] = $row->nid;
}
node_delete_multiple($nodeids);
node_type_delete($ournewtype);

```
> 4 votes

---
Tags: 7
---


# Question
Title: How to auto-submit a form using Drupal Form API?
I need help with making a drupal form. I've made the form and it works perfectly fine, all it does is capture the email, ip, and date and time of a user. The problem is I don't want the user to have to click a button in order to submit the form, I want the form to automatically submit after a second or something.

```
//form hook, form elements start here

function form_casl_form($form, &$form_state) {
//sometext here
 $form['some_text'] = array(
    '#markup' => '<p><b>Simply click the button to subscribe.</b>
    </p>'
);

  //submit button
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Subscribe'),

  );
  return $form;
}
    //validate hook

```

Is there anyway to do this? I'm very close to finishing and this is the only thing I'm stuck on, any ideas would be appreciated!

# Answer
There is no solution to auto-submit a form using only Drupal Form API. You will need to add some lightweight custom JavaScript to your form in order to achieve this. The proper way to add JavaScript to your form is to use the #attach attribute of the form.

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

```

The JavaSript code itslef is pretty simply, just remember to properly wrap it in a Immediately Invoked Function Expression and to use Drupal.behaviors and jQuery Once.

```
Drupal.behaviors.YOURMODULE = {
  attach: function(context, settings) {
    $('.your-form-selector', context).once('YOURMODULE').delay(10000).submit();
  }
}

```
> 4 votes

# Answer
This one is a pretty easy method by adding `'onChange'` to the `'#attributes'` array:

```
/**
 * Custom form handler.
 */
function FORM_EXAMPLE($form, &$form_state) {

  $form['complete_projects_radios'] = [
    '#type'          => 'radios',
    '#title'         => t('Project status'),
    '#default_value' => 0,
    '#options'       => [
      0 => t('Current'),
      1 => t('Complete'),
    ],
    // Define the onChange like so:
    '#attributes'    => [
      'onChange' => 'this.form.submit();',
    ],
  ];

  $form['complete_projects_submit'] = [
    '#type'       => 'submit',
    '#value'      => t('Apply'),
    // The submit itself is necessary, but now it can be hidden:
    '#attributes' => [
      'style' => ['display: none;'],
    ],
  ];

  return $form;
}

```
> 16 votes

---
Tags: 7, forms, javascript
---


# Question
Title: Exception handling in drupal : How one can deal with warnings in Drupal?
How one can deal with warnings in Drupal? If the code is getting executed smoothly, **then what's the purpose of these warnings?** Is there any way to deal with drupal "warnings", "notices".

**one example here is:** I have written hook\_uninstall

```
function hook_uninstall(){
   if (field_info_field('hide_field')) {
        field_cache_clear();
        field_delete_instance('hide_field');
        field_delete_field('hide_field');
    }
}

```

and this code is throwing warning:

**Warning:** Illegal string offset 'field\_name' in field\_delete\_instance() (line 772 of modules/field/field.crud.inc).

**Warning:** Illegal string offset 'entity\_type' in field\_delete\_instance() (line 773 of modules/field/field.crud.inc).

**Warning:** Illegal string offset 'bundle' in field\_delete\_instance() (line 774 of /modules/field/field.crud.inc).

**Warning:** Illegal string offset 'field\_name' in field\_delete\_instance() (line 781 of modules/field/field.crud.inc).

**Warning:** Illegal string offset 'field\_name' in image\_field\_delete\_instance() (line 480 of /modules/image/image.module).

**and there is no halt in the execution of the code. I'm very much curious about how drupal deals with exceptions, warnings, notices.**

**What does these warnings mean?**

**And can we contribute our module to drupal community if warnings or notices exits in module?**

**Can anyone share their piece of knowledge here?**

# Answer
> 1 votes
The purpose of warnings are to **warn** you that something is wrong with the code you've executed. They are provided by PHP, not by Drupal (though Drupal can trigger them if required). Notices are similar, but considered less urgent. Warning/notices are not fatal, so don't halt the scripts' execution.

The way to "deal with" them is to simply fix the code, which might mean fixing *your* code, reporting a bug to a core/contrib issue queue, digging through a request to make sure that the value of variables being passed around are what they're expected/required to be, or something else.

Some people might tell you just to disable warnings/notices so that they're not bothering you visually, but as in all walks of life, hiding a problem instead of fixing it is a bad idea.

There isn't a catch-all answer to fixing every possible type of warning. You need to debug the site, find out exactly what and where the problem is, and apply your skills as a developer to fix them.

I don't know what the policy is for contributing modules that containing warnings/notices. I would hope that they are, at least in an initial review, rejected if they cause such things, but that might not be a practical expectation.

Regarding how Drupal deals with them: the answer is that it doesn't, really. You can switch on and off the display of error messages through the admin UI, but Drupal can't, and doesn't, have any interest in fixing these errors, or helping you any further to narrow down what's causing them. It's just a PHP app at the end of the day.

Incidentally, Drupal does implement its own PHP error handler (`_drupal_error_handler_real()`), so that it can log errors and exceptions in the watchdog, and/or to the screen.

# Answer
> 0 votes
**Notices vs Warnings vs Errors**

There are three main ways in which PHP will report problems: notices, warnings and errors.

**Notices**

These are the least important. According to the official PHP website, notices are generated when:

"the script encountered something that could indicate an error, but could also happen in the normal course of running a script."

**Warnings**

Warnings are more serious, but probably won't break your site. According to the official PHP website, warnings are:

"non-fatal errors. Execution of the script is not halted."

**Errors**

Errors are the most serious type of problem and may break your site. According to the official PHP website, warnings are:

"Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted."

**Option 1: Disabling Error Reporing on Your Drupal Site**

One the solution, and probably the one you'll take first, is to stop the errors from showing.

* Go to Configuration \> Logging and Errors.
* You have three choices:
    + **None** will disable all error reporting.
    + **Errors** and warnings will display on the most serious problems.
    + **All messages** will display all problems and is probably only useful for developers.

**Option 2: Fix the Problem**

Yes, yes, I know this is a controversial idea. Fixing a problem is definitely harder than hiding a problem.

Here are some suggestions to help you fix the problem. Please backup your site before trying any of these.

Make sure your Drupal site and all your modules and themes are up-to-date. Search Google and Drupal.org for anyone who has reported the same message. See if they have found a solution. Read the message itself for hints about the problem. For example, the problem in the image at the top of this tutorial is all/modules/calendar/includes/calendar\_plugin\_display\_page.inc on line 47. This tells that the problem may well be with the Calendar module, because the error is coming from the Calendar module folder.

---
Tags: 7, debugging
---


title: Send Mail to Specific Roles

text:
# Question
Title: Send Mail to Specific Roles
I need to send Emails to site users with specific role like "Administrator".

This is achievable using view on any action like "After saving new content".. etc..

But i want to send emails on one menu click event, I have menu item in Management Menu of Drupal and on click of that i want to send mails to all admin users.

How this is achievable?? Please suggest me guys..

Thanks in advance..!!

# Answer
With custom module. See hook\_menu()

As page\_callback define your "send mail" function for restricted user roles
> 1 votes

---
Tags: routes, rules
---


# Question
Title: Grouping the nodes based on the taxonomy terms
A specific taxonomy page should display its description as well as the grouped teasers of the pages with the other taxonomy terms. For example: An article (Article1) is having 2 taxonomy terms : Accounting, Finance. Another article (Article2) has 2 taxonomy terms: Accounting, Money.

My output **when I see the Accounting term page** (Example: http://www.myexample.com/group/accounting), the page output will contain the Accounting term description and the grouping of the remaining Taxonomy terms that the articles are linked to.

**Finance**

* Article 1
* Article x
*

**Money**

* Article 2
* Article y
*

I need a little customization here by grouping the articles with the remaining Taxonomy terms. I tried Views with Taxonomy Display and Taxonomy Views Integrator. But, couldn't organize the output.

Is there a way to alter the output of the 3 different taxonomy terms using Views?

# Answer
> 0 votes
**Create a view add two fields:**

1. Node title
2. Taxonomy Term

**Follow these steps :**

1. Taxonomy Term" field to "Exclude from display
2. Set format = unformatted list in Format section
3. Set group Field as taxonomy term

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


# Question
Title: Automatically update Drupal core/modules for a large number of sites (with Drush)?
I'm the administrator of a lot of Drupal websites on different hosting providers.

Some have drush; others don't (and can't: like shared hosting).

Every time there is a Core upgrade, I spend 1 or 2 hours updating everything (I make a backup of every website before an upgrade).

Updating sites with Drush is simple, but I need to do it for every website, like :

* drush @dev up
* drush @othersite up
* and wait... wait... wait...

How can I automatically update Core (and modules) on:

* all my drush sites ? (I think : cron with bash script)
* all my non-drush sites ?

Is this safe, or do you not recommend it?

# Answer
What I would suggest, is to store all your Drupal sites in GIT repositories. With a separate branch / repo for Core and as many as necessary for /sites/\*

Then you can easily do updates to cores by a simple pull. For shared hosting, pull locally, then sync by lftp to your distant hosts.
> 5 votes

# Answer
With Drush you can use

```
drush @sites up

```

To update all your sites at once.

I guess you could use drush to remotely update your non drush sites too.
> 1 votes

# Answer
You can use drush command to update your site

```
drush upc --no-core

```

More druh commands
> 0 votes

---
Tags: drush, updating
---


# Question
Title: Configuring views to display all book-pages inside a book, from whenever you are inside the book
Configuring views to display all book-pages inside a book, from whenever you are inside the book.

Is this possible? If so please advice the way to do it.

The contexual filter of **All sub nodes of this book page** creates an error soon as I relate it to any position or Node ID on a book-hierarchy. When set **view all pages** instead - other books page is viewed together with the pages I want to display.

(The Relationships here is set to **top level book** with **Require this relationship**)

# Answer
> 1 votes
I did found the reason why it not work (as it should), it's probably a bug at the "filter criteria", who not where working with setting of *Book depth*. I am lucky because I had different content-types on each level of the book. And when trash away the book depth *filter criteria* I could set filtering on the *Content type* instaed, and all works out as I wanted. So this problem is solved,now I can **display all book-pages inside a book, from whenever you are inside the book** without any problem.

---
Tags: views
---


title: add a link next to the search button?

text:
# Question
Title: add a link next to the search button?
I like to add a "help tips" link next to the search button. I made some changes on the "search-block-form.tpl.php" (see below) but it does not show on the search result page.

Some documentation on the web suggests using function hook\_form\_alter to make the changes. Thank you in advance

```
<div>
  <?php if (empty($variables['form']['#block']->subject)): ?>
    <h2 class="element-invisible"><?php print t('Search form'); ?></h2>
  <?php endif; ?>
  <?php print $search_form; ?>
  <a class="h_tips" href="help_tips">help_tips</a>
</div>

```

# Answer
> 1 votes
```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['help_link'] = array(
      '#markup' => '<a class="h_tips" href="help_tips">help_tips</a>',
    );
  }
}

```

That should do the work, but I am not sure if the id 'search\_block\_form' the right one is. If you don't have any custom module, just place this code into your current template's template.php, replace MODULENAME with templatename, save and clear cache.

---
Tags: search, forms
---