# Question
Title: How to add a JS confirmation popup when clicking an #ajax button
I have a basic FAPI button input that is #ajax enabled and that's working fine, but I want to add a JS "Are you sure?" confirmation popup when clicking the button before the code actually runs, and I'm not sure how to do that because FAPI's JS seems to be eating the click before I can get to it no matter what I do.

I've tried adding an inline onclick handler, like so:

```
$form['search_filters']['channels']['channel_delete_' . $channel->nid] = array(
  '#type' => 'button',
  '#name' => 'channel_delete_' . $channel->nid,
  '#value' => 'Delete',
  '#attributes' => array(
    'class' => array('confirm'),
    'onclick' => "return confirm('Are you sure you want to delete that?')"
  ),
  '#button_type' => 'no-submit',
  '#ajax' => array(
    'callback' => 'delete_channel_callback',
    'wrapper' => 'channel_container_' . $channel->nid
  ),
);

```

...which doesn't help, and I've also tried adding:

```
$('.confirm').click(function(e) {
  e.preventDefault();
  alert('Is this recognized')? // never runs
});

```

in my module's JS which is also ignored.

Any other ideas? Is there a way to add a submit handler to the top of the stack which Drupal #ajax will recognize?

# Answer
Drupal is a PHP framework, and it's amazing how much fancy AJAX stuff you can get using that and the FAPI. But it has it limits and for a use case like this, I would suggest that you use custom JavaScript. Also instead of using the usually JavaScript dialog, you could use jQuery UI to create a themable dialog instead.

Anyways the problem that you're facing is probably caused because you use AJAX on the submit button. Since you are using AJAX for the actual delete call, `preventDefault` and the like won't work.

What you would have to do is something like this. (This is not widely tested but should work.)

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

    var events = $('.confirm').data('events'); // Get the jQuery events.
    $('.confirm').unbind('click'); // Remove the click events.
    $('.confirm').click(function () {
      if (confirm('Are you sure you want to delete that?')) {
        $.each(events.click, function() {
          this.handler(); // Invoke the click handlers that was removed.
        });
      }
      // Prevent default action.
      return false;
    });
  }
}

```
> 15 votes

# Answer
The question is old, but I was also interested in it. In my opinion, the easiest way is to use the click event in your Ajax definition, because Drupal uses the mousedown event as default:

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('some value'),
  '#attributes' => array(
    'class' => array('some-class'),
    ),
  '#ajax' => array(
    'event' => 'click',    //add this line!
    'callback' => 'some_callback',
    'wrapper' => 'some-wrapper',
  ),
);

```

Then you just need to add a `.mousedown()` event to your button in your Javascript file, because it is fired before the click event:

```
$('.some-class').mousedown(function() {
  //do something
});

```

If you still want your Ajax Request called with the mousedown event, you can use a custom event:

```
//change this line in the Ajax Defintion of your button
'event' => 'click',
//to
'event' => 'custom_event',

```

Then you can trigger this event in the `.mousedown()` event of your Javascript file:

```
$('.some-class').mousedown(function() {
  //do something
  $('.some-class').trigger('custom_event');
});

```

Both versions work!
> 5 votes

# Answer
confirming that Jeroen is fixing the googletorp's code.

However, i myself discovered that the evens of type "mousedown" have to be unbid and binded again. So the piece of code that worked for me is the following:

```
(function ($) {
  Drupal.behaviors.confirm = {
    attach: function(context, settings) {
      var events =  $('.form-submit-delete').clone(true).data('events');// Get the jQuery events.
      $('.form-submit-delete').unbind('mousedown'); // Remove the click events.
      $('.form-submit-delete').mousedown(function () {
    if (confirm('Are you sure you want to delete that?')) {
      $.each(events.mousedown, function() {
        this.handler(); // Invoke the mousedown handlers that was removed.
      });
    }
    // Prevent default action.
    return false;
      });
    }
  }
})(jQuery);

```
> 4 votes

# Answer
Have you tried running your JS inside of a Drupal behavior? It could just be that your click handler is being attached after Drupal's.

Either way though you should be able to unbind Drupal's click handler on the button so that you're called first and you can call Drupal's Ajax click handler manually (and conditionally).
> 0 votes

# Answer
Answering to note that googletorp's code is not 100% correct.

You need to change the line where the events are stored to this:

```
var events = $('.confirm').clone(true).data('events'); // Get the jQuery events.

```

This way you eliminate any object reference problems, so when unbinding the click events, it doesn't unbind in your var as well ;)

Also, be advised that since jQuery 1.8 the .data() method has been deprecated. Getting event data is now done via an internal data structure:

> **.data(“events”)**: jQuery stores its event-related data in a data object named (wait for it) events on each element. This is an internal data structure so in 1.8 this will be removed from the user data name space so it won’t conflict with items of the same name. jQuery’s event data can still be accessed via jQuery.\_data(element, "events") but be aware that this is an internal data structure that is undocumented and should not be modified.

Source: http://blog.jquery.com/2011/11/08/building-a-slimmer-jquery/
> 0 votes

# Answer
I found many useful answers above and was able to get my form working. Putting it all together, this is what worked for my application: A delete form button with a confirmation dialog and AJAX callback to modify the contents of a select list.

**The javascript:**

```
$form['my_form']['delete_button_js'] = array(
  '#markup' => '<script type="text/javascript">
  (function ($) {
     // override the default confirmation dialog behavior
     Drupal.behaviors.confirm = {

      // Get the jQuery events.
      attach: function(context, settings) {
      var events =  $(\'.deleteButtonClass\').clone(true).data(\'events\');

      $(\'.deleteButtonClass\').unbind(\'mousedown\'); // Remove the mousedown event.

      $(\'.deleteButtonClass\').mousedown(function () {
           // Popup the confirmation
           if (confirm(\'Are you sure you want to delete the Group?\')) {
             // if YES, then we fire the AJAX event
             $(\'.deleteButtonClass\').trigger(\'deleteGroupEvent\');
           }
           // Override the default action.
           return false;
        });
    }
            }
  })(jQuery);
  </script>
  ',
);

```

**The form element (select list) to be modified:**

```
$form['my_form']['select_list'] = array(
         '#type' => 'select',
         '#title' => t('My Title'),
         '#options' =>  $optionsArray,
         '#size' => 5,
         '#prefix' => t('<div id="mySelectList">'),
         '#suffix' => t('</div>'),
    }

```

**The button:**

```
$form['my_form']['delete_button'] = array(
  '#type' => 'button',
  '#value' => 'Delete',

  '#attributes' => array(
      'class' => array('deleteButtonClass'),
    ),

  '#ajax' => array (

    // this is the custom event that will be fired from the jQuery function
    'event' => 'deleteGroupEvent',

    'callback' => 'ajax_delete_callback',
    'wrapper' => 'mySelectList',
    ),

);

```

**And finally, the AJAX callback:**

```
function ajax_delete_callback ($form, $form_state) {

  // callback implementation code

  return $form['my_form']['select_list'];
}

```
> 0 votes

# Answer
I have fixed this by modified the drupal misc/ajax.jx file.

Create a copy of ajax.js file and put it any custom module and modified the `Drupal.ajax = function (base, element, element_settings) {` function in beforeSend:

```
beforeSend: function (xmlhttprequest, options) {

    if( ajax.url =='/?q=field_collection/ajax'){ // condition for when click on the Remove button
      if (confirm('Are you sure you want to remove this?')) {
       ajax.ajaxing = true;
       return ajax.beforeSend(xmlhttprequest, options);
      }
      xmlhttprequest.abort();
    } else{
        ajax.ajaxing = true;
        return ajax.beforeSend(`xmlhttprequest`, options);
     }
},

```

Its working fine for me.
> -1 votes

# Answer
Maybe a bit old, but I am wondering why we cannot just use:

```
(function($, Drupal, window, document, undefined) {

Drupal.behaviors.oc_ua_pc = {
  attach: function(context, settings) {
    $('#button').click(function () {
      if(confirm('This action cannot be undone and you cannot change the form later. Do you want to submit?')) {
        return;
      }

      return false;
    });
  }
}
})(jQuery, Drupal, this, this.document);

```
> -1 votes

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


title: Mimic webform date field in custom form

text:
# Question
Title: Mimic webform date field in custom form
In one instance we are using a webform to create a form and it uses field type 'date'. The end result looks like this:

I would like to mimic this, but in a custom form. Currently what I have is:

Code:

```
 $form['date_starting'] = array(
  '#type' => 'date_select',
  '#title' => t('Starting'),
  '#date_label_position' => 'within',
  '#date_format' => 'm d Y',
  );

```

# Answer
If you have date\_popup enabled you can achieve the calendar part by using this:

```
$form['date_starting'] = array(
  '#type' => 'date_popup',
  '#title' => t('Starting'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-3:+3',
);

```

Then you can style the input field as a calendar button and use javascript to copy the date value to your date select.
> 0 votes

---
Tags: forms, datetime
---


# Question
Title: How to import content in markdown format?
I have text in markdown format. How should I go about importing this into my site? I would think a Feeds Tamper plugin to convert markdown to html would be ideal.

Does such a thing exist? Is there a straightforward way to convert markdown to html in Drupal?

# Answer
Why complicate things by importing markdown? If html format is what is desired, there are many options to convert it beforehand. For example this simple python implementation.

As tenken suggested, Markdown filter is an option to consider.
> 1 votes

---
Tags: 7, importing-exporting, feeds, input-formats
---


# Question
Title: how to filter view having three group with one or and two and group?
I am having a view with three group filter i want to add condition like this

**Example Below:**

group1

field1 (and) filed2

**AND**

group2

field1 (or) filed2

**OR**

group3

field1 (or) filed2

what issue i actually face is when i change the second and third group filter to **AND** automatically the first and second group value is changing to **OR** how to solve this

Thanks in advance.

