# Question
Title: Views - Rewrite Content:Link field based on content type
I'm using Content:Link as a field in a view to make a link button in a list of content. How can I rewrite the results based on content type?

For instance, if the content type is an Article, it would say "Read More" but if it's a Product Display, it would say "Buy Now".

Thanks! :)

# Answer
> 0 votes
I think you need Views Conditional Field module for this. Based on condition show other field which will output different text.

Module page explains :

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> ```
> Equal To
> Not Equal To
> Greater Than
> Less Than
> Empty
> Not Empty
>
> ```
>
> Views conditional allows you to output text based on the result of the condition.

---
Tags: nodes, views
---


# Question
Title: Drupal not able to make any outgoing HTTP requests
So, my drupal setup is on a NAS architecture. It's a portal for a college department and is hosted on the campus NAS. This basically means that my web server has to connect through an internal proxy within the campus to be able to connect to the internet outside.

I have Drupal 7.16 and I've still not performed a core update to the latest version of 7. Here are the issues I'm facing:

1. No update status or available updates for any of the modules and core - My drupal is simply not able to receive any update information what so ever. I keep getting "No available updates found" or "No available update data" whenever I try to check manually
2. Not able to install any modules directly from the URL - Whenever I try to paste a module's url, I keep getting the following error: "HTTP error 110 - Unable to fetch package". I'm still installing all modules manually by extracting and moving them to the modules folder.
3. I have the module mollom installed to moinotr spam comments, but I haven't been able to get this module working. This is the error that I get when I go into mollom's configuration page: "The Mollom servers could not be contacted. Please make sure that your web server can make outgoing HTTP requests."

So, keeping these three issues in mind, I think the main issue is the fact that either my Drupal or my web server aren't able to make any outgoing HTTP requests to any URL.

Here's what I think could be the causes for this issue:

1. Proxy settings? - Should I change the proxy settings for drupal somewhere? I have Drupal 7.16 which doesn't have proxy support unless you install this patch: http://drupal.org/node/7881#comment-4134240 But installing the patch didn't make any difference. I still get those errors. Should I also be asking my system admin to setup a dedicated user for the drupal's proxy settings? How would this work?
2. Folder/file permissions - I've checked the folder permissions and don't think it's the issue here, but maybe I'm wrong
3. Apache not able to make outgoing HTTP? - Could this be an issue with Apache? I've also tried using wget on the server and it works without any issues. I also tried running a php script like this(since cURL is not installed on my server and I would have to ask my system admin for it):

$content = file\_get\_contents('http://www.example.com/test.html'); var\_dump($http\_response\_header);

This script ran without any errors whatsoever.

I'm really not sure what the issue is here, and when I go ask my system admin to add/remove packages or change config files, I need to be making some sense. So can someone please tell me what the issue I'm facing here is?

Thanks,

Kaushik

# Answer
> 0 votes
Ok so, my server didn't have defined proxy global variables like http\_proxy, https\_proxy etc. I had to setup that and then filled in my proxy details in default.settings.php and voila!! It's all working now :)

---
Tags: 7, proxies, http-request
---


# Question
Title: Views date field does not follow custom date format
I have a custom date format defined (via code), and this is what I see in the administration pages:

Custom Date Formats (png screenshot)

In views, I've attached a field, and trying to use a formatter, but they're all showing up like this:

Views Date Format (png screenshot)

I can't seem to select my m/d/y feature, and even the default (short, medium and long) are strange. I have tried clearing caches, and the usual. The view is being exported with a feature, and I have not tried recreating it, yet. Any ideas?

Here's the code generating the custom date format:

```
/**
 * Implements hook_date_formats().
 */
function custom_date_formats()
{
  $formats = array();

  $formats[] = array(
      'type' => 'm_d_y',
      'format' => 'm/d/Y',
      'locales' => array(),
  );

  return $formats;
}

/**
 * Implements hook_date_format_types().
 */
function custom_date_format_types()
{
  return array(
      'm_d_y' => t('m/d/Y'),
  );
}

```

# Answer
> 1 votes
I still did not find the answer to this problem, but fixed it. I fixed it by simply saving the custom date format form in Date & Time in Drupal. Simply submitting that form, without making any changes, refreshed the Drupal views, and it started working properly.

I will look into the submit handler to see what caused the problem, and post if I find anything.

# Answer
> 0 votes
In my case, I had to manually do what you did AND ALSO manually set a variable using `variable_set()`.

For example, if (as in your example) your date format's "type" is "m\_d\_y" and the format is "m/d/Y" then you'd need to do:

```
variable_set('date_format_m_d_y', 'm/d/Y');

```

After that, the Views should start working, and no manual work is required like saving a form.

That said, this doesn't seem ideal, and I'm wondering if I'm just missing a hook or something, but at least it works and it can be automated.

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


# Question
Title: Receiving notifications when user edits a node?
Newbie here! I'm running a site on Drupal 7 (iloveqatar.net) and users have the ability to submit their own content (News, Events, etc...).

I'm facing a couple of issues.

1) When users submit new content that's in moderation to be approved, I don't get any notification. What's the best module to a) send emails to moderators / admins so they're aware there is content that needs to be approved and b) Display the notification on the site (like an unread message counter).

Right now I click on "Needs Review" on the admin bar on the top of the site every few hours just in case theres new content.

2) This one is the more problematic issue. When a user submits an event for example, and it's then approved, the user still has the ability to edit his/her post, which then creates a draft that needs to moderated and approved. However since it's creating a draft of an existing note, I'm not seeing it under the 'needs review' table. I actually have to go to that specific event and then edit it to approve the changes. Of course that's no good for me, because I can't go around checking every single post just in case there's an edit.

Does anyone know of a solution for this so that I can get notified and/or it shows up in 'needs review' ?

Please do let me know if I need to include any additional information to get help.

Thank you so much in advance!

# Answer
Newer versions of the Workbench Moderation module integrate with Rules. I am not sure if the patch is in the stable tree, or whether you need to use the dev version, though.

Assuming you have a version that supports this, then

* add a new rule
* for the reaction, choose **Node: After moderation transtion**
* for the action, choose **Send mail**
* if needed, you can add conditions based on the old and/or new moderation state.

After that, just configure the conditions and the email that gets sent out.
> 0 votes

# Answer
Notify module is good solution for your 1st problem.It is sending mails when any new content or comment added into your site. Check the module on https://drupal.org/project/notify.
> 0 votes

---
Tags: nodes, notifications
---


# Question
Title: Missing icons with CKEditor for Drupal 7
I've recently installed CKEditor 4 for Drupal 7 module and some of the toolbar's icons don't seem to show up.

They are: Add Media Media Teaser Break and YouTube (to name a few).

I've cleared the Drupal and Browser cache, but that hasn't helped. I've also ensured that I've got the right skins (reuploaded just in case). I tried multiple skins and these same buttons don't seem to want to appear.

Does anyone have any ideas for how to resolve this issue? Test thread is here. http://iloveqatar.net/forum/content/test-0#comment-36224

