# Question
Title: How to create username with firstname and lastname using feeds and tamper?
On Feeds tamper module page (amazing module btw), it says that the module permits to \[...\]

Examples: \[...\]

* > Combine separate 'firstname' and 'lastname' fields into one 'name' field.

But I don't find any documentation on how to do this. Any help?

# Answer
> 1 votes
Depending on your source data, you want to use the "Rewrite" plugin of Tamper to combine the fields. More described in: https://drupal.org/node/1973776

---
Tags: users, importing-exporting, feeds
---


# Question
Title: Drupal 7: How to create a slideshow using Twitter Bootstrap Carousel?
I'm a newbie when it comes to Drupal. But I know HTML/CSS, jQuery and Twitter Bootstrap quite well. I already have Bootstrap and jQuery installed and working fine.

I want to take advantage of Twitter Bootstrap responsive features and create a Twitter Bootstrap Carousel (photo slideshow) on the homepage. http://twitter.github.com/bootstrap/javascript.html#carousel

How can I set that up so that the photos and article links can be setup from Drupal 7 admin?

# Answer
It's very late to answer this question, but I guess it will be helpful to any other like me who seeks for assistance in creating a carousel with the use of TB(Twitter Bootstrap). Drupal community has come up with a module called views\_bootstrap or bootstrap\_carousel

which will help you create a responsive carousel powered by TB and Drupal. The instructions given in the project page should almost give you what you want cheers!
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: How are user.tokens.inc and other similar files included?
I notice that many core modules in Drupal 7 implement `hook_token_info` and `hook_tokens` in a `hook.tokens.inc` file, but I can't figure out how this file is included. Should I be doing the same with my own module? How can I be sure it will be loaded?

# Answer
> 7 votes
They do it by way of `hook_hook_info()`:

> Defines one or more hooks that are exposed by a module.
>
> Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.

As luck would have it, the example from the docs shows exactly how the Token module does it:

```
function hook_hook_info() {
  $hooks['token_info'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens'] = array(
    'group' => 'tokens',
  );
  return $hooks;
}

```

> Should I be doing the same with my own module?

Totally up to you - it certainly can't hurt, other modules that need to implement your hook will just have an extra option for storing the hooks. But if you don't, they can still implement your hooks in the .module file anyway.

---
Tags: tokens
---


# Question
Title: How do I get the modified field value of a VIEW
I have a VIEW which pulls on the content field of a type. I specified I want the rewrite rules to trim to 25 characters with an ellipsis.

Unfortunately I also override the template (views-view-unformatted--XXX.tpl.php) and when I echo out the structure of the entire node and entity in template.php I see nothing of a modified field -- only the full data.

How do I adhere to the requirements of the field set in the VIEW?

# Answer
I am not exactly sure of what your are looking for. When I need to change the output of a field I usually change the $view-\>result for the field in hook\_views\_post\_execute.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Is Drupal forum module suitable for a massive forum
If I use the Drupal forum module (not the advanced forum module) to create a forum website (30 replies per page) and if the forum grew to a massive forum, will this module decrease the performance?

Drupal is caching the comments separately, will that going to be a problem?

# Answer
It depends on how 'massive' is your forum, what level of control you expect to have on the forum and how powerful and well configured is your server. There are Drupal forums with couple of hundred thousand users that work kind of fine, but if your main goal is to have a large and capable forum, you get much better performance and features out of specialized forum software like VB.

While Drupal forum provides rudimentary functionality, you will have hard times attaining many common specialized forum features like assigning different moderators to each forum, post thanks (which exists in D6 but not in D7), merging threads, banning users for certain amount of time, limiting posts/threads per day, and the list goes on and on.

The only pros that I can think of is integration to Drupal core, which makes sense only if you already have a Drupal site.
> 1 votes

# Answer
Try discourse, the best forum platform :).

If you don't mind running a server with a slightly different tech stack, its definitely worth it. Lots if interesting thoughts behind a great technology and a good team & community with a mission to repair the way forums work :).

There have been some attempts of integrating it with Drupal, I haven't followed for a while, but it is feasible.
> 0 votes

---
Tags: nodes
---


title: Using drush up with --gitinfofile

text:
# Question
Title: Using drush up with --gitinfofile
I tried to manage drupal modules with the --package\_handler=git\_drupalorg which needed me to add the --gitinfofile option. Using drush dl this works but if I try to update my modules with drush up the version information is the same as of the drush dl version. Is there a fix for this or a guide which explains how to use drush with the git version control system. I am using the drush 6.2.0 version.

# Answer
**Update:** As mentioned in the comments below, the actual answer here is that the git deploy module is required for `--package-handler=git_drupalorg` to work correctly.

If you just want to track the latest HEAD from some branch of some module, then you can use `drush dl` with `--package-handler=git_drupalorg` to download the file, and use `git pull` when you want to update your code.

`drush pm-updatecode` is best used in instances where you wish to track the latest stable release of the module.
> 0 votes

# Answer
I have this solution that has worked well for me, but requires a 1-line hack of a drush file, **so use it at your own risk**. Really the only problem is to remember to redo the hack when you upgrade drush. Below I broke it all down for completeness.

1) For download

> drush pm-download MODULE\_NAME --package-handler=git\_drupalorg --gitinfofile

2) For update

> drush pm-update MODULE\_NAME --package-handler=git\_drupalorg --gitinfofile --gitcheckoutparams=-f

To make these your default options, add the following to sites/all/drush/drushrc.php

```
$options['package-handler'] = 'git_drupalorg';
$command_specific['pm-download'] = array('gitinfofile' => TRUE);
$command_specific['pm-update'] = array('gitinfofile' => TRUE, 'gitcheckoutparams' => '-f');
$command_specific['pm-updatecode'] = array('gitinfofile' => TRUE, 'gitcheckoutparams' => '-f');

```

3) Put the following hook in sites/all/drush/SITENAME.drush.inc

```
/**
* Implements HOOK_pm_post_update().
* NOTE: Bottom section of package_handler_post_download($project, $release)
*       from file PATH2DRUSH/drush/commands/pm/package_handler/git_drupalorg.inc
*/
function SITENAME_pm_post_update($project) {
  $release = $project['releases'][$project['candidate_version']];
  if (drush_get_option('gitinfofile', FALSE)) {
    $matches = array();
    if (preg_match('/^(.+).x-dev$/', $release['version'], $matches)) {
      $full_version = drush_pm_git_drupalorg_compute_rebuild_version($project['full_project_path'], $matches[1]);
    }
    else {
      $full_version = $release['version'];
    }
    drush_pm_inject_info_file_metadata($project['full_project_path'], $project['name'], $full_version);
  }
}

```

4) Hack drush file PATH2DRUSH/drush/commands/pm/updatecode.pm.inc

```
/**
 * Run the post-update hooks after updatecode is complete for one project.
 */
function pm_update_complete($project, $version_control) {
  drush_print(dt('Project !project was updated successfully. Installed version is now !version.', array('!project' => $project['name'], '!version' => $project['candidate_version'])));
  // HACK - send over entire $project to all HOOK_pm_post_update implementations
  //drush_command_invoke_all('pm_post_update', $project['name'], $project['releases'][$project['candidate_version']]);
  drush_command_invoke_all('pm_post_update', $project);
  $version_control->post_update($project);
}

```
> 0 votes

---
Tags: drush, installation, updating
---


title: Can DrupalGap consume Views as HTML?

text:
# Question
Title: Can DrupalGap consume Views as HTML?
Is it necessary to write all the mobile app's own html files for displaying Drupal configured Blocks / Pages / Views? I was hoping I could just rebuild my primary Navigation menus using the DrupalGap `settings.php` files or hook\_menu, but leave the callbacks to just inject the return HTML?

For example...

```
drupalgap.settings.menus['user_menu_standard'] = {
    links:[
    {
        title: 'A Title',
        path: '/some-content-type',
        options: {
            attributes: {
                'data-theme': 'b'
            }
        }
    },
};

function my_module_menu() {
  var items = {};
  items['airlines'] = {
    title: 'airlines',
    page_callback: 'my_module_airlines_page'
  }
  return items;
}

// No mobile dedicated html file necessary. I essentially want a webview with a phonegap native menu.
function my_module_airlines_page(html) {
  div.innerHTML = html;
}

```

Is this - or something similar - possible to automatically reuse the Drupal's front-end within DrupalGap?

# Answer
> 1 votes
DrupalGap is typically used to consume Views as JSON results. It can then use the JSON to decide how to display the HTML inside the app.

Check out this example for creating a page in your App that will fetch and display Views content:

http://www.drupalgap.org/node/219

Out of the box, it easily lets you create lists and tables of your Views data.

---
Tags: views, blocks, theming, javascript
---


# Question
Title: Saving file to drupal site using drupalgap
I am trying to save an image from Android emulator to a Drupal site using DrupalGap, but I am unable to do this. This is my ajax call which I wrote to save the data to drupal site.

My click function

```
   $('#page_node_create_submit').on('click',function(){

try {
      var title = $('#page_node_title').val();
      if (!title) { alert('Please enter a title.'); return false; }

      var body = $('#page_node_body').val();
      if (!body) { alert('Please enter a body.'); return false; }

      var filef = $('#page_node_filef').val();
      if (!filef) { alert('Please select file.'); return false; }

     //var datastring = 'node[type]=drupalgap&node[title]=' + encodeURIComponent(title) + '&node[language]=und&node[body][und][0][value]=' + encodeURIComponent(body) + '&node[files][field_filef_und_0]=' + '&fid=47' + '&uid=1';
     //alert(datastring);
     //return false;

      $.ajax({
          url:"http://192.168.1.146/drunew/?q=services/session/token",
          type:"get",
          dataType:"text",
          error:function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
          },
          success: function (token) {
          // BEGIN: drupal services node create login (warning: don't use https if you don't have ssl setup)
          $.ajax({
              url: "http://192.168.1.146/drunew/?q=my_services/node.json",
              type: 'post',
              data: 'node[type]=drupalgap&node[title]=' + encodeURIComponent(title) + '&node[language]=und&node[body][und][0][value]=' + encodeURIComponent(body) + '&node[files][field_filef_und_0]=' + encodeURIComponent(filef),
              dataType: 'json',
              beforeSend: function (request) {
                        request.setRequestHeader("X-CSRF-Token", token);
                     },
              error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('page_node_create_submit - failed to login');
                console.log(JSON.stringify(XMLHttpRequest));
                console.log(JSON.stringify(textStatus));
                console.log(JSON.stringify(errorThrown));
              },
              success: function (data) {

               $.mobile.changePage("main.html", "slideup");
              }
          });
          // END: drupal services node create
          }
        });
    }catch (error) { alert("page_dashboard - " + error); }
return false;

});

```

