title: Style tabs/links that anon can't see

text:
# Question
Title: Style tabs/links that anon can't see
What would it take to style tabs (of the MENU\_LOCAL\_TASK variety) differently for tabs that anonymous can't see. I have various admin-only tabs that I'd like to automatically call out as admin-only tabs (so that my admins/mods can keep track of what normal visitors can and can't see).

Maybe something like a call to `user_access()` within the hook\_menu's `title_callback` attribute and stuffing a css class in the menu title if anon fails? This would mean adding this to every MENU\_LOCAL\_TASK though. I was hoping for something a little more global/automated.

What about taking it one step further and having a css class on *all* links that would be hidden if anon were viewing the page?

Drupal 6.

## **My solution**

Riffing on Andy's answer.

```
/*
 * Add css class to menu items that anonymous users don't have access to.
 */
function [themename]_menu_item_link($link)
{
    global $user;

    // Not necessary to do this for Anon
    if ($user->uid != 0) {
        // Temporarily impersonate Anon
        $original_user = $user;
        $old_state = session_save_session();
        session_save_session(false);
        $user = drupal_anonymous_user();

        // See if Anon has access to this menu item
        $map = explode('/', $link['href']);
        _menu_check_access($link, $map);

        if (! $link['access']) {
            $newStyle = array('attributes' => array('class' => 'non-admin'));
            $link['localized_options'] = array_merge($link['localized_options'],
                                                     $newStyle);
        }

        // Restore user
        $user = $original_user;
        session_save_session($old_state);
    }

    // Resume rendering of this link
    return theme_menu_item_link($link);
}

```

# Answer
> 1 votes
`menu_local_tasks()` is a good place to start looking. This calls `theme_menu_item_link()` which is the pertinent theme function to look at. It makes sense to do any access checks in the preprocess and you'll also need a custom theme function to handle the variables you set. You mention `user_access()` in the Q, but it's important to remember that the access callback could by *any* function. For that reason it's necessary to impersonate the anonymous user (note the link isn't specifically for anon users, but the fundamentals are the same). You can get the menu item type, access callback, and access arguments from `$link`. The bit of code to do the actual checks would look something like:

```
if ($menu_item_type & MENU_LOCAL_TASK) {
  global $user;
  $original_user = $user;
  $old_state = session_save_session();
  session_save_session(FALSE);
  $user = drupal_anonymous_user();

  if (!call_user_func_array($access_callback, $access_arguments)) {
    // Anon's don't have access to this local task
  }

  $user = $original_user;
  session_save_session($old_state);
}

```

A note regarding performance: none of the calls access the database, except possibly the access callback (which could do anything). `user_access()` caches a role's permissions, so that would only access the DB the first time. Other access callback's might not do this. It wouldn't be particularly difficult to cache the results of the access callback yourself (keyed by access callback and serialised arguments).

---
Tags: 6, routes
---


title: Reference a Field in Content Type

text:
# Question
Title: Reference a Field in Content Type
I created a content type with a text field in an Omega subtheme called "Prepaid" in Drupal 7. When a user inputs a hex value, it will create a div within the content area with inline CSS that changes the background color. I know the PHP to make this work, but I am having issues determining where to place the function, where to call the function, and how to reference the field I created in the code. I am not new to coding, but I am new to coding within Drupal. If anyone can help, I would be eternally grateful.

# Answer
Create `node--YOOR_TYPE_NAME.tpl.php` and `print_r($node)` object, find what you need and place it on write tag style
> 0 votes

# Answer
It's happend with the help of preprocess function on the template.php. in drupal 7 themename\_process\_page(&$variables).use this function.

or you need to use default theme in drupal7\[Bartik\] . or Specific content type for create node--\[content-type\].tpl.php
> 0 votes

---
Tags: entities, nodes
---


title: Notifications during a file download

text:
# Question
Title: Notifications during a file download
As a newcomer to Drupal 7, I'm trying to understand how auditing and events can be used together.

For example, I have a content type of document, which is basically a name field and a file. I would like an email to go out whenever an authenticated user downloads the document and also have a report that shows how ( and when ) downloaded the document. Does anyone have any suggestions on the best way ( modules, design patterns, etc ) to go about setting this up?

Thanks in advance

# Answer
Download Count can produce file download statistics.

Additionally, because Download Count has Rules integration, you can create a Rule that will send an e-mail when a file is downloaded.
> 1 votes

# Answer
I managed to solve this by creating a workflow rule that emailed the group of users whenever the node holding the content is viewed.
This also means that any issues around not having google analytics is resolved.
Finally, the emails match the auditing that is available to the administrator so that is used as a final stop.
> 0 votes

# Answer
A couple thoughts and approaches.

I have tracked file downloads before, but I did mine using Google analytics and setting goals. You can easily track what is clicked when and get very page specific. Within google analytics the reporting is done for you, much better than anything Drupal could ever provide, and it can even email you when your 'goal' is met (which could be as little as one download). Check out GA goal conversions, which specifically have instructions to track downloads, even. http://support.google.com/googleanalytics/bin/answer.py?hl=en&answer=55580

If you want to go a Drupal route, then perhaps Ubercart or Drupal Commerce? An ecommerce module would require a person to download 'buy' the file and then download it after 'payment' is complete. If you are giving this away for free, then of course the price is 0, but, full tracking is available within drupal and notifications sent out consistently.

Hope that helps
> -1 votes

---
Tags: 7, notifications
---


# Question
Title: Drush command can't find Drupal module function
I created sample command in Drush.

I put it to sites/all/drush.

I am on my site root and calling this command works ok. But when I try to call any Drupal function in drush\_MY\_COMMAND function I am getting:

> Error: Call to undefined function

Could someone give me any hint how to solve this issue?

# Answer
> 4 votes
It sounds like your site is not being selected. Try calling your command with your cwd in the same folder as your settings.php file (e.g. cd sites/default); that should work. You may also create an alias for your site, and call your command from any directory via `drush @site mycommand`

---
Tags: 7, drush
---


# Question
Title: How do I keep the cron from removing a poll from my front page?
I am running Drupal 6 and cron from my crontab. I created a poll on a site that I have inherited and moved it into the first sidebar where it appeared until the cron ran. I can duplicate this (cron runs every hour) . How do I keep it from doing this?

