# Question
Title: Debugging your code under SimpleTest when the behavior is different
I'm dealing with a weird problem where a few of my tests are dying from exceptions when run inside of SimpleTest, but I'm unable to reproduce the problem outside of the SimpleTest environment. In particular, it appears that exceptions that I'm catching in my module code get intercepted by SimpleTest before they even leave my try block.

I'm able to debug my test script using xdebug, but for whatever reason, I can't get SimpleTest to pass on the debugger info to my code when it's running under SimpleTest. So when SimpleTest calls `$test->run()` on one of my tests, the test starts up in its own, SimpleTest-unaware process. And my debugger sits on its hands (they have hands, right?) and runs as if everything is copacetic.

Is there some option in SimpleTest that will allow me to get the **XDEBUG\_CONFIG** environment variable passed on to the subprocesses that SimpleTest spawns?

# Answer
> 0 votes
I have a provisional answer to this, although I'm hoping someone will supply a better one than this one.

First of all, setting XDEBUG\_CONFIG as an exported environment variable will let you stop your test script, but not your actual Drupal code. The reason is sort of ugly. SimpleTest interacts with your code using its own mini-browser. So your SimpleTest test runner is as completely isolated from your Drupal application as your browser at home is isolated from the web server you get your page from. There's no connection at all.

So how do we use xdebug via a browser? One way is to set a get parameter, and add the XDEBUG\_SESSION\_START variable to your URL, like this:

> http://my-site-i-want-to-test/node/42?XDEBUG\_SESSION\_START=my-key

When your test web server sees XDEBUG\_SESSION\_START, and you have your server set up to connect with your IDE, your server connects up with your IDE, and away you go.

So, here's my not-really-very-good solution to the problem: I get drupalGet and its twins to add XDEBUG\_SESSION\_START to the string SimpleTest uses to communicate with your server.

SimpleTest is actually using PHP's curl extension to create its mini-browser. If you look at the implementation of drupalGet in WebTestBase.php, you'll see something like this:

```
  protected function drupalGet($path, array $options = array(), array $headers = array()) {
    // We re-using a CURL connection here. If that connection still has certain
    // options set, it might change the GET into a POST. Make sure we clear out
    // previous options.
    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));

    // lots of stuff omitted here...

    return $out;
  }

```

The $options argument gets passed to $this-\>buildUrl(), which takes the regular format for URL options. We need to add something to the query string, so we need to pass

```
$options = [
  'query' => [
    'XDEBUG_SESSION_START' => 'my-key',
  ],
];

```

This unfortunately requires you to edit your test and pass $options whenever you want to get control of your application via your debugger.

A slightly better solution is to override drupalGet() in your test class, since AFAICT, all the other drupal\*() methods ultimately call drupalGet(). In your overrided version, you just append the 'query' info above to the $option array that is passed to it, and then call the original method. You can even watch for a environmental variable in your SimpleTest test script, and only add the 'query' string when you see it.

---
Tags: 8, testing, debugging
---


# Question
Title: In views, show the number of users who have subscribed to the organic group
I am using the following modules
1. Organic Groups
2. Views

A content type called **Course** has been created. It has been set as an organic group. It has group members(Users who have subscribed to the course).

I have created a view which shows the list of all the groups (Nodes of type Course). In another column, I want to show the number of users who have subscribed to the group(course).

# Answer
> 0 votes
This is how to get the OG membership ID:s to start with.

1. Add new view. Show -\> OG membership (important!)
2. Then in some display add a contextual filter -\> OG membership: Entity id.
3. Provide default value -\> Type -\> User ID from logged in user.
4. Override title: %1's groups. Specify validation criteria -\> User.

Now you have the list of ID's.

5. Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -\> Group Node from OG membership.
6. Add a field -\> Content: Title. Relationship -\> Group node from OG membership.

Now you get the titles too. For test add some filters and sort criteria.

---
Tags: views, organic-groups
---


# Question
Title: I'm using Webform. How can I use JavaScript in it?
I am using webform. I'm going to create to fields. First one should be taxonomy term name, and second one should be taxonomy term values. In this case I'm trying to use javascript. When you choose a category in first field, it should be seen categories acording first one. For example: when you choose "animals" category in first field, it should be seen "bear", "lion", "sparrow" and other categories in second. When you choose "fruits" category in first field it should be seen "apple", "bananas", "ananas" and other categories in second. How to solve this problem?

# Answer
You should try Webform conditional module.

> This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.

Screencast Demo

View a demonstration form
> 0 votes

---
Tags: javascript, webforms
---


# Question
Title: Views : hide thumbnail for all but one content
Ive created a View called "most recent articles" that are made up of 4 contents. I have the thumbnail displayed along with title, body and tags for each content. This is sorted by Most recent article by published date. How can I only display the thumbnail for the latest content (1) but the other 3 articles not display the thumbnail at all?

# Answer
> 0 votes
The module Display suite gives the option to add different views mode for different rows. Here is a video tutorial ,in this lesson you cover how one can use view modes and display suite to allow multiple options of layouts for content display. This allows a user to have a different layout of the same content for different scenarios of the site. Combining this with views and you can start to see the power of display suite in action.

---
Tags: views
---


# Question
Title: how to hide a field when adding content through node/add for a content type?
I have 7 fields in a content type and the last field value, I am updating programmatically. So it should not be displayed when adding content to it. What should I do.

# Answer
> 2 votes
The way I prefer is to use Computed Field module. Not only it creates a field that's not editable for users, it also takes care about hooks, cache, and lets you simply choose recalculation strategy (on save / on display). All you really need to care with it, is the very code that calculates field's value.

# Answer
> 1 votes
Hope this will help field\_hidden

Field Hidden defines five hidden field types

text, long text integer, decimal, floating-point Hidden in forms Hidden fields are always rendered as elements in forms.

# Answer
> 0 votes
Go and edit the node content type and in Field Settings change the Field Visibility and Permission.

Just remove the edit permission to any role.

# Answer
> 0 votes
You can add a field in your form programmatically as follows :

```
function hook_form_alter($form,&$form_state, $form_id) {

 if ($form_id == 'your_form_id') {

$field_hidden_value = 'enter your computed value here' ;
   $form['field_hidden'] = array(
      '#type' => 'value',
      '#value' => $field_hidden_value,
   );

  }
}

```

# Answer
> 0 votes
If you are looking to avoid creating a custom module/using code:

Then:

* **Setup a new rule with the event:** Begin \[your form name\] being built
* **Setup a new action:** Rules Forms \> Set an attribute of an element in the form
* Set the attribute #access to false

The form element will now be hidden.

If you are trying to avoid creating a custom module, this does the trick.

---
Tags: entities, nodes
---


# Question
Title: How can I change the "content type" field name particularly in a view?
I have a few content types on my Drupal instance. Eg. case study, forum topic etc.

I have built a view, to display few nodes and their content types.

In this view, I want to display the content type as case studies instead of case study, forum topics instead of forum topic.

I don't want to change the content type globally, but I want to change the content type only in this view.

Is there any hook that I can write to make this change?

# Answer
Add a field to each of your content types, let's call it "Nickname" and enter the value you want to appear in your view, ie for Case Study enter "Case Studies". Now add Nickname to your View fields, and it should output the right text for each content type.
> 1 votes

---
Tags: views, hooks
---


title: Unable to change backend language

text:
# Question
Title: Unable to change backend language
During install, it is possible to choose the language to be used on the admin screens. However, in this new Drupal 7.40 instance it was not chosen at install time. I need now to change the language from the default English (this is NOT a multilanguage issue).

Every tutorial I read tells me to click the "Add Language" button on Administration \> Configuration \> Regional and language \> Languages. But there is no such button, there isn't even a "Languages" option under "Regional and language":

# Answer
The option is displayed only after activating the "Locale" core module on the admin \> modules page.
> 0 votes

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


# Question
Title: What's the latest in the page lifecycle a module can send an HTTP header?
For CDN purposes I am collecting the modified times of various pieces on the page and want to set the Last-Modified header to them. What's the latest during a request a Drupal 7 module can call `drupal_add_http_header`?

I know the answer but I think this is a very interesting question and I somehow doubt most people would know the answer, so I will leave this open for a few days and then post the answer.

### Note

To avoid insane answers like using runkit or doing your own request cycle, I will say the answer is userland PHP only, and less than 10 line of code.

# Answer
Headers can be sent anytime up until the content is sent to the page which happens in `drupal_page_footer()`. The whole page is output buffered: `_drupal_bootstrap_page_header` has the `ob_start` and `drupal_page_footer` has the `ob_flush`.

Headers are also overwritten by default so there is no reason why you can't re-send the Last-Modified header at any point.

So, how about `hook_exit()` (called from `drupal_page_footer` just before the `ob_flush`).
> 5 votes

# Answer
Use `hook_page_alter()` to add an `#attached` property to the `$page` renderable array, this will be executed by `drupal_process_attached()` at the end of `drupal_render()`, which is called at the end of `drupal_render_page()`, which is called near the end of `drupal_deliver_html_page()`.

`drupal_page_footer()` is called after `drupal_render_page()`, but since the output of `drupal_render_page()` is printed, that would be too late.

Example:

```
function example_page_alter(&$page) {
  $page['#attached']['drupal_add_http_header'][] = array('Last-Modified', 'Wed, 15 Nov 1995 04:58:08 GMT');
}

```
> 1 votes

# Answer
If the module provides the page delivery call back, then the module **should** be able to inject the header at any point up until the callback calls `drupal_get_http_header()`.

My solution was posted before the edit was added. In terms of being possible to do it 10 LoC, how is 5?

```
function mymodule_page_delivery_callback_alter(&$delivery_callback) {
  $delivery_callback = $default_delivery_callback == 'drupal_deliver_html_page'? 'drupal_deliver_html_page' : 'mymodule_page_delivery_callback';
}

function mymodule_page_delivery_callback($page_callback_result) {
  drupal_add_http_header('X-Example', 'skwashd showing off');
  drupal_deliver_html_page($page_callback_result);
}

```
> 0 votes

---
Tags: 7, hooks
---


title: Add a block to a render array

text:
# Question
Title: Add a block to a render array
I have a block I would like to add it to my renderable array (given to a page callback), with prefix and suffix - what's the cleanest way to do this?

I understand I can do it this way:

```
$markup = '';
if ($block = block_load('views','results_anonymous-block')) {
    $block_content = _block_render_blocks(array($block));
    $build = _block_get_renderable_array($block_content);
    $markup = drupal_render($build);
}

$content['page'] = array(

    '#markup' => $markup,
);

return $content;

```

But wondered if there was a better way (e.g. without rendering the block or using the private function).

# Answer
Modules provide their block titles and contents through implementations of hook\_block\_view(). If you're looking for something similar to your posted code that doesn't rely on calls to private functions, what's below should give you a render-ready array that you can place anywhere within another render array.

```
$renderable_block_data = module_invoke('views', 'block_view', 'results_anonymous-block');
$renderable_block_contents = $renderable_block_data['content'];

```

Caveat: while the docs for D7's version of hook\_block\_view() suggest that the returned "content" key should be a render array, some modules/blocks may be implemented in such a way that they return plain HTML strings, in which case you'd need to put the content in a #markup element before adding them to your parent render array.

Further discussion can be found in this drupal.org post.
> 2 votes

---
Tags: blocks, theming
---


# Question
Title: How do I use a referenced entity in a Views contextual filter?
I'm building a media server for my university. I have an "artist" content type for each performer, and then a 'track' content type for individual track (there are no 'albums', BTW). For each track, you can select the artist in edit mode, using an Entity Reference. So far so good!

On each Artist page is a block view with a table listing that artist's songs (the filter is 'show all tracks with a contextual filter of "artist"). Still good!

On each track page, I want to show "all tracks by this artist" as a table. I've tried "artist" as the contextual filter, and even tried both "referencing entity" and "referenced entity" as relationships, to no avail. If I put an artist NID in to the fixed value in the 'artist' contextual filter, it works fine. But I'm pulling my hair out, trying to get the artist to dynamically be referenced by the block's contextual filter, using the tracks 'artist' entity reference.

Am I missing something here? It really seems like it shouldn't be that hard. Thanks in advance!

# Answer
For the curious, with Huelfe's help I solved it with a custom PHP code, in order to obtain the applicable NID for that contextual filter. Seems like something that should be built in to Views already...! I've successfully reused the string or several other projects as well.
> 1 votes

---
Tags: entities, views
---


# Question
Title: Altering fields before rendering: hook or template?
I have made some recent posts about Drupal 8 and its paradigm for altering fields. Having spent many hours reading up on APIs and some trial and error, I have come to the conclusion that I am really not sure how to proceed with certain basic tasks, such as altering a field.

So the point of this post is to see how one should go about a task such as altering a field.

First, let me describe exactly what I am trying to do. I would like to edit a field before it is rendered. It is an image field. So all I need to do is alter the target\_id of the field that points to the image. I want this to happen in every view, display, etc.

Some thoughts:

1. Overriding via templates: I don't think this makes sense. Seems a template gets a render array, and that one would want to alter the array before the theme does its thing. Also, I want to be able to switch out themes, so this approach is non-ideal
2. Rewriting field in Views: since I want the fields to be altered regardless of whether it is Views, Display Suite, etc, this would not make sense
3. Module hooks: I think this is what I need to do, but the info online on Drupal 8 is fairly sparse. For instance, I found out by trial and error that `mymodule_preprocess_field` will not get called if the field is being shown by Views. The Views hooks won't make sense because as I mentioned I need to alter a field regardless of Views.

So this takes me to 3. You can see Drupal 8 hooks here. At first I was trying to use `hook_preprocess_HOOK`, and in my case `mymodule_preprocess_field`. But as mentioned above that was not getting called in Views displays. Then I thought about `mymodule_preprocess`, but deciphering its `$variables` array is proving daunting, and the more I read about Drupal 8, the more I am convinced that this probably is not really in the spirit of Drupal 8.

The field specific hooks don't seem to be a match, for instance, `hook_field_info_alter` seems like it is for altering meta data.

So finally, I came to the conclusion that with Drupal 8 being so Entities focused, I probably need to look at an entity hook. For instance one of the following:

```
hook_entity_prepare_view
hook_ENTITY_TYPE_view
hook_ENTITY_TYPE_view_alter
hook_entity_view

```

But coming to this conclusion, a) I am not sure it is the right conclusion, and b) if it is the right conclusion, how to choose one of the above and how to actually implement it? (Note, using dsm(), debug() in Drupal 8 often results in results that are not very decipherable since so many array elements are protected.)

Anyway, I am curious how others would go about this!

EDIT: The above entity hooks are not called for taxonomy page... So I guess that takes me back to `hook_preprocess` which seems to be the only way to alter the field in all cases. But still trying to decode the $variables array and figure out the right methods/functions to make changes.

Thanks

# Answer
You can configure views in many ways and the hooks, that are called, will change accordingly.

You can easily debug this, if you put a "catch all" hook into your module and print out the hooks that are called:

```
function mymodule_preprocess(&$variables, $hook) {
   echo "<em>$hook</em><br>\n";
}

```

Then your page will be full of hooks, that are called at different places and you can try to narrow it down to the hook you need.

The next step would be to install devel and enable kint and debug the variables of the hooks, that you are interested in:

```
function mymodule_preprocess(&$variables, $hook) {
   if ( $hook == 'views_view_grid' ) {
      kint($variables);
   }
}

```
> 1 votes

---
Tags: views, 8, hooks
---


# Question
Title: How do I get the index number of currently displayed slide of a Views Slideshow into the jQuery Cycle's "Before" advanced option?
According to this StackExchange Answer, you can access jQuery Cycle options like so:

```
//on before function
before: function (curr, next, opts) {
    alert(opts.nextSlide + " of " + opts.slideCount);
}

```

However, the instructions in the views plugin say, "If one of the options you add uses a function, example fxFn, then you need to only enter what goes inside the function call" so in the Advanced Options *before* box I only put:

```
alert(opts.nextSlide + " of " + opts.slideCount);

```

This code yields the error `Uncaught ReferenceError: opts is not defined` in the console.

How do I access these jQuery Cycle variables (mainly the index of the current slide) from within my "Before" advanced option code?

# Answer
> 1 votes
Looking at the JS code for views\_slideshow\_cycle:

```
case "before":
  var beforeValue = advancedOptions[option];

  beforeValue = Drupal.viewsSlideshowCycle.advancedOptionCleanup(beforeValue);
// transition callback (scope set to element to be shown):
function(currSlideElement, nextSlideElement, options, forwardFlag)
  settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
    pager_before_fn(currSlideElement, nextSlideElement, options);
      eval(beforeValue);
  }
  break;

```

Your code isn't actually executed within the scope of the `before` callback, it's executed afterwards. The variable that the module provides is named `options` rather than `opts`, hopefully that will resolve to what you need and the change should be as simple as:

```
alert(options.nextSlide + " of " + options.slideCount);

```

---
Tags: views
---


# Question
Title: How to reset node id to a lower number - Drupal 7
I have loaded thousand of nodes in different tests. How can I safely delete all the extra nodes and obly the database table to increment the node nid after the next valid (not deleted) nid? I.e., now I have 50 valid nodes, and the index starts at 250.000. How can I force it to start at nid = 51 without making the whole database crash ?

**A secure way, please. Not low level, but with a module or something that respects referential integrity of the whole database.**

# Answer
> 0 votes
The node id is the primary key of the {node} database table. You need to reset the "auto\_increment" property of that table to 1 (or 51 in your case). You can do that with PHPMyAdmin, or other MySQL client.

---
Tags: 7, nodes, database
---


title: Webform Conditionals and Email Values

text:
# Question
Title: Webform Conditionals and Email Values
The scenario is, I have a form that you order multiple types of stationery. Depending on what items are ordered determines, what email needs to be sent the form results.

The issue I am running into is I need a way to prevent emails from being sent to the other print vendors if their fields are left blank.

Right now they all receive every email it just shows up blank because I have it set to exclude blank fields.

Any guidance would be greatly appreciated!