But the above code is not working for file field, then after doing some R&D I got to know that first we have to get the fid, then save it.

Below is the respone after creating the fid for the image.

```
{"fid":"47","uri":"http://192.168.1.146/drunew/my_services/file/47"}

```

Here my doubt is how can I integrate this response in my above ajax call to save the image in drupal site.

Any help, thanks..

# Answer
Once you have the File ID, that means you've successfully saved the file to your Drupal site. Next up (typically), you'll want to attach that File ID to a new/existing Entity (e.g. node).

If you are creating a new node, use a POST, if updating an existing one, use a PUT.

**New**

> /my\_endpoint/node.json

```
{
  type: 'article',
  language: 'und',
  title: 'Hello',
  file_images: {
    und: [ {fid: 12 }]
  }

```

}

**Existing**

> /my\_endpoint/node/456.json

```
{
  type: 'article',
  language: 'und',
  title: 'Hello Again',
  file_images: {
    und: [ {fid: 12 }]
  }

```

}

FYI, the latest version of DrupalGap now supports image fields, so you shouldn't have to write any custom code.
> 1 votes

---
Tags: 7
---


# Question
Title: Adding links to EntityForms on submission confirmation page
I'm working on a site that has a series of EntityForms I'd like to guide users through. After filling out the initial form, I want the submissions confirmation to recommend subsequent forms based on some of the values in the submission. I figure I can do this with a custom form submission handler, but I was wondering if it would also be possible to do this with Rules. I can make a Rule trigger on EntityForm values, but I don't know what kind of actions to include (I haven't done much with Rules yet).

Any thoughts on using Rules here, or any other approaches to this problem?

# Answer
> 1 votes
One rules action you could use would be the `System > Show a message on the site` where you could use replacement patterns to build your recommended links to other forms. This way users would always see the message regardless of the initial entityform redirection page. (This is actually a very handy concept and I will file it away for future use :)

Note: in order to get the replacement patterns you need, you may need to add conditions to your rule in order to make the right data available to the rule.

---
Tags: entities
---


# Question
Title: Should I use the theme layer or a module to create a complex, static page?
We have a few pages like the following on my site, everpurse.com: https://everpurse.com/home

They contain moderately complex markup and CSS. My approach to creating these pages is to create a module that uses `hook_menu()` to create a menu callback. The callback itself returns a render array containing something like:

```
return array(
  '#theme' => 'ep_homepage',
  '#attached' => array('css' => array(...)),
);

```

The module provides an ep-homepage.tpl.php template file that contains all the markup, including language, HTML, etc. The `#attached` CSS file styles everything.

It seems, though, that the proper "Drupal way" to do something like this is to put all the CSS and markup in the theme directory, and all the language inside of `t()`, and expose the language via preprocessed variables in the module. But there are a number of reasons I don't like this approach:

* Some of the language is very markup-heavy. There may be sentences like `Available now <span class="limited-time">for a limited time only</span>.` Putting this into the module mixes module concerns with theming concerns.
* The CSS in the theme gets aggregated, which means it will be loaded on every pageload—including pages that don't use it. (That is, by putting page-specific CSS into the theme, you sacrifice the benefits of using `#attached`.)
* Even when putting all the markup into the theme, the page callback has to return *something*. But if the theme is taking care of all the markup, what should the page callback return? Just theme('ep\_homepage')? This would mean the module should create an empty implementation of the ep-homepage template, and allow the theme to override it with a template of its own, right? This seems like such a silly workaround and a bunch of extra work, just to meet Drupal best practices.

So, I guess my question is: what is the Drupal best practice for a page like this? (And I'd rather not use Page Manager/Panels, since the markup is so complex that I'd rather edit it in a Git-controlled template file than via the Panels UI.)

# Answer
The "Drupal way" would be to NOT create a module to hold content, and NOT create a module for a specific page(s). "Drupal way" would likely be to (1) put all of the language/content w/markup into a *node*, (2) put other outside-of-content markup and styles into \*.tpl.php files and css files, (3) put any PHP functionality that isn't available already in contrib into a custom module, and (4) NOT put any content/language into a theme or into a module.
> 1 votes

---
Tags: theming, 7
---


# Question
Title: How do I create and render a custom region?
How do I create and render a custom region in Drupal 7, when the Display Suite module is used? I am not able to show/display a block into a custom region and confused with the files structure. Please suggest any solution.

# Answer
> 0 votes
I got the solution and so sharing with all, if it could help someone:

Creating a custom region in our theme if we are using display suite module is slightly different.

1.First define region in your theme's .info file (same as we do without display suite)

```
regions[name_of_region] = 'Name of Region'

```

2.Then print the following line in your template file wherever you want to display

```
print render(block_get_blocks_by_region('name_of_region'));

```

# Answer
> 0 votes
To create a custom region, I found I needed to add my region (called `customregion`) to the .module file:

```
$layouts['bootstrap_3_9'] = array(
  .......
  'regions' => array(
    'left' => t('Left'),
    'right' => t('Right'),
    'customregion' => t('Custom Region'),
  ),
  .......
);

```

and then just reference it in template:

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

```

---
Tags: theming, display-suite
---


# Question
Title: Fire $.colorbox.resize() after overlay content is AJAX loaded?
Im using the colorbox and colorbox\_node module. Out of the box you have to specify a fixed height for the overlay. However I want the overlay to be the same height as its content.

This can be done with $.colorbox.resize. The issue is that it doesnt work if I call it on cbox\_complete. The reason is that cbox\_complete happens before the content is loaded with AJAX, so its as if there is no content and the height is set to 0 (plus padding).

Ive got it working with the following. Its not a great solution, Its not completely robust and the time delay before the resize isnt an ideal user experience.

```
        $(document).bind('cbox_complete', function(){
            setTimeout($.colorbox.resize,1000);
        });

```

UPDATE - I dont know if its best practice (I expect not) but the following placed in the tpl file works:

UPDATE 2 - I spoke too soon. This screws up in IE8 (im not testing on 7 or 6). For one node the 'x' to close the overlay is missing. For the other node only the top 20px or so of the overlay is visible.

```
<script type="text/javascript">
    (function($) {
        Drupal.behaviors.global_custom_two = {
                attach : function(context, settings) {
                        $.colorbox.resize();
                }
    }})(jQuery);
</script>

```

# Answer
> 2 votes
Drupal has behaviors for interacting after ajax events. For more information on drupal javascript see http://drupal.org/node/756722

You should be able to do it using something like this:

```
(function ($) {

  Drupal.behaviors.yourBehavior = {
    attach: function (context, settings) {
      $(document).bind('cbox_complete', function() {
        setTimeout($.colorbox.resize, 1000);
      });
    }
  };

})(jQuery);

```

The easiest way to implement this, if you want it in your theme is to put that above code in a script.js file in your theme (you can name that file anything and have as many separate files as you like) then in your info file have

```
scripts[] = script.js

```

You can also put it in a js subdirectory and in your info file then put

```
scripts[] = js/script.js

```

You can then also put other behaviors in there too.

That will load your javascript on all pages though, which in some cases is desired but in some cases is not.

If you only want it to load on some pages then you call

```
drupal_add_js('path/to/js/file.js');

```

from wherever you want to load it.

For example, if you only want it to load on full node pages you could put this in your THEMENAME\_preprocess\_node() function in your template.php file.

```
// Only attach this on full node pages.
if (!empty($variables['page'])) {
  drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/script.js');
}

```

Or you could do it in a module using something like hook\_node\_view().

# Answer
> 0 votes
If you don't want to use setTimeout and hope the content is in the DOM, you can check the context for an element you know should be there in a behavior attach callback. For example:

```
(function ($) {
  Drupal.behaviors.yourBehavior = {
    attach: function (context, settings) {

      $('.selector-in-your-loaded-content', context).once('your-selector-processed', function() {
        $.colorbox.resize();
      });

    }
  };
})(jQuery);

```

The reason the cbox\_complete callback gets called before your content is there is because the Ajax load has completed from Colorbox's point of view. However, since Drupal is delivering an array of Ajax callback commands, they run after Colorbox's event, and those commands are where your content is added to the DOM.

Most (all?) of the Ajax commands fire Drupal.attachBehaviors() when they are done, which is where you should be checking if your content has loaded.

---
Tags: 7, javascript
---


# Question
Title: Custom Drupal (Block)Module not showing in Blocks
Relatively new to Drupal. I have created a custom Module that is supposed to create a block. I refferenced a successful module that accomplished the same end goal (implementing a custom HTML build).

I have done the "Disable \> Delete \> Clear Cache \> Re-Install/Activate Module" process a few times, with no luck. Any help or insight would be appreciated!

**Here is my code for the .info file:**

```
name = History of Alcohol Timeline
core = 7.x
package = Legal Thinking Age
php = 5.2.4
version = 7.x-1.0
project = lta_hoa

```

**Here is my code for the module:**

```
<?php

function lta_hoa_timeline() {

$output = <<<TIMELINE

  ...

TIMELINE;

return $output;

}

function lta_hoa_block_info() {

  $blocks['lta_hoa'] = array(
            'info' => t('History of Alcohol')
        );

  return $blocks;

}

function lta_hoa_block_view($delta = ''){

  // Setup blocks
    $block = array();
    switch ($delta) {
      case 'lta_hoa':
      drupal_add_css(drupal_get_path('module', 'lta_hoa') .'/css/jquery.fancybox.css');
      drupal_add_css(drupal_get_path('module', 'lta_hoa') .'/css/media-queries.css');
      drupal_add_css(drupal_get_path('module', 'lta_hoa') .'/css/style.js');
      drupal_add_js(drupal_get_path('module', 'lta_hoa') .'/js/jquery.fancybox.pack.js');
      drupal_add_js(drupal_get_path('module', 'lta_hoa') .'/js/jquery.timelinr-0.9.53.js');
      drupal_add_js(drupal_get_path('module', 'lta_hoa') .'/js/lta_hoa.js');
      $block = array(
          'subject' => t('History of Alcohol'),
          'content' => lta_hoa_timeline()
        );
        break;
        default:
          break;
    }

    return $block;
}