# Answer
> 1 votes
I would highly recommend Elysia Cron, it allows fine grained control of crons provided by modules (ie poll) in which you can completely disable the cron of a specific module (or change the timing from the global setting for that specific module's cron; in your case, 1 hour), which seems like something you might need to try out. See attached for an example settings screen on a D6 site (the checked boxes mean that cron is disabled).

---
Tags: blocks, cron, polls
---


# Question
Title: Custom VBO action fails silently / works with AJAX error in Views Admin
Here is an action I need to use with VBO:

```
/*
 * Implements hook_action_info()
 */
function ams_action_info() {
  $action = array(
    'ams_archive_action' => array(
      'type' => 'ams_survey',
      'label' => t('Archive survey'),
      'configurable' => FALSE,
      'triggers' => array('any'),
//      'behavior' => array('changes_property')
    )
  );
  return $action;
}

/*
 * Implements a registered drupal action to set the archive bit on given survey
 */
function ams_archive_action(&$entity, $context = array()) {

  drupal_set_message(print_r($entity, TRUE));
  $entity->archive = 1;
  entity_save('ams_survey', $entity);
}

```

I selected the action in the list for a Bulk Operations field in a table view for my custom entities 'ams\_survey'. The view and operations form look fine but executing the action just reloads the page. If I execute in the preview in view builder admin, I get an error popup starting with "An AJAX HTTP error occurred." but the action is successfully performed.

A block display for this view is being loaded and displayed inside a form callback which is being loaded in a page callback from hook\_menu(). I have tried turning off AJAX and turning off views cache with the same result.

# Answer
The malfunction was due to the VBO form appearing inside another form. I changed the page callback to be a regular function (not form builder) that loads the block view and actions are working.
> 0 votes

---
Tags: ajax, views
---


# Question
Title: Where does the query table "taxonomy_term_data_node" come from?
I'm troubleshooting a Views' query which uses `taxonomy_term_data_node.weight`, but there is no table of this name. Actually, the table name is taxonomy\_term\_data as you well know. So how is this table reference made? I do not see that alias in the query.

```
SELECT node.title AS node_title, node.nid AS nid,
  taxonomy_term_data_node_1.weight AS taxonomy_term_data_node_1_weight,
  taxonomy_term_data_node.weight AS taxonomy_term_data_node_weight,
  'node' AS field_data_field_category_child_node_entity_type,
  'node' AS field_data_field_category_parent_node_entity_type
FROM {node} node

LEFT JOIN (
  SELECT td.*, tn.nid AS nid
    FROM {taxonomy_term_data} td
    LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
    LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
    WHERE  (tv.machine_name IN ('category_child')
  )
) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid

INNER JOIN (
  SELECT td.*, tn.nid AS nid
  FROM {taxonomy_term_data} td
  INNER JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
  INNER JOIN {taxonomy_index} tn ON tn.tid = td.tid
  WHERE (tv.machine_name IN  ('category_parent'))
) taxonomy_term_data_node_1 ON node.nid = taxonomy_term_data_node_1.nid

WHERE (((node.status = '1') AND (node.type IN ('group_by_test'))))
ORDER BY taxonomy_term_data_node_1_weight ASC, taxonomy_term_data_node_weight ASC
LIMIT 1000
OFFSET 0

```

# Answer
> 2 votes
```
LEFT JOIN (
  SELECT td.*, tn.nid AS nid
    FROM {taxonomy_term_data} td
    LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
    LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
    WHERE  (tv.machine_name IN ('category_child')
  )
) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid

```

Is the same as this.

```
LEFT JOIN (
  SELECT
    td.*,
    tn.nid AS nid
  FROM {taxonomy_term_data} AS td
  LEFT JOIN {taxonomy_vocabulary} AS tv ON td.vid = tv.vid
  LEFT JOIN {taxonomy_index} AS tn ON tn.tid = td.tid
  WHERE (tv.machine_name IN ('category_child'))
) AS taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid

```

The AS Alias has been omitted on the join statements in the example query.

# Answer
> 3 votes
taxonomy\_term\_data\_node is the alias used for the `SELECT` that is part of the first `LEFT JOIN`.

```
LEFT JOIN (
  SELECT td.*, tn.nid AS nid
    FROM {taxonomy_term_data} td
    LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
    LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
    WHERE  (tv.machine_name IN ('category_child')
  )
) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid

```

---
Tags: views, database
---


title: How to design content for sub-pages

text:
# Question
Title: How to design content for sub-pages
Just looking for more experienced drupal developers to steer me in the right direction, it's kind of a basic question:

What is the best way to design the content of the pages, as in, I have the page templates done (front/sub-pages), now I have a bunch of informational sub-pages that I have to design the content for. I thought I could just populate them using the wysiwyg editor, but starting to realize that has limitations. So what's the protocol?

thanks

# Answer
I think you should try Display Suite

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc.

This is a great tutorial to understand how Display Suite works.

Hope this answer may help you.
> 1 votes

# Answer
If I understand you correctly: change your input type to "Full HTML". Then write your own HTML.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to decide wich responsive base theme is better for a certain project?
I know that each project is different and there´s no such a thing as one size fits all. BUT, when you want a responsive theme, you have the choice to start it from scratch or use a base theme. The Omega Theme and the adaptive theme are both responsive and very popular. Afetr you tried both maybe you select one according to your personal tastes, but what do you keep in mind yo actually make that choice? Wich features?

Thanks for your insight!

Note: I´ve updated the post to add the Adaptive Theme instead of the mothership. I´ve checked and it seems Omega and Adaptive are very popular responsive grid themes. (Thanks Clive!)

# Answer
> 5 votes
Yes, it really does depend on your needs. I went through this exercise last year. These were my considerations.

Since we are a web design/development shop, we needed a base theme that we could potentially use for the majority of future Drupal 7 work. For Drupal 6, we had been using Zen, but decided to start fresh with D7.

At the time, the decision really boiled down to Omega, Adaptive Theme, and Boron. From here, I worked out what my dream requirements were (in no particular order):

1. Uses 960.gs seamlessly
2. Responsive layouts
3. As much config as possible via the UI
4. HTML5 starter templates
5. Works well with Panels

#1 and #5 are debatable pluses, but were hard requirements.

Something that works well with Context was also nice, but not a hard requirement because we leverage Panels so much. Mobile integration was not a requirement for us, beyond the response layouts, also due to Panels.

At the time, Omega was the only real match. 960.gs can be added to any base theme, but the UI control over the grid and grid assignments is a huge bonus for us (allows clients and non-technical people to change layout without needed to bug the developers).

Now that we have several Omega-derived sites deployed, I still think we made the right decision and am glad we put a lot of thought into the process.

# Answer
> 4 votes
In my experience, it is faster to get a good theme up using Adaptive theme with Pixture Reloaded (or one of the other AT sub-themes) and this is a good choice if you only have a few sites and don't want to dive deep into theming. You are basically accepting the general look and feel of one of the sub-themes and tweaking it for your needs. If that works for you it is a relatively easy way to go.

Omega is a more of a 'framework' and requires more work up front, but is more flexible. There is a very active Omega group on GDO. Also, using Delta and Context is popular for controlling page layout and with Omega Tools you can make a sub-theme from the admin UI and export/import theme settings. If you are going to be doing lots of sites and/or dive deep into theming Omega is a good choice.

---
Tags: theming
---


# Question
Title: How do I create and theme an image link in Drupal 7 Views?
Ok... here goes. I've had a lot of trouble trying to track down any sort of example like this, and the Drupal 7 Views documentation doesn't even document the views-view-field.tpl.php.

I'm trying to override the default display for a field inside of a view because the default field html content is not at all sufficient to my needs. I can almost do it, except that the views module likes to inexplicably wrap the field content in a that I cannot override through the templates. Also I'm forced to hack into the field's $row variable internals directly, which does not strike me as a good long term strategy.

**views-view-fields--slider.tpl.php**

```
<div class="slider-item">
  <a href="<?php echo $fields['field_slide_link']->content; ?>">
    <img src="<?php echo $fields['field_slide_image']->content; ?>">
  </a>
</div>

```

**views-view-field--field-slide-image.tpl.php**

```
<?php echo image_style_url('slide', $row->field_field_slide_image[0]['raw']['uri']); ?>

```

**views-view-field--field-slide-link.tpl.php**

```
<?php echo $row->_field_data['nid']['entity']->field_slide_link['und'][0]['safe_value']; ?>

```

So to summarize the two problems:

1. Diddling with the $row internals directly makes me quite uncomfortable. Surely there's a better and safer way of getting the not quite raw field values that I care about.
2. The rendered field content is always wrapped in a div.field-contain and I cannot eliminate it through the template, as I would have expected. I'm loath to call strip() to remove the html (I can think of several use cases where I might not want that wrapper).

# Answer
I never was able to remove the stray div.field-contain.

To accomplish the same sort of image linking I wanted I was able to specify a re-write rule on the field-slider-image field inside of the View configuration. You set the rewrite to be a link and then have the link be

> \[field-slide-link\]

This prints out the image wrapped in the appropriate link, with all the specified attributes.

Rewriting Drupal Views Output Custom Theming CSS

This completely elliminated my need to hack on views-view-field--field-image-link.tpl.php
> 0 votes

# Answer
This doesn't directly answer your two questions but should help...

The Views documentation on template overrides doesn't need to be particularly good...as those overrides are self documenting.

Open up any View for edit, open the Advanced fieldset, and click "Theme: Information" at the bottom.

You'll get something like this:

A complete list of every template file available for every field, and the view itself. From there you should be able to experiment quite quickly to find the template name you're looking for.
> 1 votes

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


# Question
Title: Core files updated, but getting "No Pending Updates" message
This is my first time developing for Drupal, and it came time to update the site. I followed all the instructions in the update.txt file by doing the following:

1. backed up files and databases
2. put site in maintenance mode
3. deleted old files and installed new ones
4. ran update.php

The problem I'm running into is that update.php is telling me that there are "No Pending Updates". However, when I take my site out of maintenance mode and flush my cache, I'm still getting messages that I need to install security updates. Is this just a problem with my alerts system, or is there something I'm missing in the update?

Thanks, in advance, for helping a Drupal Noob.

# Answer
> 0 votes
Hope this is helpful for other beginners:

Turns out, what I did wrong was not copy the new core files from the modules directory. I assumed that I wouldn't need to copy those (just like the "sites" folder), and I feared losing my installed modules. Turns out, as you probably already know, the core files in the modules folder needs to be updated as well.

---
Tags: 7, updating
---


# Question
Title: Programatically create nodes, taxonomies and relationships via exisiting database
I have a client that wants a Drupal port. They have a MySql DB with a small built by hand backend. The data structure is about standard in terms of a business organization.

People

* Department
* Specialty
* Location
* Etc

How can I create taxonomies as well as nodes from a MySql Script from the old database?

# Answer
> 2 votes
http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7 \- only thing to note is making sure the taxonomy terms don't exist before you add them, which you can easily do with a function like this (recently wrote this for a project)

```
function taxonomy_import_add_or_get_term($term, $vocabulary) {
  $tid = taxonomy_get_term_by_name($term, $vocabulary->title);
  if (count($tid) > 0) {
    $tid = array_shift(array_keys($tid));
  }
  else {
    $term_object = new stdClass();
    $term_object->name = ucwords(strtolower($term));
    $term_object->vid = $vocabulary->vid;
    taxonomy_term_save($term_object);
    $tid = $term_object->tid;
  }
  return $tid;
}

```

---
Tags: 7, taxonomy-terms, nodes, database
---


# Question
Title: Drupal 7 easy breadcrumb module hides breadcrumbs
When I install the easy breadcrumbs module my breadcrumb disappears. I am wondering if there is a particular settings that I need to change. If I am on the homepage the breadcrumb home is displayed. As soon as I install the easy breadcrumb the breadcrumb is hidden. I tried clearing the cache but that didn't fix the problem. I also changed the theme to see if it was a theme issue but that didn't fix it.

# Answer
> 0 votes
Have a look at the Easy Breadcrumb project page. The answer to your question is in the Configuration section of it. Here is a quote from module's project page:

> To start using it, just go to the admin modules page (URL admin/modules/list), locate and activate it under the category "others", then go to the blocks list page (URL admin/structure/block) and locate the block named "Easy Breadcrumb", and configure it like any other block (region, URLs, etc.).
>
> The configuration page of this module is under Admin \> Configuration \> User Interface \> Easy Breadcrumb (URL admin/config/user-interface/easy-breadcrumb).
>
> Configurable parameters:
>
> * Disable the default Drupal's breadcrumb.
> * Include / Exclude invalid path alias as plain-text segments.
> * Exclude some paths from the segments to be generated.
> * Include / Exclude the front page as a segment in the breadcrumb.
> * Customize the title of the front page segment in the breadcrumb.
> * Include / Exclude the current page's title as a segment in the breadcrumb.
> * Use the real page's title when it is available instead of always deducing it from the URL.
> * Print the page's title as a link or as plain-text segment.
> * Use a custom separator between the breadcrumb's segments.
> * Choose a transformation mode for the segments' title.
> * Make the 'capitalizator' ignore some words (words not to be capitalized).

---
Tags: breadcrumbs
---


# Question
Title: Convenient way to copy & paste links to uploaded file attachments when editing Drupal 7 content?
In Drupal 6, when enabled, the upload module presents a handy list of all the files attached to a Page node. The list includes the file URL in plain text for convenient copy & paste into the Page node body. E.g.

Drupal 7 replaced the upload module functionality with file fields in core. The listing provided by this functionality does not display the file URL. E.g.

How can I conveniently copy and paste the file URL using this Drupal 7 method?

Note: Right-click + Copy file location is *not convenient* because you end up with extra overlay related information on your URL. Furthermore, you also always get the full URL instead of just the parts you want (i.e. relative link).

# Answer
> 1 votes
IMCE will let users browse to it and insert links to the files inside a text area if that's what you're going for. You could also programmatically alter the form and provide a copy to clipboard link next to the file in the listing.

---
Tags: 7, files
---


# Question
Title: How can I extract info from the user_profile array
So I know that the $user\_profile is basically an array. And when I use the DSM command with devel I saw all that info in the array, but how on earth do I begin extracting and displaying data from that?

I'm still not too keen on php, trying to learn as I go and on the side. I understand the concepts of an array and how to get top level stuff. But for those items embedded in other arrays embedded in yet more arrays, I'm not sure how to get to those and display them.

For a simple instance I just want to take the username of the profile currently being views and display it on a custom user-profile.tpl page. And I see it with devel, but I don't know how to get it.

# Answer
> 1 votes
In drupal 7 on the user-profile.tpl.php to which you refer the whole user object is loaded so you can output the different pieces you see in devel by doing this (a modification of the default user-profile.tpl.php you've copied to your theme):

Default:

```
<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>
</div>

```

Modified:

```
<div class="profile"<?php print $attributes; ?>>
  <?php print render($user->name); ?>
  <?php print render($user->signature); ?>
  <?php print render($user->timezone); ?>
  //and so on...
</div>

```

On Drupal 6 the only difference is

```
<?php print $user->name; ?>
//dropping the render wrapper (which is good practice in D7 but is not used in 6)

```

---

As the questioner mentioned in the comments the above will display the currently logged in user's info. To get the info of the user's page you are visiting (ex. YOUR\_BASE\_URL/user/2) you can do this (this will also work with aliased user pages):

```
<?php
   /*call this ($user_page_object) whatever you want but it is ill advised to
     call it $user as that will conflict with the $user object for the currently
     logged in user*/
   $user_page_object = user_load(arg(1));
?>
<div class="profile"<?php print $attributes; ?>>
   <?php print render($user_page_object->name); ?>
   <?php print render($user_page_object->signature); ?>
   <?php print render($user_page_object->timezone); ?>
   //and so on...
</div>

```

And to access additional fields you may have added you can drill into the $user\_profile array which contains those fields. (Which would've been added here admin/config/people/accounts/fields).

I recommend using the devel module to kpr or dpm (I prefer kpr) to look into those two vars, ie:

```
<?php
kpr($user_page_object);
kpr($user_profile);
?>

```

---
Tags: 7, users
---


title: Show a list of all forms

text:
# Question
Title: Show a list of all forms
> **Possible Duplicate:**
> How to list all the form IDs

I have been searching for a way of listing all forms that are hooked to a Drupal site. I have read this post How to list all the form IDs, saying that it is impossible.

Now impossible is a big word in my vocabulary;-) If need be I can scan every single module file for the hook\_form () function. Yet I am seriously hoping there will be a less hack like solution no matter what the resource cost might be. Any suggestions?

# Answer
> 0 votes
Well I ended up using Hook\_form\_alter () to add every form that was being called (and was not on my form list yet) to a form list.

Then I wrote an admin interface that enables the administrator to select what forms are still active/should be listed. Next to this I implemented a REST service for the Services module to GET the list of forms.

The fact that the hook\_form\_alter () has to preform a DB request to see if the form is on the list everytime a form is viewed is some what performance heavy, but since there is no help, this is the best I can think of. If anyone has interest in the code, drop me a line, ofcourse better ideas are welcome;-)

---
Tags: forms
---


# Question
Title: Setting author when creating a new node via Cron
I'm creating a new node using hook\_cron(). It all works except the node author is always set as anonymous (uid = 0). How can I assign a user to the new node, with say uid 21 for example?

Below is the node creation code that I have in a function that gets called within hook\_cron().

```
$node = new stdClass();
$node->type = $type;
$node->title = "Some node title";
$node->language = LANGUAGE_NONE;
$node->uid = 21;
node_object_prepare($node);

$node->body[$node->language][0]['value'] = '';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'html_text';

$node->field_quote[$node->language][0]['value'] = $some_value;
$node->field_quote[$node->language][0]['format'] = 'plain_text';

$node = node_submit($node);
node_save($node);

```

Even though I state `$node->uid = 21;`, it always results in an anonymous author.

# Answer
> 6 votes
You have two options.

Either set the uid after the node\_submit() call and before node\_save(), or set `$node->name` to the username of the user that should be the author. The reason is that `node_submit()` will set the uid of the node based on the value of `$node->name`.

# Answer
> 2 votes
You are setting `$node->uid` before calling node\_object\_prepare(), but that function contains the following code.

```
global $user;
$node->uid = $user->uid;
$node->created = REQUEST_TIME;

```

You need to set `$node->uid` after calling `node_object_prepare()`, and thus your code should be like the following one.

```
$node = new stdClass();
$node->type = $type;
$node->title = "Some node title";
$node->language = LANGUAGE_NONE;
node_object_prepare($node);

$node->uid = 21;
$node->body[$node->language][0]['value'] = '';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'html_text';

$node->field_quote[$node->language][0]['value'] = $some_value;
$node->field_quote[$node->language][0]['format'] = 'plain_text';

$node = node_submit($node);
node_save($node);

```

Be sure you don't set `$node->name` when you set `$node->uid` at the same time, or node\_submit() will set `$node->uid` with the following code.

```
  if (isset($node->name)) {
    if ($account = user_load_by_name($node->name)) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }

```

What is the difference between setting `$node->uid`, and setting `$node->name`? The difference is that in the first case you don't cause Drupal to call user\_load\_by\_name() all times you call `node_submit()`. This means you are not causing Drupal to call DrupalDefaultEntityController::load(), and DrupalDefaultEntityController::buildQuery(). The first function invokes some hooks that are used to alter the query, such as hook\_query\_alter().
As you seem to set the same user as author of more than one node, it would be better if you call `user_load_by_name()` as in the following code.

```
$account = user_load_by_name($name);

$node = new stdClass();
$node->type = $type;
$node->title = "Some node title";
$node->language = LANGUAGE_NONE;
node_object_prepare($node);

$node->uid = $account->uid;
$node->body[$node->language][0]['value'] = '';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'html_text';

$node->field_quote[$node->language][0]['value'] = $some_value;
$node->field_quote[$node->language][0]['format'] = 'plain_text';

$node = node_submit($node);
node_save($node);

```

That is the code I would use if you are not using other code that returns you the user object to use for the node author.

---
Tags: cron
---


# Question
Title: StackExchange-style "related tags" block using drupal views?
StackExchange sites, and various other site around the 'net, have a nice tag drill-down feature: You can go to a tag page, like https://drupal.stackexchange.com/questions/tagged/views, and then you can select tags from the "related tags" block, and you are sent to a page that filters contents on the union of the two tags. You can do this as many times as you want, and you end up with only content that has **all** of the tags you've selected. The tags in the "related tags" block are sorted by popularity, and list the number of items tagged.

Is it possible to do this in drupal? How would one go about this? I'm imagining something like a content-view for the tag page, filtered by tags; and then a taxonomy-view for the block, filtered by relationships with contents in the first view. Seems like a bit of a complex mission. Is there a simpler way?

# Answer
There's a module that I believe does what you want: Similar by Terms

> This Drupal module attempts to provide context for content items by displaying a block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Blocks are available based on similarity within each of the defined vocabularies for a site as well as a block for similarity within all vocabularies.
> 0 votes

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


title: Trouble aligning text with WYSIWYG

text:
# Question
Title: Trouble aligning text with WYSIWYG
I have added TinyMCE to work with one of my text formats, and I added the different alignment buttons. When I try to center some text it adds "text-align: center" to the p... but when I save it, it goes back to normal. I would like to fix that to be able to align text and images. I installed a module called WYSIWYG Filter and added "text-align" in Text properties... still doesn't work. I also added "p\[style|text-align\]" to the "HTML elements and attributes" section... still doesn't work.

Any ideas of what could I be missing? ...I'm using Drupal 7 BTW

# Answer
> 0 votes
If you're using the filtered HTML input format, that would be stripping it out.

If not, it sounds like your markup is weird. The way you describe it, what might work if it read `<p align="center">` (not that I recommend this) reads `<p style="text-align:center">`. I think WYSWIG editors tend to prefer classes to putting styles right in the markup, so I'd do something like `<p class="centered-text">` and add `.centered-text{ text-align:center }` to your stylesheet.

I would double-check your site with a DOM inspector to make sure your style on your `<p>` isn't being overridden by a stylesheet. If nothing else works, you could use a different editor. jWYSIWYG, openWYSIWYG, Whizzywig, and nicEditor use `align="wherever"` instead of `style="text-align:wherever"` which might work (again, I don't recommend this, but it's a potential short-term solution. For reference, MarkItUp and WYMeditor don't offer alignment buttons, and CKEditor, FCKEditor, TinyMCE, and YUIeditor do it the "right" way, using `style=""`)