# Answer
You may want to try out the Rules module. It allows a lot of powerful conditions and actions to be configured. You may also pair it with the Webform Rules module to connect it to your Webforms (https://www.drupal.org/project/webform\_rules).
> 0 votes

---
Tags: webforms
---


title: Passing global variables to alter hooks

text:
# Question
Title: Passing global variables to alter hooks
The problem I have is that it seems that I can use global variable created inside another module, only if I use it inside callback function. I successfully tested it by inserting code inside existing modules.

The global variable is $subtotal.

```
function uc_checkout_pane_simple_quote($op, &$arg1, $arg2) {
    global $subtotal;
drupal_set_message($subtotal);

function uc_webform_pane_checkout_pane_callback($nid, $op, &$arg1, $arg2) {
  global $subtotal;
  drupal_set_message($subtotal);
}

```

In both cases the message shows the correct value.

However, inside other functions it is does not work.

```
function uc_webform_pane_checkout_pane_alter(&$panes) {
  global $subtotal;
  drupal_set_message($subtotal);
}

function uc_cartdetails_checkout_pane_alter(&$panes) {
  global $user;
  global $subtotal;
  drupal_set_message($subtotal);
}

```

What am I missing here?
What I am trrying to do: to show or hide checkout pane based on $subtotal value.

```
function uc_cartdetails_checkout_pane_alter(&$panes) {
global $subtotal;
  foreach ($panes as &$pane) {

    if (($pane['id'] == 'webform_nid780') && ((40 - $subtotal) > 0) ) {
      $pane['enabled'] = FALSE;
      }

    }
 }

```

# Answer
The problem is not the global variable, but the fact you are using a function like `drupal_set_message()` inside a alter hook, which is not necessarily invoked when Drupal is outputting a page.
If you want to debug a hook, it's better you go with `watchdog()` and check in admin/reports/dblog if there is any message. You need to enable the Database Logging or the Syslog module to see any output; in the latter case, you will see the output on the syslog of your computer, instead of admin/reports/dblog.
> 0 votes

# Answer
I'm not sure why globals don't behave well in Drupal, but it seems like what you're really asking is how to get global-like behaviour.

What you want is drupal\_static. Your code should look something like:

```
function uc_webform_pane_checkout_pane_alter(&$panes) {
  //'uc_checkout_subtotal' can be whatever you like.
  //I assume '0' is a good default for this variable.
  $subtotal = &drupal_static('uc_checkout_subtotal', 0);
  drupal_set_message($subtotal);
}

function uc_cartdetails_checkout_pane_alter(&$panes) {
  $subtotal = &drupal_static('uc_checkout_subtotal', 0);
  drupal_set_message($subtotal);
}

```

...and so on, applying that same pattern wherever you need to write or read your global values.
> 0 votes

# Answer
Well, for whatever reason inside ubercart alter functions I was not able to use globals. I ended up with basic altering of form like this:

```
function hook_form_alter(&$form, $form_state, $form_id) {

 if ($form_id == 'uc_cart_checkout_form' && isset($form['panes']['webform_nid780'])) {
 global $subtotal;
 if ((40 - $subtotal) > 0)  {
 $form['panes']['webform_nid780']['#access'] = FALSE;
    }

 }
}

```

which works no problems.
> 0 votes

---
Tags: theming, 6
---


# Question
Title: Attach a handler to the "event" of autocomplete select with jQuery
I'm using Views Autocomplete Filters on an exposed node title field. I would like to attach a handler to the "event" when the user selects one element from the autocomplete list without applying this patch which would actually trigger a "real" event.

For the simplest example: if the user has selected one element from the autocomplete list, show an alert() message. (I wouldn't do that because it's ugly, but it's the easiest demonstration of the solution.)

# Answer
I had a similar issue with a Drupal autocomplete field I had created, where I wanted the form submitted when an item from the dropdown was selected.

This blog post addressed the issue for me: http://othermachines.com/blog/smart-autocomplete-navigation-drupal-7

The relevant JQuery code you'll want to look at on that page is this:

```

(function ($) {

  Drupal.behaviors.programmeSearch = {
    attach: function (context) {

      $('#edit-autocomplete-field').focus(
        function(){
          $(this).val('');
      });

      $("#edit-autocomplete-field", context).bind('autocompleteSelect', function(event, node) {

        var key = $(node).data('autocompleteValue');
        var label = $(node).text();

        // If matches found...
        if (key != '0') {

          // Set the value of this field.
          $(this).val(label);

          // Redirect user to entity path.
          window.location = Drupal.settings.basePath + key;
        }
        else {

          // If no matches, reset.
          $(this).val('');
          $(this).focus();
        }
      });
    }
  };

})(jQuery);

```

You probably won't need all of that code. Whatever you want to happen on the select event, put in the condition beginning with

```
if (key != '0') {
```
> 1 votes

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


# Question
Title: How to create and send via email a PDF file with rules?
I need to create and send via email a PDF file with Rules using Drupal 7. I need to send it as an attachment, not as a link.

I found this post, Generate PDF with Print PDF and send in email, but Views PDF MIMEMail is a D6 module.

How can I do this?

# Answer
You should write a port to Drupal 7. The Views PDF MIMEMail module codebase is pretty lightweight (~300 LOC). Essentially, it's a

1. **.info** file declaration
2. A **.module** declaring a theme function
3. Various Rules integration functions (**.rules.inc**).

You can figure out how to convert the **.info** & **.module** by Googling around how to convert a **.info** to D7 and look up how `hook_theme()` changed in D7. There's a comprehensive guide on porting D6 modules to D7 if needed.

As for #3, the Rules module has some internal documentation that describes how to integrate Rules in D7. There's likely a few structural changes you'll need to do, but essentially most PHP code should stay the same.
> 1 votes

---
Tags: 7, rules, files, views
---


# Question
Title: How do I install a 3rd party PHP library in sites/all/libraries - can I just plonk it in there?
For example, according to the Drupal module s3fs, I can -- to quote their README.txt :-

> 2b) If you don't have drush, go to to http://aws.amazon.com/sdk-for-php and click the orange "AWS SDK for PHP" button. On the page you're sent to, click the "aws.zip" link. Extract that zip file into your Drupal site's sites/all/libraries/awssdk2 folder such that the path to aws-autoloader.php is sites/all/libraries/awssdk2/aws-autoloader.php

So, yeah, that's effectively: downloading the library, and plonking it sites/all/libraries and that's it. *But it doesn't work!* I get:

> Unable to load the AWS SDK. Please ensure that the awssdk2 library is installed correctly.

I've tried everything else in the README.txt : drush installer, specific version of AWS SDK, permissions...

# Answer
> 0 votes
> How do I install a 3rd party PHP library in sites/all/libraries - can I just plonk it in there?

Answer: \- It would appear you can, in *some cases* at least. With the example given the question, the problem was not whether or not a 3rd party php library could be just placed in the libraries folder, but rather some other unrelated issues that appear now to be resolved (the s3fs module make, coredumperror was very responsive today in helping me and they have updated their documentation). https://www.drupal.org/node/2596683#comment-10467823

**Update**

The "unrelated issues that appear now to be resolved" are that one of the setup procedures for the s3fs, as described in the README.txt, now work. By 'now work', I mean that I can install the module and do the described setup and use the S3fsStreamWrapper class provided with the module to read a file from an Amazon S3 bucket, more detail here https://www.drupal.org/node/2596683#comment-10467823 I had tried other approaches to reading S3 in Drupal, e.g. using examples elsewhere but was unsuccessful with those. But with this s3fs module I am now successful. With the s3fs module I had originally ran into issues whereby I got the aforementioned "Unable to load the AWS SDK. Please ensure that the awssdk2 library is installed correctly." error as stated in my question. But one of the maintainers of s3fs, coredumperror replied and updated the documentation as they discovered it had errors. So thanks very much to coredumperror on that, most appreciated. They have described what they changed in the above link. With this setup documentation updated and corrected, I was then able to use the s3fs module and read from a S3 file using the S3fsStreamWrapper provided with the module.

---
Tags: 7, installation
---


# Question
Title: Import image using feeds and image path?
With Drupal 7, I am using feeds to import an XML file. That file has a relative image path I can import, but not the image itself.

How can I save the image to the node itself instead of saving the image path?

# Answer
I believe it should work automatically, but you need to use a valid path schema, for example: `public://images/myimage.jpg`. Otherwise Feeds needs to know the absolute path to these images. If needed, use Feeds Tamper to correct image paths.
> 0 votes

---
Tags: 7, media, feeds
---


# Question
Title: Is it possible to import custom XML files with the Feed Import module?
With the feed import module I see that you can import CSV files and RSS feeds. But what about custom XML files that follow our own defined format. Is it possible to tell the Feed Importer to import these files?

# Answer
Yes it is. You need the Feeds Xpath Parser module
> 2 votes

# Answer
There is also Feeds extensible parsers module which is more flexible than Xpath Parser which is more user friendly and supports more formats (including XPath XML & HTML).
> 1 votes

---
Tags: 7, feeds
---


title: Reverse Entity Reference in a Paragraph

text:
# Question
Title: Reverse Entity Reference in a Paragraph
I have a Paragraph with an Entity Reference Field "link". This Paragraph belongs to Content Type B.

I want to create a reverse Entity Reference for "Link": all nodes that have the paragraph with this Entity Reference should be listed.

I tried

* content\_dependency \- does not seem to work with Entity References within Paragraphs
* reverse\_node\_reference \- not working at all?
* Custom View: did work with a entity reference without a paragraph (relationship referencing ER field) but not with the paragraph....

Any ideas?

# Answer
> 3 votes
After many days of unraveling views, entity references, and paragraphs, I finally figured this out. The moment was celebrated with an awkward, club-footed jig.

For context, I'm building a financial data delivery site that connects investment fund managers with funds to manage. My content types look like this:

I have an entity type called **Contact**, which has inside it a Paragraph field called **Job History**. There are 3 different job history paragraph bundles for 3 different types of jobs, but each type has fields for Job Title, Phone, Email, Employment Date, and an entity reference field called *Fund*. I also have another entity type called **Fund**, which is referenced by the *Fund* reference field.

```
1. Contact (entity)
- Job History (paragraph)
-- Fund
-- Job Title
-- Phone
-- Email
-- Employment Date

2. Fund (entity)
- Various fields (irrelevant to this solution)

```

I want to create a table view that will appear on all Fund pages, and show any contacts, with their contact info, for said Fund. In other words, this view should display any Contact nodes that reference the current Fund node, along with those nodes' phone, email, etc fields. I can achieve this using only Views...

1. Create a content view and filter by node type: Contact.
2. Add a relationship, *Content: Field (Job History)*. This allows me to access the fields inside the Job History paragraph field.
3. Add all above fields I want to display (name (title), job title, phone, & email) to the Fields section, making sure each one uses the *Paragraph item from field\_job\_history* relationship.

At this point, I have a view that displays **all** contact nodes & their fields. Let's narrow it down to those that reference only the current Fund node.

4. Add a relationship, *Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field\_reference\_fund)*. Use the existing relationship, *Paragraph item from field\_job\_history*.
5. Add a contextual filter for Content: NID. Use relationship, *Content entity referenced from field\_reference\_fund*. Provide default value: Content ID from URL.

The view will now display the fields within the paragraph, and limit the results to only those nodes that reference the current node.

I hope this provides the solution you were looking for!

# Answer
> 1 votes
This is what I get of your question. There is an Entity reference field.say Node with ID=1 points to nodes `3` and `4` but nodes `8,9,5,6` points to `1`. So by filtering the `1` you need to get `8,9,5,6` not `3,4` .

1 ---\> 2

1 ---\> 3

5 --\> 1

6 --\> 1

8 --\> 1

9 --\> 1

after entering `1` `5,6,8,9` must be listed.

By this assumption This is the solution. No module is needed. Just create a View of Content type B and check the

**Entity Reference Field**

*A bridge to the Content entity that is referencing Content via field\_reference*