# Answer
For ease of use I would suggest looking at Views Raw SQL. While Views is a powerful query builder, it sometimes makes assumptions and in a general sense is designed to solve 80% of general types of listings and queries -- when implementing advanced logic, it can fail short.

Another option is to use the Views API Hooks (hook\_views\_query\_alter) and alter the query using a small custom drupal module.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Get view via php based on page number and 1 argument (uid)
I have a view that it has an contextual filter based on "uid". Now I need to get it via PHP and I can use views\_embed\_view(). But I need to get only page FOO or page BAR and views\_embed\_view() accepts only "arguments/contextual filter".

Which is the correct way to call views FOO, for display BAR, using argument "uid = X" and get only "page = Z"

Thanks.

M.

# Answer
You can specify a page inside a view with views\_embed\_view().

Fisrt argument will be the view's name

Second will be the page you want to display (Defaults to default)

And then as many contextual filters you want/have

So it will look something like this views\_embed\_view('view\_mahcine\_name', 'page\_3', uid);
> 0 votes

# Answer
I think you have 2 options to set the pager offset programmatically:

Because `views_embed_view()` does not take any parameters for a pager or exposed filters directly, I think you could implement your own version of its "guts" that also internally sets the pager data manually. Here's an excerpt of how to do that from this post (disclaimer, I've not personally tested this):

```
$view_args = array(); // contextual filter args go here
$view_object = views_get_view($view_name);
$view_object->set_current_page($offset); // manually set page offset
$html = $view_object->preview($view_display, $view_args);

```

Alternatively, if really have to use `views_embed_view()`, then I think you'll have to modify the `$_GET` global variable directly before-hand, or ensure that your "page" query string is already in the URL. As far as I know views typically extracts the pager offset directly from `$_GET['page']`. The trick here is that it's not necessarily guaranteed that view's internal build/execute methods didn't manually overrride the pager data in some way, and you would have to be sure you don't have any conflicts with other pagers on the same page. It's also never great to be manipulating globals directly. Anyway, for most vanilla views, setting `$_GET['page']` before calling `views_embed_view()` would likely work, but the first solution is still probably preferred.
> 0 votes

---
Tags: 7, views
---


# Question
Title: calculated field in views based on another view
i have a view with items and prices, each item has an id, another view taken from a different content type also shows items and their base price the id of the item will be the same (basically one list is items containing seller prices and another is the market price, there can be many sellers but only one market price).

now i want to show in the first view a calculated field that will display the difference between the seller price (price of an item in first view) and the market price (the price of the item containing the same id in the second list).

is there a way to do it? if so how?

# Answer
One way to do this would be to create a field template for that specific field. Then you could first print the value of the seller price, and then do the calculations in php and print the difference.

You can specify that the field template only be used for a specific field in a specific display of a specific view by naming it correctly. You'll find the pertinent names in your view edit page under Advanced -\> OTHER -\> Theme: Information. The default contents of a template file are also available there by clicking on the field name.
> 0 votes

---
Tags: views
---


# Question
Title: How do you render a set of checkboxes without using drupal_get_form()?
I want to use a '#type' =\> 'checkboxes' render array to display some checkboxes on the page. They aren't going to be part of a form that ever gets submitted, as they are purely for browser-side user interaction. So I don't need any of the extra functionality provided by drupal\_get\_form(). I *just* need a few `<input type="checkbox">` elements.

Unfortunately, Drupal appears to simply refuse to render '#type' =\> 'checkboxes' render arrays unless you pass the array through `drupal_get_form()`. When I try, absolutely nothing except

```
<div class="form-item form-type-checkboxes">
 <label>Landmarks</label>
 <div class="form-checkboxes"></div>
</div>

```

gets rendered.

Is there any way to get Drupal to render an `<input type="checkbox">` element without using `drupal_get_form()`?

# Answer
> ...I just need a few `<input type="checkbox">` elements.

Just render it as plain html, and if you absolutely want a render array, then create your own theme function for it.

```
$variables['content']['checkboxes'] = array(
    '#markup' => '<div class="display"> Please select every sport that you play.<br> Soccer: <input type="checkbox" name="sports" value="soccer"><br> Football: <input type="checkbox" name="sports" value="football"><br> Baseball: <input type="checkbox" name="sports" value="baseball"><br> Basketball: <input type="checkbox" name="sports" value="basketball"><br>
</div>'
);

```
> 3 votes

# Answer
use this tested code

```
$element = array(
 '#type' => 'checkboxes',
 '#title' => 'test',
 '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
 '#parents' => array(),
);

$form_state = array('values' => array());
$form_Build = form_builder('just_test', $element, $form_state);
print drupal_render($form_Build);

```
> 2 votes

# Answer
I believe this doesn't work because `form_process_checkboxes` isn't called if you don't run it through the form API.

Before you `drupal_render` your element, try running it through `form_process_checkboxes` manually.

```
$form['yourCheckboxes'] = form_process_checkboxes($form['yourCheckboxes']);
print drupal_render($form);

```
> 1 votes

# Answer
An example of code :

```
$accounts = user_load_multiple(array_keys($values));
foreach($values as $uid => $value) {
  $element[$delta][$uid] = array(
    '#type' => 'checkbox',
    '#title' => format_username($accounts[$uid]),
    '#checked' => !empty($value),
    '#attributes' => array('disabled' => 'disabled'),
  );
}

```

Later (may not be needed in your code):

```
drupal_render($element);

```
> 0 votes

# Answer
Have you looked at theme\_checkbox? Unfortunately, it only renders the checkbox, so you'd have to add the labels yourself. But if you're really looking for a Drupal-esque solution, this could be viable.

Example:

```
<?php

$element = array(
  '#id' => 'checkbox-id',
  '#name' => 'checkbox-name',
);

echo '<label for="checkbox-id">Checkbox</label>'. theme('checkbox', array('element' => $element));

?>

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: What is the correct way to render content from custom content type?
I am new to Drupal and am realising that there are a number of ways to perform even the most basic task but it is hard to know which way is right.

When rendering fields from a custom content type which of the following ways is correct/most efficient/safest way or am I wrong and there is another even better way?

Option 1 - this way seems a little verbose but I have read in a number of places that this is the correct way to render individual fields.:

```
<?php $included = field_view_field( 'node', $node, 'field_what_s_included', array('label' => 'hidden') );
            print render($included);
        ?>

```

Option 2 - This way seems much neater and is also written about a lot:

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

```

Thanks for clarifying this for me.

James

# Answer
> 2 votes
Option 2 is the preferred option.

Use the default node.tpl.php as a reference.

You can see it uses the hide() function to hide fields it doesn't want to render and the render() function to render fields.

This is because all the processing you are doing in option 1 with field\_view\_field() has already been done and is ready to render, so you don't need to do it again.

I recommend doing some reading on overriding themeable output, which involves overriding markup with theme functions and template files.

---
Tags: entities, theming
---


# Question
Title: Image getting delete away by the cronjob later in drupal 7 using theme settings
i\`m using system theme settings alter to add 4 images for theme, images are getting deleted /swept away by the cronjob later .trying using FILE\_STATUS\_PERMANENT images are not getting set as permanent

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

  $form['themeA_settings']['header-page']['header_background_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Header Background'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('header_background_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  '#submit' => array('themeA_submit_handler'),
  );

  $form['themeA_settings']['block1']['block1_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('block1 image'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('block1_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  '#submit' => array('themeA_submit_handler'),
  );

 $form['themeA_settings']['block2']['block2_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('block2 image'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('block2_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
'#submit' => array('themeA_submit_handler'),
);

$form['themeA_settings']['footer']['background_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Footer Background'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://themebackrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
 '#submit' => array('themeA_submit_handler'),
  );

  }
   function themeA_submit_handler($form, &$form_state) {
        // Load the file via file.fid.
     if (isset($form_state ['values']['header_background_file'])) {
     $file = file_load($form_state['values']['header_background_file']);
          }
     if (isset($form_state ['values']['block1_file'])) {
       $file = file_load($form_state['values']['block1_file']);
           }
       if (isset($form_state ['values']['block2_file'])) {
          $file = file_load($form_state['values']['block2_file']);
        }
      if (isset($form_state ['values']['background_file'])) {
       $file = file_load($form_state['values']['background_file']);
     }
           // Change status to permanent.
           $file->status = FILE_STATUS_PERMANENT;
          // Save.
        file_save($file);
          // Record that the module (in this example, user module) is using the file.
        file_usage_add($file, 'user', 'user', $account->uid);
     }

```

# Answer
A quote from the docs:

> Note: New files are uploaded with a status of 0 and are treated as temporary files which are removed after 6 hours via cron. Your module is responsible for changing the $file objects status to FILE\_STATUS\_PERMANENT and saving the new status to the database. Something like the following within your submit handler should do the trick ...

You would need to put the example code that follows in the docs, into a function that you add as a submit handler:

```
$form['themeA_settings']['header-page']['header_background_file'] = array(
  '#type' => 'managed_file',
  ...
  '#submit' => array('your_custom_submit_handler'), // <-- This line is new
);

```

The function itself could look like this then:

```
function your_custom_submit_handler($form, &$form_state) {
  // Load the file via file.fid.
  $file = file_load($form_state['values']['my_file_field']);
  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;
  // Save.
  file_save($file);
  // Record that the module (in this example, user module) is using the file.
  file_usage_add($file, 'user', 'user', $account->uid);
}

```

You can of course reuse that function for all your files.
> 1 votes

---
Tags: theming
---


# Question
Title: How to set permissions of creating content only for referenced users
I have 2 content types: Courses and Documents. In Documents there is a node reference field which connects it to Courses (actually with a Node Reference URL Widget). In Courses there is a user reference field.

I'd like to add permission of Document content creation only the user who is referenced in Courses. Is it possible somehow? I tried it with Node access user reference modul (it has a "Grants for referenced users to create content" option) but it adds the create permission in every Course content, not only in that he/she is referenced.