---
Tags: wysiwyg, nodes
---


title: Accent caracter encoding

text:
# Question
Title: Accent caracter encoding
I move a Drupal site and DB from old server to new (almost same setting) the site on the new server is running "almost" perfectly, but for the accent caracter encoding... here is the problem.

The site is requesting the file "Québec.jpg" i know for sure I spy it with firebug, and the Québec.jpg is where it should. The only problem is the the photo is not showing properly

If I change the file name for : QuÃ©bec.jpg it work...

I prefer not thinking about all the change i should do, so now the question why it's doing that, and what to change to fix that, file is there, request it ok, but mix-and-match don't append !

Thanks in advance

# Answer
The contents of your tables are not stored in the encoding that is specified for those columns. So you need to find out how the characters are stored and what the specified encoding is, e.g. using phpMyAdmin. It seems the characters are stored in UTF-8, but the columns are identified as latin1. If I recall correctly I've used this conversion script successfully in the past for a similar situation. Of course, **always backup your database** before attempting such operations! Or try it on a copy first.

You can also drop all tables and fully reimport the old database, this time choosing the correct character encoding. (It's best to have everything in UTF-8, so if the old database dump is not in UTF-8, you could convert the .sql file first and then import it as UTF-8).
> 1 votes

---
Tags: database, files
---


# Question
Title: How to stop Drupal for setting node changed date on creation?
This is my second question about my issues with creating custom migration script.

I am creating only new nodes and don't care about updates.

Code:

```
        $node = new stdClass();
        $node->type = 'migrate';
        $node->title = $content['title'];
        $node->language = LANGUAGE_NONE;

        $node->created = (int) date('U',strtotime($content['created']));

        $modified = $content['modified'];
        if (! empty($modified) && $modified != '0000-00-00 00:00:00') {
            $modified = (int) date('U',strtotime($modified));
        } else {
            $modified = 0;
        }
        $node->changed = $modified;

        node_object_prepare($node);

        #some lines later
        node_save($node);

```

E.g my $modified is set to 0 and after save I see updated column of this node row in admin content list with current datetime value.

# Answer
> 15 votes
You should be able to preserve the original `changed` time by first setting a custom property on the node object, say `$node->modified`, in your migration script prior to calling `node_save()`, and then implementing the node\_presave hook:

```
/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {
  $node->changed = $node->modified;
}

```

This will work since `node_save()` sets `$node->changed` prior to calling all modules which implement `hook_node_presave()`.

---
Tags: 7, nodes
---


# Question
Title: Can't create foreign key using SCHEMA API
I am trying to create 2 tables, linked together, using this code:

```
$schema['parent'] = array(
    "fields" => array(
        "id" => array(
            'description' => 'The primary identifier',
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE,
        ),
        'data' => array(
            'description' => 'The stored data.',
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
            'default' => '',
        ),
    ),
    'primary key' => array('id'),
);

$schema['child'] = array(
    // {{{fields

    "fields" => array(
        "id" => array(
            'description' => 'The primary identifier',
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE,
        ),
        "parent_id" => array(
            'type' => 'int',
            'unsigned' => TRUE,
        ),
        'data' => array(
            'description' => 'The stored data.',
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
            'default' => '',
        ),
    ),
    // }}}
    'indexes' => array(
        "parent_id" => array("parent_id"),
    ),
    'foreign keys' => array(
        'parent_id' => array(
            'table' => 'parent',
            'columns' => array('id' => 'parent_id'),
        ),
    ),
    'primary key' => array('id'),
);

foreach ($schema as $key => $value) {
    print $key . "\n";
    db_create_table($key, $value);
}

```

The tables are created, but the foreign keys are not. Using MySQL/InnoDB. How to fix it?

Also how to set ON DELETE CASCADE and ON UPDATE CASCADE?

# Answer
Schema Reference

> Foreign key definitions were added in Drupal 7 for documentation purposes only, and do not modify the database.
> 8 votes

---
Tags: 7, database
---


title: Call counter module in a page

text:
# Question
Title: Call counter module in a page
How can I place visitor stats in a page from Counter module in Drupal 6? I'm looking for the php Code. Maybe it can be done with:

```
<?php print theme(); ?>

```

but I don't know the exact code.

# Answer
> 1 votes
Effectively, the Counter module shows that information in a block. If you want show the content of that block in a page, without setting the block to appear in that page, you could use the following code.

```
$block = module_invoke('counter', 'block', 'view');
if (isset($block['content'])) {
  print $block['content'];
}

```

Keep in mind that the Counter module shows the content of that block to users with the "view counter" permission. If you want to show that content to users without that permission, you need to use different code.
Keep in mind that executing that code causes many SQL queries to be executed; some of those queries update some database tables. It is probably better to cache the output returned for that block.

Considering this, it is probably better to make the block provided from the Counter module in that page.

# Answer
> 1 votes
I believe Counter creates a block that you can then position. If you need to do it programmatically, see this question and answer: Programmatically printing a block

# Answer
> 0 votes
This code works fine too:

```
$tvisit = db_result(db_query("SELECT counter_id FROM {counter_today} ORDER BY counter_id DESC"));
$cvisit = db_result(db_query("SELECT `counter_value` FROM `counter_data` WHERE `counter_data`.`counter_name` = 'site_counter'")); ?>

```

---
Tags: 6, theming
---


title: Include .inc file for my own module

text:
# Question
Title: Include .inc file for my own module
I have written my own module for example called: calc and i have used `module_load_include('inc', 'calc', 'form.inc')` in my calc.module file, and placed form.inc file inside my module's directory: calc/form.inc but it doesn't see that file. What am I doing wrong?

I am using Drupal 6.

# Answer
It should be:

```
module_load_include('inc', 'calc', 'form');

```

(The 'inc' in the first argument automagically appends as the extension)
> 6 votes

# Answer
With `module_load_include('inc', 'calc', 'form.inc')` you are including the form.inc.inc file present in the directory where the calc.module file is present.

If you want to include the form.inc file in that directory, you need to use `module_load_include('inc', 'calc', 'form')`, as Jimajamma said.

The first argument of module\_load\_include() is `$type`, the second is `$module`, and the third is `$name`. They are concatenated together using the following code.

```
$file = './' . drupal_get_path('module', $module) . "/$name.$type";

```

When you don't pass `$name` to the function, it will use for `$name` the same value passed for `$module`.

You could also include a relative path in `$name`, such as `'includes/form'`; in that case the loaded file would be `'includes/form.inc'`, where includes is a directory contained in the directory containing the module whose name is passed as second argument.
> 3 votes

---
Tags: 6
---


title: Cannot find installed ffmpeg

text:
# Question
Title: Cannot find installed ffmpeg
I installed ffmpeg according to the ffmpeg instructions I found on d.o.

When I do `which ffmpeg` it tells me /usr/local/bin/ffmpeg but when I search in Finder for it (installing with MAMP) it tells me it's at /Applications/MAMP/bin/php/php5.3.6/bin/ffmpeg/ffmpeg .

I've tried pasting both of those paths into the field in Video configuration that says "Absolute path to FFmpeg executable. When you install a new FFmpeg version, please clear the caches to let Drupal detect the updated codec support." but then I get `FFmpeg not found at [either of those paths]`.

I have tried removing the extra copies, to no avail. I've tried setting the document root in settings.php, to no avail. I've tried installing and building it manually as well as with `brew`. No dice.

# Answer
That message error is returned also when the FFmpeg executable is found, but its output is not the module is expecting.

`TranscoderAbstractionFactoryFfmpeg::adminSettingsValidate()` contains the following code.

```
  if (!$ffmpeg['ffmpeg-found'] || ($version = self::getVersionFromOutput($ffmpeg['raw'])) == NULL) {
    form_set_error('video_ffmpeg_path', t('FFmpeg not found at %path. To convert videos and create thumbnails you have to install FFmpeg on your server. For more information please see the !documentation.', array('%path' => $ffmpeg_path, '!documentation' => l(t('documentation'), 'http://video.heidisoft.com/documentation/ffmpeg-installtion-scripts'))));
  }

```

`PHPVideoToolkit::getFFmpegInfo()` contains the following code.

```
$formats = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -formats');
$codecs = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -codecs');
$filters = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -bsfs');
$protocols = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -protocols');
$pixformats = $this->_captureExecBufferFallback($this->_ffmpeg_binary . ' -pix_fmts', $this->_ffmpeg_binary . ' -pix_fmt list');
$help = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -h');

self::$ffmpeg_found = $data['ffmpeg-found'] = !empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE;

```

The message error could be returned when:

* The module is not able to detect the FFmpeg version from its output
* The module finds the string "not found," or "No such file or directory" in output returned from `ffmpeg -formats`
* The command line fails for any reason

In the latter case, the first condition of `!empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE;` is `FALSE`, and `$data['ffmpeg-found']` is set to `FALSE`, causing the error message you see.

For trouble shouting, you can:

* Execute `ffmpeg -formats` and check the output doesn't contain *not found*, nor *No such file of directory*
* Test FFmpeg works perfectly when running from the command line
* Execute the following code, and verify `$buffer` is not an empty array

```
$command = "ffmpeg -formats"; // Use the full path of the command line you are testing.
$buffer = array();
$err = 0;
exec($command . ' 2>&1', $buffer, $err);

if ($err !== 127) {
  if (isset($buffer[0]) === FALSE) {
    $tmp_file = '/tmp/_temp_' . uniqid(time() . '-') . '.txt';
    exec($command . ' &>' . $tmp_file, $buffer, $err);
    if ($handle = fopen($tmp_file, 'r')) {
      $buffer = array();
      while (!feof($handle)) {
        array_push($buffer, fgets($handle, 4096));
      }
      fclose($handle);
    }
    @unlink($tmp_file);
  }
}

```

I would execute the code I shown in the last point with both the executables, just to see if there is a difference. To be sure the problem is not file permissions, I would execute the code using the same user that runs PHP code, which means I would put the code in a PHP file on the server, and run it as http://example.com/test.php. (Replace example.com with the domain name of the site you are testing.)

If the output of the command contains *not found*, or *No such file of directory*, but it works perfectly for you, it could be the module is being too cautious about what the command returns, and it assumes it would not work even if it effectively works. In this case, there is few that can be done, if not changing the code used from the module to detect when FFmpeg would not work.

In the case you get an empty `$buffer` array from the test code I described, it means the user used to run PHP doesn't have the necessary permissions to execute the command. In this case, you need to change the permissions.

As you have FFmpeg installed in two different directories, I would also check there aren't some conflicts between the commands, just to be sure. I am thinking, for example, to some files the command copies in another directory, and that is version dependent; if you have two versions of FFmpeg, that could be an issue.
> 2 votes

---
Tags: 7, files
---


title: video module, MIME problem

text:
# Question
Title: video module, MIME problem
I have installed the video module of the Drupal 7 distribution. I have added the "video" field to my content type. When I upload the mp4 format of the video, I get the following message:

> No video with support format and MIME type found.

What should I do?

# Answer
Changing the player set to play files of that type might help. If not, installing one of the transcoders like ffmpeg or Zencoder will fix it. If that's not practical, you can use other modules besides Video, and create your own video field, for example the jPlayer module (which takes any m4v videos, a variation on mp4)
> 0 votes

---
Tags: files
---


# Question
Title: How to populate search form with search term in View / Panels / Page?
I've using Views and Page Manager to create a custom search results page. You can see it here:

http://quotefail.com/search/node/world

The page is being generated by Page Manager. I've got a Search Form in the top panel, but it starts empty. I'd like it to be pre-filled with the search term that was used to generate this page.

How can I prepopulate the search form with that search term?

Here is my page config:

Here is my Search View in the center panel:

# Answer
> 3 votes
Looks like from that link that the search form is the search block form, so you can do this as a theme form alter (you could also make a custom module in a similar fashion with form alters but this should serve your needs). This goes in your template.php for your theme:

```
function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'search_block_form':
      //checking if arg(2) exists so it doesn't try to do this if some visits the search page straight away
      if(arg(2)){
        $form['search_block_form']['#default_value'] = arg(2);
      }
      break;
  }
}

```

---
Tags: 7, search, views
---


title: Developing for Drupal 7

text:
# Question
Title: Developing for Drupal 7
I am trying to wrap my head around the Drupal 7 framework using the debugger in eclipse. The thing is, I'm feeling a little overwhelmed with the endless function calls and watching data bounce back and countless number of times (I'm sure it could actually be counted with more patience).