and Save. Make sure you have not selected the `A bridge to the Content entity that is referenced via field_reference` you must select `A bridge to the Content entity that is referencing Content via field_reference` as *Relationships*. To see what contents are pointed from Content type B, Create a contextual filter of `nids`. This node ID will be the node IDs of content type B (it's role equals to `1` in above example). Click on it and select the relationship. like this

Select *Title* as Fields and now by entering any input as node ID of content type B the contents that are related to this node are listed.

If you are using URL alias you can simply use this method in `hook_preprocess_node` get the node ID and use `views_embed_view()` function and passing the node ID as parameter to get this view's result.

---
Tags: entities
---


# Question
Title: Subscribe/unsubscribe user from mailchimp list after purchase
I am using mailchimp 7.x 3.3 Module and ubercart is integrated for role selling, also I have rules module installed.

I have users subscribed to the mailchimp list, my requirement is when a user from my list purchase any order he should be unsubscribed from one list and subscribed to other mailchimp list, so that I can track the users from the list who did not purchase any order.

I am thinking of doing it using rules, In rules I have an event "when the user completes checkout", I want to add the action on same event, the action should be "unsubscribe from one list and subscribe to other list" but unfortunately I dont have any way to select the list there.

Please find the screenshot of rules interface below, help would be greatly appreciated.

This is event interface

This is Action Interface

# Answer
Because MailChimp doesn't want you to just subscribe people without their permission, it makes you put this into a field.

We have clients, however, who put the subscription opt-in into their Terms of Use agreement. A way around this is to create your own rule:

```
/**
 * @file
 * Rules integration for the mailchimp lists module.
 */

/**
 * Implements hook_rules_action_info().
 */
function mymodule_rules_action_info() {
  $items = array();
  $items['mailchimp_lists_id_user_subscribe'] = array(
    'label' => t('Subscribe or unsubscribe entity from a MailChimp list ID'),
    'parameter' => array(
      'entity' => array(
        'type' => '*',
        'label' => t('Email Address'),
        'description' => t('The email to subscribe.'),
        'wrapped' => TRUE,
        'allow null' => FALSE,
      ),
      'list_id' => array(
        'type' => 'text',
        'label' => t('MailChimp List ID'),
        'description' => t('The list ID found in the mailchimp dashboard.'),
        'allow null' => FALSE,
      ),
      'subscribe' => array(
        'type' => 'boolean',
        'label' => t('Subscribe'),
        'description' => t('True to subscribe, False to unsubscribe'),
      ),
    ),
    'group' => t('MailChimp'),
    'access callback' => 'mailchimp_lists_rules_access_callback',
    'base' => 'mymodule_rules_action_entity_subscribe',
  );
  return $items;
}

/**
 * Action callback: Subscribe an entity to a list.
 */
function mymodule_rules_action_entity_subscribe($entity, $list_id, $subscribe) {
    $email = $entity->value();

    $choices = reset($field_info['instance']['default_value']);
    $choices['subscribe'] = $subscribe;

    if ($subscribe == 1) {
        mailchimp_subscribe($list_id, $email);
    } else {
        mailchimp_unsubscribe($list_id, $email);
    }
}

```

Where *mymodule* is the name of your custom module. This will provide the rule integration you're actually looking for.

Be careful, though: This method could get you banned from Mailchimp. It's best to combine it with a double opt-in process to prevent people from reporting subscription abuse.
> 0 votes

---
Tags: emails
---


title: Drupal commerce taxes and ip location

text:
# Question
Title: Drupal commerce taxes and ip location
Im using smartip to show taxes to users by country, but I have a problem:

If a user is browsing the web with a USA IP but the order address is France?

So I have to use two conditions when calculating product price:

One user IP is in USA And order address comparison is USA.

This doesnt work, I suppose when calculating product price the order is not complete, so i dont know how solve it.

# Answer
> 0 votes
The **order's billing profile will always be authoritative on an order**. If you want to be able to provide tax/shipping estimates, you have two options:

1. Use something like Commerce Cart Estimate to provide **an estimate** by request to a customer. This doesn't put it on the order, but simply provides the estimates in a block.
2. Take the result of the SmartIP lookup and stick it in the billing address on the order. That way when the customer sets the actual billing address, it will just override it and it will stick. You should be able to swing this with the Smart IP module since it has a rules integration. Just tack it onto the order if it doesn't already have a billing address. Then, let commerce's rules do the rest and output the order's values.

Something that isn't out of the box would be to ask the user: Pop up a box or a block somewhere on the page that asks them to verify their country/postal code.

---
Tags: commerce
---


# Question
Title: Drupal Commerce Change Order Weight at Checkout
I am using Commerce FedEx to retrieve quotes at checkout and using a SmartPost setting that requires packages to be over 1lb. to return a quote from FedEx. I need to have the order shipping weight from Commerce Physical Products default to 1lb. for the entire order weight if the order weight is under 1lb. at the time of checkout. I do not want to make all of the products a minimum of 1lb. due to inaccurate quotes if multiple items are ordered so I am looking into a solution with Rules, but cannot seem to get an Action that will allow me to do this.

Example: One product is 0.25lbs. When two are ordered, the shipping weight should be 1lb. at checkout to receive a quote. When six are ordered, the shipping weight should be 1.5lbs.

# Answer
You can use `HOOK_commerce_fedex_rate_request_alter(&$request, $order)` to alter the request before it goes out:

```
function MYMODULE_commerce_fedex_rate_request_alter(&$request, $order) {
    // Test this value and set it to whatever you'd like.
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Value'] = 1;
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Units'] = 'LBS';
}

```

Just test the value and update it if you want.
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Automtically creating new redirects and alias on node_save
Here is the code I'm using to change the name field of my nodes if they contain certain phrases.

```
$query = new EntityFieldQuery();
$query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_product')
    ->fieldCondition('field_my_name', 'value', 'Old Phrase%', 'LIKE');

foreach ($result['node'] as $key => $value) {
    $node = node_load($key);
    $node->field_my_name[LANGUAGE_NONE][0]['value'] = str_replace('Old Phrase', 'New Phrase', $node->field_my_name[LANGUAGE_NONE][0]['value']);
    node_save($node);
}

```

It successfully changes the name; however, I'd like to automatically create a new URL and also a redirect entry from the old URL to the newly generated one.

I have `pathauto` installed and my URL Alias is configured to use the `my_name` field, but the code above does not change the Alias.

# Answer
Pathauto should automatically create a new alias with the updates (unless you have it turned off on the node). pathauto.module lines 519-522:

```
// Skip processing if the user has disabled pathauto for the node.
if (isset($node->path['pathauto']) && empty($node->path['pathauto'])) {
  return;
}

```

The Global Redirect module can then provide 301 redirects to the new URL alias.
> 1 votes

---
Tags: nodes, database
---


# Question
Title: Theme the taxonomy tags list in the node teaser
In my Drupal site I have node teasers that show taxonomy terms. As it stands they are like:

Tags:

Houses

```
<div class="field field-name-field-tags field-type-taxonomy-term-reference field-label-above">
  <div class="field-label">Tags:</div>
    <div class="field-items"><div rel="schema:category" class="field-item even">
        <a datatype="" property="rdfs:label skos:prefLabel" typeof="skos:Concept" href="/tags/houses">Houses</a>
    </div>
  </div>
</div>

```

I cant locate where the `<a>` anchor tag is being generated. I want to be able to change it to a `<button>` tag instead of anchor.

Any ideas how to do this?

# Answer
Take a look at this tutorial that shows you how to create a custom formatter for specific field types. The taxonomy term field type machine name is `taxonomy_term_reference`
> 0 votes

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


# Question
Title: Can Ubercart be adapted to print a letter?
When an order is received through Ubercart, the details can be viewed and printed, but can the *print order* option be expanded to do more? When I ship product, I like to **include a personalised letter** in addition to the standard order form.

Can I craft such a letter, so that it prints out after the order page, showing letterhead, date, customers address, and separate envelope?

# Answer
Yes. In D7 there's a 2 step process to this.

1. Copy **ubercart/uc\_order/uc\_order-invoice-page.tpl.php** to your current theme directory and flush your cache; this will let you create your own custom version of the the order template.
2. Add this snippet to your new template after `<?php print $content; ?>`; this will add some markup/CSS that will be rendered as a new page when treated as a printable document.

```
<?php /* Print only from administration page*/ ?>
<?php if(preg_match('/admin\\/store\\/orders\\/\\d+\\/invoice\\/print/', current_path()) == 1): ?>
  <div style="page-break-after: always;"></div>
  <div id="letter-region">
    <p>NEW PAGE</p>
  </div>
<?php endif; ?>

```

If you're running a D6 site, it's a little more of pain (D6 UC ignores some theming conventions).

1. You'll need to copy **ubercart/uc\_order/templates/uc\_order-customer.tpl.php** to **ubercart/uc\_order/templates/uc\_order-custom.tpl.php**
2. Have a module define a new custom template via `hook_uc_invoice_templates()`: `function MYMODULE_uc_invoice_templates() { return array('custom'); }`
3. Set the new invoice in order setting page (**admin/store/settings/orders/edit/basic**).
4. Use the code in the above D7 example inside **uc\_order-custom.tpl.php**. You'll have to modify since I don't think current\_path() exists in D6. However, the same frontend logic still exists (add some extra markup in the template with CSS to generate a 2nd page).

There might be a better way to do this, but I've not touched D6 UC templating in a long time.
> 1 votes

---
Tags: theming, ubercart
---


# Question
Title: How do I display random nodes within a week?
I have added Global:Random in Sort Criteria.

It displays nodes that are too old. How could I set the period to 1 week?

***The nodes displayed are from last year and year 2013, how to set views to display nodes within a week.***

# Answer
> 1 votes
You can add filter for **Content: Post date** and configure the filter criteria as follows:

# Answer
> 1 votes
You can achieve it by below steps.

1. Add filter criteria **Content: Post date**.
2. Follow the screenshot for **Content: Post date** field configurations.

---
Tags: nodes
---


# Question
Title: Using the back button after logging out shows you pages from the authenticated user's session
Using the back button after logging out shows you pages from the authenticated user's session.

I found a solution for this, need to set the header like this to fix this issue-

```
drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');

```

But the problem where i need to set this header? I set the header in `index.php` file. After that i am not able to see any other pages while i am logged in. **(getting page not found error)**

Any solution, how to fix this issue??

# Answer
> 0 votes
You can implement hook\_init() in any of your custom modules

```
<?php
/**
* Implements hook_init().
*/
function YOUR_MODULE_NAME_init() {
     drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}
?>

```

---
Tags: caching, security
---


# Question
Title: How to sort null field values in Drupal?
I have a **content type** with one field of type text.

I add content for **5 nodes**.

For 2 nodes among 5, I entered nothing in text-field.

So scenario is 3 nodes have data in that field and **2 of the nodes are empty**.

Now I'm sorting on behalf of that particular text-field in my custom module and the result is:

**It hides node with empty content.**

**It means only 3 nodes are visible, empty values are not visible.**

**Expected result should be, the fields that don't have any value inside should also get sorted and the resulting nodes would be seen either at the top of all sort-able content or below it.**

*How can I achieve this?*

# Answer
You can achieve it by installing Views Sort Null Field module.

> This module provides an additional sort for FieldAPI fields, which sorts by whether the field is empty or not. This allows empty (i.e. NULL) values in fields to be sorted last.
> 2 votes

# Answer
You can may be do ifnull function

```
IFNULL(node_data_field_value_some.field_important_value,0)  AS node_data_field_value_some_field_important_value

```
> 0 votes

---
Tags: nodes
---


# Question
Title: How to render a Views Content Pane programmatically?
I have a view which displays all content of type "news" which is tagged with a specific tag, e.g. "world" (passed as parameter to the view).

The view machine name is `news`. It has a display of type Content Pane (machine name `panel_pane_1`). It also has a contextual filter set to "field\_tags".

How to render this view content pane programmatically, passing tag value "world" to it?

(I've found `ctools_content_render` but no idea if this is the right function for this task and how to use it)

# Answer
You can use

`views_embed_view`

e.g

```
print views_embed_view('news', 'panel_pane_1', 'world');

```

Any additional parameters will be passed as arguments, i.e contextual filter values.
> 4 votes

# Answer
You can use views\_content\_views\_panes\_content\_type\_render(). Here is a detailed example:

```
  // Important to include target content type.
  // You can also use 'views' content type but with a different render function.
  module_load_include('inc', 'views_content', 'plugins/content_types/views_panes');
  // Use your views machine name and display name here.
  $subtype = 'views_name-display_name';
  // Adjust settings to yours. You can debug ctools_content_render to see
  // all available settings in $conf. Or check
  // views_content_plugin_display_panel_pane::option_definition().
  $conf = array(
    'items_per_page' => 2,
    'offset' => 0,
    'more_link' => 1,
    'override_title' => 1,
    'override_title_heading' => 'blablalba',
    'override_title_text' => '',
    'pager_id' => 0,
    'use_pager' => 0,
  );
  // (optional) Prepare ctools context and context keys if your argument type
  // is 'context'. Check handling of other argument types in
  // views_content_views_panes_content_type_render().
  $conf['context'] = array('mycontext');
  $context = array(
    'mycontext' => ctools_context_create('node', $node),
  );
  // Render views pane.
  $pane = views_content_views_panes_content_type_render($subtype, $conf, $args, $context);

  // Get pane HTML.
  $output = render($pane->content);

```
> 0 votes

---
Tags: 7, views, chaos-tool-suite
---


# Question
Title: How to add field update your password in drupal webform?
I want to add **three fields** in webform:

1. Current password
2. New password
3. New Password Again

Current password should be existing password and last two fields(New password ,New Password Again)should update only if current password is correct(validated). In short I only wants to add "update your password functionality" in my website using webform .

Any Idea how to do this ?

# Answer
Webform Password Field

> This module allows you to add a password component to a webform. It doesn't validate the password in any way.
> 0 votes

---
Tags: hooks, webforms
---


# Question
Title: Ability to order fields for each content in a content type
I have a custom content type which is rendered by a custom tpl php. I would like to have the ability to control the order in which the fields are displayed for each contents.

I can use the order of the fields defined in the content type, but that will affect all the contents for that content type. Can I have some field in which I can specify the order of the content types that is being displayed? So that based on the field containing the order, I will render the fields in configured order.

Or else what would be the best way to do that, so that I can get control over the order of each content?

# Answer
> 0 votes
Field display weights (per node) is the solution. This allows me to configure the order of the fields for each nodes.

# Answer
> 2 votes
It's not clear how you define the order of the field, but if you put extra information in the node and want to use this to change the order of the fields before output, you can use the weight property to change the order in an alter hook:

```
hook_node_view_alter(&$build) {
if ( $build['field_sort_order']['0']['#text'] == 'sort it this way' ) {
   $build['field1']['#weight'] = -10;
   $build['field2']['#weight'] = 10;
   ...
}
...

```

---
Tags: theming, nodes
---


# Question
Title: how to hook checkout pane defined in another module?
I try to make a small change to Drupal Commerce Coupon pane (add a div to it). I tried to hook this function:

```
    function commerce_coupon_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
              // Allow to replace pane content with ajax calls.
              $pane_form = array(
                '#prefix' => '<div id="commerce-checkout-coupon-ajax-wrapper">',
                '#suffix' => '</div>',
              );
        (..)
}

```

To do this I created a function in my module:

```
function <mymodule>_form_commerce_coupon_pane_alter(&$form, &$form_state, $form_id) {
        $form['#prefix'] = '<div id="collapsable-panel"><p>You have coupon? Add it here.</p>' + $form['#prefix'];
        $form['#suffix'] = $form['#suffix'] + '</div>';
    }

```

but it do not work. I think that there should be other way to hook checkout pane but I cannot figure out how to do this.

# Answer
> 0 votes
Problem solved. Hooking Drupal Commerce panes works quite diffrent than hooking functions from other modules. At begining: *form* in commerce\_coupon\_pane\_checkout\_form is confusing - this function in fact doesn't create form but is "added" as a fieldset to one big checkout form. And of course it cannot be hooked.

What do you need to change behaviour of panes defined in Drupal Commerce and other commerce modules:

1. Read: Checkout info hooks
2. create `function <mymodule>_commerce_checkout_pane_info_alter`
3. Inside this function override pane settings using: `$checkout_panes[<pane_name>]['callbacks']['checkout_form'] = <your_custom_pane_function>`
4. create `<your_custom_pane_function>($form, &$form_state, $checkout_pane, $order)`
5. Probably there will be need to call existing implementation of pane and change some configuration of form returned form this existing implementation.

and thats all :)

# Answer
> 0 votes
`commerce_checkout_form_PAGE` is a form ID. Use it inside of `HOOK_form_FORM_ID_alter` to edit a particular page of the checkout process. Like so:

```
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
    $form['#prefix'] = '<div id="collapsable-panel"><p>You have coupon? Add it here.</p>' + $form['#prefix'];
    $form['#suffix'] = $form['#suffix'] + '</div>';
}

```

Alternatively, you can also do a generic alter and check the build info in `$form_state`:

```
function MYMODULE_form_alter(&$form, &$form_state) {
  if ($form_state['build_info']['base_form_id'] == 'commerce_checkout_form') {
    // We're in checkout.
    $form[PANE_ID] ...
  }
}

```

---
Tags: commerce
---


# Question
Title: Commerce minimum quantity and purchase multiplier
I have added a field to content type **Product** with the purchase quantity (default 1). Products can only be purchased by this quantity. For example, if its value is 5, you could buy 5, 10, 15, and so on. This is configured by products, and some products could have a value of 1, and others could have a value greater than 1.
After read some post about "quantities" and "minimum quantity", I haven't found how to do it. I have tried with some modules like Commerce Extras, and Commerce Add to Cart Extras. But without success.
Could some one give me some ideas how to do it?
Thanks in advance.

# Answer
> 0 votes
Ryan's answer on this question is the approach you'd want to take:

1. Install Commerce Custom Product.
2. Create a new line item type that has new quantity select field and widget. Expose this to the add to cart form.
3. Hide the regular quantity selection to the add to cart form.
4. Use a rule to take the value in the field you created in step 2 and set the quantity field to that value on the line item.

---
Tags: commerce
---


# Question
Title: How to change path of file from absolute to relative?
In my website, some of the images are having absolute path of old server *.*.*.*/old\_directory/sites/, but now I have changed my server, I want that these images should be picked from /sites/ path of my current instance.

Anyone has any suggestion??

# Answer
Install any one of the below modules.

1. Pathlogic
2. Portable path
> 1 votes

---
Tags: .htaccess
---


# Question
Title: How to prevent pager_default_initialize from getting initialized?
I'm calling this function pager\_default\_initialize on a certain condition. But once this function gets called, it initializes default pager everywhere I `return theme('pager')`.

What I want is

```
if(condition == TRUE)
pager_default_initialize($total, $limit, $element = 0) get executed
theme('pager') works!
if(condition == FALSE)
pager_default_initialize($total, $limit, $element = 0) not get executed
theme('pager') should stop work. I don't want pager when condition is FALSE.

```

but problem is once `condition == TRUE` gets satisfied, I got pager everywhere.

**Any way to uninitialize this pager function on certain condition?**

# Answer
The easiest way would be to override `theme_pager()`:

```
function MYTHEME_pager($variables) {
  if (!pager_is_disabled()) {
    return theme_pager($variables);
  }
  return '';
}

```

Where `pager_is_disabled()` is a function you write that determines the current status. You could store that info in static vars, a Drupal variable, database, cache, whatever makes most sense for your use case.
> 0 votes

---
Tags: paging
---


# Question
Title: Add properties to an entity hook_schema_alter
I need to implement a custom module that adds fields and properties to an entity defined in another module. I felt the best way to do this was using hook\_schema\_alter and hook\_update\_n to achieve the data structure updates. However, I do not see these new fields on my entity. Is there another step to take to attach these to the entity via code?

# Answer
> 12 votes
Using the third-party Entity API module, you can:

* Implement hook\_schema\_alter().
* Use something like db\_add\_field() to actually make the change to the DB in YOURMODULE\_install() or updateN(). `hook_schema_alter()` does not actually create the field in the database. It just tells other modules at the code level that the field exists in the schema.
* Implement hook\_entity\_property\_info\_alter(). This tells the Entity API module that this field exists as a property of some entity, where it lives in the database table, and how to access it.
    + Clear the cache to have the new properties showing up.

An example property in the $info array is basically the following one:

```
  $properties['survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make business logic easier.',
    // This is the schema field you made.
    'schema field' => 'survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );

```

# Answer
> 5 votes
Here is a working example which implements `hook_schema_alter`:

```
/*
 * Implements hook_schema_alter().
 */
function mymodule_schema_alter(&$schema) {
  $schema['tablename']['fields']['fieldname'] = array(
    'type' => 'varchar',
    'default' => null
  );
}

/*
 * Implements hook_install().
 */
function mymodule_install() {
  if (!db_field_exists('tablename', 'fieldname')) {
    $schema = drupal_get_schema('tablename');
    db_add_field('tablename', 'status', $schema['fields']['fieldname']);
  }
}

/*
 * Implements hook_uninstall().
 */
function mymodule_uninstall() {
  if (db_field_exists('tablename', 'fieldname')) {
    $schema = drupal_get_schema('tablename');
    db_drop_field('tablename', 'fieldname');
  }
}

```

Where `mymodule` is your module name, `tablename` your table name and `fieldname` is your field name.

---
Tags: 7, entities
---


# Question
Title: How to call function from PHP file (or another module) in JS file from my custom module?
After this question, I try to write custom module to add support Views Infinite Scroll to Background Images module. Here is my code:

**my\_module.module**

```
/**
 * @file
 * Module file for Background Image for Views Infinite Scroll.
 */

/**
 * Implements hook_page_build().
 */

function my_module_page_build() {
  // Settings.
  drupal_add_js(array(
    'viewClass' => '.view-content',
    'nodeClass' => '.node-content',
  ), 'setting');
  // Add JS to page.
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
}

/**
 * My function.
 */

function my_module_function() {
   // Code here
}

```

And **./js/my\_module.js**

```
/**
 * @file
 * This is main script of Background Image for Views Infinite Scroll.
 */

(function($, Drupal) {

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      $(Drupal.settings.viewClass).on('DOMNodeInserted', function() {
        // Code here
      });
    }
  }

})(jQuery, Drupal);

```

How call function `my_module_function()` in my JS file?

# Answer
You can add a menu callback in your module, that will be used by JS to send-receive values from PHP.

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['my-module/my-function'] = array(
    'title' => 'Ajax callback for my function.',
    'page callback' => 'my_module_function',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_function() {
  // Remember you have to print your results if you want to
  // send any values back to JS.
  print 'Hi, there!';
  drupal_exit();
}

```

Now in your JS code, you make an Ajax call and, optionally, get values back from PHP (if desired).

```
$.ajax({
  url: Drupal.settings.basePath + "?q=my-module/my-function",
  done: function(data) {
    // If my_module_function returns any value, it will come in the data variable.
    alert(data);
  }
});

```
> 2 votes

---
Tags: javascript
---


# Question
Title: How to allow an OG group admin to create and add a user to a group?
I have a situation where our D7 site is connected to a LDAP server (with LDAP) module. However, I need a way to allow an Organic groups administrator to add a user (who has not yet logged in) and automatically enroll that user in that same group.

How might I address this?

My first thought is to just build a form where the OG admin adds the user name to a queue. When that user finally logs in, I would use the user\_save() hook to add them to the appropriate group.

# Answer
I found a round about way. I made my own form with two values and a `user_access('administer group')` check. The first value is the group id and the second is the user name.

In the `myform_form_submit()`, if the user name exists in the users table, I run `og_group` to subscribe that user. If the username does not exists and the user has not logged in, I add them to a queue as a key value pair of username and group id.

When the user logs in, hook\_user\_login() searches through that queue to find any instance and if so, subscribes them to that group.
> 0 votes

---
Tags: 7, organic-groups, users, authentication-authorization
---


title: Static field of taxonomy term

text:
# Question
Title: Static field of taxonomy term
I have a content type with a static field that I want to reference a specific TAX term. When a new node is added, I want the term to default to a specific reference, and I don't want the author to change it. I was thinking that a STATIC FIELD could work, but not sure how to hard code the term reference.

put another way, I want to Hard code the TAXONOMY term into a field of another node type.

any other ideas on how this would be done or alternatives?

# Answer
One alternative could be adding a regular term reference field that has the particular taxonomy term you want referenced set as the default value. Then in a hook\_form\_FORM\_ID\_alter call the node edit form for the specific content type and set the #access value to FALSE for that field.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Need rule: if Giftcard used to pay order, then skip PayPal, if Giftcard not used then goto PayPal
My Drupal Commerce site allows customers to buy vouchers (each voucher is a product), which are paid for using PayPal and which gives them a code. The system then allows them to book classes, using a voucher rather than PayPal. Using commerce giftcard module, customers fill out the voucher (giftcard) code in the giftcard pane at checkout. Apply the voucher and the the total to pay goes to zero and the voucher value is reduced by the cost of the class. Checkout says no payment is required, all is well, class is booked.

However, when no voucher code is entered checkout still says no payment is required, even though the total is not zero. In this case I need a rule checking the total of the order, allowing no-pay-progress if total is zero (i.e. gift card has been applied) else require PayPal (i.e giftcard code has not been applied and total is \> zero).And that is where I get stuck. Any help on how to formulate this rule much appreciated.

# Answer
> 0 votes
Payment methods are enabled via Rules. One of the Rules conditions is to check the balance of an order. Have you not tried adding this to your rule that enables PayPal as a payment method?

---
Tags: rules, commerce
---


# Question
Title: How to pass PHP variables to Javascript/jQuery?
I found this way to send variables from PHP to Javascript.

Inside the `template.tpl.php` file, I have the following code.

```
<?php
  echo '<div class="drupal-vars" style="display:none;">'.json_encode($variables).'</div>';
?>

```

Within Javascript, I have the following code:

```
(function ($) {
  $(document).ready(function() {
      var variables = jQuery.parseJSON($('.drupal-vars').html());
      //Remove if youwant to clean the code.
      $('.drupal-vars').remove();
  });

}(jQuery));

```

I found another solution, but it's more complicated, although it may be better architectured.

1. Is there a better way to do it?
2. How ugly is what I am doing here?

---

The tutorial goes like:

> I'll start by creating a hook\_menu() implementation to establish a page callback:
>
> ```
> <?php
> function helper_menu() {
>
>   $items = array();
>
>   $items['js-vars'] = array(
>     'title' => t('Javascript Variables'),
>     'description' => t('Javascript Variables'),
>     'page callback' => 'helper_page_callback_js_vars',
>     'access arguments' => array('access content'),
>     'type' => MENU_CALLBACK,
>   );
>
>   return $items;
>
> }
> ?>
>
> ```
>
> Next, I'll define the page callback:
>
> ```
> <?php
> function helper_page_callback_js_vars() {
>
>   // include module javascript file
>   drupal_add_js(drupal_get_path('module','helper') . '/js/helper.js');
>
>   // define variables you'd like to pass to the DOM
>   $js_vars = array(
>     'js_vars' => array(
>       'message' => t('Hello @username', array('@username' => $GLOBALS['user']->name)),
>       'an_array' => array(
>         'color' => t('red'),
>         'name' => t('Eric'),
>       ),
>     ),
>   );
>
>   // pass variables to javascript
>   drupal_add_js($js_vars, 'setting');
>
>   // generate some page output
>   return "TEST";
>
> }
> ?>
>
> ```
>
> And here is the contents of the javascript include file I stuck in my module directory:
>
> ```
> $(document).ready(function(){
>
>   // debug variables directly in FireBug
>   console.debug(Drupal.settings.js_vars);
>
>   // popup mesage passed from Drupal
>   alert(Drupal.settings.js_vars.message);
>
> });
>
> ```

# Answer
You'd be better off using `drupal_add_js()` to pass your object in the JS `Drupal.settings` object:

```
// In PHP:
drupal_add_js(array('myModule' => array('variables' => $variables)), 'setting');

// In JS
var variables = Drupal.settings.myModule.variables;

```

Drupal handles all the conversions of objects/arrays internally and this is just a much cleaner way of doing it...at the moment you're including raw JSON as part of the page output which isn't great in terms of semantics; also bear in mind that search engines will pick up this text even though you're hiding it for users with javascript.

I'd also recommend separating this logic out from the template file itself and put it in a `template_preprocess_` function in your theme's `template.php` file...again it's just cleaner. e.g.

```
function MYTHEME_preprocess_html(&$vars) {
  $variables = $your_variables;
  drupal_add_js(array('myModule' => array('variables' => $variables)), 'setting');
}

```

Have a look at the link to the `drupal_add_js()` function, there are quite a lot of options and you'll probably find them quite useful.
> 16 votes

# Answer
Also, in other cases, you can use drupal\_to\_js function. It Converts a PHP variable into its Javascript equivalent.

```
<?php
  $php_settings = array(
    'key1' => 'value1',
    'key2' => 'value2',
  );
?>
<script type="text/javascript">
  var phpSettings = <?php echo drupal_to_js($php_settings); ?>
</script>

```
> 1 votes

# Answer
an example on how to convert node datas to a js object:

in template.php

```
function mythemename_preprocess_node(&$variables){
     drupal_add_js(array('node' => $variables['node']), 'setting');
}

```

in the page.tpl.php

```
  var node = Drupal.settings.node;
 // console.log(node);

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Deny node access based on custom field value (Using Code)
I'm new in Drupal so please bare with me. I am looking to **restrict access** to the article node based on a **custom field value**. So if the custom field value is set to 1 then allow access for all user expected anonymous user. I have a custom field of '**special article**' and this has a Boolean values of 1 (true) and 0 (false). I have tried numerous ways of doing this and I can deny access to every **article node**, but I only want to do it on the articles where the '**special\_article**' field is set to 1. This is what I have so far and it restricts all articles from displaying to the anonymous user.

```
    function mymodule_node_access_records($node) {

  $grants = array();
  if ($node->type === 'article' && $node->status) {
    $grants[] = array(
        'realm' => 'mymodule_myrealm',
        'gid' => 1,
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'priority' => 0,
    );
  }

  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function mymodule_node_grants($account, $op) {
  $grants = array();

  if (user_access('can view member articles', $account)) {
    $grants['mymodule_myrealm'][] = array(1);
  }

  return $grants;
}

```

I tried to add the following to the above ccode but that didn't work.

```
function mymodule_node_access_records($node) {

      $grants = array();
      if ($node->type === 'article' && $node->field_special_article['und'][0]['value'] == 1 && $node->status) {
        $grants[] = array(
            'realm' => 'mymodule_myrealm',
            'gid' => 1,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
        );
      }

      return $grants;
    }

```

If anyone can help me out with this I would be really grateful. Thanks

Edit: Just to clarify, I would like to achieve this using code in a custom module to understand Drupal development better. Thanks

# Answer
> 1 votes
Have a look at Nodeaccess.

> The upshot is, this module allows you to do things like 'node 123 can be viewed by authenticated users and edited by admin users and joeuser'. As an added bonus, update and delete permissions are separated, so you can make sure users with edit permissions cannot accidentally delete pages.

# Answer
> 1 votes
Ok, so after changing my code a bit and republishing the content in Drupal (republishing the content was key!) this is what worked. I hope it helps someone at some point.

```
/**
 * Implements hook_node_access_records().
 */
       function mymodule_node_access_records($node) {
      $grants = array();
      if (array_key_exists('field_special_article', $node)) {
      if (array_key_exists('und', $node->field_special_article)) {
      if ($node->field_special_article['und'][0]['value'] == 1) {

            if ($node->type === 'article' && $node->status) {
              $grants[] = array(
                'realm' => 'mymodule_myrealm',
                'gid' => 1,
                'grant_view' => 1,
                'grant_update' => 0,
                'grant_delete' => 0,
                'priority' => 0,
              );
            }
          }
        }
      }

      return $grants;
    }

    /**
     * Implements hook_node_grants().
     */
    function mymodule_node_grants($account, $op) {
      $grants = array();

      if (user_access('can view special articles', $account)) {
        $grants['mymodule_myrealm'][] = array(1);
      }

      return $grants;
    }

```

---
Tags: nodes, hooks, users
---


# Question
Title: Place tag before input text field in search-block-form
I would like to add an li tag infront of the input field in the search-block. Should be possible with hook\_form\_alter. I've already printed the array containing the search-block-form, but I couldn't find input type text to add a prefix value.

```
function myTheme_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     print_r($form); -> no input type text here to add prefix to.
   }
}

```

# Answer
> 0 votes
The "input" type you are referring to, is actually the element defined inside the array `$form['search_block_form']`, of `#type` 'textfield'. That's the element that provides the input field when rendered.

In order to add a `<li>` tag in front and back of this input field, try using the properties `#prefix` and `#suffix`. Also I would suggest creating a custom module for this, avoid using it inside the template.php file. Try the following (haven't tested it myself, though).

```
function myModule_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     $form['search_block_form']['#prefix'] = '<li>';
     $form['search_block_form']['#suffix'] = '</li>';
   }
}

```

---
Tags: hooks
---


# Question
Title: How to render a Commerce pane programmatically?
I've the following code:

```
$panes = commerce_checkout_panes();
$payment_pane = $panes['commerce_payment'];

```

which loads one of Commerce pane which contains the array like:

```
array (size=15)
  'title' => string 'Payment' (length=7)
  'page' => string 'review' (length=6)
  'file' => string 'includes/commerce_payment.checkout_pane.inc' (length=43)
  'base' => string 'commerce_payment_pane' (length=21)
...

```

How do I render that pane programmatically?

This is part of `commerce_checkout_form_review` form (which is normally present at `/checkout/%/review`), but I need to render only payment part (checkboxes) but in different place.

# Answer
Panes are forms. Run them through `drupal_get_form` but you'll need to pass in some extra options:

```
require_once drupal_get_path('module', $payment_pane['module']) . '/' . $payment_pane['file'];
$order = commerce_order_load($order_id);
$payment_form = drupal_get_form($payment_pane['callbacks']['checkout_form'], $payment_pane, $order);
$output = drupal_render($payment_form);

```
> 2 votes

---
Tags: 7, theming, commerce
---


# Question
Title: How to render user profile edit form in block?
I want to render fields of user profile edit page like "User Name ","current Password","email" in a customblock

# Answer
> -1 votes
I would suggest creating a view that displays user content. You should be able to add any fields you want from the user profile to the view. Then add a new display to the view with the 'block' type.

---
Tags: hooks
---


# Question
Title: Is it possible to create a view of Nodequeues
I'm trying to create a list of all my nodequeues using Views, To be clear I'm not trying to create a view that showing the content within a Nodequeues, but rather create a views that lists the Nodequeues themselves is this possible? if so how do do it?

# Answer
In order to create listing of all nodequeues with views I would have exposed nodequeue\_queue table to views.
> 0 votes

# Answer
Excerpt from the Community Documentation of Nodequeue (about "**Automatic Creation of Views**"):

> When configuring Nodequeue, you can opt to "Automatically create one view per queue" (you may wish to leave this off if you plan to create the views yourself).
>
> The views created automatically cannot be deleted from the Views interface because they are implemented "in code". However, if you disable the auto-creation, then clear caches, these views will be removed.
>
> **It is highly recommended that you use the Views module to display your subqueues.** However, if you choose not to, you can alternatively use a small PHP snippet.
>
> To use nodequeue from Views (D7), add a 'relationship' to the queue, and typically set to 'require this relationship'. Optionally add 'nodequeue: Position' to match the preset queue order.
> 1 votes

# Answer
I don't know if it's possible to get Views to list queues as such. But here's something I did to achieve a similar result, that is: a view that lists queues.

I created a new content type (called "collection" in my case) with a field for nodequeue ID. This allowed me to add a description, author, and other metadata that Nodequeue doesn't do. For individual colelction display, I created a view of the queue's content attached to the node by way of the ID. Then I made a view that showed collections, which effectively lists the queues. (In fact I made another queue to curate the collections and my view displayed that meta queue.)

I hope this is helpful!
> 0 votes

# Answer
Steps to make a view from node queue:

1. Create a node queue and add some article(content) to it.
2. Create a view and select fields in format section show (fields).
3. Click on Add relationship in advance section.
4. search for Node-queue and add the relationship.
5. check the Require this relationship checkbox, check the Limit to one or more queues (recommended) checkbox and Select the node-queue name which you have created earlier and hit apply button.
6. Now in fields section just add the field you want from you node queue content and Only the article(content) added to the node queue content will get appear in display of view.
> -1 votes

---
Tags: views, nodes
---


# Question
Title: Displaying multiple nodes inside a single view block
I am somewhat new to drupal.

My goal is to display the 5 most recent nodes with a specific tag ("slideshow") in a, well, slideshow.

I am trying to use a views block in order to do that. But when I add the block to the main page, it shows nothing. I've also tried modifying the template 'archive' view, but it shows a link to a different page with the contents of a specific month instead of the posts themselves:

How can I have it so the content themselves are all displayed in this block?

# Answer
> 1 votes
1. Create a new View (rather than trying to alter an existing one like Archive).
2. Add a Block display.
3. Set the "Number of items to display" to 5
4. Add filter(s) so that only the nodes you want are displayed
5. Add a sort by the created date of the node, descending, so the ones at the top of the list are the most recent.

---
Tags: views, nodes, blocks
---


# Question
Title: admin approval required for specific roles registered using profile2_regpath
I am using profile2\_regpath for registrations .

I have 3 roles. Students, Centers and Organisations. Is it possible to activate the users which are registered for Student role without admin approval ?

The users who registered for centers or organizations role must need admin approval.

Default "Account settings" in Drupal have the option to activate users without admin approval but I can not specify the roles there.

Any clue? or any other module which I should be using instead profile2\_regpath

# Answer
> 1 votes
You may be able to use Rules to accomplish this. Create a new Rule that is triggered when a user account is created. Then add a condition that checks what the role of the user is. And finally, an action that activates the user account. I think that would work - although I'm not sure if those triggers/conditions/actions exist. They probably do. :-)

---
Tags: users
---


# Question
Title: Change drupal 7 way of hashing password?
Hi I am trying to migrate users from a legacy custom CMS site that used "sha256" technique to hash passwords to drupal 7 platform.

Upon further reading I came to know that drupal 7 stores passwords as salted and sha512 hash.

How can I change drupal 7 way of storing password hashes/ authentication of users to sha256 technique? Any direction would be helpful.

# Answer
> 4 votes
This is entirely possible but requires custom code for your alternative solution. For an example see: https://www.drupal.org/node/1109374#comment-4711644

From the linked thread you may simply:

(1) Create a new module, I called mine projectname\_legacy\_auth

```
/**
 * supply alternate authentication schemes
 */
variable_set('password_inc', drupal_get_path('module', 'projectname_legacy_auth') . '/projectname_legacy_auth_password.inc');

function projectname_legacy_auth_uninstall() {
  // put it back the way it was...
  variable_set('password_inc', 'includes/password.inc');
}

function projectname_legacy_auth_disable() {
  // put it back the way it was...
  variable_set('password_inc', 'includes/password.inc');
}

```

(2) add the authentication mechanisms you need to projectname\_legacy\_auth\_password.inc'. In this case, it's md5().

```
/**
 * simplified example for md5, no salting
 */
function user_check_password($password, $account) {
  if ($account->pass == md5($password)) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Simplified example for md5 hashes, no salting
 */
function user_hash_password($password, $count_log2 = 0) {
  return md5($password);
}

/**
 * this is probably a bad idea :-)
 */
function user_needs_new_hash($account) {
  return FALSE;
}

```

# Answer
> 0 votes
~~This isn't possible, and it really shouldn't be. Your best bet is to reset all passwords and require that users change them when they want to access the new site. It's a pain in the butt, but it's the "right" way to do it.~~

I was wrong! See @tenken's comment below...

---
Tags: 7, migrations, users
---


# Question
Title: How to customize the 'node content links' block?
I'm using Organic Groups to make groups, and have made two content types to be added to the groups. I'm also using the OG extras module, so now I have the 'Node content links' block, where users may add content to the group. I want some of the users to see one of the links to create one content type, and the other users to see the other link to create the other content type.

How am I able to do this? Do I need to use organic group roles? If so, I'm unable to find out where I set this type of role for a member. I know where I can create them, but not assign them.

# Answer
I was looking for this myself and come across this link: http://makandracards.com/jan0sch/11463-drupal-organic-groups-extras-add-content-links

If you're using Drupal 7 and Organic Groups (2.x) you probably have the OG extras module enabled.

The documentation to enable the "create content" links for your organic group nodes is sparse. Therefore a short howto:

* Enable all needed modules Enable the module entityreference prepopulate!
* Go to "Structure" -\> "Content types" and select your group content type, not your group type.
* Click on "manage fields" and edit the field "og\_group\_ref".
* Enable the checkbox labeled "Enable Entity reference prepopulate".
* Enable the block named "Node content links".
* Now you should be done. Steps 4-5 are needed for every group content type in case you have multiple content types that can be posted to groups.
> 1 votes

---
Tags: organic-groups, users
---


# Question
Title: Assigning revision owner when moderating backwards with Workbench
I have a site that has a complex set of permissions and roles to support a workflow we have defined with Workbench Moderation. This particular workflow has the "normal" three states:

* **Draft**
* **Needs Review**
* **Published**

The workflow is set up to allow both forward progression through the workflow (eg, **Draft** to **Needs Review**) and also backwards (eg, Needs Review to Draft). The site also uses the basic features in Workbench, and content creators like the **My Content**, **My Drafts**, and **Needs Review**, etc, pages / views that it provides.

OK, here is my problem. One of the common tasks are editors pushing nodes back to **Draft** status for original authors to do major work on. The problem is that if you examine `node_save`, revisions have their `$uid` set to the used who did the save (ie, `$user->uid`). In this case, it would be the editor. Therefore, the new draft shows up in the editor's queue and not the original author's (if you examine the view for this page, you can verify this behavior).

I am curious whether others have run into this problem and how they solved it.

Using a `hook_node_presave` to set the isn't an option, as it fires too soon, and `node_save` would nuke any changes, anyway.

I suspect that I could do a `hook_node_update`, eg

```
function mymodule_node_update ($node)
{
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

```

but I am worried that there may be side effects that I am not considering.

Are there better options?

# Answer
Old question, but in response to the comment, this is the solution that I deployed. As far as I know, it has been working well:

```
/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

/**
 * Implements hook_workbench_moderation_transition().
 */
function mymodule_workbench_moderation_transition($node, $previous_state, $new_state) {
  if (isset($node->nid) && isset($node->vid) && isset($node->uid)) {
    mymodule_node_update($node);
  }
}

```

This covers the case where a user updates a node via the edit form, and when a user pushes a node through moderation via the workflow forms.
> 4 votes

# Answer
Try the most recent patch over at Publishing/Unpublishing a revision changes the author of that revision. Or, if it's been committed, try a version of the module containing the fix.
> 1 votes

# Answer
I was having this same issue, and I was able to fix it by updating the "My Drafts" view to include revisions that belong to the current user OR revisions where the original node author is the current user.

> I added the relationships Content Revision: Content (which links to the original node) and then Content: Author (using the content revision: content relationship)
>
> I added the filter User: Current (Yes) using the relationship Content: Author (which uses the node's original author, instead of the revision author) and put it in an OR relationship with the extant User: Current filter.

https://www.drupal.org/node/2382215#comment-10471868
> 1 votes

---
Tags: 7, workbench
---


title: Exporting Panel setting to a Feature

text:
# Question
Title: Exporting Panel setting to a Feature
Does anyone know how to add the **Panels** \> **Settings** \> **General** \> **'Make all views available as panes'** checkbox to a feature?

I guessed the Strongarm box but I don't see the setting.

# Answer
> 1 votes
Fixed. ctools\_content\_all\_views was being used in a Panopoly feature so I had to learn how to use the Features Override module.

# Answer
> 1 votes
Yes, it's variable and it's in the Strongarm box. His name is ctools\_content\_all\_views. It can be not set by default - then just submit your form and check again.

# Answer
> 0 votes
If you are using strongarm then check node/%/node is unable then `page_manager_node_view_disabled` is set to false

---
Tags: panels, features
---


# Question
Title: How do I change the uploaded file name after the node has been saved?
How can I change the name of an uploaded file after the node has been saved? I know there is the FileField Paths module for this purpose, but it's still buggy for Drupal 7. I looked at the source of the module, but I can't extract the necessary code.

The only thing I know is that I should use `hook_node_update()` and `field_attach_update()`, but I don't know how to use them.

# Answer
> 4 votes
Perhaps this will help you. Last night I wrote a code which is meant to auto-generate a file and attach it to the node. When the node is about to be saved, the function removes the uploaded file from the node and creates and attaches the new file.

In your case, you might be able to just update the file name with file\_copy and resetting the filefield.

```
    function MODULE_node_presave($node) {
    /*
    *  Out with the old - detach file object
    */

    if (isset($node->field_filefieldname['und'][0]['fid'])) {
     file_delete(file_load($node->field_filefieldname['und'][0]['fid']));
    }
    unset($node->field_filefieldname['und'][0]);  //just for good measure

    /*
    *  In with the new
    */

    $filename = 'newfilename.dot';
    $filepath = conf_path().'/files/yourpath/';
    $touchout = $node->title;

    $tempFile = file_directory_temp().'/'.$filename;

    file_put_contents($tempFile, $touchout);

    $file = (object) array(
        'uid' => 1,
        'uri' => $tempFile,
        'filemime' => file_get_mimetype($tempFile),
        'status' => 1,
        'display' => 1,
      );

   /*
   *  File save operation, puts file in /sites/default/files and records update in db
   */

    if (file_prepare_directory($filepath, FILE_CREATE_DIRECTORY)) {
     $file = file_copy($file, 'public://path/'.$filename, FILE_EXISTS_REPLACE);
    }

   /*
   *  Reattaches our severed file, good as new.
   */

    $node->field_filefieldname['und'][0] = (array)$file;
    }
    ?>

```

# Answer
> 2 votes
If you know the file id (and don't mind running some PHP code) it's very easy:

```
$file = file_load($fid);
file_move($file, 'public://new/path');

```

# Answer
> 0 votes
Here is the method of changing the file when a file has been added to the database just before it get saved by using `hook_file_presave()`:

For example:

```
/**
 * Implements hook_file_presave().
 */
function hook_file_presave($file) {
  // Change the file timestamp to an hour prior.
  $file->timestamp -= 3600;
  if ($file->filename == 'my_file.wav') {
    $file->filename = 'mynewfile.wav';
  }
}

```

See also: How can I rename uploaded files programatically? (auto-rename image files)

Note: This method do not rename filename of file, just filename in file\_managed table, so if you'd like to rename the file it-self, you need to move it manually (e.g. `$file = file_move($file, $uri);`). See this post.

To change it after a file has been added to the database, use `hook_file_insert()`, for example:

```
function hook_file_insert($file) {
  // Add a message to the log, if the file is a jpg
  $validate = file_validate_extensions($file, 'jpg');
  if (empty($validate)) {
    watchdog('file', 'A jpg has been added.');
  }
}

```

---
Tags: 7, files, nodes
---


# Question
Title: How to change filename before it get saved without changing source URL using tamper plugin?
I've URL which is mapped to file field (image) via Feed Ex.

I'm trying to change the filename before it's get saved using tamper plugins (e.g. concat or regex), however it is also changes the requesting URL causing saving the invalid image files which consist html with *404 error*.

How do I use Feeds Tamper plugin to modify data (filename) after the file is downloaded but before it's get saved? Or I need to find some other alternative way of doing that?

# Answer
> 0 votes
It seems it's not possible using tamper plugins (as far as I've tried).

As workaround, this can be achieved by using `hook_file_presave()`, for example:

```
/**
 * Implements hook_file_presave().
 */
function mymodule_file_presave($file) {
  if ($file->filename == 'ShowImageXML.asp') {
    $filename = date("ymd", $file->timestamp) . '-' . $file->filesize . '.jpg';
    $uri = 'public://images/' . $filename;
    $file = file_move($file, $uri);
  }
}

```

See also a feature request: #2596841

---
Tags: importing-exporting, files, feeds
---


# Question
Title: How can I rename uploaded files programatically? (auto-rename image files)
I am aware that the File Paths module allows administrators to use tokens to set patterns for renaming files, but as of writing (Jan 2015) there are more than 100 bugs in the queue and no updates to the dev version in almost one year. (I also installed it and it and was unable to get it working.) So, I want to do this programmatically.

**My goal is to rename all new user-uploaded image files on my Drupal 7 site to this pattern:** `[uid of logged in user][timestamp].extension`.

Being able to rename them with the UID is very important because these files are often downloaded and exchanged (sent back and forth via email, without reference to Drupal), and we need an easy way to identify which user originally uploaded the file after it has been downloaded from the site.

I am using the Transliteration module. For inspiration, I also took a look at the File Entity Paths module, but it didn't provide me any insight. I further consulted this article on file-naming best practices from Acquia but it provides no suggestions for doing this programmatically.

# Answer
> 4 votes
Assuming you are talking about the core file functionality, you can modify the filename in hook\_file\_presave() and modify the `filename` property.

```
function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];
}

```

Drupal will handle changing any other properties that need to be changed.

Some issues to be aware of:

* Upload forms will expose the new name to the user after he clicks 'Upload'. It may be confusing to upload a file with a regular filename and see it changed to a string of numbers.
* There is a note on the hook\_file\_presave documentation that the hook "doesn't distinguish between files created as a result of a copy or those created by an upload." If you do need to distinguish, check out the $file-\>source property or try calling menu\_get\_object() to figure out if the user is on a page with an upload form or not.
* Consider using a dash between the uid and the timestamp for your naming convention. Your timestamps will all start with 1 (until 2033 anyway), and users with UIDs ending in 1 (e.g 11, 21, etc.) will make the filename confusing to read.

# Answer
> 1 votes
To rename files properly before they got saved (when a file being inserted or updated), use `hook_file_presave()` to change the filename in the table, or `hook_file_insert()` after a file has been added to the database, then use `file_move()` to actually move that uploaded file.

Here is an example using `hook_file_insert`:

```
/**
 * Implements hook_file_insert().
 */
function mymodule_file_insert($file) {

  if (strpos($file->filename, 'ShowImageXML.asp') !== FALSE) {
    $ext = strpos($filename, '.') !== FALSE ? drupal_strtolower(substr($file->filename, strrpos($file->filename, '.') + 1)) : '';

    $filename = sprintf("%d-%d.%s", $file->uid, $file->timestamp, $ext);
    $uri = 'public://' . $filename;
    watchdog('mymodule', 'File has been renamed from !old_file to !new_file.', array('!old_file' => $file->filename, '!new_file' => $filename), WATCHDOG_INFO);
    $file = file_move($file, $uri);
  }
}

```

If you need to do the same when a file has been added to the database, use `hook_file_presave` with similar code as above, but it's only for renaming file names in `file_managed` table, not in the file system.

# Answer
> 0 votes
Since Drupal manages the files usually you dont need to rely on file naming conventions to know what user uploaded a file and when. You can just look it up in the db.

If you really need to change the file paths: Option 1 An easy way to do this is by adding a computed field that looks the managed files the user uploaded and creates/manages copies by appling any pattern you may want. Then on node display you use the copy

Option 2 You alter the file upload widget or you use a module like the ones you propose to do this. This method requires no copies

Option 3 You go with a headless Drupal method. I.e. you dont use the node edit form but you create your own with Jquery, Angular, or anyother fronted framework. Then you create an API on the drupal side and you do whatever you want with the uploaded files before you persist/manage them and create a node. This method gives you suberb control and you can apply other custom functionality too (e.g. conversion of file types with imagick or custom cropping or annotations...) Howver if you go with this method make sure you take care of security issues (e.g. CSRF handling) that normally drupal takes care of automatically

---
Tags: 7, files
---