# Answer
> 0 votes
If you are using the Node Reference URL Widget to add the create link then you could use panels (with the built in context) to hide that link if the user is not referenced on that node. This would not stop people from going to the url directly but would keep the honest people from creating content on nodes that they are not referenced on.

If you need a more secure way to prevent the creation of the document nodes I assume you would need to write some code or do some rules magic.

Rules magic idea: Create a flag that is hidden like I mentioned above. When the node is flagged then if the user reference is the current user then create the node and go to the edit page(and unflag when done). If not then unflag and show a message.

---
Tags: 7, users, nodes
---


title: Drush unable to bootstrap to database

text:
# Question
Title: Drush unable to bootstrap to database
I am not able to get drush to work properly:

1) I can download modules & themes through drush but I cannot enable them (more details below). 2) Also I cannot use the omega commands even though they are listed (more details below).

= I installed Composer & Drush as per docs.drush.org/en/master/install/ = Drush is properly installed on my computer, when I type drush version I get: Drush Version : 7.0-dev

My system setup: Linux mint 17 KDE with Xampp 1.8.3-4

I guess my problems are (partly?) caused because Drush was not able to start (bootstrap) the Drupal database. So I run mysql from command line:

```
user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

```

In my system `mysqld.sock` is in a different location, namely /opt/lampp/var/mysql/mysql.sock. So I created a symbolic link in /var/run/mysqld/ but this has no effect. Still have the same problems. Maybe caused by permissions?

I have spend a few days of and on (had to stop out of frustration) and I cannot get drush to work.

Details of my problems: 1) I can download modules & themes through drush but I cannot enable them:

```
user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > drush en disqus
Command pm-enable needs a higher bootstrap level to run - you will need to invoke [error]
drush from a more functional Drupal environment to run this command.
The drush command 'en disqus' could not be executed. [error]
Drush was not able to start (bootstrap) the Drupal database. [error]
Hint: This may occur when Drush is trying to:

bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details.
connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See drupal.org/node/1428638 for details.
Drush was attempting to connect to:
Drupal version : 7.34
Site URI : http://default
Database driver : mysql
Database hostname : localhost
Database port :
Database username : root
Database name : drush
PHP executable : /usr/bin/php
PHP configuration : /etc/php5/cli/php.ini
PHP OS : Linux
Drush version : 7.0-dev
Drush temp directory : /tmp
Drush configuration :
Drush alias files :
Drupal root : /opt/lampp/htdocs/drush
Site path : sites/default

```

When I add

```
'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost',

```

or:

```
'host' => '127.0.0.1',

```

to settings.php as per this post I get following error:

```
user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > drush en disqus
PHP Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /opt/lampp/htdocs/drush/includes/database/mysql/database.inc on line 46
Drush command terminated abnormally due to an unrecoverable error. [error]
Error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in
/opt/lampp/htdocs/drush/includes/database/mysql/database.inc, line 46

```

2) Also I cannot use the omega commands even though they are listed:

```
user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > drush help --filter=omega
All commands in omega: (omega)
omega-export (oexp) Exports the theme settings of a given theme from the database to the
.info file.
omega-guard (ogrd) Runs guard for the given theme including Compass and LiveReload by
default.
omega-revert (orev) Reverts the theme settings of a given theme by deleting them from the
database.
omega-subtheme Creates a Omega subtheme.
(osub)
omega-wizard (owiz) Guides you through a wizard for generating a subtheme

```

# Answer
> 3 votes
OK I've got drush working:) For other people who might have a similar problem (hope I use the right terms):

I had to install "php5-mysql" (and dependencies) in Linux (for example through "synaptic package manager"), php5-mysql is a MYSQL module for PHP5 which contains mysql PDO support. With this I was able to enable modules and use the omega commands. Drush uses the PHP installed in Linux and not in Xammp, I had this module in Xampp but not in Linux.

You can see which php.ini file drush uses by typing "drush status" in your terminal.

You can see which php.ini file is used by your web server by navigating to admin/reports/status of your drupal site. Next click the "more information" link on Drupal's status page's PHP section. This shows the phpinfo() page. Locate the Configuration File (php.ini).

To check that the mysql PDO support is installed (part of "php5-mysql"), type the following in a terminal: php -i|grep PDO If support is installed you should see something like this: PDO PDO support =\> enabled PDO drivers =\> mysql PDO Driver for MySQL =\> enabled

---
Tags: 7, database, drush
---


title: Use GET instead of POST for AJAX call

text:
# Question
Title: Use GET instead of POST for AJAX call
I was wondering if anyone had any tips for use a GET call with ajax forms instead of POST?

One of our ajax calls is returning some JSON that we want to be cached in the browser. If we can switch the call to GET then that caching will happen for us.

# Answer
It is easy to use GET instead of POST, but Drupal sends a lot of information about dom-elements and loaded css/js, so that it is often too long for a GET request..

```
var ax = new Drupal.ajax("element-name", this, element_settings);
ax.options.type = "GET";

```

If you do not use these, you can strip them:

```
//Override parameters for Get Requests
var backup = Drupal.ajax.prototype.beforeSerialize;
Drupal.ajax.prototype.beforeSerialize = function(element, options) {
  if(options.type != "GET") backup.call(this, element, options);
}

```
> 4 votes

# Answer
Use the Views Ajax Get module to convert post request to get

> This module will make your ajax-enabled Views, use GET instead of POST.
> 1 votes

---
Tags: 7, ajax
---


# Question
Title: Getting "Additional uncaught exception thrown while handling exception"
I tried to install module `Commerce Event Ticket`, added all the requirements, then enabled `Commerce Event Ticket` and got an error message:

```
Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.owner' in 'field list': SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.owner AS owner, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 187 of /home/content/q/u/a/quaa7882/html/sites/all/modules/entity/includes/entity.controller.inc).

Additional

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.owner' in 'field list': SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.owner AS owner, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 187 of /home/content/q/u/a/quaa7882/html/sites/all/modules/entity/includes/entity.controller.inc).

```

Now, this message also appears on the page without admin rights i.e. my page is **Offline** now! How can I fix this? Thank you!

# Answer
> 0 votes
Okay after this error, I ran `www.mysite/update.php` it applied a few updates after which I was able to access the admin pages but if i wanted to access my front page, I'd still get

**Fatal error: Call to undefined function field\_info\_field\_map() in /home/content/q/u/a/quaa7882/html/sites/all/modules/addressfield/addressfield.tokens.inc on line 92**

instead. I then removed the module `addressfield` by ftp manually and my site was back up and running so that I can care about my module(s) separately.

---
Tags: 7, commerce
---


# Question
Title: How to 'inject' the "read more" link into a textfield / paragraph (inline)
Due to client's demand the situation is that I can't use the default (trimmed) body text as a teaser text in a view listing nodes. Instead I have an extra text field which contains 2-3-4 paragraphs so that the client has 100% control of what the teaser text would look like etc.

I would need to place a "read more" link at the end of that custom teaser text. I tried different methods to place such a link inline with the teaser text – but couldn't find a way to actually have a working setup.

* I tried the read more module – which works fine with standard situation, replacing/placing the "read more" link inline – but that won't help me here.
* I tried overriding the field in views – but that won't let me place the "read more" *inside* the last paragraph. Either I keep properly formated paragraphs, or I use "inline" or "inline-block" for the p but then the paragraph-structure collapses.
* I also tried the read more control module – but that seems to solve problems that I don't have (hiding "read more" links if there is not 'more' to read)

I suppose this must be possible – and would gladly appreciate any tipps or pointers that would lead me in some direction.. thnx!

# Answer
If the goal is simply to get the read more link to appear visually inline with your last paragraph, I think you can do that with pure CSS. As you noted, formatting all your `<p>` tags as inline elements will break the paragraph structure. You can avoid this simply by using a `:last-child` selector, e.g. http://jsfiddle.net/hdys6w2j/

That said, if you are set on having the readmore link injected into your last p tag, I guess you could throw some code like this in your custom module:

```
function mymodule_preprocess_node(&$vars) {

  //Programmatically generate the readmore link
  $read_more_link = l('Read more', 'node' . $vars['node']->nid);

  if (!empty($vars['content']['my_field'][0]['#markup'])) {

    //Replace the last </p> tag with <a href="/path/to/my/node">Read More</a></p>
    $vars['content']['my_field'][0]['#markup'] = preg_replace(
       '/\<\/p\>$/',
       $read_more_link . '</p>',
       $vars['content']['my_field'][0]['#markup']
    );
  }

}

```
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Force Language Path Prefix For Default Language
I have a multilingual site configured to use `path prefix` for URL language detection.

When no prefix is used in the URL, the default language is assumed. How can I change this behavior?

I want the site to return content only when a language prefix is set in the URL, otherwise return a "page not found" error.

**Reasoning behind this functionality:**

* Preventing duplicate content in search engines
* Keeping everything well organized (under language prefixes)
* Avoiding users to be able to view content without a language prefix and thus potentially link to it (loosing link juice)

*Edit: added reasoning.*

# Answer
The solution I found was using the Global Redirect module with the default options. It redirects all URLs without a language prefix to the correct URL with the default language prefix contained.
> 2 votes

# Answer
You can configure it from (admin/config/regional/language/edit/en) if English language is the default and change (Path prefix language code) field from empty to en for example
> 4 votes

# Answer
@ovi: Next to the language list tab, there is another tab - "Detection and selection". URL: admin/config/regional/language/configure Go to this page and enable detection method - URL. Save settings. It should work now. It worked for me without having additional modules.
> -1 votes

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


title: FlexSlider fail slideshow

text:
# Question
Title: FlexSlider fail slideshow
I installed FlexSlider as suggested on the module's in `Drupal7`. I try to put a slideshow on my home page with no luck. I tried to create the `FlexSlider Example` content but it does not create a slideshow, but only lists the images.