```

# Answer
Code looks fine to me, except for the sometimes funky indenting :)

Your function `lta_hoa_timeline()` just returns `...` in example code. If your actual code contains a whole of stuff instead of `...` and you have trouble getting that to work/display, it might have something to do with the inclusion of CSS/JS files. At the very least you should see the title of the block appear. But if `...` is your actual returned content, it should work.

Verify that you've put your block in a region, that your theme displays that specific region, and that your block is not restricted to any specific page/role/.. , and you should see your block. As suggested above, switch to a default theme, put block in a standard region like sidebar left, and turn off all restrictions
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: How to do a db api join on "has no value"?
I've got two tables, Foo and Bar. Foo and Bar can be joined by matching Foo's "nid" column to Bar's "col" column. In use, some rows in Foo will have a corresponding entry in Bar, but some won't. I now want to get all the rows in Foo that do NOT have a related entry in Bar.

I'm trying something like this:

```
$the_query = db_select('foo', 'f');
$the_query->fields('f', array('nid', 'val'));
$the_query->join('bar', 'b', 'f.nid = b.col');
$the_query->isNull('b.col');
$the_query->execute()...

```

but it's not returning anything; my method of testing for null-ness is almost certainly wrong. I've never been good at these kinds of queries, let alone being able to figure out how to do it within the context of the DB api. Any clues out there? Thanks!

# Answer
If I am reading this right, I think you need to use a left join and then test the nullness.

```
$the_query = db_select('foo', 'f');
  ->fields('f', array('nid', 'val'))

$the_query->leftJoin('bar', 'b', 'f.nid = b.col');

$results = $the_query->isNull('b.col');
  ->execute()
  ->fetchAll();

```

Very often, though, I will break down and do this with two queries. The first will get a list of nids, the second will use a `NOT IN` condition.
> 3 votes

---
Tags: database
---


# Question
Title: Views node count Taxonomy term as a field
There are a few other posts about this in general but none of them explain how to make this a field so i can keep my other fields such as Title and Image.

I am making a video site, and the taxonomy 'category' has an image attached to each term. Therefore i want the number of nodes tagged with a specific category to show but also have all the other fields i use.

I tried solutions found here: Views and node count for taxonomy terms

The above suggestions seem to ignore my image and title fields i currently have styled

hope this makes sense

# Answer
https://www.youtube.com/watch?v=w22Utjm-chs

This video explains the process.

I found my old fields didn't work anymore once i added aggregation so, you might want to remember and fields and styling you have made because you might have to rebuild the fields once aggregation is turned on.

1. add a relationship (under advanced tab) 'Taxonomy term: Content with term'.
2. turn on aggregation (advanced tab at the bottom).
3. create a field 'Taxonomy Term: Name'.
4. add any other fields associated with the taxonomy such as image or any others you created.

Style everything and done!
> 2 votes

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


title: uid = 0 for all kinds of users

text:
# Question
Title: uid = 0 for all kinds of users
I want to get the uid of a logged in user in an external php script. I am using:

```
chdir("C:/xampp/htdocs/mywebsite");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$account1 = user_uid_optional_load();
echo $account1;

```

But it always return :

> stdClass Object ( \[uid\] =\> 0 \[name\] =\> \[pass\] =\> \[mail\] =\> \[mode\] =\> 0 \[sort\] =\> 0 \[threshold\] =\> 0 \[theme\] =\> \[signature\] =\> \[signature\_format\] =\> 0 \[created\] =\> 0 \[access\] =\> 0 \[login\] =\> 0 \[status\] =\> 0 \[timezone\] =\> \[language\] =\> \[picture\] =\> \[init\] =\> \[data\] =\> \[roles\] =\> Array ( \[1\] =\> anonymous user ) )

irrespective of admin, authenticated or anonymous user. I also tried these but the result remains same.

```
global $user;
echo $user;

```

`$account1 = user_load(array('name' => check_plain($name)));
 echo $account1;`

I also checked a similar problem and uncommented `$cookie_domain = '';` ( blank cookie domain for localhost )in my settings.php but to no avail.
How can I get some non-zero uid for logged in users ?

# Answer
Because you need to login from external script... Your external script is always anonymous to Drupal since no session has been created for external script user....

If you are trying to load all online users in an external script you can check who's online block implementation in user module..
> 0 votes

---
Tags: users, cookies
---


# Question
Title: Generate PDF with Print PDF and send in email
When a user registers he has to select some options that will be defining for the invoice created afterwards.

I have a rule that will be executed when saving a user account. This is what I do:

* Rule 1: Create Invoice (invoice = content type) and Save Invoice
* Rule 2: Fill in Invoice

The invoice is generated when a user registers an account. When I go to the invoice like this:

```
http://domain.com/node/147294

```

I see the Invoice. When I go to `http://domain.com/printpdf/147294` I get a pdf with my content in it.

Now I would like to create a pdf and send it in a mail to the user that is registrated (an extra rule). But how can I do this?

# Answer
> 3 votes
Try this modules:

**Views PDF**

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

https://drupal.org/project/views\_pdf

**Views PDF Mime Mail**

> This module provides the integration of Views PDF and Mime Mail. This allows the user to send a View as a PDF to a customer by Rules.

https://drupal.org/project/views\_pdf\_mimemail

---
Tags: files, rules, emails
---


# Question
Title: What's the difference between the components ending in .system and .module in the Bug tracking system?
I am a phd student focus on automated testing of complex systems and I selected the Drupal system as a case study. First, I need to examine the bugs recorded for a number of modules in Drupal. Thus, I looked in the issues of each module, e.g. File module https://drupal.org/project/issues/drupal?text=&status=All&priorities=All&categories=1&version=All&component=file.module . But, I noticed that there exist file.module and file.system components in the issues for Drupal. And, this happens with most of Drupal modules. Thus, my question is what is the difference between file.module and file.system in the issues. I need to recorded the bugs associated to each module, so I do not know if a need to consider the bugs of .system components or .module components or both.

Thanks in advance, Best

# Answer
> 0 votes
You're reading things slightly wrong.

There's no `file.system` component, or any other component ending with `.system`.

There are systems:

* ajax system
* batch system
* file system
* etc...

These are for issues pertaining to parts of Drupal that are not located in a module. Anything in the /includes folder of a normal Drupal installation, basically. (ajax.inc, batch.inc, file.inc for the examples above)

Then there are modules:

* blog.module
* file.module
* menu.module
* etc...

These are for module-specific issues.

---
Tags: 7
---


# Question
Title: Give permissions to users to edit Drupal Views content
How to give permission to users to edit the content that are in Views. In Views the FORMAT is:

Format: Unformatted list | Settings Show: Content | Full content

Thank you in advance.

# Answer
You can control view page access using "Page settings" section on views settings page,

You can grant permission for **views edit** to any Role you like form permissions page.

admin -\> people -\> permission
> 0 votes

---
Tags: 7, views
---


# Question
Title: Form submit POST renders page before submit handler is called
I have a search form in the header that is simply adding a search term to the current URL. If you are on `example.com/list-page` and submit a search, it just sends you to `example.com/list-page?search=my-term-here`.

When I submit the form, I've noticed that the full page has to be rendered before the form's submit handler is called. Since the search modifies the current list page's results, it seems redundant when submitting a search for "my-term-here" on `example.com/list-page` to have to render `example.com/list-page` again before the submit handler is called and then render the version I actually want: `example.com/list-page?search=my-term-here`.

I've hacked around this by doing this in my form:

```
// Set to the current path so we can redirect back there after submit.
$form['submission_path'] = array(
  '#type' => 'hidden',
  '#default_value' => current_path(),
  '#weight' => -100,
);

$form['#action'] = url('search-callback');

```

The search-callback does nothing:

```
function mymodule_search_callback() {
  return '';
}

```

The submit handler then does a redirect like this to get back to `example.com/list-page?search=my-term-here`.

```
// Redirect back to the page that submitted the search.
$form_state['redirect'] = array(
  $form_state['values']['submission_path'],
  array(
    'query' => array(
      'search' => urlencode($search-term),
    ),
  ),
);

```

Is there a better way to handle this? Can the form's submit handler be called before rendering the page the form is posting to?

# Answer
> 0 votes
You need to add a submit callback that will handle the redirect:

```
 $form['#submit'][] = 'mymodule_search_callback'

```

And in that callback:

```
function mymodule_search_callback() {
   $form_state['redirect'] = current_path() . and your urlencoded serch term;
}

```

Messing with `$form['#action'`\] is not the right way to do it.

---
Tags: 7, redirection, forms
---


# Question
Title: How to use check box in select list for multiple selection in content type?
I simply want a select list like this.

Is there any options to add a field like this.

# Answer
> 2 votes
You can simply achieve that by following way.

Choose Field Widget Type '*Checkbox*' instead of *Select list*.

If you want to make appear checkboxes field as multiple select list,Add the following line in your CSS file

```
   #field-id-name{ height: 100px; overflow: auto; width: 100px;  }

```

Note: replace `field-id-name` with id name of the field; change the width and height according to your requirement.

After applying CSS, the checkbox list field in content type appears as follows.

I hope this simple solution helps

# Answer
> 1 votes
Try Dropdown Checkboxes module

> This module helps to convert multiple select lists into dropdown checkboxes using ddcl library.

---
Tags: entities, nodes
---


title: Drupal 7 AJAX error

text:
# Question
Title: Drupal 7 AJAX error
I'm getting this AJAX error when I try to manually check for updates. I also get AJAX errors when I upload an image, remove a image, use the taxonomy auto generate field: juse about anything that uses AJAX. I have two other installations of Drupal 7 on the same server, so it's not a server configuration; they all have the same modules enabled, so it's not a module problem. I don't know what it is. What's the best way to debug AJAX? I have never needed in my life to debug AJAX, but this is causing a big problem with my website. it would be a pain to start over now.