What is the best way to understand what is going on and get a good overview of how everything fits together? Is using just a debugger the wrong approach?

# Answer
> 6 votes
Using a debugger to understand which function called another one is not necessary all the time. If you look at the documentation on api.drupal.org, for example for user\_load\_by\_name(), you will notice the documentation shows the number of functions calling it, which is also a link to a page listing them.

In the case of hooks, such as hook\_field\_info(), the documentation page shows how many functions are implementations of that hook, and the number of functions invoking that hook.

The page listing the hook implementations can sometimes include functions that are not hook implementations; the short function description shown in that list makes evident when a function is not really a hook implementation.

In some cases, the documentation page lists the functions that reference a function, such as in the case of system\_batch\_page().

The documentation on api.drupal.org includes some sections that describe a group of functions correlated to each other, for example in Batch operations. The list of all the groups is on Topics.

Other topics are linked in the API reference page.

---
Tags: 7, debugging
---


title: How is this realised?

text:
# Question
Title: How is this realised?
When we implement, for example, `theme_preprocess_page(&$vars)` function, we can alter variable that are visible as not array items.

What I mean: `$vars['somevalue']` from `theme_preprocess_page(&$vars)` function is further available in `page.tpl.php` as `$somevalue`. How is it possible? Definitely there is some kind of automatic generation of variables but the implementation is unclear.