The FlexSlider libs are version 2.4.

The website is here: http://projects.busoniu.net/

the images are uploaded in the **FLEXSLIDER EXAMPLE SLIDESHOW** and I didn't upload any of it in the **FLEXSLIDER EXAMPLE IMAGE**.

I get an error when I try to edit the content:

> Notice: Undefined property: stdClass::$name in flexslider\_add() (line 395 of /data/home/buso01/domains/busoniu.net/public\_html/projects/sites/all/modules/flexslider/flexslider.module). Notice: Undefined property: stdClass::$name in flexslider\_add() (line 398 of /data/home/buso01/domains/busoniu.net/public\_html/projects/sites/all/modules/flexslider/flexslider.module).

In console chrome I can see this error:

> Uncaught TypeError: undefined is not a functionflexslider.load.js?nk4e6d:41 (anonymous function)jquery.js?v=1.4.4:34 b.extend.eachjquery.js?v=1.4.4:27 b.fn.b.eachjquery.once.js?v=1.2:55 $.fn.onceflexslider.load.js?nk4e6d:34 \_flexslider\_initflexslider.load.js?nk4e6d:24 Drupal.behaviors.flexslider.attachdrupal.js?nk4e6d:76 (anonymous function)jquery.js?v=1.4.4:33 b.extend.eachdrupal.js?nk4e6d:74 Drupal.attachBehaviorsdrupal.js?nk4e6d:412 (anonymous function)jquery.js?v=1.4.4:30 b.extend.readyjquery.js?v=1.4.4:38 u

# Answer
> 1 votes
Put the Flexslider library in sites/all/libraries.

Check Status page for error with flexslider (admin/reports/status).

---
Tags: 7, javascript
---


title: Assign anonymous node to user Id

text:
# Question
Title: Assign anonymous node to user Id
What I want to try and achieve.

An authenticated user creates a node of type 'listing' (this node obviously belongs to this user via his uid). On this node will be a link to create a new node of a different content type 'booking-request' (this link the author can't control).

Now an anonymous user can view this created 'listing' node and then they can click on the link and create a 'booking-request' node. So obviously the 'booking-request' node will belong to the anonymous user.

My question is. How can I assign this 'booking-request' node to the author of the 'listing' node after the anonymous user saves it?

Can I do this with a module or will this need custom php or both and how will I do this?

# Answer
> 0 votes
You can use Entity Reference Prepopulate.

> Allow prepopulating any Entity reference field via URL

In your booking-request set up an entity reference field pointing to user entities. Then, create a link in the listing node to booking-request node add form with the right parameter to prepopulate that entity reference field.

See README in the module:

> In order to pre-populate an entity reference field you have to supply the parameter in the URL.
>
> The structure is node/add/article?\[field\_ref\]=\[id\]
>
> Where \[field\_ref\] is the name of the entity reference field and \[id\] is the id of the entity being referenced.
>
> Examples: node/add/article?field\_foo=1 node/add/page?field\_bar=1,2,3

# Answer
> 0 votes
You can do this in following way :

1. You can do this using Rules, by checking the condition if author is anonymous of newly added content then add action, select `Set data value`. Your target should be `node:author`. Assign the value you want.
2. Using hook\_node\_insert, add condition inside your hook :

if ($node-\>type == 'your\_type' && !$node-\>uid) { $node-\>uid = 1; }

---
Tags: nodes, users
---


title: Hierarchy of users

text:
# Question
Title: Hierarchy of users
I want to do like that one user should have multiple child users, for example team lead user and team members with proper permissions. Can i do this thing in drupal 7.26?

# Answer
You can achieve that using the User Relationships module

> Administrators are able create relationship types (friend, coworker, etc). Relationship types can be setup to be one-way or mutual. If a relationship type is one-way (subscriber) only the requester is shown as relating to the requestee. Relationship types can also be set as needing or not needing approval.
>
> Administrators can give users the option to auto approve relationships on a per-relationship type basis.

If you want to assign a user under another user you can use References module

you can use This project provides D7 versions of the 'node\_reference' and 'user\_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts. See http://drupal.org/node/533222 for details.
> 0 votes

# Answer
Subuser module seems work for you.

> This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.

Customize settings links please visit `admin/settings/subuser`
> 0 votes

---
Tags: 7
---


title: Send form contents to the admin's email

text:
# Question
Title: Send form contents to the admin's email
I have created the form using custom module, and it is working fine now. In this case, when I submit the form it simply sends the mail to the particular person from particular id. For this what i did is,

```
function custom_form_my_form_submit($form, &$form_state) {
$valid_email = $form_state['values']['email'];
$from = 'karthik.k.siva@gmail.com';
$body = 'Email: '.$valid_email.'<br />URL: '.request_uri();
$to = 'karthikeyan.ameex@gmail.com'; // Set this email address - emails will be sent to this email address!
$params = array(
'body' => $body,
'subject' => 'Website Information Request',
);

if (drupal_mail('custom_form_my_form', 'some_mail_key', $to, language_default(), $params, $from, TRUE))
{
    drupal_set_message('Thanks, we will be in contact with more information soon.');
} else {
    drupal_set_message('There was an error subscribing you. Please try again later');
}

```

}

And now I want to receive the submitted form contents through email, for that what I have to do.

# Answer
You need to implement `hook_mail` too and define `some_mail_key` in your `hook_mail` :

```
/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  if ($key == 'some_mail_key') {
    $message['subject'] = $params['subject'];
    $message['body'][] = $params['body'];
  }
}

```

Then you can use `drupal_mail` function like :

```
drupal_mail('mymodule', 'some_mail_key', $to, language_default(), $params, $from, TRUE);

```

Change `mymodule` with your module's name.
> 1 votes

---
Tags: 7, forms
---


title: delete profile2 profile from a user

text:
# Question
Title: delete profile2 profile from a user
I am using Profile2 on my site, with 3 different Profile2 Profiles set up: A, B & C. These are matched to roles A, B and C.

Users can only create and edit a profile that matches their role, though C users may also have A or B profiles.

While logged in as an administrator, I accidentally added a Profile2 Profile of type C to a users account who only has role A. (Admins can add profiles of any type to existing users.)

I cannot for the life of me find a way to delete the C Profile for this A user. What am I missing? Isn't there any admin tool to remove Profile2 data from a user? The Profile2 page to edit the C Profile only has a "Save" button at the bottom, not a "Remove" or "Delete" button.

# Answer
> 1 votes
You need to have the "Administer profiles" permission.

Then you will have a "Delete profile" button at the bottom of the profile page when editing.

You can also access the profile at: `/profile-<profile_type>/<uid>/delete` and go right to the deletion confirmation box. Note that the path is compose of the word 'profile' then a hypen then the name of the profile type you created, so in your example it would be: `/profile-C/<uid>`

HTH.

# Answer
> 0 votes
I wound up creating a Rule that checks for the users role when loading the profile, and deletes profiles that don't match the role.

This is not a long term solution, because users start with Role A or B and eventually change to C, but we want to keep the info of Role A or B as part of their overall profile but just not display it.

---
Tags: users
---


# Question
Title: Hide/show pages depending on landing page click
Last year i created a drupal 7 website for a MMA Trainer . He's pretty happy about it. But now he wants to expand his business to personal training and has some new requirements.

He wants a landing page where people can click on 1 of 2 links(Gym / Personal training) Depending on what the user clicks i have to hide/show certain pages on the website

How would i go about doing this ? Is there somekind of variable i can set on a landing page that i can check in drupal to hide pages ?

# Answer
You can use Domain Access module with Subfolders Domain to create two instances Gym and personal training. This will allow you to administer content for both sections.
> 1 votes

# Answer
There are couple of modules exists for your requirement. Have a look at the following modules.

Quick Tabs

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:

Ajaxify Drupal with JQuery Ajax

> Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.

jQuery AJAX Load

> jQuery AJAX Load is an helper module for easy loading any content using build in jQuery load function.
>
> It comes with a set of modules that uses the functionality for:
>
> * Loading content on a link
> * Loading content on a Twitter Bootstrap Modal
> 0 votes

---
Tags: 7
---


title: Can I add a "OR" on a dependecy?

text:
# Question
Title: Can I add a "OR" on a dependecy?
I'm working a on a project that needs to have one of their submodules enable but not both.

I was wondering if I can have an or statement in the .info so the user would not enable both submodules.

The Drupal 7 documentation "Writing module .info files (Drupal 7.x)" does not talk about this.

# Answer
No, Drupal doesn't have any mechanism for that - dependencies cannot be conditional.

If a single module can have a dependency on an arbitrary module, it might suggest that module is trying to do too much, and should be re-thought. Maybe you should create *three* modules - one for the core functionality, one for integration with the first module dependency, then another for integration with the second module dependency. Then everybody wins, and you can accomplish it with the functionality that already exists.

Drupal 8 will introduce `enhances` and `enhancedby` to module info files to allow them to specify complementary modules, but there's still nothing for conditional dependencies (see https://www.drupal.org/node/328932).
> 5 votes

# Answer
The direct answer to your question (can you use "OR" in an `.info` file?) has already been provided, but the actual functional outcome you're looking for *can* be achieved with hook\_requirements. For instance, you might use this code in `my_module.install`:

```
function my_module_requirements($phase) {

  $requirements = array();

  if ($phase == 'install') {
      if (module_exists('submodule1') && module_exists('submodule2')) {
        $requirements['too_many_modules'] = array(
          'title' => $t('Too many modules'),
          'description' => t('You may not enable submodule1 and submodule2 simultaneously'),
          'value' => 'Too many modules',
          'severity' => REQUIREMENT_ERROR,
        );
      }
      if (!module_exists('submodule1') && !module_exists('submodule2')) {
        $requirements['not_enough_modules'] = array(
          'title' => $t('Not enough modules'),
          'description' => t('You must enable submodule1 or submodule2 (but not both)'),
          'value' => 'Not enough modules',
          'severity' => REQUIREMENT_ERROR,
        );
      }
    }

  return $requirements;
}

```