(Note, I installed CKEditor because I needed an easy solution for users to upload multiple images when created a post so I'm not really attached to CKEditor if someone has a better idea. I was using TinyMCE with the WYSIWYG module)

# Answer
Try re-upping the CKeditor library (not the module) and double-check that the owner/file permissions are set correctly on the server.

I believe TinyMCE also works with CKeditor. If you only need to attach images to content and don't need a WYSIWIG editor for your input area, you can add an Image or File field to the content type. If you're using a File field, you might also want to look up the File Entity and Media modules.
> 0 votes

# Answer
* You should check your browser console if there are any js errors appearing.
* also check in your wyswig profile page that you have checked the check-boxes for buttons to appear.
* Even if its not appearing it then you need to write some custom module code to add your buttons on toolbar.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: List 2 fields of a content type and group them based on one of them with views
I have on coupon content type with 2 fields. One is named "Campaign Owner" and the other one "Campaign Name". One owner might have several coupons generated by the site for a campaign. So the owner will have for example 20 coupons with the same campaign name. I want to create a list of campaign names and group them with campaign owner. So the list should be something like this:

## JACK(Owner Name)

1. Camp1
2. Camp2
3. Camp3

## JOE (Owner Name)

1. camp4
2. camp5
3. camp6

I've tried to create this with views but what I get is not what I'm looking for. Here is it:

## JACK

1. Camp1
2. Camp1
3. Camp1
4. Camp2
5. Camp2
6. Camp2

## JOE

1. Camp4
2. Camp4
3. Camp4
4. Camp5
5. Camp5
6. Camp5

As you can see. It lists all the similar campaign names. But kneed to get rid of the similar items. How can I do such a thing?

# Answer
> 0 votes
The answer is "views distinct" module which checks the values of each row and then removes/aggregates the similar ones.

---
Tags: views, entities
---


title: Format plural problems in Views module

text:
# Question
Title: Format plural problems in Views module
I built a Drupal 7 site using the Views module and I am using the "comment count" field.

If I choose the format plural checkbox, with a comment, it will output "1 comment", and when there are zero comments, 2 or more comments, it will output the number of comments followed by *comments*. If I want to output "no comments yet" when the comment count is 0, I can use the "No result behavior (Count the number 0 as empty)" option.

The problem is that the format plural option is not working together with the "No result behavior" option. When I use both of them, I get "0 comments" instead of "no comments yet."

How can I achieve my goal?

# Answer
> 3 votes
I managed to get this working by using the following settings for the **Content: Comment count** field:

* **Format plural** checked
* **Singular form**: @count *comment*
* **Plural form**: @count *comments*

Under **No results behavior**:

* **No result text**: *no comments yet*
* **Count the number 0 as empty** checked
* **Hide if empty** checked
* **Hide rewriting if empty** checked

---
Tags: views, comments
---


# Question
Title: How can I make my main menu link text dynamic?
How can I make my main menu link text dynamic?

**My solution:**

I tried to use Felix's answer, below, but it would not work for me. Obviously, the method suggested by Felix has worked for others and it is used in core (`user.module`, for example). However, I was able to conditionally alter my main menu link text at the theme level. I added this to template.php:

```
/**
 * Conditionally alters preprocess links variables.
 */
function MY_THEME_preprocess_links(&$variables) {
  if (MY_FUNCTION()) {
    if (isset($variables['links']['menu-562 active-trail']['title'])) {
      $variables['links']['menu-562 active-trail']['title'] = 'New blog';
    } elseif (isset($variables['links']['menu-562']['title'])) {
      $variables['links']['menu-562']['title'] = 'New blog';
    }
    if (isset($variables['links']['menu-563 active-trail']['title'])) {
      $variables['links']['menu-563 active-trail']['title'] = 'New notes';
    } elseif (isset($variables['links']['menu-563']['title'])) {
      $variables['links']['menu-563']['title'] = 'New notes';
    }
  }
}

```

# Answer
Drupal menu's are cached and this makes it hard to change then on the fly when the page is rendered. It is possible though using the functions aimed at translating menu items: see hook\_translated\_menu\_link\_alter.

This hook is called before every menu item is rendered IF it has the property `['options']['alter'] = TRUE`.

You can set this property to menu items using hook\_menu\_link\_alter.

Example code would be:

```
function MY_MODULE_menu_link_alter(&$item) {
    // add in an if statement here to just target the links you want to change on the fly
    $item['options']['alter'] = TRUE;
}

function MY_MODULE_translated_menu_link_alter(&$item, $map) {
    if($item['mlid']==89) {
        // this line is actually to change the link however if you inspect the $item
        // variable then you will be able to see the other property that you can change.
        $item['link_path'] .= 'my-new-path';
    }
}

```
> 5 votes

# Answer
If you want to change the menu link text for an existing menu item, you could also use

`hook_menu_alter`

and add a different `'title callback'`

e.g

```
/**
 * Implements hook_menu_alter
 */
function MODULE_menu_alter(&$items){
  $items['node/add/blog']['title callback'] = 'MODULE_blog_title_callback';
}

/**
 * hook_menu title callback
 */
function MODULE_blog_title_callback() {
  if ($some_condition) {
    $title = "New blog post";
  }
  else {
    $title = "New alien lifeform";
  }
  return $title;
}

```
> 0 votes

---
Tags: theming, routes
---


# Question
Title: Multiple Ubercart? Trying to do a multi-seller site.
Hello Drupal community. I'm trying to create a seller's site. This is what it needs to do:

A seller will have his own system in which customers can buy him directly.

The products that the seller will sell will be in common from all the sellers. But each seller will need to be able to set his own price.

I found ubercart (I found it amazing!!!), and it does much more than I'm asking for. I would like to know what should I do? Write a module from scratch? Extend Ubercart? Is there a multiple ubercart possibility?

Thanks for the replies!

# Answer
> 1 votes
Have a look at Marketplace.

The modern alternative to ubercart is commerce and there is a marketplace module too, though it's still in beta.

---
Tags: ubercart
---


# Question
Title: Authcache Caching Cancelled due to php error
I have authcache installed on my Drupal site that runs on commerce(not Kickstart)

On all the page I am getting

```
Cache Status: "Caching CANCELED"
Message 1: "Canceled: PHP Error: "

```

I enabled database logging but I don't see any additional information there.

My pages are rendered properly and there is no errors being displayed on the page. So I am curious about the source of PHP Error that Authcache keeps referring to.

# Answer
> 2 votes
Ironically there is an error in the error-reporting code of Authcache 7.x-2.0-beta2. Apply the patch from issue #2161095, after that the PHP error message will be displayed correctly by the debug widget.

---
Tags: caching
---


# Question
Title: Drupal module to generate compressed xml sitemap
Is there any Drupal module which can generate compressed xml sitemap like sitemap.xml.gz? The problem is I have a site with a lot of pages and the generated sitemap is very big (more than 1 MB). I have "404 not found" errors in google webmaster tools for the sitemap, but when I open the address mysite.com/sitemap.xml the sitemap is displayed after more than 5 seconds. When I test my sitemap with google PageSpeed Insights it tells me to activate compression and I will reduce the data transfer for this file with 92%. I activated compression on Nginx and now it is compressing everything but the sitemap. Now I am searching for a module generating compressed sitemap. I am usung Drupal 7 with Nginx and xmlsitemap module for generating sitemap

# Answer
You can separate you sitemap.xml into several sitemaps. Each of this maps will be a smaller than one big sitemap.

Go to `admin/config/search/xmlsitemap/settings`, in Advanced settings in Number of links in each sitemap page choose, for example, 1000 and regenerate you sitemap.
> 1 votes

---
Tags: 7, xml-sitemap
---


title: Drupal 6 and file upload problems

text:
# Question
Title: Drupal 6 and file upload problems
We have an old site running Drupal 6. When we try to upload a file via the interface, the ajax uploader spins, and reloads the "Choose file" dialogue. Checking the recent error log I get:

```
The file upload failed: field_small_banner_0

```

If I go into the location URL (?q=filefield/ahah/gallery/field\_gallery\_image/0) I get:

```
{ "data": "\x3cdiv class=\"messages error\"\x3e\nAn unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (64 MB) that this server supports.\x3c/div\x3e\n" }

```

I've seen mentions of ModSecurity but this is not active. I've checked the permissions of the files folder and this is 777.

I've checked phpinfo for the temp folder and that's set to /tmp

Many thanks :)

# Answer
> 0 votes
How big is the file? The error msg says you likely exceeded the 64MB limit. Can you upload a 1MB file?

If you can upload a 1MB file, then your solution is going to be to increase the server limits on max upload size (see your php.ini file) to allow files of the required size to be uploaded.

---
Tags: files
---


# Question
Title: Panels Pane Content Added - Stacked, need Inline
Hi I'm developing an Intranet in Open Atrium - Drupal 7. The distribution is heavy on Panels, so I am developing the Portal with them. However I have a Pane for one of the Panels and I want to upload 4/5 separate blocks into it. However the default behaviour is everything is stacked in the pane, and I would like to be able to control it so I can lay things out side by side, is there a way to do this within the Drupal System. At present I am using Negative Relative Positioning to move things where I want them. Then specifying a height for the body to get rid of the negative space it leaves - not ideal. I can't use Negative Margins because the company where the Intranet is uses a lot of IE7 and IE7 doesn't recognise negative margins.

# Answer
> 0 votes
You could use custom panel layouts (use the builder option) and create the regions you want with the size and position you want.

---
Tags: panels, theming
---


title: JQuery FadeIn effect and Omega Theme

text:
# Question
Title: JQuery FadeIn effect and Omega Theme
I am trying to use the fade in effect in Drupal when I load a page.

In my Omega sub-theme I have included the following line in its .info file.

```
scripts[] = '/js/custom.js'

```

In the script, I have included the following code.

```
$(document).ready(function() {

$("body").css("display", "none");
$("body").fadeIn(2000);

});

```

If I load the page, I see no effect at all, but I clearly see that my JavaScript is in the header.

```
<script type="text/javascript" src="http://localhost/innodru/sites/all/themes/CHILDTHEME/js/custom.js?m2zpiw"></script>

```

I have cleaned the cache and tried a lot of things, but it does not look like is working. I am using Drupal 7.

# Answer
You should not be using document.ready. Instead you should use drupal behaviors. Even though document.ready will work. Behaviors is the drupal 7 way to do things as these behaviors get called after ajax calls too.

**css**

```
body {display:none;}

```

**javascript**

```
(function ($) {
    Drupal.behaviors.fadein = {
            attach:function(context, settings){
                    $('body', $context).once().fadeIn(2000);
            }
    };
})(jQuery);

```

**And FYI**
Omega adds a 'responsivelayout' event that will get fired every time the layout is set/changed including when the page loads so you could potentially make the page display straight away on mobiles and fade in on others.

```
(function ($) {
    Drupal.behaviors.fadein = {
            attach:function(context, settings){
                $('body', context).bind('responsivelayout', function(e) {
                    if($('body', context).hasClass('responsive-layout-mobile')){
                            $('body').once().show();
                    }else{
                            $('body').once().fadeIn(2000);
                    }
                });
            }
    };
})(jQuery);

```

I have not tested the code BTW, but you get the idea
> 1 votes

# Answer
In Drupal 7 you need to wrap your jQuery in another function to use the $ alias. See https://stackoverflow.com/questions/4681309/using-jquery-in-drupal-7

```
(function ($) {
  $(document).ready(function() {
    $("body").css("display", "none");
    $("body").fadeIn(2000);
  });
})(jQuery);

```

But trying to fade in the entire body of a page sounds dubious, especially with the Omega theme which contains a lot of special JS and CSS to handle automatic re-sizing... I don't know how friendly your fade in will play with the resizer stuff from Omega.
> 0 votes

# Answer
I set the css to

```
body {
   display:none;
}

```

and then display it with a script

```
 (function($) {
        $(document).ready(function() {
        $('body').fadeIn();
    });

    })(jQuery);

```
> 0 votes

---
Tags: theming, javascript
---


title: Bulk import images & create nodes

text:
# Question
Title: Bulk import images & create nodes
Is there a way to bulk import images from server and auto create nodes for each image? this is for Drupal 7

# Answer
> 0 votes
The module Bulk Media Upload is the one that I have used in the past for that matter. From the module page:

> With Bulk Media Upload you can upload a bunch of files and a new node, taxonomy term, or other entity will be created for every file. The files are selected via a browser file upload dialog and can be stored in a file or image field. Also default values can be chosen for the other fields assigned to the new node.

I believe you will not have any difficulties, it is pretty straightforward. Also, if you come across some minor bugs, I have a couple of patches commited in its issue queue awaiting community review.

Alternatively, one can use the Feeds module to import nodes. That would be more helpful with existing files. It might require to list the files into a CSV file (for \*nix systems copy/paste from terminal the output of `ls /path/to/files`).

---
Tags: media, importing-exporting, batch-operations
---


# Question
Title: check other commerce pane validation error
I am work on commerce pane, in `hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order)` I call a function to do something in pane sumbit,

something like

```
function hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {

  do_update_something($user);
}

```

but when I am not fill another pane like address , my function called, How can I prevent submit when there is error (validation in another panes) in other panes?

# Answer
> 1 votes
check errors before call your function