This is the error I get:

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows.
> Path: /batch?render=overlay&id=3&op=do
> StatusText: OK
> ResponseText: {"status":true,"percentage":"33","message":"Trying to check available update data ...\u003cbr \\/\u003eChecked available update data for \u003cem class=\\"placeholder\\"\u003eDevel\u003c\\/em\u003e."} Drupal for Firebug General Messages There were no messages sent to the general log.
> Please use "firep($item, $optional\_title)" to output messages to this console.
> Query Logging is Not Enabled
> Please enable "Collect query info" in the Devel Module Settings (admin/settings/devel) to use this feature. There was no form altering. There was no user processing. There was no node processing. The views module is not installed. There was no page processing.

# Answer
> 5 votes
You need to disable the Drupal for Firebug module or fix it so that it doesn't return something on an ajax call.

# Answer
> 2 votes
I fixed this issue by uncommenting the max\_input\_vars=1000 field in the php.ini file.

# Answer
> 0 votes
I fixed this issue by upgrading to PHP 5.4 (I only experienced this issue with PHP 5.3, with Drupal 7)

---
Tags: 7, ajax
---


# Question
Title: override 'Edit own content' using taxonomy access
Can I override 'Edit own content' for a particular role and a particular node using taxonomy access? Or better, can I simply switch off Drupal's built-in access content module and solely rely on the settings of TAC (taxonomy access content module)?

What I'm trying to accomplish here is:

a user creates content, the user works on their own content until they think it's ready for moderation upon which they'll set a taxonomy term to 'finished content'. A moderator now comes into play and checks the content of the user. If they decide to approve the content they set a vocabulary term to 'approved content'. This triggers a rule which sets the locking vocabulary of that node to the term 'Locked'. At this point the author should not be able anymore to edit this content.

The problem is that node access permissions still allows the author to edit their own content. How would you tackle such a problem? Cheers!

# Answer
Ok, I've found a way around it. I'm using the Workbench Access module.

This module, which can be used as a stand alone module, allows you to use taxonomy terms as sections you can set on any node and then you need to assign the roles (or particular users) who can update nodes with these terms/sections. In conjunction with the taxonomy access control module I found that you must at least set the global default for that role to 'view'. If you don't, the users of that particular role won't have update AND view access which is not what I wanted. They can see what they've created but they can't change it anymore after they saved it or after a certain taxonomy term has been set, by themselves or automatically through rules.

Hope that helps others as well! Cheers!
> 0 votes

---
Tags: taxonomy-terms, nodes, users
---


# Question
Title: Is there a way to include jQuery-1.10.2 for specific php functions?
I need to include jquery-1.10.2 for a module I am building in Drupal 7. The problem is, if I include the file with drupal\_add\_js in the module's .inc file, it causes the admin menu to display strange (there is no space reserved for it on the screen, so it is usually covered) I've gotten around this by calling drupal\_add\_js right inside the page callback function for the pages that need jquery. When I do this, the admin menu works fine, but if you click on any items shown in the overlay, the first time you click, there is a javascript error saying:

> Uncaught TypeError: Cannot read property 'msie' of undefined

If you click the same button a second time, the overlay will load, but I need to fix this so that there aren't any bugs. I've done some research and it looks like this is because $.browser is depreciated as of 1.9.

So I was wondering if there is a way to include jS but to only have it applied to a specific function or maybe only to the 'content' div of the page? I did find hook\_init which supposedly runs whatever commands are inside the function as the pages for that specific module are loaded, however it still seems to apply the include to all pages of my Drupal install.

# Answer
> 0 votes
The issue is that the admin is trying to load two different versions of jQuery and causing conflicts. The latest version of jQuery Update 7.x-2.4 allows you to control the back and front end versions of jQuery. This may still cause problems with using the overlay but for the most part seems to fix the issue. If you are still having issues you will need to look into a solution on loading two different versions of jQuery, outlined here or disabling the overlay module.

---
Tags: javascript, 7
---


# Question
Title: Allow CSS styling in node filtered HTML view?
I'm working through my first major Drupal 7 implementation. My users need to create nested HTML ordered lists, with the various styling in Roman, numeric and alpha formats as listed at http://www.w3.org/TR/html401/struct/lists.html#type-values . The current project is taking place on a node of content type "book page."

This install is using CKeditor, which properly shows the various format types in edit mode.

In node view mode, though, the styles disappear, reverting to 1,2,3 format. I found in the Filtered HTML settings the statement "... and CSS are always stripped." Since CKeditor applies style commands to create the formatting method, it seems that Drupal filters them out.

Is there a method to allow styling in node view? I just discovered http://drupal.org/project/css\_injector but can't yet determine if it will do what I need.

---

Found this discussion which appears to be related. http://drupal.org/node/259527

# Answer
> 3 votes
I recommend using the WYSIWYG Filter module. In the "HTML elements and attributes" textarea there is a list of allowed HTML tags. 'ol' should be present. If it is, add '\[class|style\]' to it which will make it look like this:

ol\[class|style\]

Or, you can add @\[class|style\] to the list to enable the style and class attributes on all allowed html tags.

---
Tags: 7, theming
---


title: How to hide blocks from administrator?

text:
# Question
Title: How to hide blocks from administrator?
I need to hide some blocks from priviledged user so he won't be able to attach them to regions via the Block layout. What is the proper way of doing this?

# Answer
> 2 votes
Please open a feature request in the core queue for `'no ui'` blocks. This currently does not exist but it's an interesting (and probably necessary one).

---
Tags: 8, blocks
---


title: How to add custom CSS to each page

text:
# Question
Title: How to add custom CSS to each page
All,

I complete Drupal 7 newbie here.

I am tackling the themeing of our website (using Adaptive/ Sky theme). Now previously I would have loaded up all the CSS files in the sky.info file but then read that all the stylesheets in theme info file get loaded on every page.

What I want is to load each unique page's CSS on that page only. Example being the 'Home Page' would have its own unique CSS, same for 'About Us', 'Contact Us' pages etc.

As per my research, I am meant to use 'drupal\_add\_css' function in the template.php file, however, I dont know PHP & have no idea how to add the if condition that each page's alias should dictate which css file is preprocessed & loaded.

Any guidance would be great.

# Answer
> 4 votes
An easier way to address multiple CSS loads, is to cache and compress the CSS. You can do so by going to /admin/config/development/performance and selecting "Aggregate and compress CSS files"

But if you must have them load on separate pages I'd recommend doing it the Drupal way; separating them by content types or blocks, forms, not by URI. The simplest way to do it, is to use Theme Hooks.

For instance, to include a yourthemedirecotry/css/MYTYPE.css for content type MYTYPE;

1. Copy /modules/node/node.tpl.php into your theme directory and rename it to node--mytype.tpl.php.
2. Insert `<?php drupal_add_css(path_to_theme() . '/css/mytype.css', array ('group' => CSS_THEME)); ?>`
3. Don't forget to flush cache.

From now on, nodes with content type MYTYPE will include a yourtheme/css/mytype.css.

Likewise, you can insert CSS into specific blocks, fields, page. For more options, see Theme Hooks and drupal\_add\_css.

# Answer
> 1 votes
You can add CSS & JS files in the menu hook that you are using to call that page. Suppose you had a contact us form

```
function my_contact_us_form(){
 drupal_add_css(PATH_TO_CSS);
}

```

Now this will be added only for contact us page. Suppose its a particular node like About Us page. You can use `hook_init()` in a module or `template_preprocess()` in a template.php file If condition will be something like this. Assuming URL to be like mysite.com/aboutus

```
if(request_uri() == "/aboutus"){
 drupal_add_css(PATH_TO_CSS);
}

```

`request_uri()` is a inbuilt defined function which will return the URI of tha page being viewed.

# Answer
> 0 votes
There's a module for that!!

One of my fave modules '**CSS Injector**' allows you to set up multiple CSS 'rules' - custom CSS code that can be run on specific pages or media (e.g. phone, screen, print); PHP can also be used to place the CSS.

This will place your CSS code after all the theme and/or module CSS so you can use it to override what your site is doing.

I often use it to subtly customise the themes already available and ensures that my CSS tweaks remain in place even when the module or themes are updated (though you might need to change some ID/Class references).

Set up your rules at Configuration\>Development\>CSS Injector. Hope that answer helps!

https://drupal.org/project/css\_injector

# Answer
> 0 votes
I would suggest using the module Code Per Node. This is an easy effective way in injecting css and javascript on a per node basis.

---
Tags: 7, theming
---


# Question
Title: Rate Module: Display the rating in the comment user added to the node
Is there a way to display the rating in comment given by a user in the node? For example, in this page http://www.yelp.com/biz/ikes-place-san-francisco at the top we can see the total rating, but in comments we can see the rating given by the user.

Is there some way to do this? Thanks!

# Answer
> 1 votes
I achieved a similar thing with the Fivestar module. The trick is to let the users vote when they comment. You can find a whole description for the set-up at https://drupal.org/node/1308114. Here is an adapted version of the documentation:

> **Setting up the content type**
>
> 1. Go to `admin/config/content/fivestar` and create a new tag, e.g. called *Vote* or *Rating*.
> 2. Go to your content type and add a new Fivestar field, e.g. called "Rating".
> 3. Select the widget type *Stars (rated while viewing)* and tag the *Rating*.
> 4. Select the number of stars. Make sure it will be the same on both the content type and the comments.
> 5. Go to your content type's display settings and click the settings button for the Fivestar field.
> 6. Set *Value to display as stars* as *Average Vote*.
>
> **Setting up the comments**
>
> 1. Go to the comment field settings for your content type.
> 2. Use *Add existing field* and add the same Fivestar field you created for the content type.
> 3. Widget: *Stars (rated while editing)*.
> 4. Select the number of stars, equal to the amount that's used in your content type.
> 5. Select the voting tag you created earlier and set the voting target to *Parent Node*.
> 6. Go to the comment display settings and click the settings button for the Fivestar field.
> 7. Set *Value to display as stars* as *User's Vote* and change *Text to display under the stars* to *User's vote*.

I asked a question about how to display the average rating as stars before: How to display the average rating of a node as stars in a view?. Maybe that can help you too.

# Answer
> 0 votes
Five Star module is what you are looking for,