# Answer
> 1 votes
The theme engine runs the variables array through `extract()`, which extracts each key/value pair to a variable in the local scope.

For example, running the following code:

```
$array = array('var1' => 1, 'var2' => 2, 'var3' => 3);
extract($array);

```

will give you access to these three variables in the local scope:

```
$var1 // equal to 1
$var2 // equal to 2
$var3 // equal to 3

```

# Answer
> 2 votes
Clive's answer is correct. I am just pointing out where exactly that happens.

theme\_render\_template() is the function called by theme(), and it contains the following code.

```
  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  return ob_get_clean(); // End buffering and return its contents

```

The code that calls `theme_render_template()` is the following one.

```
    // Default render function and extension.
    $render_function = 'theme_render_template';
    $extension = '.tpl.php';

    // The theme engine may use a different extension and a different renderer.
    global $theme_engine;
    if (isset($theme_engine)) {
      if ($info['type'] != 'module') {
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
        }
        $extension_function = $theme_engine . '_extension';
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

    // In some cases, a template implementation may not have had
    // template_preprocess() run (for example, if the default implementation is
    // a function, but a template overrides that default implementation). In
    // these cases, a template should still be able to expect to have access to
    // the variables provided by template_preprocess(), so we add them here if
    // they don't already exist. We don't want to run template_preprocess()
    // twice (it would be inefficient and mess up zebra striping), so we use the
    // 'directory' variable to determine if it has already run, which while not
    // completely intuitive, is reasonably safe, and allows us to save on the
    // overhead of adding some new variable to track that.
    if (!isset($variables['directory'])) {
      $default_template_variables = array();
      template_preprocess($default_template_variables, $hook);
      $variables += $default_template_variables;
    }

    // Render the output using the template file.
    $template_file = $info['template'] . $extension;
    if (isset($info['path'])) {
      $template_file = $info['path'] . '/' . $template_file;
    }
    $output = $render_function($template_file, $variables);
  }

```

---
Tags: theming
---


# Question
Title: Can i make a node reference to some field but not the title field?
I have a salary content type and i want to reference the salary value from another content type.
Can i make a node reference to some field but not the title field?

# Answer
> 2 votes
You can make node reference to a view In a case I added a title and an image in an auto-complete and it worked fine you can check it by adding any field not a title

# Answer
> 0 votes
Ahmed solution is good enough, but you may try this one:

1. create the reference using Entity reference module
2. create new view mode and name it **referenced** for node bundles using Entity view modes module
3. in content type display setting page, use **Rendered entity** as display formatter and select referenced as rendering view mode
4. edit node's .tpl file and do what you want for those view mode

---
Tags: nodes
---


# Question
Title: How to set relationship when I create a new (custom) content to another (custom) content in Drupal
Premise: I'm new in the world of Drupal, so sorry if this is a stupid question.

What I need is to set some relationships for some new content types I created. For example, I created the "Person" content type and the "Group" content type. Using the "Relation" module I have defined the relation "is in", but now if I want to add a field for setting the relation at creation time, there are no edit widget available. The only way I found to set relationships is using the entity collector: too complicated for a user.

Example: a user creates the Person "John", and he want for him to set the relation "is in" with the Group "Drupal fans". So, during the creation of this Person he needs, for example, a select control that lets him to choose from all the groups already registered in the site.

In brief, I need to manage some entities created by me, with CRUD controls, list, etc. and I need to set some relationships from these entities.

What is the best method/ what are the best module/ how I can do this?

# Answer
> 0 votes
I hope I'm understanding your question correctly... you'd like to know what's the best way, in Drupal 7, to add a reference to a node of another content type when creating this content type? (i.e. to store a reference to a 'Group' when creating a new 'Person')?

If that's what you're trying to do, a good way to do that in Drupal 7 is using the Entity reference module.

Once you download and enable this module, you'll be able to go to the 'Manage fields' tab of your 'Person' content type and select to create a new field of type '**Entity Reference**'. That field option will only appear once you've enabled the module. Before hitting 'save' after you've selected that field type, make sure you notice that you'll have two options for the field widget: you can select for it to be a '**Select list**' in which case, it will just have a drop-down list of all the Groups currently available on your system for you to choose from when creating a person. Or you could choose '**Autocomplete**', which works better if you have a TON of groups and don't want a super long list. That'll allow the user to start typing the name of a group, and it will just automatically detect and complete it. :-)

Once you've selected those two options on the first screen, on the second screen you should select 'node' as the 'Target type' and select 'Group' as the type of the referenced node. Finally, just choose whether you want that field to be required or not and whether you should select only one or multiple values (like any other field).

Let me know if that works for you, and I hope I understood your question correctly!!

---
Tags: nodes, entities
---


# Question
Title: Drupal Gardens Template builder: Can I have this feature on my site
When you build a new site on Drupal gardens, you can select what features and blocks/regions you want on your new site.

Is there a module, which would let me choose my own set of features each time I create a new site on my own hosting (i.e. separate from Drupal gardens).

# Answer
> 1 votes
That's a proprietary part of their service. The closest you'll get is http://drushmake.me

# Answer
> 1 votes
Fusion theme + Skinr module will get you part of the way there. DG may have some customizations that are not available outside of their walled garden.

---
Tags: 7
---


title: Micro commerce feature

text:
# Question
Title: Micro commerce feature
I need to add a new feature to my site that allows users to buy a services.

We have 1 service now to be sold, and may extend to have 3 in the future with no attributes nor shipping, just a sales price. What should we use to implement this?

Commerce, ubercart or none of them?

# Answer
you can sale services in both Commerce and Ubercart. But if you look for simplicity I should tell you Commerce is simple and light enough.

At this time I can't remember any other solution on D7 except writing custom module. which I don't recommend.
> 1 votes

---
Tags: 7, commerce
---


title: Can't Create Content Type

text:
# Question
Title: Can't Create Content Type
This is from the node\_example from the Examples module on Drupal.org, I cut most part of them off now this should be an edited version of node\_example.install: http://newstartpoint.com/public/node\_example.install.txt

Now this is what I managed to get by myself: This http://newstartpoint.com/public/tudou\_update.install.txt. This above one works but the one I programmed doesn't. Can anyone give me some ideas? They seem pretty much identical.

Thanks!

# Answer
I think because of overriding 'base' property, change it to 'node\_content'

> using the "base" return component of hook\_node\_info() as the function prefix. For example, poll.module defines the base for the Poll content type as "poll", so during creation of a poll node, hook\_insert() is only invoked by calling poll\_insert().
> 0 votes

---
Tags: 7, nodes
---


title: PHP Variable in SQL LIKE

text:
# Question
Title: PHP Variable in SQL LIKE
I want to place a PHP variable in SQL LIKE, I tried many ways but no change.

e.g. today $adate is 2012-08-12%

```
$adate =  date("Y-m-d") . '%';
$tvisit = db_result(db_query("SELECT `counter_id` FROM counter_today WHERE `counter_date` LIKE '{$adate}' ORDER BY `counter_id` DESC LIMIT 1"));

```

How can I do that ?

# Answer
> 3 votes
The syntax would be along the lines of:

```
$adate =  date('Y-m-d');
$tvisit = db_result(db_query("SELECT counter_id FROM {counter_today} WHERE counter_date LIKE '%s%%' ORDER BY counter_id DESC LIMIT 1", $adate));

```

The changes from your original:

1. Put {}'s around table name so if you are on a shared database, drupal can put a prefix on automagically.
2. Put LIKE's % in the sql itself, not in the variable. You need to put in %% since % itself is drupal's way of starting a variable (kinda like \\ to put in a \\)
3. Put %s in in front of that for the variable, which is a string. Remove the {}'s since they are for table names. Granted, php will find $adate in there since it's all wrapped in ""'s but then you open up yourself to sql injection etc (however remote it would be in this specific example).
4. Put the $adate variable in the function call as an argument.
5. Take out the \`\`'s surrounding the field/column names.

---
Tags: 6, theming
---


title: Drupal front page and facebook crawlers

text:
# Question
Title: Drupal front page and facebook crawlers
I've got a drupal front\_page that reditects all anonymous users from blogs to front page. But I want to facebook clawler see my og: data, to post comments with current title. Facebook crawler got 302 on front and takes title from front page.

How can I do a (maybe) whitelist to facebook crawler to take og: data from restricted area?

# Answer
I am not sure how you are doing the redirect, but Facebook sends a USER AGENT string to signal its bot/crawler, so you could do something like:

```
  if (strpos($_SERVER['HTTP_USER_AGENT'], 'facebookexternalhit')!==FALSE) {
    // DON'T REDIRECT, we're facebook crawling around...
  } else {
    // REDIRECT, we are another bot or a user, etc...
  }

```
> 1 votes

# Answer
It depends on way how you made the redirection. Rules? Then add condition that tests user-agent and identify if it is not FB crawler. If you don't like PHP snippets you can do it by check Context which tests user-agent.
> 1 votes

---
Tags: 6, social-network
---


# Question
Title: Which Views hook do I use to alter the view results page before it loads?
I have a view that I want to change two items right before the page loads - the title, and the zipcode that determins the location to filter by.

My module detects a person's location and replaces the default value in the Views filter so that the results are properly sorted by that area.

So, the title changes to 'Viewing items around Charlotte, NC' where Charlotte, NC is the dynamic element.

I have created a module, but I am not sure what views hooks I need to use to achieve the results, especially getting the view to execute with the new location.

Here are the views hooks for D7 http://api.drupal.org/api/views/views.api.php/group/views\_hooks/7

Do I pre\_view it? pre\_render? Alter the query with the new location details before its executed?

Here is a sample of my module trying to use hook\_views\_pre\_view

```
function zipcode_filter_views_pre_view  ( &$view, &$display_id, &$args) {

    $view = views_get_view('baby_clothes_pages');
    $view->set_display('default');
    $view->set_exposed_input(array('postal_code' => $zipcode));
    $view->display['default']->handler->options['title'] = $title;

}

```

note: this reference influeced the code I used. However, the documentation is wanting. Am I even on the right track with this? http://groups.drupal.org/node/10129

# Answer
The answer was to remove the views\_get\_view function as well as the set-\>display function. There was also no need to try to execute the exposed input. All that was needed is to simply set the default values for the variables I wanted in the views\_pre\_view hook, and then Views takes care of the rest as it finishes doing its thing. Here is the resulting, correctly working code:

```
function zipcode_filter_views_pre_view  ( &$view, &$display_id, &$args) {

    $view->display['default']->handler->options['title'] = "this is the new title";
    $view->exposed_input['distance']['postal_code'] = $_SESSION['zipcode_filter']['zip'];
    $view->exposed_input['distance']['search_distance'] = $_SESSION['zipcode_filter']['distance'];

}

```

Although, I don't understand why this works - Why do I not need to specify a display? Why did having the other parts of earlier code cause it to not work properly?
> 3 votes

---
Tags: 7, views
---


title: Problem using module_load_include

text:
# Question
Title: Problem using module_load_include
I need to use `node_add()`, but when I called it in my module I get the "undefined function" message.

So I'm trying to include it using `module_load_include('inc', 'node', 'node.pages')`, but I'm getting the error message:

> Fatal error: Unsupported operand types in /var/www/vhosts/***\*.es/httpdocs/includes/common.inc on line 2946

Do you have any idea?

# Answer
I suggest you 3 method to add a node programatically

* first method

```
// required for Drupal 6
module_load_include('inc', 'node', 'node.pages');
// which nodeform you want
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node
$node = array(
 'uid' => $user->uid,
 'name' => (isset($user->name) ? $user->name : ''),
 'type' => $node_type,
  );
  // Invoke hook_nodapi and hook_node
  node_object_prepare($node);
 // Or you can also use an exiting node, for example
 // $node = node_load(123);
 // and the display the form:
 $output = drupal_get_form($form_id, $node);

```
* second method

```
 module_load_include('inc', 'node', 'node.pages');
 $node_type = 'YOURNODETYPE';
 $form_id = $node_type . '_node_form';
 global $user;
 $node = array(
'uid' => $user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => $node_type,
);
node_object_prepare($node);
print drupal_get_form($form_id, $node);

```
* third method

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
$output = drupal_render($form);

```
> 1 votes

# Answer
Maybe you are using an old version of PHP. Have you tried also running "php -l your\_file.php". That will run just the parser to see if you have any php syntax problem.
> 1 votes

---
Tags: 6, nodes
---


# Question
Title: Does a guide for installation of drupal Cartaro distribution exist?
I have been trying to install the Cartaro distribution of drupal on windows that makes drupal

a complete geo-stack. I have been unable to find complete documentation for the same and the

installation fails to detect postgis installed on the computer as well as there is some confusion about the terminology for geoserver.

# Answer
> 2 votes
Have a look at Cartaro's Getting Started guide. Especially see the quoted commands to set up permissions for PostGIS properly.

Additionally, there have been changes to the error reporting of Cartaro in July which should result in more precise error messages in case something is wrong with PostGIS.

Please report any bugs in Cartaro using its bug tracker on the Drupal site so that is does not get overlooked. We'd be happy to see a report there regarding the GeoServer terminology along with a more verbose description.

---
Tags: theming
---


title: Ajax errors on upload fields

text:
# Question
Title: Ajax errors on upload fields
I have an image field that allows a single image to be uploaded. The selection works, but if I click upload, I get an AJAX error. If I just submit without uploading first, the image is uploaded properly. If I go in to edit that image field and click remove, I again get an ajax error.

```
An error occurred while attempting to process /file/ajax/field_front_image/und/0/form-XprUtXJvTcMRlmsz3CmBs6uDFpuJcev4SO_I_PvsM-E: Array.prototype.reverse called on null or undefined

```

I get this error locally and on the production server. It happens for all image fields and it's the same error when clicking upload or remove.

How can I fix the ajax on these form fields?

# Answer
Please check your theme's jQuery and Drupal jQuery conflicts. Check 'View source' and check the jQuery version the page using.

I had similar issue when used latest jQuery in my theme.
> 6 votes

# Answer
We had this problem in 2 month ago. this problem issues form server and not depended to drupal core.we try to solve this problem, and test any ideas(clean drupal cache, recreate fields, change permission of file directories )but all of them not work. Just I can suggest you put you contentrate in server and cache layer of server( nginx cache, varnish cache if you have )

maybe be useful using clearstatecache and commands like this.

**Certaintly problem is in server not in drupal**
> 0 votes

---
Tags: 7, ajax, media
---


# Question
Title: Fatal error: Class 'Browser' not found : After Updating drupal 6.20 to 6.26
As i am update my durpal version 6.20 to 6.26 and it gives these error after updating.

```
   1) Fatal error: Class 'Browser' not found in /opt/lampp/htdocs/mydrupal/includes/common.inc(1731) : eval()'d code on line 4

   2) warning: include(Browser.php) [function.include]: failed to open stream: No such file or directory in /opt/lampp/htdocs//opt/lampp/htdocs/uls/includes/mydrupal/includes/common.inc(1731) : eval()'d code on line 3.

```

I checked the common.inc file and there is no code for "including browser.php"

# Answer
> 2 votes
The error message says `eval()'d code on line 4`. You have a PHP block, node or something similar that tries to include a file called `Browser.php`. That is not a file supplied with Drupal core. What you can do... just before line 1731 add something like `if(strpos($code, 'Browser.php')) { file_put_contents('/tmp/log', print_r(debug_backtrace(), TRUE)); exit;}` and then study the log to see where it's called from to figure it out. If it's called from block, the backtrace will contain the module and delta, if it's a node, the nid will be there and so on.

---
Tags: 6, updating
---


title: Call a template file in hook_block_view

text:
# Question
Title: Call a template file in hook_block_view
So I'm using the `$block['content'] =` right now to display the **html** for my module. But I can't bake any php into it with it laying inline like that.

How can I make a call to my custom template file that I've added to my module directory?

# Answer
> 2 votes
in your module use hook\_theme() in **drupal 7**

```
function YOURMODULE_theme() {
  return array(
    'YOURMODULE_CUSTOM_THEME_NAME' => array(
      'variables' => array('title' => NULL, 'path' => NULL), // eg: if you want $title, $path in ur tpl. you can use any variable or an entire array/object.
      'template' => 'CUSTOM-TPL',
    ),
  );

```

and in your module folder ,create CUSTOM-TPL.tpl.php

now you can call it in

```
$block['content'] = theme('YOURMODULE_CUSTOM_THEME_NAME', array('title' => $title, 'path' => $path));

```

for **drupal 6** , user 'arguments' instead of 'variables' and

```
theme('YOURMODULE_CUSTOM_THEME_NAME', $title, $path);

```

# Answer
> 0 votes
I hope this will help :)

you can call your template file by using the hook system

* register your template with hook\_theme()
* Call theme('nameoftheyourtheme', $args)

$args is an array that contains the arguments to the template as specified by your hook\_theme() implementation.

This link might also help you, Hook\_theme and template files (but its for D6)

---
Tags: views, 7, hooks, blocks
---


title: 'reversed' node refs?

text:
# Question
Title: 'reversed' node refs?
Here is the current situation: i have an artist database and users can 'like' the artist with a flag button and that works great, but i need to use the 'like' data to get some other info

Case: 1. user likes artist(flag!) 2. user logs out 3. user returns to website and logs in and gets redirected to custom page

## 4. The custom page needs to contain nodes that reffer to the artist.

Its step 4 where i got stuck, i just don't know how to display the information from B to A in a view?