```
function hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
if (!(form_get_errors()){
 do_update_something($user);
}

}

```

---
Tags: commerce, forms
---


# Question
Title: Use Timeago date format for less than 24h ago only
I would like to use the Timeago module as a date format. However, when the time ago has exceeded 24h, I would like it to show another format (e.g. 4 Feb, 2013) much like Twitter or Dribbble use.

I tried to tweak the code, but my skills let me down :/

Is there possibly a better module for this cause? Or do I have to make my own?

I found this code that shows how I want it to work, however I have no idea how to implement this to drupal.

Any help is appreciated, thanks.

# Answer
Do users really sit on a page for a long enough time, that these dates need to be updated via javascript? Most of them will click on something and end up reloading the whole page at some point. So perhaps, a php solution is an option too?

You could achieve the php solution by using the Custom Formatters module.

If you create a new php type custom formatter, with the following code (make sure it's a datestamp type):

```
$element = array();
foreach ($variables['#items'] as $delta => $item) {
  $unixstamp = $item['value'];
  $time_since = mktime() - $unixstamp;
  if ($time_since < 86400) {
    $date_str = format_interval($time_since);
  }
  else {
    $date_str = format_date($unixstamp, 'custom', 'jS F Y');
  }

  $element[$delta] = array(
    '#type' => 'markup',
    '#markup' => $date_str,
  );
}
return $element;

```

When creating the formatter, make sure you select field type 'datestamp'. Once the formatter is created, then in the manage display tab of your content type, set the field to use this formatter.

If you don't have your date stored as a separate field, you might be able to apply the custom formatter to the node modified time, by installing the Display Suite module.

If you don't want to use any of these modules but want to hack some php into your theme or something, you can still use the same logic above with format\_interval and format\_date functions.

Hope that can help.
> 2 votes

# Answer
Wherever it is that you are using timeago to show a formatted date, will a snippet like the one below do the trick for you?

```
// Assume $timestamp has the raw Unix timestamp that I'd like to display using
// the "timeago" date format supposing it is within the last 24 hrs and another date
// format - "my_date_format" otherwise.
$rule = ((REQUEST_TIME - $timestamp) <= 24 * 60 * 60);
$fallback = format_date($timestamp, 'my_date_format');
return ($rule ? timeago_format_date($timestamp, $fallback) : $fallback);

```
> 0 votes

# Answer
Create A MyCustom Module

myCustom.module contains

```
/**
 * Implements hook_date_formats().
 */
function myCustom_date_formats() {
  $formats = array('g:i a', 'H:i', 'M j', 'j M', 'm/d/y', 'd/m/y', 'j/n/y', 'n/j/y');
  $types = array_keys(myCustom_date_format_types());
  $date_formats = array();
  foreach ($types as $type) {
    foreach ($formats as $format) {
      $date_formats[] = array(
        'type' => $type,
        'format' => $format,
        'locales' => array(),
      );
    }
  }
  return $date_formats;
}

/**
 * Implements hook_date_format_types().
 */
function myCustom_date_format_types() {
  return array(
    'myCustom_current_day' => t('MyCustom: Current day'),
    'myCustom_current_year' => t('MyCustom: Current year'),
    'myCustom_years' => t('MyCustom: Other years'),
  );
}

/**
 * Formats a timestamp according to the defines rules.
 *
 * Examples/Rules:
 *
 * Current hour: 25 min ago
 * Current day (but not within the hour): 10:30 am
 * Current year (but not on the same day): Nov 25
 * Prior years (not the current year): 11/25/08
 *
 * @param $timestamp
 *   UNIX Timestamp.
 *
 * @return
 *   The formatted date.
 */
function myCustom_format_date($timestamp) {
  if ($timestamp > ((int)(REQUEST_TIME / 3600)) * 3600) {
    return t('@interval ago', array('@interval' => format_interval(abs(REQUEST_TIME - $timestamp), 1)));
  }
  if ($timestamp > ((int)(REQUEST_TIME / 86400)) * 86400) {
    return format_date($timestamp, 'myCustom_current_day');
  }
  if ($timestamp > mktime(0, 0, 0, 1, 0, date('Y'))) {
    return format_date($timestamp, 'myCustom_current_year');
  }
  return format_date($timestamp, 'myCustom_years');
}

```

Create myCustom.install & it contains

```
/**
 * @file
 * Install file for myCustom.module
 */

/**
 * Implements hook_install().
 */
function myCustom_install() {
  // Define default formats for date format types.
  variable_set("date_format_myCustom_current_day", 'g:i a');
  variable_set("date_format_myCustom_current_year", 'M j');
  variable_set("date_format_myCustom_years", 'n/j/y');
}

/**
 * Implements hook_uninstall().
 */
function myCustom_uninstall() {
  variable_del('date_format_myCustom_current_day');
  variable_del('date_format_myCustom_current_year');
  variable_del('date_format_myCustom_years');
}

```

Usage :

```
echo myCustom_format_date(1392532844);

```
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: How to hide certain items in a term reference field?
I have the taxonomy 'Types' with terms A, B and C. I've added a term reference field 'Type' to the users with the 'Types' vocabulary. Now, when people register, they can choose between A, B and C in the 'Type' field, but I'd like them only to be able to choose between A and B.

How can I hide the third option?

# Answer
> 4 votes
You can use the Entity reference module to achieve this goal.

1. Install Entity Reference module.
2. Create a view of terms, with a display type of Entity Referance, and your filters/conditions
3. Create a field of Entity Reference type.
4. In field settings: Choose its target type is Taxonomy Term.
5. In entity selection mode choose 'Views Filter by an entity referance view'. Choose the view you created above in 'View used to select entities'.
6. Now save it.

# Answer
> 0 votes
With core features, I believe you can't hide certain fields from being selected in the field.

Term Reference Filter By Views is a handy module for this. Install the module, and create a View (taxonomy terms) and add whatever filter you want to use to hide the terms that you don't want to make available (a Term ID exclusion will do). You will need to use a certain Display (read module's doc) in the View.

In the front end, user will be able to autocomplete or select the terms, but the list/pool is generated through the View, so your filters are applied automatically.

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


# Question
Title: How do we know the required parameters of hook's callback method?
I am working on creating a filter module starting with the hook\_filter\_info file. This hook requires a callback method via a 'process callback' filter setting.

Now the problem is: how do I know what parameters that this callback method requires? I have taken a look at filter.api.php and see this:

```
function hook_filter_FILTER_process($text, $filter, $format, $langcode, $cache, $cache_id)      {
$text = preg_replace('|\[codefilter_code\](.+?)\[/codefilter_code\]|se', "<pre>$1</pre>", $text);
return $text;
}

```

but I have seen this callback filter called like this :

`mymodule_process($text, $filter, $format);`

`mymodule_process($text, $filter, $format, $language);`

`mymodule_process($text, $filter, $format, $language, $cache);`

...

Now how do I know the amount of arguments that this method requires? Or does it require any argument at all?

# Answer
> 0 votes
I've never had to use this specific hook before, but I have found a breakdown of the callback in the Drupal docs:

https://api.drupal.org/api/drupal/modules!filter!filter.api.php/function/callback\_filter\_process/7

Pretty sure everything you're after will be described in the documentation. You can view all the other Filter API functions within the documentation here:

https://api.drupal.org/api/drupal/modules!filter!filter.api.php/7

---
Tags: 7
---


# Question
Title: Custom Top Admin Menu: Intergrating Permissions
Looking into build a top bar to be used for clients for quick access to edit/add pages. Big question I have is, how do you hook this into the Permissions module in core? Say if I want to allow another user to log in and assign this due to certain permissions.

Is this easily done? Or something a bit much?

```
function mymodule_preprocess_html(&$vars) {
  if (user_access('moderator')) {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css');
    $my_links = array();
    if (in_array('manager', $vars['user']->roles)) {
      $my_links[] = array(
        'title' => t('Add new page'),
        'path' => '/location',
      )
      $my_links[] = array(
        'title' => t('Edit pages'),
        'path' => '/location',
      );
    }
  }
}

```

Seen some things used as below, but having issues...

```
function mymodule_permission() {
  return array(
    'moderator' => array(
      'title' => t('Use these top links'),
      'description' => t('Blah blah blah.'),
    ),
  );
}

```

# Answer
> 1 votes
First of all I assume that the Admin Menu module isn't suffient for your needs? If not then I think you're approaching the custom module in the incorrect way.

Basically all menu routes in Drupal (node/add for example) use access arguments to determine who can access the route in question. So if you're looking to build a custom admin bar, I would rather create a new custom Drupal menu, and then add all my links in there. Then if a user does not have sufficient access rights to a menu route, Drupal will not display that specific link within the menu to the user.

If your menu links are coming from a custom module that you've written, you could apply the following example to include your module's menu items into your custom menu. You would use this within your **hook\_menu** declarations:

```
$items['my/custom/route'] = array(
  'title' => 'Custom module section',
  'page callback' => 'mymodule_custom_page',
  'access callback' => 'mymodule_custom_access',
  'weight' => 0,
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'my-custom-menu-id'
);

```

Using a custom menu instead of using your **$my\_links**\[\] array you included above, will allow greater control over each menu item within the Drupal UI too.

****EDIT: provided further explanation based on comments****

Regarding your comments I still think your approach of implementing access controls within **hook\_preprocess\_html** is not the best way. We should always be looking to separate our application logic from our frontend logic, and using that hook to apply access control goes against that best practise.

I still recommend that you create a custom menu and then add your admin links and restructure as you want it to be. Then set which roles can create each content type within your system from here **/admin/people/permissions**, and Drupal will automatically exclude the link for content types the logged in user doesn't have access to.

With regards to displaying the menu, you can just assign the menu's block to a region within your theme, and use CSS to apply styling and positioning within the browser. You can also adjust the access permissions for the block, so only certain roles will ever see your custom menu. You can do this by editing the **Visibility** settings for menu's block.

Wow I didn't expect this to be such a long winded answer haha! :)

---
Tags: routes, users, performance
---


# Question
Title: Can Panels just be uninstalled if you want to switch themes?
I used panels + panels everywhere with precision theme to build a website.