Further reading
> 6 votes

---
Tags: 7, .info
---


# Question
Title: Howto pass the uid of a node to a view inside a dynamic display suite field?
I have 1 node of the content type "tourism" and 2 nodes of the content type "tourism news". All 3 nodes belong to the same author (uid 33).

The "tourism" content type has a dynamic display suite field "news" which includes the content pane of a view. This view should displays all "tourism news"-nodes depending on the uid of the requestet "tourism"-node.

When I enter the uid 33 in the preview, the view works as it should:

But when I open the "tourism" node - depending on my configuration - all news or no news are displayed. How do I have to configure the view and the dynamic field to pass the uid to the view?

Thanks in advance.

# Answer
You are incorrectly setting the 'Argument input' for the Content Pane. It needs to be `Node -> Author`

Then you need to make sure that you pass the correct argument to it from the Dynamic Field in Display settings for the node. Make sure that you select 'View Panes' and not 'Views'. When you do it will show you the View pane view that you created, and when you select that it will present you with a select list titled: 'Content: Author uid', from which you select the only choice available, which is 'Node being viewed'.

I also do not think that setting the 'When the filter value is not available' in views will have any effect at all. This content pane display is only used for the dynamic field which will always get an argument.
> 0 votes

---
Tags: views, display-suite
---


# Question
Title: Taxonomy view : add token term_name in url
I have a view overriding taxonomy term pages with the help of Panels. I defined that pattern in URL aliases : `destinations/[term:parents]/[term:name]`.

Now I'd like to set a clone of that view, slightly different in its filters, **with the same panelizer variant** (or a variant clone), following URL pattern :`destinations/[term:parents]/[term:name]/foo` where foo is a fixed word.

How could I do that please ?

# Answer
> 1 votes
This does what expected.

**In the content pane view**, Contextual filters : Content: Has taxonomy term ID (with depth), use the filter value type "*Term name converted to term ID*"

**In the custom page**, in basics, set the path almost as in the question `destinations/[term:name]/foo` (I abandoned the `[term:parents]` part, no way).

And in arguments, choose "*argument type:term name*".

---
Tags: views, taxonomy-terms, panels, tokens
---


# Question
Title: Views and Filtering Data not getting results
I have created a view to grab all of the invoices in a system, which it does. I have two types of invoices either payable or receivable. I have two filters to start with Published Content = Yes and Content Type = Invoice. I want to be able to filter this on the invoice type so only receivable invoices show up on the view.

I have added another filter that says content type = invoice type but when I do that I get no results at all.

If I leave off the content = invoice type I get all of the invoices. How can I create a filter that will pass the invoice type to the view so I only get the receivable invoice for this particular view.

# Answer
> 0 votes
Create a relationship to the invoice type content type in the view and then add filter for the status field of invoice type taking relation ship when adding the field in the filter.

Relationship can be found under the Advanced section of the view. Pick the suitable Entity Reference for the relationship to invoice type here and add the relationship.

After that if you add the status field to the filter options you have the option to use the relationship for that field.

---
Tags: views
---


# Question
Title: How to implement an E-commerce solution for a jobboard?
What would be the best way of achieving this goal:

* From a jobs board (A content type called jobs)
* User picks particular job
* User is asked to complete a form including:

+ Checkboxes (for terms and conditions)
    + Document upload (CV, picture etc)
    + Other basic details (name etc)
* User then pays a fee via eCommerce caperbility
* All the information and documents are available for admin to view.

Any suggestions?

# Answer
> 0 votes
This can be easily done with the Recruiter Distribution and Ubercart or Commerce.

If you are not using the recruiter distribution you can used the Profile2 to created to ask

> \- Checkboxes (for terms and conditions)
> \- Document upload (CV, picture etc)
> \- Other basic details (name etc)

For the Terms and conditions you can used the Site Disclaimer module.

You need to created a role that allows them to register to the website and created a profile. After that you can add a button to Upgrade their to another role which would give the user the ability to see or do more stuff in your website.

You can follow this tutorial to learn how to upgrade a role with Ubercart. How to Configure Drupal 7 and Ubercart to Sell User Roles

---
Tags: commerce, webforms
---


# Question
Title: Importing multiple images from Dropbox with Feeds
As part of a product import, I am trying to import images from a link contained in a column of an Excel file. Each link points to a Dropbox folder with 2 image sub-folders (named PRINT and WEB). Is it possible to import multiple image files from a Dropbox folder using Feeds?

# Answer
I hope you can read the images's urls inside the Excel table – or actually let your D7 install read them? Once you have that and can actually also access the files on dropbox, it should be possible to load them into your D7 install.

I had a similar, though probably more trivial problem. I had the images' urls and all related info nicely wrapped in a simgle xml file. Looking for a way to actually import the images I came across the Media Feeds module which basically let's you 'import' media files into as an image or file field into an entity (e.g. a node).

The module's project page (https://www.drupal.org/project/media\_feeds) has also a link to a screencast – should not be too complicated once you can read the Excel table / get access to the images' urls.
> 0 votes

# Answer
The easiest way to do this is to place the images in a folder under your Dropbox Public folder. This folder allows files to be retrieved via a non-changing URL rather than the unique URL that Dropbox uses when you want to share an individual file. This functionality was removed from the free version of Dropbox on October 4, 2012 but is still available for legacy accounts or paid accounts.

You can then include the filename (and use feeds tamper to create a full URL) or include the full URLs in your import file. You must use the public dropbox folder to be able to compute these URLs otherwise it won't work.

Look for "Copy Public Link" not "Share Link" to get the URL from dropbox.com. When looking at a "Public Link" you'll see the full folder structure and filename in the URL, with a Share Link you will not see this.
> 0 votes

---
Tags: commerce, feeds
---


title: how to install package via composer?

text:
# Question
Title: how to install package via composer?
I would like to add library to my drupal 7 custom module. Library can be installed via composer, but i can't find a solution for install? How can i install this library? I have installed "composer manager" but i still can't get it running.

# Answer
To get started, add a `composer.json` file to your module. The only thing you need here is the `require` section that includes your external library.

`Composer manager` is one way to combine all of your dependencies together, but there are other options to get Drupal to load your autoload.php file. The technique I prefer is to create a project-level `composer.json` file in your Drupal root, and use the module composer\_vendor to include your autoload.php file.

The easiest way to get started is to use the composer\_generate Drush extension to build your project-level `composer.json` file.

`$ drush dl composer_generate
 $ cd /path/to/drupalroot
 $ drush composer-generate > composer.json
 $ composer install`

Composer-generate will add all of the projects currently used in your Drupal site, plus composer\_vendor, so `composer install` should just work for you. The main magic here is in the custom autoloaders added to the template; take a look at the output to see what was included.

Some caution needs to be used here, of course; the default template will put all of your modules in sites/all/modules/contrib. You can edit the template prior to running composer install if this isn't what you want.

You'll also have to be careful if you have any modified modules; there are a number of ways to deal with any hacked content, but that's a bit beyond the scope of this one question.

**Update**

If you don't want to run Drush, you can also hand-type your own composer.json file using the project https://github.com/drupal-composer/drupal-project. This is the template that composer-generate is based on.
> 6 votes

---
Tags: drush, theming, composer
---


title: Drush with multiple sites (all/modules)

text:
# Question
Title: Drush with multiple sites (all/modules)
I've searched around but found no satisfying answer yet. I have all modules in sites/all/modules, so no site specific modules are present. I'm working on a VM.

First problem - creating a dump file fails:

`drush @sites sql-dump --result-file`

Second problem - updating the modules:

`drush @sites update` targets all sites, which is nice. But the modules are in all/modules, individual sites do not have any modules

Side question: Is there a way to update only the core?

# Answer
> 0 votes
I don't really use multi-site, so my answers here are hypothetical. I recommend using a separate Drupal root for each site, unless you have a very strong reason to share code.

`drush @sites sql-dump` is not a good idea. This is going to run sql-dump in turn on each of the databases of each of the sites. If this worked correctly, you would either get all of the databases concatenated together (e.g. if you sent the dumps to stdout, and saved the result via output redirection), which you could never hope to restore, or, each database would be saved into the same result file, each overwriting the previous. Drush does not support dumping multiple databases to a single dump file.

`drush @sites pm-update` will do redundant work. It will run the code update on each site sequentially; the projects for each site are shared, so sites that are updated after the first will have most or all of their projects already updated. After updating the code, pm-update runs updatedb on each site, which does need to be done for each site's database individually. Note, however, that the most important part of an update is testing, so you might as well update each site individually.

If you want to update only Drupal core, use `drush pm-update drupal`. To update everything except core, use `drush pm-update --no-core`.

---
Tags: drush, multi-sites, updating
---


# Question
Title: Get the submitted values of a multistep webform
I need to get the submitted values of a multistep webform. It looks like webform doesn't save values from earlier steps in the usual place: $form\_state\['values'\]\['submitted'\] or $form\_state\['input'\]\['submitted'\]. I just need the submitted values of every form component at the last page.

I actually made a custom submit handler to store the values from each form in my own location in $form\_state, but I was wondering if there was a better way.

# Answer
> 7 votes
You will find the multi-page values stored in

```
$form_state['storage']['submitted']

```

Note that this array *does not* contain values from the current page and will be empty if the current page is 1.

And incidentally you can find out which page was just submitted by checking

```
$form_state['storage']['page_num']

```

# Answer
> 0 votes
My first guess would be you, if you haven't already, is to integrate the form with AJAX, so when you Click Submit to continue to the next page, it will also trigger an AJAX event, which still store the field variable information based of your custom Submit Handler function.