Using Drupal 6 and views 2.

Thanks!

# Answer
> 0 votes
In views edit \> Relationships \> add **Flags: User's flagged content** (also select Include only users who have flagged content.)

---
Tags: views
---


title: add region with module installation

text:
# Question
Title: add region with module installation
I am developing a module, that when installed, should place an HTML element in a drupal block. That block, will be inside a region. I would like the region to be added to the theme on module installation. Any workarounds?

# Answer
> 2 votes
you **cant** create custom region in a theme using custom module in a drupal way . however you can fetch available regions

---
Tags: 7, theming
---


# Question
Title: Alter a view so it adds a custom field ->textbox
I have a bit specific question.

I have a content type-\>TESTS it has the more or less the normal fields.

There is a view that displays all of the tests. So far,so good.

But the requirement is to add a specific textbox-\> SCORE of TEST for every instance.

And it should be different for all the logged in users.

For example. All users see the tests and can insert a result. This result is recorded in the database.

What should be the best approach doing so ?

Maybe: 1.Create the field "ScoreOfTest" 2.Alter the view in a custom module

Thanks in advance

# Answer
> 0 votes
When you create the content type does it reference who test scores they are? Without any reference's to who's score it is this would be hard. You could use entities I believe as you can create relationships you need then you could use views to display it.

http://drupal.org/node/1261744

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


title: load Ajax form in another page

text:
# Question
Title: load Ajax form in another page
I have a link in a block and when i click it it brings with ajax a form from another page let's call it contact. In contact page the form uses ajax to submit the data, it works ok. But when i get the form by clicking that link in another page using ajax the form loses the ajax submit. and instead it redirects me to the contact page.

How can i keep the ajax submit even if the form loads with ajax in another page???

# Answer
> 2 votes
It seems, I found some solution, may be not fully drupal-way.

Firstly, we need to load JS libraries, needed for working of ajax submit. This code helps us:

```
drupal_add_library('system', 'drupal.ajax');
drupal_add_library('system', 'drupal.form');
drupal_add_library('system', 'jquery.form');
drupal_add_library('system', 'druapl.progress');
drupal_add_library('system', 'drupal.textarea');

```

Nextly, we need to fill JS class Drupal.settings.ajax with data about page elements, which provides ajax behavior. I have not an universal solution, I only stops JS code on breakpoint in misc/ajax.js when running it on page with correct working ajax form. You can see correct values in this part of code:

```
Drupal.behaviors.AJAX = {
  attach: function (context, settings) {
    // Load all Ajax behaviors specified in the settings.
    for (var base in settings.ajax) {
      if (!$('#' + base + '.ajax-processed').length) {
        var element_settings = settings.ajax[base];

        if (typeof element_settings.selector == 'undefined') {
          element_settings.selector = '#' + base;
        }
        $(element_settings.selector).each(function () {
          element_settings.element = this;
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        });

        $('#' + base).addClass('ajax-processed');
      }
    }

```

So, in my case resulting JS code, needed to be added into startup javascript, looks like this:

```
if(Drupal.settings.ajax == undefined){
    Drupal.settings.ajax = {
        'edit-submit': {
            callback: "faqform_ajaxsubmit",
            event: "mousedown",
            keypress: true,
            prevent: 'key',
            submit: {
                _triggering_element_name: "op",
                _triggering_element_value: "Send"
            },
            url: 'system/ajax',
            wrapper:'submit-message'
        }
    };
}

```

If all done correctly, you form, loaded by ajax, will have correct ajax behavior, in my case - ajax submit.

May be there are more graceful solutions, may be diving deeper into code will help you to find them.

---

## So, here is much more graceful solution!

After some analyses of steps, maked above, I decided, that only thing we need to make ajax form, loaded by ajax, to work is fill javascript Drupal.settings array with correct data, describing forb behavior. In the above example we made it by hands, with hardcode, whitch is not true. Obviously, somewhere in drupal code it work does automatically. I found this place. It is function ajax\_pre\_render\_element in the ajax.inc. It gives array of any form element with ajax property and appends to it additional parameters, which will be converted to JS code and added to Drupal.settings array later. Exactly thing, that we need.

Here is my code now:

```
function anyform_block_info()
{
    //standart form for displaying to user
    $blocks['any_form'] = array(
        'info' => t('Any form'),
        'status' => true,
        'region' => 'content',
        'weight' => 99,
        'visibility' => 1
    );
    //hidden 'form' needed to generate and load ajax behavior settings before form loading
    $blocks['faq_form_hidden'] = array(
        'info' => t('Any fake form'),
        'status' => true,
        'region' => 'footer', //I thing, it will be better place it in footer^ in my case content is ajaxed
        'weight' => 99,
        'visibility' => 1
    );
    return $blocks;
}

function anyform_block_view($delta)
{
    switch ($delta) {
        case 'faq_form':
            $block['content'] = drupal_get_form('anyform'); //standart form
            return $block;
        case 'faq_form_hidden':
            $block['content'] = anyform_get_hidden_form(); //fake form
            return $block;
        break;
    }
}

function anyform_get_hidden_form()
{
    $form = drupal_get_form('faqform'); //give our original form
    $form = ajax_pre_render_element($form['submit']); //create settings for element with #ajax property (don't pass whole form as argument - not works)

    //makes fake form with hidden element in footer, but with correct array with settings for ajax behavior
    $fakeform['fakeform'] = array(
        '#type'=>'markup',
        '#markup'=>'<div style="display: none;"></div>',
        '#attached'=>$form['#attached'], //our magical array
    );

    return $fakeform;
}

```

So, I hope, it will solve most of your problems with drupal ajax-loaded forms. For me this solution works without any problems, and I going sleep being happy =^\_^= Good luck!

# Answer
> 1 votes
Ah.

It's a DOM thing. When you get the new contact form back (rendered via AJAX), then you have to tell the new button (in that rendered block), to issue another AJAX request -- otherwise it does it's default behavior.

-- EDIT --

What you do is embed a tag IN the form itself. When that form gets called into the DOM (via the AJAX call), the script should re-instantiate the button as an ajax button. In jquery:

```
<script>
$().ready(function(){
    $('.button').click(function(){
        // submit form via AJAX
        return false;
    });
)};
</script>

```

# Answer
> 0 votes
I've run into this problem before...I was able to get it working by loading the form in an i-frame that is in the modal window. You can set a redirect with some simple javascript in the header of the from. Doing it this way will also keep the error messages in the modal box if the form doesn't validate.

# Answer
> 0 votes
developed a custom module to make ajax things easier.. with this module you can load any pages without breaking its ajax or any other javascript/jquery functionality , this is done using Drupal.attachBehaviors .

here is the module (currently under review process)

---
Tags: forms, ajax, webforms
---


# Question
Title: Fetching specific node fields instead of whole nodes using EntityFieldQuery
The standard for fetching specific nodes from the database in Drupal 7 goes something like this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'page');
$query->fieldCondition('field_category', 'value', $category_id);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = node_load_multiple($nids);

```

For better performance, is there any way to specify that I want to load only certain fields (the title for example) of the nodes instead of loading all their their fields?

I prefer a solution that doesn't use SQL to benefit from all the goodies Drupal functions offer (reliability, caching results, future proofed, ...).

Thank you.

# Answer
> 4 votes
No, there isn't. EFQ can only return the entity id's.

While there might be ways around it, there is a logical reason for that: Modules might alter the values of those fields in various hooks, there is no guarantee that the directly returned values are the same as when loading an entity.

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


# Question
Title: How to add a contact link next to the 'submitted by' user info?
I would like to customize the 'submitted by user' section of certain contact types and add a 'contact author' link.

# Answer
> 4 votes
You certainly shouldn't need to hack core for this. There's a few ways to do this, the simplest way is to customise node.tpl.php. For example if you were using the default node.tpl.php you would copy it to your theme folder, rename it "node--yourcontenttype.tpl.php" and then open it up and find the code:

```
<?php if ($display_submitted): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```

You can then add the code to generate your contact link, something like this (untested):

```
<?php if ($display_submitted): ?>
  <div class="submitted">
    <?php print $submitted; ?>
    <a class="user-contact" href="/user/<?php print $uid; ?>/contact">Contact</a>
  </div>
<?php endif; ?>

```

---
Tags: 7
---


# Question
Title: How could the contextual filter "Content: Nid" return the TNID instead of NID?
I am using the contextual filter "Content: Nid" in Views3, and I want it returns the TNID instead of the NID *When the filter value is NOT available*.

I tried the following code.

```
$node = node_load($argument);
$argument = $node->tnid;
return $argument;

```

I also tried the following code.

```
$node = node_load(arg(1));
$argument = $node->tnid; // bzw. $argument(1) = $node->tnid;
return $argument;

```

I used that code in *Provide default value:PHP Code* Field, but nothing worked.

---

I solved the problem by adding this code to the page.tpl.php.

```
$imagemenuview = views_get_view('projectimagemenu');
echo $imagemenuview->preview('block', array($node->tnid));

```

I am still interested in the solution using the contextual filter "Content: Nid" returning the TNID instead of the NID *When the filter value is NOT available*.

# Answer
This PHP code should work:

```
$node = node_load(arg(1));
return (isset($node->tnid) ? $node->tnid : $node->nid);

```

The better way (without *evil eval()*) is to provide own plugun of type `'argument default'` which will do work. Look at `Content ID from URL` argument default plugin as an example.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Views template- how can I still use "hide if empty" behavior with my custom template?
I want to customize the output of a field on my site so I made a custom views template. Here's the code:

```
<?php foreach ($row->field_field_location_taxonomize_terms as $data): ?>

  <?php if ($data['rendered']['#markup'] == 'Unknown'): ?>
  <?php elseif ($data['rendered']['#markup'] == 'United States of America (USA)'): ?>
    <?php print 'USA'; ?>
  <?php elseif ($data['rendered']['#markup'] == 'United Kingdom (UK)'): ?>
    <?php print 'UK'; ?>
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