I now rather want to use Zen theme with basic blocks.

I wish to keep the content types with their fields.

If I uninstall panels will all instances of it be removed from the site? Or should I rather just rebuild the site from a new clean installation?

# Answer
Usually, uninstalling removes everything created by the module, its setting and its database tables.

But for what you are after, you don't even need to uninstall them, not even disabling to be honest, just don't use panels tools in your new theme.

Considering that, I would delay the idea of removing them and the old theme to after the new one is ready. Just because of "how i did it in the other theme?" kind of questions
> 1 votes

---
Tags: 7, panels, theming
---


# Question
Title: Why does a header set via drupal_set_header() revert to text/html?
I'm using the `views_rss` module in Drupal 6. Whenever I build out a View using this plugin, the following header is sent in a `template_preprocess` function:

```
drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');

```

This seems to be ignored, as the page is ultimately sent with a `text/html` header. It seems that my header is getting appended, but `text/html` is either sent first or last (whichever is ultimately interpreted by the browser) and thus has no effect.

How can I force a non-text/html header for a page output in Drupal 6?

# Answer
> 0 votes
I think you are too late in the template\_preprocess hook. The views display will have set it's header already before your hook gets called.

To test my thought have a look at the return value of the function `drupal_set_header`. It shows you all headers sent before.

If I'm right: Try implementing a hook which is is called earlier (maybe even before execution of the view query). Then your header will have precedence.

---
Tags: views, 6
---


title: What does the entity_view function do?

text:
# Question
Title: What does the entity_view function do?
After reading the documentation and searching through code, I can't quite figure out what the entity\_view function is for.

The documentation explains it executes the view callback if defined, with a fallback to the entity controller's view function. Since I use the EntityAPIController I want to use that view function, that adds a similar structure like below.

So I assumed entity\_view is to replace a structure like this (part of a page callback).

```
// Prepare the entities
entity_prepare_view('entity_type', $entity_field_query_result);

// Apply theme to all entities
foreach($entity_field_query_result as $key => $item) {
  $entity->content = array();
  $entity->content += array(
    '#theme'     => 'my_entity_theme',
    '#element'   => $item,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  $render[$key] = $entity->content;
}
return $render;

```

Thus I've replaced that with

```
$render = entity_view('entity_type', $entity_field_query_result);

return $render;

```

This however shows an empty page, where the previous function showed me a list of entities. I have custom themes applied to these entities as follows, could that be an issue?

```
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_entity_theme' => array(
      'variables' => array('element' => null),
      'template' => 'my_entity_theme',
      'path' => $path . '/template',
    ),
  );
}

```

So, is my assumption on entity\_view correct, or am I missing steps to come to a renderable output?

# Answer
> 4 votes
A EntityFieldQuery doesn't return fully loaded entities as result. Try running the query result through `entity_load('type', $result['type'])`. Then you can render the resulting entites through `entity_view('type', $entities)`.

Here an example:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'article');
$result = $query->execute();
if (!empty($result)) {
  $entities = entity_load('node', array_keys($result['node']));
  return entity_view('node', $entities, 'full');
} else {
  return array('#markup' => t('No article nodes found.'));
}