Here is a snippet from the Advanced Form Block Module, which provides AJAX for Node creation.

```
$form['#after_build'][] = 'afb_after_build';
    $rand = rand();
    $form['actions']['submit'] = FALSE;
    $form['actions']['preview'] = FALSE;
    $form['actions']['delete'] = FALSE;
    $form['changed']['#default_value'] = time() + 300;
    $form['#id'] = !empty($form['#node']->form_id) ? $form['#node']->form_id : $form['#id'];
    $form['ajax-submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Node'),
      '#weight' => 50,
      '#id' => 'ajax-submit-random-' . $rand,
      '#ajax' => array(
        'wrapper' => !empty($form['#node']->form_id) ? $form['#node']->form_id : $form['#id'],
        'callback' => 'afb_ajax_handler',
        'effect' => 'fade',
      ),
      '#submit' =>
      array(
        1 => 'node_form_submit',
      ),
    );

```

It calls a function to Save the fields, without refreshing the page...

```
/**
 * Ajax Handler that returns the forms in each individual blocks.
 */
function afb_ajax_handler($form, $form_state) {
  if (isset($form['#node']->nid)) {
    $id = $form['#id'];
    module_load_include('inc', 'node', 'node.pages');
    $node = node_load($form['#node']->nid);
    $form_state['build_info']['args'][0]->form_id = $id;
    $form = drupal_rebuild_form($node->type . '_node_form', $form_state, $form);
    $form['#id'] = $id;
    return $form;
  }
  else {
    $node = $form_state['node'];
    if (!empty($node->nid)) {
      $id = $form['#id'];
      $new_node = (object) array(
        'uid' => $node->uid,
        'name' => $node->name,
        'type' => $node->type,
        'language' => $node->language,
        'ajax_form' => 1,
        'delta' => $node->delta,
        'form_id' => $id,
      );
      $new_form_state = array();
      $new_form_state['build_info']['args'] = array($new_node);
      $new_form_state['values'] = array();
      $new_form_state['method'] = $form_state['method'];
      form_load_include($new_form_state, 'inc', 'node', 'node.pages');

      $form = drupal_rebuild_form($node->type . '_node_form', $new_form_state);
      $form['#id'] = $id;
      return $form;
    }
    else {
      return $form;
    }
  }
}

```

That being said, that is not a direct answer to your question, because without knowing the fields you are storing I can't really help you write a module, but this should give you a basic example of what "should" be done.

I think you might be able to get away without worrying about a wrapper, because you are storing data, but I could be wrong on this.

# Answer
> -2 votes
I doubt that this is the correct way to do it but... I was able to pull values from the previous page using the following,

```
$_POST['submitted']['FIELD_ID']

```

where `FIELD_ID` is the ID of the desired form field.

This seems rather sloppy and I would like to find a better solution.

EDIT: Coleman's solution is the correct solution and should be used instead of this.

---
Tags: 7, forms, webforms
---


title: Views - Custom Field Layout?

text:
# Question
Title: Views - Custom Field Layout?
I'm looking for direction on how to format the field layout of a view.

Here's the layout I'm looking for:

```
--------------------------------------------------
| Field1     | Field2      | Field3              |
| Field4     | Field5      |                     |
--------------------------------------------------
| Body                                           |
|                                                |
|                                                |
--------------------------------------------------

```

Using the "column" selection in the table settings, I'm able to "combine" fields into a single column (i.e. Field1 and Field4), but I'm stuck on how to display the Body under all the other fields in a cell that spans the whole table.

Suggestions?

I realize there are many ways to achieve my goal, in fact I've found this video that seems to be exactly what I'm looking for, but is this an overkill?

# Answer
> 2 votes
For precise control over views markup I usually take a departure from typical Drupal methods. I set the view to be a table format, then create my own view template. The reason I use the table format is that it's really easy to work with and has a simple loop through each row of the results returned from the view. From there, you can create your own markup using just the field values from each row.

Check this link: https://api.drupal.org/api/views/theme!theme.inc/group/views\_templates/7

Here's some shortcuts to get you started quickly. In your theme's directory, create a file called: views-view-table--NAME-OF-YOUR-VIEW.tpl.php

Inside that file, start by pasting the source from this (click View source on the page): https://api.drupal.org/api/views/theme!views-view-table.tpl.php/7

Then, clear your site's cache. Your view will now be using that new template and you can edit as required.

---
Tags: views, theming
---


# Question
Title: custom template for entity as referenced entity
I have a node type for which I have a custom tpl. OK.

But this node type I also have as a referenced entity in another nodetype. And in this case I need another custom tpl.

Is it possible to have another tpl and if yes: how do I name this file?

# Answer
> 1 votes
What you can do is to add a custom view mode for your node type, and then use the new view mode for your entity reference field. You have a couple of options, depending on whether you want to code a custom module, or stick with available contrib modules.

The entity view modes module will allow you to add your new view mode, or you can use hook\_entity\_info to programatically add a new view mode in a module you write yourself. This article provides an example of adding a view mode with hook\_entity\_info:

```
function acme_view_modes_entity_info_alter(&$entity_info) {
  // Define the view modes
  $entity_info['node']['view modes'] += array(
    'featured_story' => array(
      'label' => t('Featured Story'),
      'custom settings' => TRUE,
    ),
    'secondary_story' => array(
      'label' => t('Secondary Story'),
      'custom settings' => TRUE,
    ),
    // Define more in this array as needed, e.g. tertiary_story
  );
}

```

That same article also provides an overview of adding theme hook suggestions so you can supply the name you want to use for your template (the entity view modes module will handle this step for you).

For selecting the new view mode to use for the display of your entity reference, which you do on the "manage display" tab of your content type that includes the entity reference field, choose "Rendered Entity" as the Format for the field's display, then a settings-gear button will appear to the right of it. Click that button and among the available settings will be a select element to choose the view mode.

---
Tags: theming, entities
---


title: Getting the URL for every language

text:
# Question
Title: Getting the URL for every language
I have a route of a page, and I want get the link for it on every language of my site.

On my site the contact page is: en/contact for English, and es/contactenos for Spanish.

I am trying using the following code, but I am getting just the URL for the current language set for the site.

```
$route = 'contact.site_page';
$url = new Url($route);
$uri = $url->toString();

```

How do I get it for every language available for the site?

# Answer
I found the solution myself, with the following code.

```
// Get all languages of the site
$languages = \Drupal::languageManager()->getLanguages();

// Route of contact for example:
$route = 'contact.site_page';
foreach ($languages as $language) {
  $url = new Url($route, [], ['language' => $language]);
  $uri = $url->toString();
}

```
> 7 votes

---
Tags: i18n-l10n, 8, routes
---


# Question
Title: Views caching strategies - relationship between query cache and rendered output cache
First off, I'm trying to ensure due diligence and not duplicate questions that have come up before. There are numerous posts on stackexchange, and various other places, that discuss views caching and even some specifics about the different types of view caches (e.g., here and here). However, I've yet to find any details that sufficiently explain the **relationships between** different layers of views caching, and how they may impact case-specific caching decisions. For simplicity I'm also focusing the scope of this question to out-of-the box views 7.x-3.x caching options independent of other layers offered in the contrib space.

Views exposes 2 layers of time-based caching for each display, a "query results" cache and a "rendered output" cache. The specifics of what raw data each cache encompasses is clear, but the ways they interact is not. I'm specifically wondering if a hit on the rendered cache will completely bypass they query cache, or if the 2 layers operate separately. I've seen some references that claim the former (like this one), and some that claim the latter (like this one).

## Theory 1 - Separate cache layers

I was initially under the impression (and hoping) that each layer is invoked separately "in series", and that the rendered output cache hashes the actual query **results** within its cids. This way I would have an elegant way to cache the most expensive post-query load/build work, while still ensuring that new content is immediately reflected in the view ("query results" cache **off** and "rendered output" cache **on**). Some quick tests reveal that this might not be possible though, as the rendered output cache may not be aware of the current query results.

## Theory 2 - Rendered output cache "encompasses" query results cache

The other possibility is that the rendered results cache is keyed by a hash of the query itself (not the results). If this were the case, a hit on it could return the rendered output directly, without the need to consult the query cache, or DB. If this were the case then I suppose it would not make much sense to have the "query results" cache set with a time interval less-than the "rendered results" cache. The advantage of course would be that one could refresh the rendered output more frequently (if they have lots of dynamic theme logic, or frequent entity updates), while still avoiding direct queries to the DB. However, for all but the most complex view queries, this kind of separation does not seem all that advantageous.

I've done some "black box" tests that point to theory 2, but I'm not sure if there are some other settings that might be at play or if the answer differs by views version. I've also explored the code a bit, but I find it frustrating that most views' plugin methods are undocumented and occasionally hard to follow. No matter what, I think the answer to this would be useful to have as a reference for others.

# Answer
I looked into some of the internal views logic, and from what I can there are elements from each theory that are correct, but neither is 100% accurate. It seems that both caching layers are separate, and always checked in series, so the "rendered output" cache does not really have the ability to "bypass" the query layer. Additionally, the query results do **not** factor-in to any cache keys, so changes to query results unfortunately do not trigger a refresh in the rendered output.

---

## 7.x-3.x

The "query results" cache is managed in `view::execute()` and the "rendered output" cache is managed in `view::render()`. Because `execute()` is called before the "rendered output" cache logic, a "rendered output" cache hit cannot bypass the query layer. It's not totally clear to me why this is as seems a little wasteful to run a query, or even check a query cache, if the display will just be built in-full from a cache. I suspect that there is plenty of other logic in `view::execute()` (access checks, hooks, plugin management) that must always be run independent of caching, and the "query results" cache part could not easily be separated from it. Anyway, that detail is a bit tangent to the question, but maybe someone else would be able to comment on it.