> The Fivestar voting module adds a clean, attractive voting widget to nodes and comments and any entity. It features:
>
> * jQuery rollover effects and AJAX no-reload voting
> * Configurable star sets
> * Graceful degradation to an HTML rating form when JavaScript is turned off
> * Support for anonymous voters
> * Spam protection to keep users from filling your DB with bogus votes
> * Easy-to-use integration with Views module for lists sorted by rating, or filtered by min/max ratings
> * A Fivestar CCK field for use in custom node types
> * An easy-to-use Form API element type for use in other modules
> * Compatible with all versions of jQuery (1.0 - 1.8)

Check out this awesome, Demo video

---
Tags: comments, rating
---


title: Show custom menus in seven theme

text:
# Question
Title: Show custom menus in seven theme
I am using Seven for the theme of a internal application. I have custom items setup in the mainmenu, but cannot get it to show?!?!

The blocks for seven are limited to content and help (despite the .info file suggesting a few more???).

```
/admin/structure/menu/settings

```

I have set main menu to both Main and Secondary links.

```
/admin/appearance/settings

```

I have checked both main and secondary links

What am I missing? How do I get he mainmenu (or any menu) to show in the default Seven theme (without deriving a new theme from it and tweaking it's template.php, etc)???

I can do this with any other default theme...

# Answer
> 0 votes
I am afraid that Seven's `page.tpl.php` does not render these menus. You will need to subtheme it and modify `tpl.php` files to render the menus. I know you stated that you want to avoid this; however, you really should do this anyway because if you are using the theme in your app then you will at some point likely want to modify it in some way, and you don't want to customize a core theme because it will break on updates, etc.

It's worth it, because Seven is actually a great theme for internal web apps (I use it for this).

Seven's navigation was meant to be provided by Drupal's tab system. I suggest rendering your main menu and secondary menu as tabs to leverage the navigational design of Seven.

# Answer
> 1 votes
You can render menu using blocks system. Just enable "Main menu" block in the "Seven" theme. See my screenshot:

To style your menu with icons you can use the menu\_attributes module. You can add css class to each menu and style it with CSS.

Also mind that changing theme source code it not a good way. You should create a subtheme of "Seven".

---
Tags: navigation
---


# Question
Title: Get views to filter by {search_dataset} instead of {search_index}
I am working on a retrofit to an old site where I need to rework a View.

I need to add a simple exposed filter for the standard search data (Search API is not an option).

So, my View looks like

and the query looks like

```
SELECT node.title AS node_title, node.nid AS nid, SUM(search_index.score * search_total.count) AS score
FROM
{node} node
LEFT JOIN {search_index} search_index ON node.nid = search_index.sid
LEFT JOIN {search_total} search_total ON search_index.word = search_total.word
WHERE (( (node.status = '1') AND( (search_index.type = 'node') AND( (search_index.word = 'test') ))))
GROUP BY search_index.sid, score, node_title, nid
HAVING (( (COUNT(*) >= '1') ))
ORDER BY score DESC
LIMIT 10 OFFSET 0

```

This is doing the query against `{search_index}`, but I need to filter against `{search_dataset}` with a `WHERE search_dataset.data LIKE '%test%'`

views/modules/search.views.inc has `{search_dataset}` as a table in `search_views_data()`.

`views_handler_filter_search` and `views_handler_argument_search`have the logic to add this table, based on `!$this->search_query->simple()`.

How do you enable this in the UI? I can query alter this to get what I want, but I would really like to find this setting or at least try to backtrace how the query is decided to be "not simple".

# Answer
> 1 votes
Apparently, Views is much smarter than I am.

That setting is not exposed to the UI. `{search_dataset}` is only added if it is needed.

If the filter input is a single word, or multiple words separated by spaces or commas, the handler will turn this into a OR clause against `{search_index}`:

If you are familiar with the Search module, you will know that all words that have been indexed are in `{search_index}`. In other words, a single word query doesn't need to be run against `{search_dataset}`.

If you search for multiple words in double quotes, `{search_dataset}` is magically added in and the query turns into a `LIKE`:

---
Tags: views, search
---


# Question
Title: Can node refferences be automatically resolved in a view?
We are using drupal for data management for a web application. We're using the web-service api to get data from drupal views and use it on our app.

We are completely depended on views fetched via the web service.

When fetching a view, we would like to get all it's references already resolved. So if I have entity A with references to B and C, it would be great to get entity A with the data of B and C as well, not just the node ids.

Can such a thing be achieved via the web-service api?

Update:

After using relationships and a table list that can have reference node fields, I am able to see the aggregated data from B and C. I have the list of A type entities, with data from B and C, but when I request this data from the /webservice/views/MyView api I am not able to see the newly formatted data. I get the same old result with the target\_ids instead of the fields that I chose in the table list.

# Answer
Views *relationships* are used to bring in data from referenced nodes. From your view's administrative page, expand the `Advanced` section and add a relationship. Select the appropriate node/entity reference field that bridges your nodes. Now you can add fields to your view and configure them to use your relationship, which will pull in *any* data from the *referenced* entities/nodes. At this point your view should contain data you want, making it available to the web service.
> 2 votes

# Answer
Link Swanson's answer above should work, except for in some cases where you may actually need the reverse relationship (depending upon how the nodes relate to one another).

If the relationship between entity A and entity B is created by a node reference field on entity A that pulls in entity B, then you can probably just use a regular relationship.

But if the relationship between the two is from entity B pointing to entity A, and especially if your view pulls in entity A, you will most likely need a reverse relationship.

You would add the reverse relationship in the same place that Link Swanson described. It's just a different configuration option.
> 1 votes

---
Tags: views
---


# Question
Title: Why does my Data Export View use the default value for an exposed Grouped Filter?
I am using Views 7.x-3.8, Drupal 7.28 and Views Data Export 7.x-3.0-beta7.

From a view (page) with multiple fields and exposed filters, I created a homemade search engine with search results within a table. I have created an export view, attached to that view, with exactly the same fields and exposed filters. So users can export filtered search results.

From the search engine, after choosing a value for a field with exposed **grouped filter** (Any, Yes, No), the export does not consider that choice and keeps the **default value** for this filter. Same result if I activate the option "Remember last selection" on the export view.

Any idea why?

Thanks in advance.

# Answer
It could be that the export display is not attached to the page display. Try to edit the export display (typically you can not adjust the exposed filters on this page, as visiting the page will simply download all the results for the master view without considering any exposed filters).

Instead of getting your file by visiting the path of the data export, instead attach the data export to the page display where you placed your exposed filters.

You can do this by editing your data export display and adjusting the settings in your "Attach to" settings in the data export settings column (see screenshot below).

Once you click the Attach to link you'll be able to add your data export to any display in that view. Add it to your page.

Then, load the page in your browser, adjust your exposed filters until you see the results you want, and then scroll to the bottom of your page. You should see an icon that will enable you to execute the download of whatever file type you specified for your data export. For example, below I've filtered results for a page and set it to download as CSV.

By clicking the orange button, I'll download the filtered results on the page.
> 0 votes

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


# Question
Title: How can i add .pdf extention on the default upload files
When i create an article i saw that i'm allowed to upload image files only

> Allowed file types: .png .gif .jpg .jpeg

How can i add `.pdf` file extension and attached with the article?

I'm using zen theme

# Answer
> 2 votes
Go to Structure \> Content types, click manage fields for the article content type, then edit on the Image field. There you can edit the allowed file types.

**However**, note that this is an image field. It does not make sense to upload PDF files to an image type field. Instead, you might want to add a new field with type file and configure that to allow pdf files.

Also note that you can't leave the allowed values empty, that would not allow any file types.

# Answer
> 1 votes
There is a module for Drupal 6: File attachment utilities; you can get some idea from its code.

# Answer
> 1 votes
Go to "Administer -\> Site Configuration -\> File Uploads," add '.pdf' to the "Default permitted file extensions:" section, and click on "Save configuration."

# Answer
> 0 votes
You can setting by content types -\> article -\> edit and then you must adding to upload field the extension .pdf

It' s easy!

# Answer
> 0 votes
Navigate to *Administration » Structure » Content types*. Click on *Manage fields* for the "Article" content type. Note that in Drupal 7, the default "Article" content type already have a field for file attachments (named "Attachment"), so there is no need to create a *new* field, as suggested in the currently accepted answer.

Press the *Edit* link on the *Attachment* field and locate the field *Allowed file extensions*

The default attachment content type is just `txt`. Change this to `txt pdf`, and press "Save settings".

To add a PDF attachement, make sure you use the *Attachment* field (not *Image* field) for the PDF-attachment when creating new Article content.

---
Tags: 7, files, entities
---


# Question
Title: Modifying Poll Template to have big buttons for voting
I am re-skinning the poll module for an iPad/tablets.

How can I make the poll module vote page have large buttons/images instead of radio buttons.

The template has `<?php print $choice; ?>`

and thats it :(

# Answer
What I ended up doing was overriding this theme function:

```
function media_preprocess_poll_vote(&$vars)
{
    $node = menu_get_object();
    $list = array();

    $vars['choice'] = '';
    $vars['vote'] = '';

    foreach ($node->choice as $i => $choice)
    {
        $vars['choice'].= '
        <div class="poll-choice-wrapper">
            <input type="button" data-choice="'.$i.'" id="choice-'.$i.'" name="choice-'.$i.'" value="'.$choice['chtext'].'" class="poll-choice" />
        </div>';
    }

    $vars['choice'].='<input type="hidden" name="choice" id="choice" value="-1" />';
}

```

Then adding a little js:

```
jQuery(document).ready(function()
{
    jQuery(".poll-choice").click(function()
    {
        jQuery("#choice").val(jQuery(this).data('choice'));
        jQuery("#poll-view-voting").submit();
    });
});

```
> 1 votes

# Answer
In theory I think you could either use css https://stackoverflow.com/questions/20909486/css-replacing-checkbox-image

Or how about hook\_form\_alter ,

Maybe something like

```
$form['actions']['input']['Checkbox' = 'image_button';

```
> 0 votes

---
Tags: polls
---


# Question
Title: Update a single field when saving an entity
**Question:** How do I update a single field of an entity? For example, lets say I have a user and want to update field\_my\_field. How do I just update that without using user\_save?

**My Specific Problem:** I have a a bunch of user fields defined, and am trying to optimize the performance of my site. I am using **views\_bulk\_operations**, and my code is timing out (maximum execution time) because I am repeatedly calling user\_save, and it's an expensive operation.

I am only updating a single field, and would like to optimize this code. Rather than calling user\_save, which is taking 500ms to run, I'd like to update the field directly.

I attempted to use field\_attach\_update(), and that works a little better, but that's also updating all the fields. Is there any specific way just to update or save a specific field for an entity?

I'm not interested in batch operations, or anything at the moment -- I know how to do that, and can convert this into a batch so I don't run into execution timeouts. I just want to know how to save a single field for an entity.

# Answer
> 5 votes
Give a try with field\_sql\_storage\_field\_storage\_write.

See this blog post with an example:

```
//Get the id of your field
$name = 'name_of_your_field';
$info = field_info_field($field_name);
$fields = array(info['id']);

//Execute the storage function
field_sql_storage_field_storage_write('model', $entity, 'update', $fields);

```

# Answer
> 0 votes
Drupal 7 create new table for each field, there is no entry in this table if value is not available for this field. To save value in this field further use **field\_attach\_update** instead node\_load.\`

```
$field = new stdClass();
$field->type = 'story_cover'; // content type name
$field->nid = $node->nid; // node id
$field->field_number_of_pages[LANGUAGE_NONE][0]['value'] = 'YOUR_VALUE'; // field name
field_attach_update('node', $field);

```

# Answer
> -1 votes
You have to first load the logged in user and then use entity module function entity\_metadata\_wrapper to update the user field, but be pretty sure to enable the entity module.

```
            $account = user_load_by_name($uname);
    $user = user_load($account->uid);
    $obj = entity_metadata_wrapper('user', $user);
    $obj->{field_machine_name}['und']['0']['value'] ="your value" ;
    $obj->save();

```

---
Tags: 7, entities, views
---


# Question
Title: Rendering arbitrary field values without a parent entity in Drupal 8
I would like to expose to the user their choice of field formatters and the respective field formatter options. The selected formatter would then render an arbitrary array of items in the same format as a value for that field type, without any kind of parent entity.

Again, I want to render what looks to be an array of field values, **without** having an actual field or entity with a field value.

In Drupal 7 I could accomplish this using the following code (Gist formatted version):

```
// Render a file using the 'Generic file' formatter (a nice link with an icon):
$file = file_load(1);
$field = array('type' => 'file');
// File fields are stupid with their field values.
$items = array(0 => array('fid' => $file->fid) + (array) $file);
$display = array('type' => 'file_default');
$output = field_items_render($field, array(), $items, $display);
return drupal_render($output);

// Render node 1 with an entityreference formatter
$field = array('type' => 'entityreference');
$items = array(0 => array('target_id' => 1));
$display = array('type' => 'entityreference_label', 'settings' => array('link' => TRUE));
$output = field_items_render($field, array(), $items, $display);
return drupal_render($output);
// Outputs <a href="/node/1">Title of node 1</a>

function field_items_render(array $field, array $instance, array $items, array $display, $langcode = LANGUAGE_NONE) {
  $field += field_info_field_types($field['type']);

  $display += field_info_formatter_types($display['type']);

  $instance += array(
    'entity_type' => 'node',
    'bundle' => '_fake',
    'settings' => array(),
  );
  $instance['settings'] += $field['instance_settings'];

  $entity_type = 'node';
  $entity = NULL;
  $entities = array(0 => $entity);
  $entity_items = array(0 => &$items);

  // Run hook_field_prepare_view() on the field module.
  $function = $field['module'] . '_field_prepare_view';
  if (function_exists($function)) {
    $function($entity_type, $entities, $field, $instances, $langcode, $entity_items);
  }

  // Run hook_field_formatter_prepare_view() on the formatter module.
  $function = $display['module'] . '_field_formatter_prepare_view';
  if (function_exists($function)) {
    $function($entity_type, $entities, $field, array(0 => $instance), $langcode, $entity_items, array(0 => $display));
  }

  // Run hook_field_formatter_View() on the formatter module.
  $function = $display['module'] . '_field_formatter_view';
  $result = $function($entity_type, NULL, $field, $instance, $langcode, $items, $display);

  return $result;
}

```

While I can do this in Drupal 7 very relatively easily, how can I accomplish the same in Drupal 8 (or at least help lead me down the right path through all the major parts of this)?

# Answer
Yeah, you can't get around having an entity object, but it doesn't matter what it is, the only place where it's needed in the following code is FormatterBase::view(), to set #entity\_type, which will later be used for the class name.

```
<?php

use Drupal\Core\Field\FieldDefinition;
use Drupal\node\Entity\Node;

// Load the node, you can also create a temporary object or have your own
// dummy object that implements EntityInterface. (Might need ContentEntityInterface, not sure).
$node = Node::load(1);

// Create the field definition, some might need more settings, it currently
// doesn't load in the field type defaults. https://drupal.org/node/2116341
// Field name is only set to avoid broken CSS classes.
$definition = FieldDefinition::create('entity_reference')
  ->setName('whatever')
  ->setSetting('target_type', 'node');

/* @var \Drupal\Core\Field\FieldItemListInterface $items $items */
// Create a field item list object, 1 is the value, array('target_id' => 1)
// would work too, or multiple values. 1 is passed down from the list to the
// field item, which knows that an integer is the ID.
$items = \Drupal::typedDataManager()->create($definition, 1, $definition->getName(), $node);

/* @var \Drupal\Core\Field\FormatterInterface $formatter */
// Create the formatter plugin. Will use the default formatter for that field
// type if none is passed.
$formatter = \Drupal::service('plugin.manager.field.formatter')->getInstance(array(
  'field_definition' => $definition,
  'view_mode' => 'default',
  'configuration' => array(
    'label' => 'hidden',
    'type' => 'entityreference_label',
    'settings' => array('link' => TRUE),
  )
));

// Prepare, expects an array of items, keyed by parent entity ID, not sure if
// actually used, just array($items) worked too.
$formatter->prepareView(array($node->id() => $items));
print \Drupal::service('renderer')->renderRoot($formatter->view($items));

```

Yes, finding this out is not trivial, but I disagree with you that the 7.x code is relatively easy, it's just that you know the 7.x field API and internal magic callbacks very well. The main difference is that instead of building arbitrary array structures and passing them around, you need to find the right object/class/service and call methods on there. Once you found them, it's not that hard, `FormatterPluginManager::getInstance()` for example documents very well what it expects.
> 11 votes

# Answer
Yes, the various field plugins (field types, formatters, widgets) all assume there is a parent entity to the Items object they work with.

That is the 95% use case you have in mind when you write a widget or formatter, and having to litter the code with "if (I really have an entity)" checks would be really painful. \+ IIRC, allowing a field witout a parent entity would be tricky internally (no actual example in mind right now, sorry).

@Berdir's example code is correct, but after you've created the $items object, you should be able to simply do `$items->view($display_settings)`, which takes care of instanciating the formatter plugin and calling the right methods on it. It's D8's version of field\_view\_field().

Also, the code about `\Drupal::typedDataManager()->create($definition)` should only be needed if you need to work on an arbitrary field definition, that is not part of the "official" fields for the entity type & bundle.

If e.g working on the "official" body field as defined on article nodes, simply doing

```
$your_stub_entity->body->value = "foobar";
$your_stub_entity->body->view($display_settings);

```

should work ?
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Importing nested XML using Feeds XPath Parser
I have some XML formatted as such:

```
<item>
    <title>Name</title>
    <id>12</id>
    <upgrade>
        <id>13</id>
        <level>2</level>
    </upgrade>
    <upgrade>
        <id>14</id>
        <level>3</level>
    </upgrade>
</item>

```

Ultimately from this example I want 3 nodes:

* Title: "Name (1)" GUID: 12
* Title: "Name (2)" GUID: 13
* Title: "Name (3)" GUID: 14

I'm quite happy to do 2 runs of the file if necessary. I have one importer at the moment which sets up the "Name (1)" items. This works perfectly.

I have a second importer set up which I can successfully create the secondary "upgrade" nodes but only if I use \item\upgrade as the context, at which point I lose the title element so the nodes come through as " (2)", " (3)" etc.

If I use \item as the context like the initial importer, I can't seem to loop through the upgrade XML nodes.

# Answer
> 0 votes
Answered on drupal.org

Import will need to be done using the context `\\item\upgrade`.

Then to target the title from the parent node, use `..\title`.

---
Tags: feeds
---


title: Drupal 7 PDOException: SQLSTATE[42S02]

text:
# Question
Title: Drupal 7 PDOException: SQLSTATE[42S02]
Hi experienced colleagues, I have this challenge with my drupal site which is still under development. Now i can not even log in to my site. Below is the message displayed to me

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'connect\_health.trigger\_assignments' doesn't exist: SELECT ta.aid, a.type, a.label FROM {trigger\_assignments} ta LEFT JOIN {actions} a ON ta.aid = a.aid WHERE ta.hook = :hook ORDER BY ta.weight; Array ( \[:hook\] =\> node\_view ) in trigger\_get\_assigned\_actions() (line 169 of C:\wamp\www\ConnectHealth\modules\trigger\trigger.module).

Please help me out.

# Answer
> 0 votes
Make sure you've implemented hook\_schema() to define the trigger\_assignments table. Also, you should include an update hook using hook\_update\_N() to add the table if it doesn't exist already incase the module is enabled in some other Drupal site somewhere that will be receiving the updated module. The examples provided for both hooks should be enough to get you off the ground and running.

When I add a new table to a module that has already been deployed in the field, I like to use the following when defining my update hooks, for example:

```
function mymodule_update_7001() {
  $schema = mymodule_schema();
  if (!db_table_exists('my_new_table')) {
    db_create_table('my_new_table', $schema['my_new_table']);
  }
}

```

If you've already enabled the module, but haven't added the table yet, using drush you can run `drush updb` to run all existing update hooks that haven't been added yet.

---
Tags: 7
---


# Question
Title: Drupal Form Checkbox having different name and id (of my choice)
As drupal assigns title as both id and name to a form element.

```
$form['wrapper'][$unitClean.'_container'][$unitClean.'_cb'] = array(
                '#type' =>'checkbox',
                '#title' => t($unit),
                );

```

I need name and id to be different for checkboxes, textboxes and select lists. Anybody with any idea?

I want to do this because I am populating multiple form elements in a loop, need to manipulate them using JS (in form of groups) and then process them on next page.

# Answer
Found answer, done like this:

```
$form['wrapper'][$unitClean.'_container'][$unitClean.'_cb'] = array(
                '#type' =>'checkbox',
                '#title' => t($unit),
                '#attributes' => array(
                  'name' => $unitClean.'_name',
                  'id' => $unitClean.'_id',
                  'onclick' => 'checkall();'
                    )
                );

```
> 0 votes

---
Tags: forms
---


title: Advanced Forum - Forum View

text:
# Question
Title: Advanced Forum - Forum View
Hello Advanced Forum Module Experts!

I have installed the plugin and started styling on it and I also took a look on the views were they have listed a couple of views. I looked them up but I don't seem to find the view that display the discusion forums like General Discussion.

The url is /forum/view but I dont seem to find it on views

Where can I find it?

Thanks

# Answer
> 1 votes
General DiScussion - using this view `view-advanced-forum-topic-list` You can find it here - `/admin/structure/views` view name - *Advanced Forum topic list*

---
Tags: nodes
---


# Question
Title: Is it possible that these modules conflict with each other?
I have a view set up with the format Views Accordion. I have installed the module draggable views so that I can order each node as I like whenever I add a new node to the view. I'm finding that the sort version of this view display isn't rendering the drag and drop anchors at all. Is it possible that there is a conflict between Views Accordion and Draggable Views?

# Answer
> 1 votes
I'd like to clarify.

As far as I can tell, there's no way to use Draggable Views to reorder a View that uses the Views Accordion display format. However, as Jens mentioned, you can follow the instructions on the Draggable Views documentation page to clone the Views display and change its display format to *Table* or *HTML List*. This cloned display can then be used to order the items, and the order will be respected on the Views Accordion display (as long as it's part of the same View or uses Field API weights).

---
Tags: views
---


# Question
Title: Passing context to a block field of a display suite node
I have a view that displays results of nodes. In these nodes, I have a block field via Display Suite (a table view from Commerce Add To Cart Extras). The block View renders fine in a full node display, since I can easily pass the contextual filter, but I need this block field to also render in the node when it's a teaser as a result of a View.

I tried looking at the **Views default from context** module, but I can't seem to get it. How can I get my views in my teaser to just know what the context is within its particular node?

I hope this makes sense.

# Answer
> 3 votes
The way to do it:

* Enable Views content pane (views\_content, part of ctools I think)
* Create a Views display using content pane instead of block display type.
* Configure a contextual filter, but don't give it a default value.
* Configure the content pane "argument settings" to take a node id from url.
* In Display Suite, create a "Dynamic field". Move it into one of the layout regions.
* Click the cog-wheel icon in the dynamic field, choose content to display, you find your newly created Views display under "Views panes".

Good luck!

# Answer
> 1 votes
Just want to add that if even after enabling Views Content Panes + creating the Content Pane display in Views, well the Views Panes section still does not appear in the Display Suite's Dynamic Field's settings, this might be because your content pane's "Argument input" setting is not properly configured.

In my case I had selected "From context" -\> "URL" when I actually needed to select "From context" -\> "Term ID".

---
Tags: 7, blocks, views, display-suite
---


# Question
Title: How do I create a new Slideshow in the header?
I've inherited a site with a functioning Slideshow. I haven't been able to figure out how that appears on the site. And I'd like something similar to the functioning Slideshow in the header and have been unable to get that to work. The functioning Slideshow is comprised of:

A Panel Node with content:

* View: Slideshow: Slideshow Block
* Welcome Message Block
* View:Featured Articles: Featured News Block
* Home page mini

None of the objects, that I have been able to find, are set to appear (any place I can find), yet the home page shows all the appropriate stuff.

I've tried creating a new Panel Node with all the same content and it doesn't appear. I've tried creating a New Slideshow Block and putting it in the Header Region and the first image appears without rotation.

I'm confused and would appreciate some guidance.

# Answer
This is just a guess since the information provided is very limited: Often slideshows in the header are output as background images on the theme level. So maybe you should have a look at your page.tpl.php (and maybe also your template.php) to see if at some point the view is called from there and not from the panel.
> 1 votes

# Answer
I've had exactly the same thing to do this week. Do you have a HTML.inc and a slide.inc file. If it's the same set up it's pretty straight forward. it loads the variable $slide with $panel info that you call back sequentially.

Could you post some code up and I'll see if it's the same and whether I can help you.
> 1 votes

---
Tags: 7, views
---


title: How do I send and receive privatemsg?

text:
# Question
Title: How do I send and receive privatemsg?
I'm using Services with Drupal 7 and I built a rest service with it, I also included the Privatemsg module and the Entity API module.

I can see under the my service a resource called `entity_privatemsg_message` it has only retrieve and index as operations.

I also found a pm\_service supported in drupal threads by someusers here : Add Service methods .

Now I can see also the privatemsg resource in my service. but I'm missing the documentation on how to send and receive pm message over the rest service. what kind of arguments should be sent with the request. I'm working with js/jquery to make request calls ($.ajax).

Thanks for any help about the private message services.

# Answer
> 2 votes
I'm pretty sure that using Services Entity API will provide what you are looking for. An endpoint shows up for me after enabling the module.

> This module provides support for all Entity API entity types to Services. All entity types get a standard resource, similar to what Services provides for code entity types such as nodes.
>
> This module allows to get entities by properties or fields and also paging and related entities that are defined properly.

---
Tags: 7, services, privatemsg
---


# Question
Title: Disable email registration requirement in Drupal 7
I've already removed e-mail validation, but the requirement that each user supply a unique e-mail address needs to be removed too. How can I go about doing that without resorting to a messy workaround like dummy e-mail addresses (which cause problems like making contact forms silently fail)?

# Answer
For Drupal 6 and 7, the module Optional Mail will allow your users to register without providing an e-mail address. (By the way, not sure what your use case is, but we're doing this on a site heavily using Voip Drupal so we're allowing phone number only users.)
> 3 votes

# Answer
For removing unique e-mail address requirement see Shared Email module:

> The shared email module allows multiple users to use the same email address for different accounts. The module works for both registration and account updates.

Disabling email requirement for registration is quite complicated task because many things in Drupal use mail notifications. I can recommend to set special email `users.without.mail@yoursite.com` for users without emails.
> 4 votes

---
Tags: users, emails
---


# Question
Title: How can I get links in Views Slideshow to link to different URLs than just one as defined in views?
I think I am a little closer to getting my links to work, but I am running into an issue that makes my link point to something like: /content/statshttp://lacrosse.college.edu/content/stats I am trying to make it so that the maintainer of the website can just enter in the relative URL they want the link to point to. I have included screen shots of two areas that I think may be causing this.

Thanks!

# Answer
> 0 votes
I found that the answer is that I needed to set the Formatter of the link to be set to the default. You can see in the picture that I was trying different formatting options, but the default is what I needed.

---
Tags: views
---


# Question
Title: How do I periodically import from a source?
In the basic settings of a feeds importer there is a select list:

> Periodic import
>
> Every 30 min
>
> Choose how often a source should be imported periodically. Requires cron to be configured.

Merely selecting an option doesn't appear to import from my source every 30 minutes. It appears that I have to configure cron too. I've found a lot to read about this, but nothing that describes the basics.

What do I need to do to ensure my source is imported periodically? I can do a manual import without problem.

# Answer
> 1 votes
For periodic import of feed, you have to configure cron.

Let say you want to import feed in every 1 hour then configure cron to run after every 1 hour too.

In Drupal 7 you can enable cron via the Administration \> Configuration \> System \> Cron **(admin/config/system/cron)**.

For more information cron setup visit here

---
Tags: feeds
---


# Question
Title: Tag Users and Taxonomy terms in body field of a post
I am building a Social Networking site in drupal. My client requirement is to tag users and taxonomies using a '$'. For example "$john" will tag a user john with that post. and "$Arts and Entertainment" should tag the Taxonomy term to the post.

I tried hashtags module. But it is for tagging the words in body with a "#". The words are tagged under a separate vocabulary called "Hashtags".

My functionality needs **twitter** OR **facebook** like tagging of both users and Taxonomies(with a autocomplete Dropdown).

For tagging the taxonomies, I have created a separate field called Industry Tags of type Term Reference in that content type. This field will store the mapping of that particular node to the Industry Terms(Taxonomy Terms). Iam not going to display this Industry Tags field in the frontend. Instead of that i have to save the terms that user enters in the Body field prefixed with "$" to in this field. Example: "$Education".

Also for tagging users i can use "User Reference" in the same manner i mentioned above for industry tags. But i need the functionality to be something similar to twitter / facebook.

Please suggest me some ideas for implementing this.

# Answer
> 1 votes
It will be interesting logic to figure out whether `$art` is a user or the start of the `$art and entertainment` taxonomy term, but, regardless, what you are most probably looking for is an input filter that can recognize a pattern in the text and then both create a link to either the user or taxonomy term as well as actually tagging the node with that taxonomy term if it is one.

A start might be to take a peek at the Hashtags Module and change its use of `#` to `$` for the taxonomy portion and then extend it to include users.

# Answer
> 0 votes
For taxonomy terms you can use Active Taxonomy Links...I'm not sure for users...

# Answer
> 0 votes
The mention module can do this

"The Mentions module offers Twitter like functionality, recording all references to a user's username - using the \[@username\] or \[@#uid\] filter format - from various locations, providing a centralized page to track all mentions."

https://drupal.org/project/mentions

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


# Question
Title: Deleted content type shows in the "Add content" menu
I had some content types I wanted to delete so I went to Structure \>\> Content types. I deleted the content types that I didn't want to have anymore, and I cleared all the cache through drush and performance.

I also went to my database and look through to double check if they were deleted, and I found they were deleted correctly.

I have also restarted my MAMP local server.

The problem is that the deleted content types appears on "Add content" but they are not clickable. I don't want them to appear there. why does this happen?

# Answer
I had the same problem which I just managed to fix - thanks to Mołot's comment which made me think of menus. It looks like creating a content type adds an entry to the Navigation menu but deleting it doesn't delete the entry. I just disabled that menu item and now it's gone from the Add Content page.
> 2 votes

---
Tags: nodes
---


# Question
Title: Cached variable remains after truncating cache table
I updated a row in the `variables` table to change the value of a variable. Then I truncated the `cache` table. But a call to variable\_get() still returns the original value.

I thought that the variables were cached in the `cache` table, so where could this original value be hiding?

EDIT: I waited a few minutes and tried again and it was OK. So the immediate problem is solved, but I would like to understand what happened. Is there another layer of caching? It seems there must be since it could not have gotten that value by querying either `cache` (empty) or `variable` (containing new value).

# Answer
Got it - the call to `variable_get()` was during the bootstrap process, so `cache_bootstrap` table also needed to be truncated.
> 0 votes

---
Tags: 7, caching
---


title: Widgetkit Drupal alternative

text:
# Question
Title: Widgetkit Drupal alternative
Is there module that will enable user to create galleries and than embed them into article content, and display them in lightbox fashion?

For example, I can create a gallery in some UI, configure it (set gallery type, transition effects etc...) and than get gallery ID which I can use to embed it in article with some shortcode:

```
Some text...
[image_gallery ID1]
Rest of the text
[image_gallery ID2]
...
...

```

I have searched through drupal repositories and on google and didn't find anything like it. So I'd like to know if someone knows better or do I have to implement that functionality from scratch?

# Answer
Check out the **Photowall** project to see if it matches your requirements out of the box.

From the project page:

> Provides a Photowall (like Google) format for displaying images, using the JQuery Photowall plugin.

There is a nice demo showing what it does at the JQuery Photowall link.

If it is not advanced enough for your tastes, I have another idea:

Since most of the power of the YooTheme Widgetkit for Joomla and Wordpress is provided by Javascript that runs in the browser and that should work just as well when it is launched from Drupal instead of Joomla/Wordpress, it should not be too hard to adapt the Drupal module **Photowall** to make use of the *YooTheme Widgetkit* Javascript plugin, instead of the *JQuery Photowall* Javascript plugin (but it will obviously require some custom development).
> 2 votes

---
Tags: 7, entities, media
---


title: How to Create a Image Field Template

text:
# Question
Title: How to Create a Image Field Template
I've made a image field template called

"field--field-image.tpl.php"

This has override the image field. But how do I get the image to display

```
<img src="<?php print render($item); ?>" alt="..." class="img-rounded">

```

Many thanks for your help

# Answer
Quick and dirty, if all you are wanting to accomplish is to add `class="img-rounded"` to the `<img>` tag, you could do this right before you render `$item`:

```
<?php $item['#item']['attributes']['class']='img-rounded'; ?>

```

(Quick and dirty because this assumes no one else somewhere along the line has added or will be adding a class to your image.)
> 0 votes

# Answer
You can also use `entity_metadata_wrapper` and in your `template.php` use this code :

```
$photo_field = $wrapper->field_IMAGE_FIELD_OF_CONTENTTYPE->value();
$variables['image'] = theme('image_style',
    array(
            'style_name' => 'large',
            'path' => $photo_field['uri'],
            'class' => 'your_class',
        )
);

```

now in your node page `<?php print $image;?>` will work.
> 0 votes

---
Tags: media
---


# Question
Title: Limit/nullify entity reference query/loading of select options, if using hook form alter to populate with ajax
I have added an entity reference field to a profile2 profile entity. The entity type referenced by this field will contain thousands of results (university courses). I have used hook\_form\_alter to add an ajax callback to the university field which is selected before the course field. Selecting the university first, then populates the course field (which is disabled initially) with the courses available only at the selected university. Since I do not want my courses entity reference field loading thousands of courses on load, I need to nullify the query or hook into the function that populates this field. I have seen entity reference limit module but don't intend to use it. How can I achieve this? Thanks

# Answer
> 0 votes
I have managed to achieve this using hook\_entity\_query\_alter. I am not sure if this is the best approach. You can set the limit using the $query-\>range($start, $length). Return 1 row.. $query-\>range(0,1); See https://api.drupal.org/api/drupal/includes%21entity.inc/function/EntityF...

```
<?php
/**
 * We don't want to load thousands of courses into the student course entityreference field as
 * we populate it with ajax, so add LIMIT 0 and database should return empty result set
 */
function mymodule_entity_query_alter(&$query) {
  // check if we got our field
  if(property_exists($query, 'metaData') && $query->metaData['field']['field_name'] == 'field_student_course') {
    $query->range(0,0);
  }
}
?>

```

---
Tags: entities
---


# Question
Title: customer commerce profile = user profile
is it possible to get all registered users into commerce profiles? /admin/commerce/customer-profiles

I mean when I create an account for user drupal will automatically create a commerce profile

# Answer
You've got some ways to do this, I'd look first to Commerce Extra module which allows you to have an address in the user entity and prepopulate information in the commerce checkout with this.

If you want to actually duplicate the information and have a customer profile entity for each user registered, you can use Rules module for this (it is required by Commerce), you can then create a new rule, for instance in the "After saving a new user account" event that triggers an action "Create a new entity" of type commerce customer profile and then another action, "Save entity". You can check Drupal commerce default rule "Create a new account for an anonymous order" for a similar concept.
> 1 votes

---
Tags: commerce, users
---


# Question
Title: Accessing Drupal core functions in object-oriented code: Call to undefined function
I'm a Drupal procedural programmer new to OOP and enjoying it, so some of the techniques are new to me.

I'm getting a fatal error when I'm calling a standard drupal function from within code called within an object that creates a custom Rule. It appears that it's looking for the function drupal\_json\_encode\_helper on the Action object rather than from where it's supposed to look. But why? And how to I tell it to search within Drupal-land rather than object-land?

I'm on D7 with xautoload and composer, modifying the fluxdropbox module that uses fluxservices to use PSR-0 for external libraries.

> "Fatal error: Call to undefined function Drupal\fluxdropbox\Plugin\Rules\Action\drupal\_json\_encode\_helper()"

Here's the code:

```
<?php

/**
 * @file
 * Contains MakeNodes.
 */

namespace Drupal\fluxdropbox\Plugin\Rules\Action;

use Drupal\fluxdropbox\Plugin\Service\DropboxAccountInterface;
use Drupal\fluxdropbox\Rules\RulesPluginHandlerBase;

/**
 * Action for posting a status message on a page.
 */
class MakeNodes extends RulesPluginHandlerBase implements \RulesActionHandlerInterface {

  /**
   * Defines the action.
   */
  public static function getInfo() {
    return static::getInfoDefaults() + array(
      'name' => 'fluxdropbox_make_nodes',
      'label' => t('Make Nodes from Text Fiels'),
      'parameter' => array(
        'account' => static::getAccountParameterInfo(),
      ),
    );
  }

  /**
   * Executes the action.
   */
  public function execute(DropboxAccountInterface $account) {
            //here I build a nice array
            file_put_contents(drupal_json_encode_helper($feed_array), $path . '/novel.txt');

  }
}

```

# Answer
> 1 votes
It happens because `drupal_json_encode()` is defined in includes/json-encode.inc, which is not a file that is normally included when Drupal boots. To use that function, you should use code similar to the one `drupal_json_encode()` uses, although you really should use `drupal_json_encode()`.

```
include_once DRUPAL_ROOT . '/includes/json-encode.inc';
file_put_contents(drupal_json_encode_helper($feed_array), $path . '/novel.txt');

```

The code I would use is the following one.

```
file_put_contents(drupal_json_encode($feed_array), $path . '/novel.txt');

```

# Answer
> 0 votes
OK, if you change your code from

```
file_put_contents(drupal_json_encode_helper($feed_array), $path . '/novel.txt');

```

to

```
file_put_contents(drupal_json_encode($feed_array), $path . '/novel.txt');

```

The correct file will be included for json encoding.

---
Tags: 7, rules
---


# Question
Title: Multistep module not works for User Edit form (Edit Profile)
The Multistep module works well for nodes in content types, like Article, Page, etc.

But when I tried to use Multistep for Account fields, it failed. I cannot find anything about "User form" in Structure-\>Block (while other content types Multistep form will be shown here).

How could I make the "Edit Profile" form as multi-step?

# Answer
> 0 votes
Never used this module, but it seems that it could do what you need

https://drupal.org/project/step

It can be used both with deafult drupal registration system or with Profile2 module, however mind that it is still in dev version.

Cheers

---
Tags: users, forms
---


# Question
Title: display view mode on node based on field setting or taxonomy term of user profile
I'm using Display Suite which is awesome and an easier solution if you're not a coder. Now that I have created several view modes I'd like to set a particular view mode that is based on a field setting (a taxonomy term in my case) in the viewing user's account setting (I guess that's also called the user's profile, right?). It seems that DS is mostly used in conjunction with Views but I simply want users to get a different view mode when viewing the node without Views. I think I'll have to create a separate module for that or add a preprocess function to my template file but I have no idea where to start. Can anyone share their suggestions with me on how to do this? I'm not a coder but I think I can implement some code, though. Cheers!

# Answer
> 0 votes
Not entirely sure if i understood your question, but I believe the Entity view modes module might help you to define custom view modes for entities, which in your case could be a taxonomy term field in your node type or user profile.

> The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities. Custom entities are added to the entity registry via hook\_entity\_info\_alter() so they are available to any code that uses entity\_get\_info() to provide a list of view modes for an entity. This includes node and user reference fields, Views, etc.

---
Tags: users, theming, display-suite
---


# Question
Title: Best practice for displaying multiple views in a single page
I am working on a Drupal 7 website where there are many pages which utilize multiple views.

The way I am doing this right now is by creating a page from Drupal admin panel, and in the edit mode of that page I am calling views\_embed\_view to display those multiple views.

Other ways I could do this is by creating a template for that page, and putting my code inside the template.

Yet another way is to use View Fields View (https://drupal.org/project/views\_field\_view) and embed the second view inside the first one.

**I want to know, performance wise which is the best practice?**

# Answer
You can try panels to display multiple views on a single page:

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Panels includes a pluggable caching mechanism, so it could be a good and easy option for you.
> 2 votes

# Answer
Definitely Panels is a really good way to go, it will allow you to create pages and add them views or fields of entities if you use the context tool that comes with the module.

A couple of other things that might become handy are EVA module that allows you to attach a view to an entity render page.
> 0 votes

# Answer
You can use header and footer section of the view to show other views.

Step 1 : Create a view which is your own output to show.

Step 2 : Select add footer in your view and select "Global : View area" option to insert other view which you to show on that page.

Step 3 : Now you can select any view which you want to show on that page.
> 0 votes

---
Tags: 7, views, theming
---