```

---
Tags: theming, entities
---


# Question
Title: Configuring drush alias for rsync with exclude paths and file patterns
I tried adding exclude paths and file patterns to my drush alias; it didn't work, but adding the filters with --exclude= in the command works.

```
drush rsync --exclude=imagecache/* --exclude=ctools/* --exclude=js/* --exclude=tmp/* --exclude=xmlsitemap/* --exclude=*.doc* --exclude=*.DOC* --exclude=*.pdf* --exclude=*.PDF* --exclude=*.ppt* --exclude=*.PPT* --exclude=*.zip --exclude=*.ZIP --exclude=*.xls* --exclude=*.XLS* @sitename.live:%files @sitename.local:%files

```

(I wanted to create the directories but skip the contents)

I looked at a similar question but I'm not sure what I am doing wrong.

The docs for drush core-rsync explain:

> --exclude-paths List of paths to exclude, seperated by : (Unix-based systems) or ; (Windows).

here is what I tried:

```
$aliases['live'] = array(
  'root' => '/var/www/[domain]/htdocs',
  'uri' => '[site uri]',
  'remote-host' => '[host ip]',
  'remote-user' => 'rgoya',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'command-specific' => array(
        'sql-sync' => array(
            'no-cache' => TRUE,
        ),
        'rsync' => array (
            'mode' => 'rlptDz',
            'exclude-paths' => 'css:imagecache:ctools:js:tmp::xmlsitemap',
            'exclude' => '*.tmp',
            'exclude' => '*.doc*',
            'exclude' => '*.zip',
            'exclude' => '*.xls*',
        ),
    ),
);

```

I also tried 'mode' =\> 'azv'

**Also**, can I use regexp in the exclude patterns? some extensions are lowercase, some are uppercase .pdf / .PDF

# Answer
Your subsequent 'exclude' items in the PHP array are overwriting their previous ones, so the example above only has --exclude=*xls*

drush help rsync does not explicitly document the syntax for --exclude but I assume that it's similar to --explude-path and that would mean you should do something like this:

```
'rsync' => array (
  'mode' => 'rlptDz',
  'exclude-paths' => 'css:imagecache:ctools:js:tmp::xmlsitemap',
  'exclude' => '*.tmp:*.doc*:*.zip:*.xls*',
),

```

EDIT: looking into the example.aliases.drushrc.php there is this tip included:

```
// if you need multiple exludes, use an rsync exclude file
'exclude-from' => "'/etc/rsync/exclude.rules'",

```

That's maybe the best way to go.
> 5 votes

# Answer
this is what is working now for sql-sync and sql-dump - have not executed drush-rsync again since it's now unnecessary after my original sync, for the time being

```
$aliases['local'] = array(
'root' => '/var/www/[root dir]',
'uri' => '[uri]',
'path-aliases' => array(
    '%files' => 'sites/default/files',
    '%dump-dir' => '/home/decibelplaces/drush-dumps',
),
'command-specific' => array(
    'sql-sync' => array(
        'no-cache' => TRUE,
        'structure-tables' => array(
            'common' => array(
                'cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog','search_index',[some other custom tables],
            ),
        ),
    ),
    'sql-dump' => array(
        'structure-tables' => array(
            'common' => array(
                'cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog','search_index',[some other custom tables],
            ),
        ),
    ),
    'rsync' => array (
        'mode' => 'avzu',
    ),
),

```

);

with drush syntax:

```
drush sql-sync @yoursite.remote @yoursite.local --structure-tables-key=common --no-ordered-dump --sanitize=0 --no-cache

```

also, to save a sql dump in a specified file with a date

```
drush @yoursite.local sql-dump --structure-tables-key=common --result-file=[path to file result]/local_`date +"%Y_%m_%d-%H:%M"`.sql

```
> 0 votes

# Answer
Drush does not support multiple options with the same key (e.g. --exclude=a --exclude=b) unless the command supports *strict options*. See `drush topic docs-strict-options` for more information on strict option handling. Basically, strict options require that gloabl Drush options appear before the command name, and every option after the command name is passed on without being parsed by Drush. This also means that command-specific options cannot include strict options, as only options from the command line are passed on to rsync as a strict option.

You therefore must use 'exclude-paths' in command-specific options if you would like to exclude multiple items in drush rsync.
> 0 votes

---
Tags: drush
---


# Question
Title: Using setAttributes() returns a fatal error
I have the following code in a rule:

```
$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

```

I need to add a class to the thumbnail picture. I change the code as follows, but I get a fatal error about calling a member function on a non-object.

```
$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));
$image->setAttribute("class", "AnyClass");

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

```

What am I doing wrong?

# Answer
> 2 votes
The error is simply caused from the fact you are trying to access a member function for something that is an object; in fact, `theme_image_style()` is returning a string, not an object. This is true also for Drupal 8.

> Returns HTML for an image using a specific image style.

To set attributes, just use the following code.

```
$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail', 'attributes' => array('class' => array('AnyClass'))));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

```

It works because `theme_image_style()`, as `theme_image()`, accepts a list of attributes to add to the image tag.

---
Tags: media
---


# Question
Title: Print current logged in user without link
I'd like to print out the name of the user that is currently logged in, but not have it be a link.

Currently I have:

```
<?php print l($user_name, 'user/' . $user->uid);?>

```

But this prints out a link to their user profile. Any way to make their name just text and not a link?

# Answer
`l()` is the function that creates a link, so...

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

```
> 1 votes

---
Tags: 7
---


# Question
Title: user_presave doesn't work correctly when new account is created
My users have 2 fields: 'A' and 'B'. The value of the second one depends on the value of the first one and is set by the following custom module:

```
function MYMODULE_user_presave (&$edit, $account) {
    $tid = $edit['field_A']['und'][0]['target_id'];
    if (isset ($account->roles[3])) {
        $B = taxonomy_term_load(8);
        }
        else {
            $B = taxonomy_term_load($tid);
        }
    $edit['field_B']['und'][0]['fid'] = $B->field_B['und'][0]['fid'];
}

```

It works fine, but when an anonymous user registrates himself/herself, it fails: the `if` is evaluated as true and the new user gets the wrong value in 'B'. When I commented out the `if` and only left over the `else` action, it did work, so it has something to do with the `$account`.

What's going wrong and how can I solve this?

**Note:** role 3 is the built-in administrator role.

---

**Edit:** This is my final code after @m1n0's answer:

```
function MYHOOK_user_presave (&$edit, $account) {
    $tid = $edit['field_A']['und'][0]['target_id'];
    if ($account->is_new OR !isset ($account->roles[3])) {
        $B = taxonomy_term_load($tid);
        }
        else {
            $B = taxonomy_term_load(8);
        }
    $edit['field_B']['und'][0]['fid'] = $B->field_B['und'][0]['fid'];
}

```

# Answer
> 2 votes
As stated in the documentation (https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook\_user\_presave/7), you need to check whether the user is being created or not with the following code:

`if ($account->is_new)`

The reason is that `$edit` contains the values submitted, and `$account` contains the existing user data - but on user registration, there is no user that already exists in the database. Your code should check whether new user is being created and in that case assign some default value (like you already have with `$B= taxonomy_term_load($tid);`)

---
Tags: 7, hooks, users
---


# Question
Title: In Drupal 7 Views, how can I display a block on every page of a view?
I am trying to display a SimpleAds block for every page of my view. How can this be accomplished?

Clarification: I would like to display the block once for each page of results. I am using the infinite pager module.

# Answer
Simple:

https://drupal.org/project/block\_views

Also related:

How can I show a block in a view page, excluding it's paginated pages
> 1 votes

# Answer
So your view has a path, right? In the block configuration, at the bottom, where it says "Show block on specific pages, select "only the listed pages."

Then put your path in the box: my-view-path/\*

Or am I misunderstanding the question?
> 0 votes

---
Tags: views
---


# Question
Title: Views contextual filter from custom taxonomy field
I have added a custom field to taxonomy vocabulary. Now I need to use contextual filter from Views to display items that matches that custom field value in URL, e.g. /my\_page/custom\_field\_value . Is it possible with Drupal 7 and Views 3.x ?

# Answer
> 1 votes
Yes! If the view is a view of nodes you have to add the relation based on the term field, than you should have the contextual filter available.

# Answer
> 1 votes
Or you can use a term view with the custom field as the filter and create a relationship to content tagged with the taxonomy term. That way you can modify the title of the view to match the term as well.

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


# Question
Title: Outputting main menu in full in page.tpl.php
I'm using the code below to print my main menu in page.tpl.php:

```
<?php
$main_menu = menu_navigation_links('main-menu');
print theme('links', array(
'links' => $main_menu,
'attributes' => array(
'id' => 'main-menu',
'class' => array('links', 'clearfix'),
),

'heading' => array(
'text' => t('Main menu'),
'level' => 'h2',
'class' => array('element-invisible'),
),
));
?>

```

However, it is only outputting the top-level menus of my navigation. Is there a piece of code I can add that will output submenus too?

# Answer
Calling menu\_navigation\_links() with only the menu name by default provides only the top level links. To delve deeper you need to provide the second `$level` argument, eg:

```
$main_menu =menu_navigation_links('main-menu', 1);

```

will provide the top and next level links, and:

```
$main_menu =menu_navigation_links('main-menu', 2);

```

will provide one level deeper.
> 5 votes

---
Tags: 7, routes, theming
---


# Question
Title: How do I programatically create a Bean 'instance' in code?
I am trying to make a sort of `hook_setup_beans()` function (similar to `hook_setup_blocks()`) to create some bean instances by default when a user turns on a bean\_example module I am making. This would be called from `hook_install()`.

Is there a standard path for doing this?

I am playing with `bean_create()` and `bean_save()` right now.

Thanks

p.s. I also asked this at https://drupal.org/node/2173783

# Answer
Creating bean instance programmatically. https://drupal.org/node/1436186

```
<?php
  $bean = bean_create(array('type' => 'my_bean_type'));
  $bean->label = 'Administrative Label';
  $bean->title = 'Bean Title';
  $bean->delta = 'bean-machine-name';
  $bean->field_block_content = array(
    'en' => array(array(
      'value' => '<p>Text</p>',
      'format' => 'wysiwyg_editor',
    )),
  );
  $bean->save();
?>

```
> 1 votes

---
Tags: entities, installation, blocks
---


# Question
Title: How to set up a date field based scheduled newsletter with Simplenews?
On my Drupal 7 site I have on the one hand a news letter set up with the module Simplenews. On the other hand I have a content type with a date field. Now I would like the newsletter being scheduled by the date field. To be more precise:

The news letter should work as a reminder. Two days before the date saved in one of the date fields the news letter should be send.

How would that be possible. Actually I think, this does not work with rules, as there is not any triggering event, that could generate scheduled rule.

# Answer
You could schedule a rule when the content type with the date field is generated. You'd need to create a rule component that sends the email you want. Schedule the component on content creation with the date field as the execution time.

I'm using this mechanism to delay some heartbeat activities on my site. Works a treat.
> 0 votes

---
Tags: rules, emails
---


title: Template naming /style questions

text:
# Question
Title: Template naming /style questions
Good Morning,

I'm using a custom template for an area where members are logged in. I would like to have a specific template for all pages of the Member content type. I've been able to do this with a page template a la page--node--11.tpl but I don't seem to be able to change the node template to include all the details of the page template (a la the side bars)

Any suggestions for how I can do this with a content type template. I have custom configs for the sidebars and footers for this content type so I'd like to be able to use a general template and not one for each node.

# Answer
> 0 votes
You can have node type specific page templates by adding custom template name suggestions from the template preprocessor then using those template file names.

For more information see Page templates depending on node type.

---
Tags: theming, entities
---


# Question
Title: Is there an option for radio buttons with Facet API + Search API (database)?
I am using several check box facets. Some of the facets allow me to use check boxes for multiple values. There is one facet, however, of taxonomy terms for which I want to only allow a single choice; and per the client's spec, it must be a radio button.

I can't seem to figure out how to do that. I installed the Facet API Select sandbox module, but that just gives me a drop-down box (and what sucks is when I make a selection, I stay locked on that one and don't get the other choices back). I installed Facet Bonus pack, but the select option from that keeps giving me a PHP error.

I am using Views on top of Search API database. It may be that I am missing something conceptually, as I am still getting my arms around Facets.

If there isn't an option for radio buttons, then I will contribute a patch to the Facet API Select sandbox module (if it is feasible). This is for a paid client, so this is happening.

EDIT: I need to clarify my biz case of what I'm trying to do. I have 3 facets with check boxes of multiple items to filter down. On a fourth facet, I provide a list of filters, but need to allow one item to be selected. So, my choices look like:

Facet 1: Type of product \- phone \- tablet \- tv

This would filter down the main product category, i.e., single select option the client wants a radio button for.

Facet 2: Color \- red \- blue \- green \- black

Facet 3, Facet 4, etc., would be like Facet 2, where the user can select multiple check boxes for the various sub categories.

These facet categories are taxonomy terms, if that matters.

# Answer
There is a patch for the Facet API Bonus module that adds a radio buttons widget.

The issue with the patch is https://drupal.org/node/2034777

With this patch you also need to use the Facet API module patch mentioned by RajeevK in the comments of your question, which can be found at https://drupal.org/node/1393928

If you try those patches and comment back in those issues with how it worked out for you it will also help progress those issues so that the patches can be committed and you no longer have to use patched modules - a win for all.
> 1 votes

---
Tags: 7, search
---


# Question
Title: flowplayer with videojs module and video-js
I'm not sure how to integrate videojs module with video-js libraries because at the moment I am using the code for *video-js* to open the *swf player* in my drupal page which works fine. However I can't get it to play *FLV type video* and that is because apparently I need *flowplayer* as fallback from *html5*.

My question is where should I place the *flowplayer* folder in conjunction with the rest? Should it go in `sites/all/libraries` and then I create a content type with field to use videojs module?

Why do I even need videojs module if you can just place video-js javascript code and html code in body of node?

# Answer
As the project page says

If you are using latest videojs module i.e `7.x-2.3` with 3.x video.js version it comes with *Flash* fallback. Video.js library will handle the flash fallback option. You don't need to install *swf tools* or *flowplayer API*. You don't need to place *flowplayer* folder inside *libraries* folder.

If you would like to use flow player API you might need to use `7.x-1.x` version of video.js module. As long as you follow installation instructions here you are good to go with `7.x-3.x` version of module. Make sure you use right library of video.js version vs Module version as shown above and follow instructions in Readme file.
> 1 votes

---
Tags: media, files
---


# Question
Title: Get "File Upload Error" when I try to upload any images to Node
This was and is working fine in my local environment, but when its on the server (hosted by Justhostme) I get this error whenever I try to upload a new image to a node. I've seen advice that it could be my temp directory so I've changed this and set 777 permissions on it. I'm very stuck with this now. I'm not getting any more error message so nothing to hint at what else it could be.

heres hoping.

Edit. I've checked the logs, and these 3 messages appears when I try to upload. The refered to folder has 777 access too. Msg 1.

```
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access public://field/image/leaflet_front.jpg in file_save_upload() (line 1541 of /home/xxx/public_html/includes/file.inc).

```

msg2

```
Upload error. Could not move uploaded file leaflet_front.jpg to destination public://field/image/leaflet_front.jpg.

```

msg 3

```
The file upload failed. field_image_und_0

```

# Answer
There is a long thread in the Drupal.org site surrounding this issue, I didnt locate it at first due to my error message being masked. After many hops around the net I did finally locate it, and it seems to effect quite a few people.

See this link

http://drupal.org/node/1002048

post #154 has a link to the patch for both version 7 and 8 of Drupal.
> 3 votes

# Answer
My site has not been moved yet, so I am speculating here. WHat have you checked so fa?. Was the image directory under your domain directory? If you edit the content and select the image name is it pointing to the correct path for the online directory? Have you spoken to your host about this?

Edit:

I just saw your edit adding the error messages and realize I missed that this was during an upload. I assume the path exists. Does the image fall within the size parameters for uploading the image?
> 1 votes

# Answer
# Need to change permission

you just need to change the permission of file folder in drupal-7.26/sites/default/

=\> *sudo chmod 777 -R files*
> 1 votes

# Answer
## I have not played with either file much yet. Looking through .htaccess I do not see any settings that look like a culprit. I did find something in php.ini that leads to a question.

;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads. file\_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not ; specified). ;upload\_tmp\_dir =

; Maximum allowed size for uploaded files. upload\_max\_filesize = 256M

---

Check your settings. It may affect something. However, I am unclear about how this works on the server. I thought PHP was provided by the server so I would think they handle php.ini. Is it accessible to you? Whatever you find, please tell us in this question what happens.
> 0 votes

---
Tags: media
---


# Question
Title: The link generated by a View's header (Global: Text area) is only visible for the admin role and I need it to show for other roles
I have the following code in the View's header (Global: Text area).

```
<?php
  global $user;
  if (user_access('create page content', $user)) {
    $output = l(t('Publica un artículo nuevo'), 'node/add/articulo');
    print $output;
  }
?>

```

If I log in as admin I can add an "articulo" by clicking on the link that the PHP generates in the header of the view. However if I log in as a different role I can still add an "articulo" by using the navigation menu but for some reason the link generated by the code above disappears i.e. the link is only visible for the admin role and I want it to be visible for other roles as well. I have tried changing the permissions for the different roles but it has not worked. If the other roles can create content from the navigation menu why does this link disappear for them. Do I need to change something within the view or ...?

Thanks in advance.

# Answer
As per your code , you need to make sure two things...

* Logged in User should have create page content access in permissions since your code checks for that permission
* Logged in User should also have access to create articulo content "node/add/articulo" since l function checks for user access of the path he is trying to access.

Make sure logged in user role have both permissions in your permissions list. Clear cache and rebuild permissions before verifying.

In your case , Make sure the different role you are mentioning has "create page content" permission.
> 1 votes

---
Tags: views, users
---


# Question
Title: user_register_form not give pre filled form
I have created a module for user listing. when I edit any user then call drupal\_get\_form('user\_register\_form', $existing\_account);, its not give me form with user data.

I used Profile2 module to add some custom filed in user registration page. Now in admin , I need those custom fields with user data in it. for that I used drupal\_get\_form('user\_register\_form', $existing\_account); function where $existing\_account = user\_load($uid, $reset = TRUE);

```
  function mymodule_create_subscriber() {
  ....

  $existing_account = user_load($uid, $reset = TRUE);

  .......
  $extra =drupal_get_form('user_register_form', $existing_account);

   $form = array_merge($form,$extra);

     $form[actions]['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Update Subscriber'),
      '#weight' => 30
$form['#validate'][] = 'mymodule_create_subscriber_validate';
  $form['#submit'][] = 'mymodule_create_subscriber_submit';
....
}

function mymodule_create_subscriber_validate(&$form, &$form_state) {

 ....some code

  return;
}

function mymodule_create_subscriber_submit(&$form, &$form_state) {
$account = array();
  $account = $form_state['values'];

......
 $account = user_save($existing_account, $account, $category);
   .....
}

```

Please help me where I am doing wrong or what should I do?

# Answer
> 0 votes
You are trying to hack user registration instead of extending the feature in a right way.

If your requirement is additional validations on user registration form try using hook\_form\_alter.

More about hooks here.

---
Tags: 7
---


# Question
Title: Is there any need to check the block name when my module just define a block?
I am reading "Drupal 7 Module Development", and I followed the book's steps to create a block in my module.

```
/**
   * Implements hook_block_info().
   */
  function first_block_hook_info() {
    $block = array();

    $block['list_modules'] = array(
      'info' => t('A listing of all the enable modules'),
      'cache' => DRUPAL_NO_CACHE
    );

    return $block;
  }
  /**
  * Implements hook_block_view()
  */
  function first_block_view($block_name ='') {
    if ($block_name == 'list_modules') {
      $list = module_list();

      $theme_args = array('items' => $list, 'type' => 'ol');
      $content = theme('item_list', $theme_args);

      $block = array(
        'subject' => t('Enable modules'),
        'content' => $content
      );

      return $block;
    }
  }