In terms of cache keys both cache layers are keyed by the view name, the display name, the cache type and then a hash of a bunch of contextual "stuff" from `views_plugin_cache::get_cache_key()`. A look at this `get_cache_key()` method is insightful as it shows that a some common contextual data is always factored-in (user roles, language, base\_url), but the "rendered output" case takes things a bit further by also hashing the raw query string, but not the query results. So if the raw query changes, the rendered output will be refreshed, but if the query results change, the rendered output will still be returned from cache.

So I think that from a performance perspective each cache layer can really be dealt-with independently, but the "rendered output" cache will still most directly govern how often "stale" data is displayed. I could further conclude that:

* The refresh interval for the base *list of items* in the view is greater-than-or-equal-to whichever cache interval is larger (the actual list of items can't update until both caches expire for any given view).
* If the "rendered output" cache for a given view refreshes before the "query results" cache, the list of items won't refresh, but the content displayed for each item could (i.e. a new item added to the list 5 seconds ago still won't be shown, but teaser text that was updated 5 seconds ago on an item that was in the list previously would update).
* Even when the "query results" cache is not influencing the final output it still offers a performance boost for `view::execute()`.

It's also worth noting that some of this behavior could be changed by overwriting methods in the views\_plugin\_cache class locally, such as `views_plugin_cache::get_cache_key()`.

## 8.0.0

As of 8.0.0-beta7 views (core) retains the option for time-based caching. As best I can tell it will behave like 7.x-3.x but it's really too early to do any conclusive testing - see this meta discussion. What is clear however is that many of the concerns and limitations around views time-based caching may become moot, as it looks like D8 views will also support tag-based caching. This should offer a way for truly smart expiration of cached data.
> 4 votes

---
Tags: 7, views, caching, performance
---


# Question
Title: Best Practice of Extending Another's Theme?
I have a standard theme developed by others that I would like to add a custom view template to.

Is it OK to just create a new "views-view-table--MYVIEWNAME.tpl.php" file in the theme directory itself?

Or, is there a way to create a "sub-theme" for my stuff that inherits everything from the original theme?

Thanks. Bill

# Answer
> 1 votes
This is partly up to developer preference and specific use case but generally, if it is a custom theme, as in this case, you would add templates and modify css/template.php/etc. in the custom theme you already have.

If it is a theme from drupal.org or some other theme source, where updates for that theme may come in future, then it is best to create a sub theme of that theme (which you can do even if that theme is already a sub theme of another theme).

# Answer
> 0 votes
Templates are used by a theme on a most-granular-first basis.

This means that the system looks for something that is very specific to what is being rendered and then moves up the tree looking at more and more general options until it finds one that matches.

So a custom views-view-table--MYVIEWNAME.tpl.php file won't cause the standard views-view-table.tpl.php file to fail for other views with different names because they won't match that template file.

You can even make it more specific by name the display as well as the view if you have more than one display in your view.

---
Tags: views, theming
---


title: Views BEF checkbox count in drupal 7

text:
# Question
Title: Views BEF checkbox count in drupal 7
I have created views with BEF check boxes as a filter criteria.

I want to get count of each check boxes as mentioned in below image.

Reference link.

My view name is **photo\_search**. So I have renamed below tpl to `views-exposed-form--photo-search.tpl`

> I have copied views-exposed-form.tpl from views/theme to mytheme/templates . But its not working (Cache cleared & Rescanned tpl from views).

# Answer
First of all make alter in your view and place the code.

// Set an index if there are multiple terms used.

```
    $index = 0;
    // Used for the array's string index.
    $string_index = '';
    // Continue for each vocabulary that is used.
    while (isset($form['tid' . $string_index])) {
        // Cycle through each of the terms.
        foreach ($form['tid' . $string_index]['#options'] as $tid => $option) {
            // Build a query to get the nodes for this term that have been
            // specified as filters.
            $query = db_select('node', 'n')
                    ->fields('n', array('title'))
                    ->condition('n.type', $form_state['view']->display_handler->handlers['filter']['type']->value, 'IN')
                    ->condition('fa.field_advertisements_value', 'forsale', '=')
                    ->condition('ti.tid', $tid, '=');
            // A quirk in db_select(). You need to add the join separately.
            $query->innerJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
            $query->innerJoin('field_data_field_advertisements', 'fa', 'fa.entity_id = n.nid');
            $results = $query->execute();
            $count = $results->rowCount();

```

// get the count of nodes or watever with your costom query

```
            $val = $form['tid' . $string_index]['#options'][$tid];
            $form['tid' . $string_index]['#options'][$tid] = str_replace("<span>(" . $count . ")</span><span>(" . $count . ")</span>", "<span>(" . $count . ")</span>", $val . '<span>(' . $count . ')</span>');
        }
        // Increment for the next tid index in the array.
        $index += 1;
        $string_index = '-' . $index;
        //$string_index = '_' . $index;

```
> 0 votes

---
Tags: theming, views
---


title: Extend Theme to Different Content

text:
# Question
Title: Extend Theme to Different Content
I've installed a theme on my site, and can't figure for the life of me how to extend the theme to different content.

For example, comments are themed on the blog pages; however, when I add new content types with comments, the theme is not applied to these comments.

How do I get the theme to extend to the different content types?

# Answer
Worked this one out after a bit of fiddling, so for others trying to figure it out too...

1. First find the template file you need to override - if it's part of a module, it might be in the module templates folder. Otherwise install Theme Developer - it will help you track down the template that's being used for that content https://www.drupal.org/project/devel\_themer
2. Chances are you'll need to override that template with one from your theme - identify the template theme that you want to use (easiest done using Theme Developer on the page that is coming up how you want), then copy that template file from your theme templates folder (\[theme\].tpl.php) to your sub-theme templates folder
3. Rename the template file in your sub-theme templates folder the same as the one you want to override (as identified in step 1), and voila.
4. (optional) you might find a CSS file somewhere is still screwing up the way your content looks (in my case it was in the module css folder) - you can either tweak it with other tools like CSS Injector, or copy the offending CSS file into your sub-theme css folder and tweak it there.
5. If you are overriding CSS, you'll need to identify the CSS file in the sub-theme .info file (found in your sub-theme folder) - add the following line: **stylesheets\[all\]\[\] = css/filename.css** (where filename.css is the name of the tweaked CSS file) under the line **stylesheets\[all\]\[\] = css/custom.css**
> 0 votes

---
Tags: theming
---


title: Use Pager with a webservice

text:
# Question
Title: Use Pager with a webservice
I use a webservice to get data instead of using mysql and I try to show results with a pagination:

```
function partenaire_search_partners(){
  $results = partenaire_ws_get_partners();
  foreach($results->Partenaire as $partenaire) {
    $rows[] = array($partenaire->raisonSociale);
  }

  $headers = array(
      array(
          'data' => t('Raison Sociale')
      )
  );
  $output = theme('table', array('header' => $headers, 'rows' => $rows)) . theme('pager');

  return $output;
}

```

I can restrieve my data, but either with 10 or 200 results I never see the pagination. Do you have some clues to help me resolve this issue ?

Thanks

# Answer
Are you using Drupal 7 then copy paste this function after your partenaire\_search\_partners()

```
function pager_array_splice($data, $limit = 9, $element = 0) {
global $pager_page_array, $pager_total, $pager_total_items;
$page = isset($_GET['page']) ? $_GET['page'] : '';

// Convert comma-separated $page to an array, used by other functions.
$pager_page_array = explode(',', $page);

// We calculate the total of pages as ceil(items / limit).
$pager_total_items[$element] = count($data);
$pager_total[$element] = ceil($pager_total_items[$element] / $limit);
$pager_page_array[$element] = max(0, min((int)$pager_page_array[$element],   ((int)$pager_total[$element]) - 1));
return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

```

and add this line to below of your foreach loop

```
  $paging =  pager_array_splice($rows, 10);

```

then use copy this line

```
   $output = theme('table', array('header' => $headers, 'rows' => $paging)) . theme('pager');

```

instead of this

```
     $output = theme('table', array('header' => $headers, 'rows' => $rows)) . theme('pager');

```
> 2 votes

# Answer
```
<?php

/*
* Implements hook_mennu()
*/
function test_menu() {
  $items['test'] = array(
    'title'             => t('Test'),
    'page callback'     => 'test_search_page',
    'access callback'   => True,
  );

  return $items;
}

function test_search_page(){
    $form = drupal_get_form('test_search_form');

    return $form;
}

function test_search_form($form, &$form_state){
  $header = array(t('id'), t('name'), t('firstname'));
  $rows = Null;
  $form['name'] = array(
    '#type'             => 'textfield',
    '#title'            => t('Name'),
    '#required'         => True,
    '#default_value'    => isset($_GET['name']) ? $_GET['name'] : Null
  );

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

  if (isset($_GET['name'])){
    $rows = get_data();
  }
  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Aucun résultat.')
  );
  $form['pager'] = array('#markup' => theme('pager'));

  /*
  if (isset($form_state['table'])) {
    $form['table']  = $form_state['table'];
  }
  $form['pager'] = array('#markup' => theme('pager'));
  */
  return $form;
}

function test_search_form_submit($form, &$form_state){
   $form_state['redirect'] = array(
    // $path
    'test',
    // $options
    array('query' => array('name' => $form_state['values']['name'])),
    // $http_response_code
    302,
  );
}

//$header = array(t('id'), t('name'), t('firstname'));

function get_data(){
    $data =  array(
        0   => array(
            'id' => '0',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        1   => array(
            'id' => '1',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        2   => array(
            'id' => '2',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        3   => array(
            'id' => '3',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        4   => array(
            'id' => '4',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        5   => array(
            'id' => '5',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        6   => array(
            'id' => '6',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        7   => array(
            'id' => '7',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        8   => array(
            'id' => '8',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        9   => array(
            'id' => '9',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        10   => array(
            'id' => '10',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        ),
        11   => array(
            'id' => '11',
            'name'  => 'pokpokpok',
            'firstname' => 'pokpokpok',
        )
    );
    $paging = pager_array_splice($data, 2);

    return $paging;
}
/*
    $header = array(t('id'), t('name'), t('firstname'));

    $form_state['table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $paging,
      '#empty' => t('Aucun r?sultat.')
    );

    $form_state['rebuild'] = True;*/

function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

```
> 0 votes