```

As far as editing the output, this works fine. However, if the field is empty, the Label (set in views) for the field will still be printed, even though I have *Hide if empty* checked under **No Results Behavior**. If I remove my custom template, then the label is hidden when there is no value, so there must be something wrong with my template. Any ideas?

# Answer
> 1 votes
Quick and dirty, how about turning the label for this field off in Views and add something like:

```
<?php if (!empty($row->field_field_location_taxonomize_terms)): ?>
  <div>Label:</div>
<?php endif; ?>

```

at the top of this template? (Changing up the HTML around Label: to match your system and t()'ing it, etc)

---
Tags: views, theming
---


# Question
Title: How to create and display user content submission form?
Drupal 7

Could someone point me to the right direction on how to create a submission form through which users can post content? I have a specific content type that I expect the users to fill in while submitting.

I know it's horrible, but i was thinking to link to the relevant admin page, but there must be a better way (something like Views but for submission forms)

Thanks, Markus

# Answer
> 1 votes
The create content pages are separate from Drupal's admin section. You can set up the permissions so users can add content of a specific content type but don't have access to any other content types or the admin section.

There's also a permission 'View the administration theme' if this isn't set for a particular role, but they can add content, then the Create Content page will use the default theme. There's also a setting at the bottom of the appearance page, if you deselect 'Use the administration theme when editing or creating content' then everyone who accesses the create content pages will use the default theme also.

# Answer
> 0 votes
You can allow anonymous users to submit content using the node/add form, but consider some precautions:

* Keep the nodes unpublished (if possible) until an admin can approve
* Any text box should have limited HTML options
* Any links should be set to rel="nofollow"
* Set up a rule to email an admin whenever node of that type has been added

---
Tags: users, nodes, forms
---


title: Can't change theme on view in Drupal

text:
# Question
Title: Can't change theme on view in Drupal
I have just create a view with a page as a display. There is a theme option under the advance setting. I change the theme and save the setting. However the theme I saw didn't change at all. Can anyone advise what went wrong? Actually, I look at the them option again, it didn't being saved even I have saved.

# Answer
I think you're misunderstanding what the theme link in the advanced section of views. It is meant to help themers choose the right template file, show which template file is being used and get quick access to the default template code.

In order to change the theme on a specific Drupal page, take a look at the ThemeKey module.
> 1 votes

---
Tags: views, theming
---


title: Importing a feed from a filefield?

text:
# Question
Title: Importing a feed from a filefield?
I'm ultimately needing a way to regularly upload and parse through a multi-page spreadsheet and then summarize some data from it.

After trying Sheetnode (and disliking its Excel importing implementation, which creates a new node for each sheet in the spreadsheet), I'm thinking the Data module coupled with Feeds might be the best solution.

However, I'm needing some way to download the original spreadsheet after parsing. Ideally, this would mean the user adds a spreadsheet to a filefield and hits upload, after which the original is stored in that field and Feeds API is starts to do its magic.

To this end, **is there any way of having Feeds import from a file uploaded via the Field API instead of through Feeds' import page?**

(Or alternately, the user uploads via Feeds' Import page and the original spreadsheet is then stored in a fieldfield -- either works.)

Many thanks!

# Answer
Here's how I did this:

1. Create content type called "Report"
2. Add File field
3. Create a Rules action that uses PHP Excel Reader to parse through the spreadsheets, storing stuff from one sheet in a Data table, other stuff (Mainly row counts) into a serialized text field.
4. Display content as needed via Views templates.
> 0 votes

# Answer
well bottomline is:

You want to import a spreadsheet (maybe with multiple sheets in it) on a regulary basis.

I'd suggest the module migrate, you find the possiblility to import csv-files (and also an example if i remember right).

Migrate has maybe a little more effort in the start, but it also has many nice features like a hightwatermark, means if there is a counter or a timestamp in your file (for each record), then migrate can skip easily over former imported items.

Also tranformation of data is (if neccessary) with migrate possible.

At least you should have a close look at the module migrate.
> 0 votes

---
Tags: feeds, entities, files, database
---


# Question
Title: Pulling content from other nodes into a Panel Node
I'm using Panel Nodes\* to let users create content with varying layouts. I'm wanting to display another node in one of the panels.

When I create the Panel Node and go to create a new Content pane, I click Entity then Rendered Node. However, the Entity dropdown only lists "This node". If I click Node instead and then try to insert a Node Content panel content type, the Node dropdown is still "This node". What am I missing?

I've tried using EntityReference to associate a Panels node with the other content type, but it doesn't increase the options available to me.

**Any idea how I'd render a node from another content type in a Panel Nodes Panel?**

Thanks!

`*`Yes, I know I should use Panelizer, but I'm wanting to know if there's a way to do this without converting everything I've done thus far to that.

# Answer
When you add an Object to your Panel Pane, you will find in the left column the option to add an "Existing node", choosing this, you can add a node id of the content you want to add.

If you want to dynamically provide different nodes provided by the user input on the node form using a node reference field, you need to add a context to the panel by using this reference field and then the referenced node will also be available.
> 4 votes

---
Tags: 7, panels, nodes, entities
---


# Question
Title: Using "Security Review" gives file permission errors, how to fix them?
I've searched the drupal docs and all over the internet, but I don't find a concrete answer regarding what file permissions the drupal directory should have.

I've been redirected to this page: http://drupal.org/node/244924

On almost every search, but this page doesn't actually tell me what each file's permission should be. I'm trying to pass "Security Review's" permission test, but it literally says ALL my files have wrong permissions.

I know its a very specific question, but can anyone give me a specific CHMOD number for each directory and files in the directories?? I've spent a good portion of the day looking for this with no success..

# Answer
If your webserver user is the same as your account user that you use to login and update the files, then the files should be 440 and folders 550. However, this will make it hard to edit or update the code of the site as you will have to change the permissions back to 755/644 before doing the update.

Note, also, that using anything other than 0 as the final digit in the three is likely the wrong value on a shared server where you do not know/trust every user of the server.

The security review test is about "defense in depth" that prevents a poorly coded file-upload tool from becoming a way to overwrite executable files in Drupal's installation. Sometimes it's OK to ignore some of the reviews from security\_review module.
> 4 votes

# Answer
You should have 755 on directories and 644 on files, try this on your root directory:

Directories,

```
find /path/to/base/dir -type d -exec chmod 755 {} \;
```

Files:

```
find /path/to/base/dir -type f -exec chmod 644 {} \;
```

another important thing is ownership which is depend on your server configuration. please update your question and add more details about your server.
> 2 votes

---
Tags: files
---


# Question
Title: Mark a location on a map (Google Maps/OpenLayers) on a node creation or edit page - but with which module?
I have a custom content type, and I would like my users to **mark a location on a Google Maps/OpenLayers map, save these coordinates**, and on the frontend, show the location's map and the GPS coordinates.

So the user has the opportunity to just simply click on the map somewhere, and mark a location. BUT if the user wants to, he/she can also type an address, and geocode it. (In this post, the OP just wants the latter opportunity.)

I would also like to have a page where the different locations are listed, which are related to the given nodes. Plus maybe some search opportunities.

Geolocation Field seems correct, but I'm a bit confused whether the other modules are better for this task, or what's the difference between them.

The possible modules:

---

(For example, Get Locations looks promising because of the many opportunities. But OpenLayers too... Geolocation Field seems like a little simpler, but also with less opportunities (concentrating on just marking a place on the map). By the way, I don't really understand Get Locations field's module page, firstly it states that it has *"Support for Geolocation (Drupal 7)"*, but later there's the following sentence: *"Please note* \- *Do not install the `Location` module or the `Geofield`, `Addressfield` or `Geolocation` modules at the same time as `Getlocations_fields`, this will not work."*)

# Answer
I had a good experience with Geolocation Field.

I used this module on dealing website to show location of store. It lets you mark location via node creation/edition form and have display formatter to rendering the address as PNG or Google map.

It was simple and good enough.
> 3 votes

---
Tags: google-maps, javascript, entities, location
---


# Question
Title: Provide User with list field of images to select
I am using the flexslider module in conjunction with the views slider to create a slideshow on my Drupal project. Instead of just allowing the user to upload an image for the slideshow (the image really just acts as a background), I would like to provide the user with a list of possible images to choose from. I'm new to Drupal, so this is probably a really easy thing to accomplish, but multiple Google queries have left me in the dark.

# Answer
> 0 votes
I previously used IMCE for FileField module:

it opens a simple file browser and let you select files from configured path of server.

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


# Question
Title: Custom content type with a gallery and its "subgalleries" (or categorized gallery) in D7
I have a content type with some custom fields, and I would like to have a gallery in it, with the images grouped into predefined "categories" - like a "subgallery".

For example, I have a *"building"* content type, and I would like to categorize the photos of it depending on of which part of the building (house) these photos were made or if they are simply *archive* photos, etc.: you can think of categories e.g. like *"Inside"*, *"Outside"*, *"Archive"*, *"Misc."*

I made a drawing to make it clearer:

What would be the best way to solve this problem?

Thanks for any kind of ideas!
Ask if anything is unclear.

---

In the meantime, I found a Media Gallery issue related to the topic: New feature: Gallery containers (other related issues: Hierarchical galleries, Categorizing galleries)

# Answer
I don't know how well exactly this will fit in with your use case, but this is how I'd do it:

* Create a content type called "*SubGallery*", add an **Image** field to it with **unlimited** cardinality.
* Create the content type you want to contain the sub-galleries ("*Building*")
* Add an **Entity reference** field to the "*Building*" type that references an **unlimited** number of "SubGallery" nodes.
* Choose "**Inline Entity Form**" as the widget for that field, which will allow users to create the "*SubGallery*" content types within the same form as the "*Building*".

You can make use of the standard node title field for the name of the sub-gallery, or you might add a vocabulary called "*Gallery Type*", and add a field referencing that to the "*SubGallery*" content type. Then when your users add a new sub-gallery via the inline edit form, they can choose one of your pre-defined gallery types to associate with it.

If you do add the vocabulary and no longer need a node title for the sub-galleries,you could use Automatic Nodetitles to fill it in automatically and hide it from the users.
> 3 votes

---
Tags: entities, files, media
---