```

`first_block_view($block_name = '')` is using `if ($block_name == 'list_modules')` to check which block should be rendered, but I think Drupal will only send list\_modules' to my module.

Is there any need to check the block name in `hook_block_view()`?

# Answer
While your module defines only a single block, technically no, it's not necessary.

But, as soon as you want to add another block, you'll need to distinguish between that and the existing one, so you'll need to check the block delta.

It's a good practice to get into, even if it's not *strictly* necessary to test the delta in the block view function.
> 4 votes

---
Tags: 7, blocks
---


title: Setting role based access control

text:
# Question
Title: Setting role based access control
Since we launched we have added many new job roles and wish to set all new wiki pages so everyone can access. At present we are having to manually tick each role.

Is this possible?

# Answer
Tick "Authenticated User" and the rest will automatically become ticked
> 0 votes

---
Tags: users
---


# Question
Title: drupal 7 PDOException error saying I'm missing a table or view mysite_drupal.cache_views
The full warning message goes like this: `PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mysite_drupal.cache_views' doesn't exist: TRUNCATE {cache_views} ; Array ( ) in cache_clear_all() (line 165 of /home/user/mysite.com/includes/cache.inc)`. should I try to manually create it?

# Answer
> 3 votes
Yes, if cache\_views is missing and you have the Views module installed, you need to create it.

To do so, simply duplicate the standard cache table and rename it to cache\_views; they share the same columns.

You might also need to re-create the cache\_views\_data table, also with the same columns.

# Answer
> 2 votes
From a mysql command prompt, you can go

```
show create table cache;

```

That will show the create table syntax for a cache table.

Change the table name to cache\_views and you can use that SQL to recreate the table.

For example:

```
CREATE TABLE `cache_views` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching views...'

```

You can also create the table in PHP with something similar to:

```
$schema['cache_views'] = drupal_get_schema_unprocessed('system', 'cache');
db_create_table('cache_views', $schema['cache_views']);

```

You may also need to recreate `cache_views_data` in a similar way.

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


# Question
Title: View restricted to a specific taxonomy term
I have a custom content type called Property with taxonomy term fields set up for example for vocabularies Train Station, Style, and Area.

I would like to create a view showing only those Properties with a specific term within the taxonomy for example only the ones with the term London Bridge in the Train Station vocabulary.

I assumed this would be Filter Criteria in the view, however the only related option I can see is Content:Has taxonomy term which brings in all Properties that has Train Station - but I cant see how I can add the extra filter of only London Bridge within Train Station

Any ideas?

# Answer
Assuming I understand the question correctly - potentially the easiest way to achieve this is to add a 'Term Reference' field to your 'Property' content type.

This needs to point at the taxonomy 'Train Station', and you can have multiple term references if you need other terms to describe properties.

You can then use this term reference field as a view filter. You'll be looking for **"Content:term\_reference\_field\_name"** as opposed to "**Content:Has taxonomy term**" This will allow you to filter on a particular taxonomy term.

Good luck!
> 0 votes

# Answer
What you are looking for is very basic functionality in Drupal. By default, if you go to a term's page, for example taxonomy/term/1, what you get is indeed a teaser list for all nodes that have that term.
> 0 votes

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


# Question
Title: Emails are not triggering when MIME mail is selected
I want to send HTML emails on webfrom submission. Gone through many tutorials as well as Questions on stack but didn't found a proper solution. I am using three modules to send these HTML mails.

MIME mail,Mail system,SMTP Authentication Support

I had configured all the settings in **MAIL system** module. when all the the class are set to **MIMEmailsystem\_SMTPmailsystem**.

Mails are being sent but am not getting "**Send e-mail as HTML**" option my webform email configuration"

When i am setting "**Webform module class**" to **MIMEmailsystem**, "**Send e-mail as HTML**" is visible but mail are not getting dispatched.

# Answer
You can change the email template format From Custom Template to Default Template or you can create your own template using place it in templates folder (/sites/all/themes/your-theme-folder/templates) and name it webform-mail-webform-node-id.tpl.php
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: Comment notify options confusing for users
I am using the Comment Notify module so that users can be notified when someone responds to their comments in forums. On a users account page the options are very confusing - there is a tick-box to receive notifications, and also a drop-down, which only contains two options: "No notifications" and "Replies to my content". The text below the drop-down is also confusing.

Have I got a configuration issue, or is this working as designed?

# Answer
As discussed in the comments: no, you haven't got a configuration issue, and yes the module is working exactly as designed.

If your users are likely to find that confusing, you can use `hook_form_alter()` in a custom module/theme to change the text to something that makes more sense. Or even hide one or more of the options altogether, if that's what you need.
> 0 votes

---
Tags: comments, nodes
---


# Question
Title: WSOD for logged users after upgrading some module
I have updated the following modules on my website:

ctools
context
devel
ds
libraries
metatag
pathologic
rel\_to\_abs
variable
webform

After the upgrade whenever I log in, I am not able to access any page (not just the administration area).
Anonymous users have no problems.
Downloding the whole website and installing it locally with the backup before the update, everything works fine. I have enabled debug logs and all possibile error reporting options, but I have no error or warning of any kind.
I have increased the memory limit, clean every cache and run the registry rebuild via php.
I have no ssh access to the host, so I cannot run any remote debugging.
Can someone point me out to a possibile solution?

# Answer
> 0 votes
go into you database, set the status to 0 on the rows for each of the modules you mentioned. Reinstall each module one by one to find the problem module.

you could also try adding this to the top of index.php (remember to remove it later)

```
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

```

# Answer
> 0 votes
The problem ended up being Devel 7.x-1.4 dropped support for PHP 5.2.
A patch has been submitted to fix the issue and has been commited to the dev release.
See the issue report here.
Thanks for your support.

---
Tags: 7, debugging, wsod
---


# Question
Title: Get context of overlay (get parent page information)
Is it possible to get the context, like the full URL, or the containing page path, title, etc., while inside an overlay page?

For example, I have a form pop up inside an overlay, and I want to, inside that form, be able to get the context of the page that triggered the overlay popup. I can't pass any information via the URL... I'd just like to be able to do something like arg(0) for the containing page (what's faded out in the background of the overlay.

Right now, if I do arg(0), request\_uri(), $\_GET\['q'\], etc., it always returns the overlay path, like http://www.example.com/path/i/want#overlay=overlay/path

(I want the 'path/i/want' portion of the URL, somehow).

# Answer
> 2 votes
Unfortunately the PHP that's rendering the child page knows nothing about the parent page over which it's going to be placed. You could write an AJAX callback that checks window.location and reports back to the server, but that would have to run after the page was fully rendered.

# Answer
> 0 votes
I recently struggled with the same question and found a possible solution using PHP. The path stored in $\_GET will always return the child path of the overlay. Like in your example:

http://www.example.com/path/i/want#overlay=overlay/path

Using current\_path() will return “overlay/path” not “/path/i/want#overlay=overlay/path”.

The good news is that the URL of the parent window is still stored in \*$\_SERVER\['HTTP\_REFERER'\]\*. The bad news is that ‘HTTP\_REFERER’ may not always be set…depending on the client browser configuration.

But if this is acceptable risk or it’s something you feel your application can compensate for, then you can get the parent path from \*$\_SERVER\['HTTP\_REFERER'\]\*.

In my testing, 'HTTP\_REFERER' returned the absolute path (e.g. http://www.example.com/path/i/want). If you want just the relative path, you can get it like so:

```
<?php
function mymodule_get_overlay_parent path() {
  global $base_url;
  // Get the HTTP Referer.
  $referer = $_SERVER['HTTP_REFERER'];
  // Check for and remove the base url to return just the relative path.
  // Otherwise, return the referer as is.
  if (strpos($referer, $base_url) === 0) {
    $parent_path = substr($referer, strlen($base_url));
  }
  else {
    $parent_path = $referer;
  }

  return $parent_path;
}
?>