---
Tags: paging
---


# Question
Title: How can I survey anonymous users before they can read content?
I want to do a survey for all non-logged in users (a webform or something similar) before they can read a certain piece of content. I want authenticated users to not be bothered with it. These surveys will only be for selected pieces of content.

I have been looking around. I can't find a solution for Drupal 7. I'd like to use webform, but I am open to learning about different options.

# Answer
> 0 votes
Thanks for the help.

I ended up using the rules module along with rules url argument module.

I used the rules module to watch out for anonymous users, and query strings of "?surveycomplete=yes". I did this check for all nodes of my desired type that did not have a node reference to a webform.

If a user was anonymous and did not have the query string, then I redirected to the webform that the node was associated with.

To make the webform redirect appropriately when it was completed I changed the redirect location to the original node with the query string appended.

The downfalls with this approach is that every node that there is a 1 to 1 relationship for content to webforms when a many to 1 would be nice. Also, anyone could technically by pass the survey via appending the query string.

---
Tags: webforms, users
---


# Question
Title: Redirect user based on role and node content
I want to redirect a user when they login based on what role they have and whether they have created a node of a type.

So if the user has administrator role, direct user to admin url else if the user has role list\_user, check if user has content of type new listing, if they don't, direct them to create node listing if they do have created node of type listing, direct them to profile.

I have this set up in separate rules but I'm sure it will work better and faster by just having one php block of code in the template.php

My only problem is, I don't know php and everything I've tried doesn't work very well or not at all.

Any help would be appreciated.

# Answer
Use Rules module to redirect based on user roles.

1. After Installing Rules module, Go to Admin -\> Configuration -\> Rules (admin/config/workflow/rules/)
2. Add new rule
3. Enter rule name & select User has logged in from React on Event
4. Add new condition and set User has Role Select the required role and Save
5. In Action add new action Set it Page Redirect & enter the redirection URL
> 1 votes

# Answer
You should create basic module instead of heaving it in your theme (template.php file).

Create empty directory called your\_module in sites/all/modules and create your\_module.info and your\_module.module files inside. Here is info what should you put into .info file. For basic implementation you need only **name** and **core** properties.

.module file must implement hook\_user\_login() (this hook will be triggered after user login). Read more here. Here is pseudocode implementation of your problem:

```
<?php
function your_module_user_login(&$edit, $account) {
  if (something) {
    $edit['redirect'] = 'admin';
  }
  elseif (something_else) {
    $edit['redirect'] = 'admin/content';
  }
  elseif (something_else_2) {
    //
  }
}

```

Read more how to create drupal module
> 0 votes

# Answer
This is a fairly vague questions as few different problems need to be solved before you have a complete solution. I think @zaporylie is right and is a push in the right direction. My answer here acts as further help; but you will need to find out how to get details of the node type and what content types the user has. I use a debugger PHPStorm; that when you create a breakpoint you can all the variables that are available to retrieve.

If you want to find a user role you can use ( the elseif is a guess ! )

```
global $user;

if (in_array('administrator', $user->roles) {
    drupal_goto($youradminurl);
}
elseif (in_array('list_user', $user->roles) && $node->type == $user->contenttype)){
      drupal_goto($differenturl);
}

```
> 0 votes

---
Tags: redirection
---


title: Add field collection table in code

text:
# Question
Title: Add field collection table in code
I am creating a form to collect data for a specific content type which has a field collection in it.

So basically I am creating nodes manually through form API. What I need to do is to add a field collection table to my form which corresponds to the field collection I declared in the node type.

I have got how the table is rendered in the original add content form, which is like this:

```
[field_student_grades] => Array
    (
        [#type] => container
        [#attributes] => Array
            (
                [class] => Array
                    (
                        [0] => field-type-field-collection
                        [1] => field-name-field-student-grades
                        [2] => field-widget-field-collection-table
                    )

            )

        [#weight] => 5
        [#tree] => 1
        [#language] => und
        [und] => Array
            (
                [0] => Array
                    (
                        [#entity_type] => field_collection_item
                        [#entity] => FieldCollectionItemEntity Object
                            (
                                [fieldInfo:protected] =>
                                [hostEntity:protected] => stdClass Object
                                    (
                                        [uid] => 1

```

But I do not know how to deal with the \[und\] and \[hostEntity:protected\] and stdClass Object in code.

# Answer
You can't access Protected members directly.

you'll need to extend the class that represents that object to provide getter methods for the protected properties.
> 0 votes

---
Tags: forms
---


# Question
Title: When user is registered to drupal site ,disable admin approval notification
I want to disable admin approval notification when user is getting registered to a drupal site. I don't want to send notification mail to the admin.

# Answer
> 6 votes
You can disable the administration approval option in configuration page /admin/config/people/accounts of your site.

Otherwise, if you wish to maintain adminstration approval but only disable the email, add the following line at your settings.php:

```
$conf['user_mail_register_no_approval_required_notify'] = FALSE;

```

Links: Disable register email notification

# Answer
> 1 votes
According to the question to disable the ADMIN notifikation, the right conf is $conf\['user\_mail\_register\_pending\_approval\_notify'\] = FALSE;

---
Tags: users
---


# Question
Title: Using hook_js_alter to change localsettings variable in the autologout module drupal
I want to know how to use hook\_js\_alter to change the localSettings variable in autologout.js.

In autologout.module in line number ( 377 - 389)

```
$settings = array(
    'timeout' => $refresh_only ? ($timeout * 500) : ($timeout * 1000),
    'timeout_padding' => $timeout_padding * 1000,
    'message' => t('@msg', array('@msg' => $msg)),
    'redirect_url' => url($redirect_url, array('query' => $redirect_query)),
    'title' => t('@name Alert', array('@name' => variable_get('site_name', 'Drupal'))),
    'refresh_only' => $refresh_only,
    'no_dialog' => $no_dialog,
  );
drupal_add_js(array('autologout' => $settings), 'setting');
drupal_add_js(drupal_get_path('module', 'autologout') . "/autologout.js");

```

In this it passes the settings variable to the javascript file.

I want to change " 'title' =\> t('@name Alert', array('@name' =\> variable\_get('site\_name', 'Drupal')))," attribute using "hook\_js\_alter" in my custom module so that javscript takes the new value.

# Answer
The structure of the `$javascript` array passed to `hook_js_alter()` is similar to the following one. (I reported only the relevant part of the array.)

```
array(
  'settings' => array(
    'data' => array(
      0 => array('basePath' => '/'),
      1 => array ('pathPrefix' => ''),
      2 => array('ajaxPageState' => array ('theme' => 'bartik', 'theme_token' => 'oFpiDA70-NnnvSdIL6bFt1oLccvTT5SZeOp3G34cOfs')),
      3 => array ('overlay' => array('paths' => array('admin' => 'node/*/edit node/*/delete node/*/revisions node/*/revisions/*/revert node/*/revisions/*/delete node/add node/add/* overlay/dismiss-message user/*/shortcuts admin admin/* batch taxonomy/term/*/edit user/*/cancel user/*/edit user/*/edit/*', 'non_admin' => 'admin/structure/block/demo/* admin/reports/status/php'))),
      4 => array('overlay' => array('pathPrefixes' => array())),
      5 => array('overlay' => array('ajaxCallback' => 'overlay-ajax'))
    ),
    'type' => 'setting',
    'scope' => 'header',
    'group' => -100,
    'every_page' => true,
    'weight' => 0
  )
  // ...
);

```

I would use the following code for `hook_js_alter()`.

```
if (isset($javascript['settings']['data']) && is_array($javascript['settings']['data'])) {
  foreach ($javascript['settings']['data'] as $index => $settings) {
    if (isset($settings['autologout']['title']) && is_array($settings['autologout'])) {
      $javascript['settings']['data'][$index]['autologout']['title'] = 'Your value';
      break;
    }
  }
}

```
> 1 votes

---
Tags: hooks, javascript
---


# Question
Title: How to use other properties in hook_entity_property_info_alter()
I want to extend the entity properties of OG-Membership to use it as a token in rules.

It works fine adding the property (for example the string 'test' as returned in the getter\_callback is printed in a reaction rule (sending email)). But I could not find out, or how to debug/access, the other properties present in OG-Membership in the rules context. To put it differently:

How can I access the group id ($gid) of the OG-Membership in my getter callback?

This works well:

```
function mymodule_entity_property_info_alter(&$info){
  $properties = &$info['og_membership']['properties'];

  $properties['og_custom_property'] = array(
    'label' => t('My custom Label'),
    'type' => 'test',
    'description' => t('OG Membership Custom Property.'),
    'getter callback' => 'mymodule_callback'
    );
  return $info;
}

```

But here I cannot access the $gid, or anything, for that matter:

```
function mymodule_callback(){
  //do some stuff with the $gid and $etid of the OG-Membership
}

```

Any help is appreciated; maybe someone knows how to debug the in rules available properties? Thanks.

# Answer
If you use hook\_entity\_property\_info\_alter() you have access to the entity in question in the callback as well.

```
function mymodule_callback($item){
  //$item is the entity in question in my case $og_membership
  //hence I can acces the gid like this:
  $og_membership = $item; //redundant, just to show what I mean
  $gid = $og_membership->gid;

  //either do some more stuff or just return the gid as an example
  return $gid;
}

```

Now I can access the property and it returns the gid. For example in rules:

```
[og_membership:og_custom_property]

```

Hope this is useful to others as well.
> 2 votes

---
Tags: hooks, rules, entities
---