```

---
Tags: modal-dialogs
---


# Question
Title: Do wildcards not work with Menu Local Task?
I am getting an offset error , Undefined offset: 4 in \_menu\_translate()

```
 $items['admin/content/import-dashboard/new'] = array(
    'title' => 'Import Dashboard',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_dashboard_new_content',"article"),
    'access arguments' => array('Import Dashboard Permission'),
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
    'expanded' => TRUE,
  );
    $items['admin/content/import-dashboard/new/%'] = array(
    'title' => 'Import Dashboard',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_dashboard_new_content',4),
    'access arguments' => array('Import Dashboard Permission'),
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
    'expanded' => TRUE,
  );

```

I simply want to default new to article, and also use wildcards to support other arguments.

I'm pretty flexible in my approach, so feel free to throw a few suggestions if it could be done better.

Can someone quickly suggest where I made my rookie mistake?

---

Indeed, changing to Menu Callback works when using the wildcard.

```
$items['admin/content/import-dashboard/new/%'] = array(
    'title' => 'Import Dashboard',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_dashboard_new_content',4),
    'access arguments' => array('Import Dashboard Permission'),
    'type' => MENU_CALLBACK,
    'expanded' => TRUE,
  );

```

Would still like to know why it fails when it a MENU\_LOCAL\_TASK or MENU\_NORMAL\_ITEM

# Answer
The problem is that your menu items are local tasks, which are menu tabs, so on a given page drupal will load all the tabs for the current page.

So on the admin/content/import-dashboard/new page it loads your tab menu items:
admin/content/import-dashboard/new
admin/content/import-dashboard/new/%

but when it goes to get the second item there is no 4th param on the current page so it gets that error.

This is why when you change it to not be a MENU\_LOCAL\_TASK it stops the problem.

If you have a page that has menu tabs where the last part of the path is a wildcard, how could drupal know what all the possible tabs are? It can't.

This is why when you see menu tabs they are things like node/%/view, node/%/edit, etc. so you have a finite number of tabs and each has its own definition.

As a side note, yes you can use multiple menu item types, but using `MENU_LOCAL_TASK | MENU_NORMAL_ITEM` doesn't really make sense. As an example `MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT | MENU_VISIBLE_IN_BREADCRUMB` is one that would make sense.

Also, I'm not sure if this is your full hook\_menu() or if admin/content/import-dashboard exists somewhere else, but usually if you're doing tabs there is a parent page (in this case admin/content/import-dashboard) and a tab that is MENU\_DEFAULT\_LOCAL\_TASK.

There is however the ability to set in your menu item:

```
'tab_parent' => 'admin/content/import-dashboard/new'

```

This allows you to set the parent page to use for tab items. Without this it defaults to the path of the tab item minus its last path part.
> 1 votes

---
Tags: routes
---


# Question
Title: $entity_wrapper->save(true) vs. entity_save('node', $entity)?
Say I've got the following block of code:

```
$language = language_default();
$values = array([...]);

$entity = entity_create('node', $values);
$entity_wrapper = entity_metadata_wrapper('node', $entity);

$container = entity_create('field_collection_item', array('field_name' => 'field_container'));
$container->setHostEntity('node', $entity, $language);
$container_wrapper->save();
$entity_wrapper->save(true);
entity_save('node', $entity);

```

The above block of code invokes three different save() methods. Is this strictly necessary? Does entity\_save cascade to $container\_wrapper-\>save() and $entity\_wrapper-\>save() if I do not explicitly call these? Are all three necessary?

Things appear to work find if I skip $entity\_wrapper-\>save(true)...but am I missing something?

# Answer
You need just one save call. All of them invoke the same code, the controller's save method (or node\_save in node's case).

The wrapper modifies the original entity by reference, so it doesn't need an explicit save of its own (and the other way around).
> 4 votes

---
Tags: entities, nodes
---


title: specify context on hook_menu drupal

text:
# Question
Title: specify context on hook_menu drupal
I would like to check if particular node instance exists then load that node. if the instance does not exist, then display message. So far:

```
function MODULE_menu() {
    $items['ds-some'] = array(
        'title' => 'Some',
        'page callback' => 'some_display',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
        'file' => 'inc/some.pages.inc',
    );

    return $items;
}

function MODULE_theme(){
    return array(
        'render-some' => array(
            'template' => 'page--some',
            'variables' => array(
                'node' => NULL
            ),
            'path' => path_to_theme().'/templates',
        ),
    );
}

```

in file inc/some.pages.inc

```
    function some_display(){
            $build = array();

            $nid_some = db_select('node', 'n')
                ->fields('n', array('nid'))
                ->fields('n', array('type'))
                ->condition('n.type', 'SOME_TYPE')
                ->execute()
                ->fetchCol();

            //load first instance
            $someNode = node_load($nid_some[0]);

            if (!empty($shopNode)) {

//Attempt 1
    //            $build['ds-some'] = array(
    //                '#theme' => 'node',
    //                '#node' => $someNode,
    //                '#view_mode' => 'full',
    //            );

//Attempt 2
    //            $build['ds-some'] = node_view($someNode, 'full');

                $build['ds-some'] = array(
                    '#theme' => 'render-some',
                    '#node' => $someNode,
                );
            }
            else {
                drupal_set_message(t('It appears there is no instance present');
            }
            return $build;
    }

```

The first two attempts ended with the title of the Node instance but Drupal is no rendering the whole page(template file, views, etc). In my last attempt, i use custom theme function that it works, however. It is not rendering the context for the node type specified. How to specify context when working with hook\_menu(), so that the context configured will load blocks and views? Thank you for any help.

# Answer
I don't know how the Context module handles Entity types, but it loads entity type definitions using the entity ID (from the URL). In your case, you are creating a menu item without any arguments, just specifying business logic in the callback, and your menu item path is not a node path. That's why the Context module can't find any entity type definition. In this case you can specify additional context reactions by path (by your custom path) and display blocks.

You don't need to specify double `fields` method; you can write much simpler code.

```
$nid_some = db_select('node', 'n')
  ->fields('n', array('nid', 'type'))
  ->condition('n.type', 'SOME_TYPE')
  ->execute()
  ->fetchAll();

```

If you need to fetch only one row from the database, you can use the following code.

```
$nid_some = db_select('node', 'n')
  ->fields('n', array('nid', 'type'))
  ->condition('n.type', 'SOME_TYPE')
  ->range(0,1)
  ->orderBy('nid', 'DESC') // Additional sorting
  ->execute()
  ->fetchAll();

```
> 1 votes

# Answer
I will answer to the part that is not about the Context module, since the `hook_theme()` implementation is not correct.

*render-some* is not a correct theme function identifier, since that needs to be an identifier PHP is able to use as function name or as part of a function name. Even when the theme implementation is done in a template file, and not in a function, Drupal will always use the identifier to find some functions required for the theme implementation, such as:

* `template_preprocess_render-some()`, the preprocess function implemented from your module
* `hook_preprocess_render-some()`, the preprocess function implemented by other modules
* `template_process_render-some()`, the process function implemented from your module
* `hook_process_render-some()`, the process function implemented by other modules

Even if you don't plan to use preprocess or process functions for that template file, using *render-some* as theme identified doesn't allow other modules to implement those preprocess or process functions, since the function name Drupal would look for isn't a function name allowed from PHP.
> 1 votes

# Answer
To answer how to activate context, here is snippet:

```
$context = context_load('NAME_OF_CONTEXT');
context_set('context', $context->name, $context);

```

For complete info on how to render the page programmatically, activate context, etc in this post http://margotskapacs.com/2014/02/rendering-page-programmatically-to-create-permanent-urls-like-shop-gallery/
> 0 votes

---
Tags: routes
---


# Question
Title: Language links shown enabled for pre-translated nodes
The current snapshot below is of a node which was edited before I installed i18n. So when I go to edit that node "Translate" tab does not appear.

I've many nodes like this. The problem in such nodes is that in the language switcher block, all languages are shown enabled even though translations aren't available.

**What is the solution? Should I simply resave such nodes created before i18n was installed?**

So in this current snapshot, all non-English languages should have been shown as striked as I've not enabled translation for this node.

>

# Answer
> 0 votes
Manually saving those pre-existing nodes does it. Untranslated languages are shown striked out.

---
Tags: i18n-l10n
---


title: Contextual filter + exposed filter

text:
# Question
Title: Contextual filter + exposed filter
My view have following "EXPOSED" filters with Industry. And Contextual filter of Taxonomy. So when I do asia/agriculture. %1 should be Asia and it's coming along fine. But %2 should go to Exposed Filter and it should filter out all the nodes with "agricultural" term.

Is it possible in Drupal?

# Answer
Check out the Views Filter Harmonizer module. It allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Here is a quote about it (from its project page):

> Views Filter Harmonizer solves an operational foible with the Views module regarding filtering. Normally, when a Views field has been assigned both an exposed filter and a contextual filter, then both filters get applied to the View's results set -- **always**. This is not configurable behaviour. It's hard-coded.
>
> As a consequence, contradictory search clauses easily occur, causing a counter-intuitive user experience with some White Screens of Disillusionment. Since the contextual filter sets the "bounds" for the page, any filtering by the visitor through the exposed filter on that page can only narrow down the results set, not broaden it. In other words the exposed filter appears not to be working properly.
>
> This small module allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.
>
> This is most common on initial page load. After that the contextual filters will silently retreat and let the exposed filter values as selected by the visitor do their thing without interfering.
>
> This means that you can take advantage of friendly URLs using contextual arguments instead of ugly and verbose query parameters. Put the URLs anywhere on your site, in emails and in newsletters to take visitors to tailored Views pages. Having arrived there, visitors may then further filter these pages to their heart's content using the View's regular filters you exposed. And they won't experience any odd behaviour.
> 3 votes

---
Tags: views
---


# Question
Title: How can I get the cid of the latest comment I saved using comment_save?
This is my code to programmatically save comment:

```
  $comment = (object) array(
    'nid' => $loaded_node->nid,
    'cid' => 0,
    'pid' => 0,
    'uid' => $loaded_node->uid,
    'mail' => $account->mail,
    'thread' => '00/',
    'created' => $loaded_node->created,
    'changed' => $loaded_node->created,
    'is_anonymous' => 0,
    'homepage' => '',
    'status' => COMMENT_PUBLISHED,
    'subject' => $comment_body_subject,
    'language' => $node_language,
    'comment_body' => array(
      $node_language => array(
        0 => array (
          'value' => $comment_body_value,
          'format' => 'msg_filtered_html',
        )
      )
    ),
  );

  comment_submit($comment);
  comment_save($comment);

```

I want to get the cid of comment just saved. How can I get that?

# Answer
> 3 votes
Since `comment_save()` is using `drupal_write_record()`, and cid is the primary key for the comment table, the value of `$comment->cid` is updated after the call to `comment_save()`.

# Answer
> 3 votes
The cid value should be in the comment object after it has been saved. So you should simply be able to use something like this:

```
comment_save($comment);
drupal_set_mesage("ID is " . $comment->cid);

```

---
Tags: nodes, comments
---


# Question
Title: how to open drupal login and signup form on modal form.
I just want to open login form in modal box as per semantic ui framework http://semantic-ui.com/modules/modal.html. I just want to use this framework. Is this possible with theming or custom module is require for this.

Any help would be appreciated.

# Answer
You should include the necessary javascript in your theme .info file or template or module with drupal\_add\_js() , then you should use the code defined in the link you provide to target the element that you want to apply the functionality too. This elememnt may be generated by a module that specifies a theme function and uses a template (tpl.php) file in which you would put your markup.
> 3 votes

---
Tags: theming
---


title: why feed importer cron fails?

text:
# Question
Title: why feed importer cron fails?
In my drupal 6 website, we have used feed importers to import feed, but from few days We are not getting new feeds and then I have gone to 'status report' in admin panel and checked status report & I found that cron is not running.As I have seen that there is problem in cron I imported feed manually and it worked for me.

When I tried to run feed import cron manually from status report page I got error "cron run failed"

As I am new to Drupal, I dont know that from where I should start cron failed troubleshooting.

Can anyone suggest me the way.

# Answer
> 2 votes
I got the answer to this problem.

I used debug code `if ($hook == 'cron') watchdog('cron', "hit $module cron");` in `function module_invoke_all()`

where to put debug code ?

In module.inc file of core drupal, add

```
 $function = $module .'_'. $hook;
 $result = call_user_func_array($function, $args);

```

between this two line of module\_invoke\_all() function, add above debug line.

It will look like :

```
$function = $module .'_'. $hook;

if ($hook == 'cron') watchdog('cron', "hit $module cron");

$result = call_user_func_array($function, $args);

```

After putting above line in module.inc,run cron manually and check log in recent log entries.

Because of this debug statement, I found the module which was not allowing to run cron.

I corrected the custom module code in that and cron started working fine.

# Answer
> 0 votes
My best bet would be to check the server log files (apache or nginx, depends on what you are using). You can usually do that in the hosting admin panel or by going to the server directly via ssh.

---
Tags: feeds, cron
---


title: Users unable to view order history

text:
# Question
Title: Users unable to view order history
I have drupal 6 with ubercart When a user clicks on View order history, it takes them to a please register or login page. Admin can see order history just fine.

I've checked the options for Allow customers to view order invoices from their order history in Order settings and it's set to true. I've checked permissions and its set to allow authorized and even anonymous users to view own orders. Yet they keep getting this strange redirect to register or login.

I'm wondering if anyone has any suggestions where else to check for the problem. I haven't been able to find the solutions yet.

Thanks!!

UPDATE: I just noticed what when the Admin account tries to look at another users order history mysite.com/user/105718/orders even admin gets please login or register. I've triple checked permissions and its set for admin to have access to everything and for users to view their own order history. Still not working.

# Answer
> 0 votes
Have you looked at the view permissions? They override drupal core permissions.

Also, is there an order content type, or entity type? You have to grant anon and auth users access to view their own order content type in drupal core permissions.

# Answer
> 0 votes
figured it out, apparently there used to be a order\_history view or something, but it was no longer there. So I created a new order\_history view and assigned it permissions, now the order history tab on users works fine.

---
Tags: ubercart
---


title: How to extract content from database

text:
# Question
Title: How to extract content from database
How can I extract my content from the database? My specific use case is to be able to migrate my content out of Drupal to do a 100% clean re-installation and then restore all my original content, but just in general, it seems to be a huge gap in the design of a content management system that I can put content in to be managed, but I can't get it back out again.

I understand that there are a myriad of variables in this use case such as module-specific tables that may contain some of my content. I'm asking about the base case without regard to those individual considerations. I would like to start simple; I can address additional, specific factors as they come up.

In searching online, I've only found workarounds to this issue. I'm not asking about workarounds (eg. the Features module) or ways to do something else that is similar to my question. Is it possible to extract my content from the database--at the very least, for the purpose of reloading it into a new, identical installation.

Put another way: in a vanilla installation, in what tables is the content stored?

# Answer
> 0 votes
There's almost certainly no such thing as "no individual considerations" on Drupal sites.

Even on a Drupal 7 site with no contributed or custom modules, this isn't easy to do. You might have many content types, with all their fields and associated configuration.

Some tables you'll need to look at are node, node\_type, node\_revision, field\_data\_\*, field\_revision\_\*, maybe taxonomy\_\*, maybe others.

Migrate module, Feeds module, and others can help with this too, as Ayesh mentioned.

---
Tags: database, migrations, backups
---


# Question
Title: What is the Aegir make_working_copy SCM option mean?
If one creates a platform and chooses to preserve the working copy, does this initiate a .git clone that the aegir user from CLI, could update and merge branches to?

> Create a new platform:
>
> > Drush make option:
> >
> > > * Normal - Discards SCM files
> > > * Working copy - preserves SCM files

Where is the working copy directory?

# Answer
The 'Drush make option' field in the Aegir user interface (when creating a new platform based on a makefile) simply determines whether or not the `--working-copy` option is passed to Drush make.

The `--working-copy` option for Drush make "preserves VCS directories, like .git, for projects downloaded using such methods." (source: Drush.org)

Passing the `--working-copy` option leaves the .git directories intact (as if you had done a manual `git clone`) and hence allows you to pull in updates, etc. However, this is not the recommended way of updating modules in Aegir, so the 'Normal - Discards SCM files' option is preferred.

The aegir\_make\_working\_copy module provided this functionality for Aegir 1.x, before it was merged into Aegir core 2.x.
> 2 votes

---
Tags: version-control, aegir, drush
---


title: Two dependent Flags in my Application

text:
# Question
Title: Two dependent Flags in my Application
I have a rating website and on every node i have two separate flags, one is Like, and another one is disklike, so that i can get a count of how many people likes that particular div and how many of them dislikes them. What i want to achieve is, that say if someone likes a node, the dislike should be disable or even invisible , and vice versa. I am using a view to show the nodes a the moment, so will i have to uses pre process of views to do it or what is the way going about it?

# Answer
I would start by looking at the Flag Module Documentation and look into several of the ways you might accomplish this:

1. You can hook into the Flag Module via PHP, so, in preprocess, you can see if a node has been flagged by either the like or dislike flag (or none yet) and display just the one or both of them when the node is displayed.
2. You can also hook into the Flag Module via Javascript: it provides two events you can act upon, so, for instance, after a user has clicked on a flag, you can via jQuery hide the other flag.

And of course, with Views, you can filter on whether or not a node has been flagged by a particular flag or not and then list them accordingly.
> 0 votes

---
Tags: ajax, flags
---


title: Drop down select list by author id

text:
# Question
Title: Drop down select list by author id
I have a website that has users with role "sellers". The website has a nodes/stores that belongs to the sellers.

So let's say I have 3 users and 10 nodes for their objects. The names will be fictive, just to explain better this specific task.

Users with role "sellers":

1. John
2. Mark
3. Cindy

Nodes/stores

1. John's store 1
2. John's store 2
3. John's store 3
4. Mark's store 1
5. Mark's store 2
6. Mark's store 3
7. Mark's store 4
8. Cindy's store 1
9. Cindy's store 2
10. Cindy's store 3

Every seller will be able to login into the website and see his/her stores, but cannot create or edit a node/store. Only admin will do that. When creating these stores the admin will make author by the user name. For an example:

John's three stores nodes will have author as John, so the seller John when log into his user pages, will be able to see his stores. That's ok and already accomplished.

When John's wants to make some new offers will send a form that will be sent to the admin. The specific thing is, John will be able to select a drop down list with his stores (in this case 3) and select what stores will have this new offer, so on sending the email, the admin will know for which stores is the new offer.

How can I create this kind of drop down select list based on author id?

I have acknowledge with custom modules and lot's of hooks, so creating a custom form wont be difficult.

# Answer
> 2 votes
Code to fetch Stores of a user -- Replace node\_type with your node type...

```
global $user;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid and type = :type', array(':uid' => $user->uid, ':type' => 'node_type'));
// Result is returned as a iterable object that returns a stdClass object on each iteration
foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}

```
* Create a Custom Form -- Form API Reference
    + Create two fields
    + 1. Select Field - Options Source - Run a query against node table to get list of node id's given user id filtered by type and status of node
        2. Offer Request - Text Area
    + On Submit handler
    + Read Select Field Values , Offer Request Text
    + Send Email to admin using hook\_mail

---
Tags: forms
---