# Question
Title: Choose header content from entity-reference dropdown?
Been struggling with this for a while... I know there is probably a fairly easy way to accomplish it but I haven't been able to figure it out.

The goal: When a user creates a new page for the site, I would like them to be able to choose from several different headers using a drop-down list. I know I can set up blocks for the different headers and use the built-in functionality to have them appear on different content types or pages, but for various reasons I would like to have the header as a custom field within the page content type.

I have created a "Header Content" content type and used the Entity Reference module to populate a select list field in the page content type. I can display the selected option or the rendered entity it refers to in the body of my page without any trouble.

What I can't figure out is how to display the rendered entity in the header section instead of the main content.

Put another way: When creating a new page or editing an existing one, the user should be able to select existing nodes from a drop-down list (this part is done). The selected node should show up in the header region (this part is giving me trouble).

I think it could be accomplished in one of two ways:

1) Using Views: I tried creating a views block to read either the reference or rendered content from the parent page and display it in the header (or wherever I place the block) but I can't seem to get the relationship right.

2) Using a custom module This seems pretty straightforward but I'm not sure how to reference the value of "field\_header" (the name of my custom field using hooks. I'm also not sure if the data will be available if I configure field\_header not to display in the configuration.

This seems like a problem that's likely to be solved already. Maybe I'm not phrasing it correctly when I search because I haven't been able to find any examples to help me solve it.

# Answer
> 1 votes
What I'm 99% sure you want is the Header Image module. It works by being able to select a piece of (node) content to place in some region thats been pre-defined.

Eg, put an image in some header region of your site. Or text or whatever ....

# Answer
> 1 votes
Hmm... looks pretty good but the important thing I was looking for was the ability to choose the header from a drop-down when creating the page. As far as I can tell, the module only works from the other direction -- assigning nodes to the header.

I was able to hack it together by editing page.tpl with the following:

```
// If the current node has a field called "field_header" and that field has content
if( $field = field_get_items('node', $node, 'field_header', $node->language) ) {
    $nid = $field['0']['target_id'];
    $delta = 0;
    $language = 'und';

    $entity = entity_load('node', array($nid));
    $header_content = $entity[$nid]->body[$language][$delta]['value'];
}
if ( !empty( $header_content ) ) {
    // Hacked together replacement for header content
    echo '<div class="region region-header"><div class="block-inner clearfix">';
    print render($header_content);
    echo '</div></div>';
}
else {
    // Render original header content
    print render($page['header']);
}

```

I'm sure there are a zillion better ways to accomplish this -- and I plan to figure out a few when I have time. For now, this works pretty well considering I already had blocks set up with header content that now act as fallbacks.

Thanks again for your help -- I'd love to see any other pointers. This is my first Drupal site and I'm very impressed and a little intimidated so far.

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


title: How do I use confirm_form()?

text:
# Question
Title: How do I use confirm_form()?
I have a custom block made in the edit-mode of a node, and I would like to have it linked to a confirmation screen. So I figured out that I'll use confirm\_form(). After a few days, I'm not able to get this function working.

Is there anyone who can tell me what I do wrong or what I'm supposed to do?

This is the `switch` statement that defines my actions when hitting the button.

```
case ACTION_FICHE_OFFLINE :
    if ($form_state['buttons']['5']['#value'] == ACTION_FICHE_ONLINE) {
      $form_state['values']['status'] = '1';
        drupal_set_message('FICHE ONLINE', 'warning', FALSE);
    }
    else {
      confirm_offline($form, 'Are you sure?', 'dashboard', t('This action cannot be undone'), 'Confirm', 'Cancel', 'fiche_offline');
      $form_state['values']['status'] = '0';
      drupal_set_message('FICHE OFFLINE', 'warning', FALSE);
}
    break;

```

The formal parameters for `confirm_offline()` are the following ones:

* `$form`
* `$question`
* `$path`
* `$description = NULL`
* `$yes`
* `$no = NULL`
* `$name = 'confirm'`

What code should I use in `confirm_offline()`?

# Answer
`confirm_form()` is a form builder; as such it should be called from a menu callback or another form builder function. From the code you shown, I take you are calling it from a form submission handler, and that is not how you should use that function.

As example of code that shows a confirmation form, you can look at system\_modules(), the form builder associated with the "admin/modules" path. The function contains the following code.

```
  // If the modules form was submitted, then system_modules_submit() runs first
  // and if there are unfilled required modules, then $form_state['storage'] is
  // filled, triggering a rebuild. In this case we need to display a
  // confirmation form.
  if (!empty($form_state['storage'])) {
    return system_modules_confirm_form($visible_files, $form_state['storage']);
  }

```

The form submission handler for the "admin/modules" path, system\_modules\_submit(), then contains the following code.

```
  // Redirects to confirmation form if more modules need to be enabled.
  if ((!empty($more_required) || !empty($missing_modules)) && !isset($form_state['values']['confirm'])) {
    $form_state['storage'] = array(
      'more_required' => $more_required,
      'modules' => $modules,
      'missing_modules' => $missing_modules,
    );
    $form_state['rebuild'] = TRUE;
    return;
  }

```

Settings `$form_state['rebuild']` to `TRUE` tells Drupal to call again the form builder which (basing on the value of `$form_state['storage']`) shows the confirmation form, rather than the form listing all the modules found for the Drupal site.
> 2 votes

# Answer
You need a form, which shows your text and buttons, and you need an URL go call this form.

1. Define your path by implementing hook\_menu(). If you are new to Drupal, you should find the D6 menu system handbook helpful.
2. Define a form with help of the Drupal FAPI. This FAPI tutorial guides you step-by-step.

You'll find working code examples for both steps in the Example Module.

Once this is working, you can call your URL with drupal\_goto().
> 0 votes

---
Tags: forms
---


title: theme_links() override has no effect

text:
# Question
Title: theme_links() override has no effect
So I want menus to output in a custom way. I would not output the following HTML.

```
<ul attributes>
    <li attributes>
       <a href="foo">foo</a>
    </li>
    <li attributes>
       <a href="bar">bar</a>
    </li>
 </ul>

```

I would replace it with the following one.

```
<nav attributes>
   <a attributes href="foo">foo</a>
   <a attributes href="bar">bar</a>
</nav>

```

So I put in the template.php file the following function (my theme is called mFAC).

```
function mFAC_links($variables) {
    // custom stuff
}

```

I am starting with a light alteration, but nothing seems to have any effect. I cleared the cache.

Is there anything I am missing?

# Answer
> 1 votes
You can use YOUR\_THEME\_menu\_tree() for this. You can target it to a specific menu using YOUR\_THEME\_menu\_tree\__MENU\_NAME(). Make sure you return the variable after alterations. Refer this for more details.

# Answer
> 1 votes
You can override the menu wrapper in this manner:

```
function YOURTHEME_menu_tree__MENU_NAME($variables) {
  return '<nav class="menu'.$variables['delta'].'">' . $variables['tree'] . '</nav>';
}

```

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


# Question
Title: Subdomain involuntarily redirects to primary domain after logging in or saving
I made a development site using development.breinwijzer.be as subdomain. After I've logged in, I'm already back at my primary domain www.breinwijzer.be.

* I tried different browsers.
* I cleared caches.
* I cleared browser caches.
* I checked the settings.php file of the development site to see if I have the correct database set for the development site.

Other than this, I'm clueless.

# Answer
In the `settings.php` someone uncommented `$base_url` and put the primary domain of the site as a value. Changing the value into the subdomain I was working in solved the issue.
> 2 votes

---
Tags: 6, redirection
---


# Question
Title: Menu links and content to appear in different languages
I have a small link in my page; when I click it, the whole website should come up in a different language, i.e. menus and the content. What modules should I need for this to be done perfectly?

For example, I saw this website, where alignment and layout also get changed a bit.

# Answer
> 1 votes
The site is using the Internationalization module, but the different alignment, and layout is caused from a core feature Drupal has: When the language is one that is written from right to left, and a module adds a CSS file to the HTML output, e.g. using `drupal_add_css(drupal_get_path('module', 'system') . '/system.admin.css');`, Drupal search a file named system.admin-rtl.css, and uses it when that file is present; otherwise, it just uses system.admin.css.

In that site, the files having that "extension" are the following ones:

* /modules/cck/theme/content-module-rtl.css
* /modules/filefield/filefield-rtl.css?
* /modules/nice\_menus/nice\_menus\_default-rtl.css
* /modules/node/node-rtl.css
* /modules/poll/poll-rtl.css
* /modules/system/defaults-rtl.css
* /modules/system/system-rtl.css
* /modules/system/system-menus-rtl.css
* /modules/user/user-rtl.css
* /modules/views/css/views-rtl.css
* /themes/basic/css/style-rtl.css

To notice that, for example, /modules/poll/poll-rtl.css is not used instead of /modules/poll/poll.css, but together; /modules/poll/poll-rtl.css should then just contains the CSS styles that are specific for a right-to-left language.

The same is done for a left-to-right language; the difference is that Drupal looks for a file named, e.g., /modules/views/css/views-ltr.css, instead of /modules/views/css/views-rtl.css.

---
Tags: 7
---


# Question
Title: Put the access callback function in a separated file
When I put the access callback function in a separated file I get an error.

```
$items['node/%node/join'] = array(
    'title' => t('Join Game'),
    'page callback' => 'agentweb_membership_join',
    'page arguments' => array(1),
    'access callback' => '_agentweb_membership_join_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'join.page.inc',
);

```

When I put `_agentweb_membership_join_access()` in `join.page.inc` I get an error, but when I move it to `agentweb_membership.module` everything works correctly.

Why does it happen?

# Answer
> 6 votes
The access callback has to be in the same file; the file passed in the "file" property gets loaded only if the access callback returns `TRUE`. The only other "solution" is to use an include at the top of your module.

---
Tags: 7, routes, hooks
---


# Question
Title: Taxonomy field not visible for anonymous users with content create permission
When creating a new node, anonymous users can't see taxonomy field but administer can see it.anonymous users have permission to create nodes.

How can I show it to anonymous users?

# Answer
> 2 votes
You just have to give anonymous user the permission of administer taxonomy.

---
Tags: 6, taxonomy-terms
---


# Question
Title: Overriding theme_item_list() not working
I have the following code in the theme `template.php` file:

```
function MYTHEME_item_list(&$variables) {
  // my custom stuff done to theme_item_list
  return $output;
}

```

And also this:

```
function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'item_list' => array(
      'variables' => array(),
    ),
  );
}

```

I have cleared cache many times.

Looking at the theme registry I can see that my override is getting picked up:

```
[item_list] => Array
  (
    [function] => MYTHEME_item_list
    [type] => theme_engine
    [theme path] => profiles/eurostar/themes/eurostar
    [variables] => Array
      (
        [items] => Array
          (
          )
        [title] =>
        [type] => ul
        [attributes] => Array
          (
          )
      )
    [preprocess functions] => Array
      (
      )
    [process functions] => Array
      (
      )
  )

```

Unfortunately none of this works. Does anyone have an idea of what I'm doing wrong?

**UPDATE:**
So, this works: theme('item\_list', $variables);

This does not: theme\_item\_list($variables);

# Answer
You don't need to implement `hook_theme()` if you just want to override an existing theme function.

I've just tried this code in my template.php file:

```
function MYTHEME_item_list(&$variables) {
  // my custom stuff done to theme_item_list
  return 'test';
}

```

And all calls to `theme('item_list')` now return the string 'test', and nothing else.

You'll need to clear Drupal's caches once you've implemented the function, that might also be an issue.
> 3 votes

---
Tags: 7, theming
---


title: How to change default "Create" label?

text:
# Question
Title: How to change default "Create" label?
I want to change the '**Create**' label for a specific Content type.
I made a new content type called 'Bid Offer':

I want to show this to the users as '***Make Bid Offer***' instead of '**Create Bid Offer**'

Any help appreciated

# Answer
Put the following code into a custom module.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bid_offer_node_form') {
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
  }
}

```

or

```
function mymodule_form_bid_offer_node_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
}

```

To change the URL, you can just set a path alias and alias *node/add/bid-offer* to *make-offer* or whatever you fancy should you need to.

Just for reference:

`hook_form_alter()`

`hook_form_FORM_ID_alter()`

**EDIT**

Following on from your comment, please try the following code (I've used it recently so I know it works):

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bid_offer_node_form') {
    drupal_set_title(t('Make Offer'));
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
  }
}

```

or

```
function mymodule_form_bid_offer_node_form_alter(&$form, &$form_state, $form_id) {
    drupal_set_title(t('Make Offer'));
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
}

```

Reference:

`drupal_set_title()`
> 1 votes

# Answer
Create bid\_offer module with title callback returning node form. It should look like this (I didn't check it live!)

```
function bid_offer_menu_alter(&$items) {
  unset($items['node/add/bid_offer']); //unset core add path
}

function bid_offer_menu() {
   $items = array();
   $items['create/bid_offer'] = array(
     'title' => 'Create bid offer',
     'title callback' => 'bid_offer_title',
     'title arguments' => array(1),
     'page callback' => 'bid_offer',
     'page arguments' => array(1),
     'type' => MENU_CALLBACK,
     'access callback' => TRUE // You can customize this
   );

function bid_offer_title($type) {
  drupal_set_title(t('Make bid offer'));
  }
  return t();
}

function bid_offer($type = null) {
     if($type->type == 'bid_offer') {
       module_load_include('inc', 'node', 'node.pages');
       global $user;
       $new_node = new stdClass;
       $new_node->type = 'bid_offer';
       $new_node->language = LANGUAGE_NONE; //localization
       $new_node->user = $user->uid;
       $new_node->name = (isset($user->name) ? $user->name : '');
       $form = drupal_get_form('bid_offer_form', $new_node);
       return $form;
     }
   return drupal_not_found();
}

```

After that you're be able to create your bids from http://yoursite/create/bid\_offer

You can change

```
'type' => MENU_CALLBACK

```

to MENU\_NORMAL\_ITEM for visible menu.

**Important! Do not afraid of creating module. I'm not developer, just Drupal enthusiast and if you think logically you can make it.**
> -1 votes

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


# Question
Title: How to install ckfinder outside the ckeditor module folder?
I have installed both the ckeditor module and the ckfinder plugin. They work fine. So far so good.

The problem is that I have ckfinder plugin inside the ckeditor module folder (sites/all/modules/ckeditor/ckfinder). Then every time I update the ckeditor module I lost the ckfinder plugin.

I'm sure that there is a way to put **ckfinder** inside the **libraries** folder instead but I don't know to do it in the right way.

# Answer
maybe this helps:

> This module allows you to use CKFinder with the WYSIWYG version of CKEditor. This module requires both the libraries and WYSIWYG modules. Please read the installation instructions carefully.

found here: https://github.com/jrsinclair/Drupal-WYSIWYG-CKEditor-CKFinder-bridge

**Update 21 August 2012** This module has now been published on Drupal.org. You can find it at: http://drupal.org/project/WYSIWYG-CKFinder
> 2 votes

---
Tags: wysiwyg
---


title: Admin page for every special page

text:
# Question
Title: Admin page for every special page
I'm creating a web site in Drupal 7, there are home page, and three main taxonomy pages(they are primary links), the client is asking, to tell the truth they are insisting on me to make custom admin pages for every primary pages, sounds like primitive but they want to control every part of the main pages manually. How can I handle this task? I've already created these pages with views. Has anybody faced before with this type of issue?

# Answer
I'm not sure exactly what you mean by "custom admin pages", but to give complete control over the layout of the content you could use Panels and perhaps also Panelizer. The Panels in-place editor is probably enough for the client's needs, but you might show them the backend editor instead because it looks (and is) far more powerful/complicated. It may even have the benefit of scaring them away from having the control themselves and asking you to go back to your original plan.

EDIT:

Here's how I would go about this using Panels, Views, Rules, and Flag. This may not be the most optimal way, but it uses well-supported modules.

1. Make a panel for the home page.
2. Make a flag for each section that needs to appear on the home page.
3. Make a view (content pane) for each section. The view should display the most recent node tagged with the flag for that section. Add each view to the appropriate place on the home page panel.
4. Add a rule that, when a node is flagged, uses the trim flag action to ensure that only one node is flagged with that flag at any given time.

If you do this, your content editors can simply flag the pages they want and they will be displayed in the appropriate sections automatically. (I have used all these modules to do a similar thing in the past, though I have not built this exact workflow.)
> 0 votes

---
Tags: views, nodes, users
---


title: sql error when installing a module

text:
# Question
Title: sql error when installing a module
after enabling raydash module the message appear
`PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unsigned NOT NULL COMMENT 'The session id foreign key',`token`VARCHAR(32) NOT' at line 4: CREATE TABLE {raydash_stream} (`nid`INT unsigned NOT NULL auto_increment COMMENT 'The table for the stream',`entity\_id`INT unsigned NOT NULL auto_increment COMMENT 'The entity in the video stream that\ncoresponds to the token',`session\_id`VARCHAR(128) unsigned NOT NULL COMMENT 'The session id foreign key',`token`VARCHAR(32) NOT NULL,`connected\_token`VARCHAR(32) NOT NULL COMMENT 'The token this video-stream is connected', PRIMARY KEY (`nid`,`entity\_id`,`session\_id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'The table stores video stream'; Array ( ) in db_create_table() (line 2684 of C:\xampp\htdocs\drupal\includes\database\database.inc)`.
How to fix it?

# Answer
The Raydash module (if it's this one) appears to be a sandbox project that isn't even hosted on Drupal.org.

Sandbox projects are not suitable for production use and usually have a number of bugs; this is what makes them sandbox projects rather than real modules on Drupal.org.

Also, the Raydash module I linked to only had one commit a year ago. Drupal 7 has changed some since then so it's unlikely that this module would still work "out of the box" if it ever did.

I would disable the module for now and either:

* Consider forking the module and fixing it yourself (giving back the patches if you succeed) or

or

* Looking for a different solution.
> 1 votes

---
Tags: 7, database
---


title: Insert module inserts image twice?

text:
# Question
Title: Insert module inserts image twice?
So I'm kind of new to Drupal and I apologise if this is a stupid question. But I've been trying to get both FlexSlider and Insert to display correctly in the frontend. I've add them to the basic content content type.

Both modules have an image field and display associated with them and they do indeed show up in the frontend, but if I use the Insert module then the image gets show twice and I can't get FlexSlider to appear before the content.

The Edit screen displays correctly:

You can see the slider image field is before the body content and title as I've defined in fields and there is only one image upload and an insert button which works as expected.

But then if you look at what is output on the home page:

You can see that (a) the slider is showing at the bottom of the page and (b) the uploading images are displayed unless I delete them after uploading and inserting them.

# Answer
> 3 votes
You just need to go to the "Manage Display" admin page for your content type (e.g. http://mysite.com/admin/structure/types/manage/article/fields for the 'article' content type).

There you can hide/reorder all of the fields in your content type.

I would guess that currently you have a display field that's aggregating the "Image" field inside of it, and that you also have the "Image" field itself set to display. This would account for the same image being displayed twice.

---
Tags: 7
---


# Question
Title: Where to place PHP code for a node if not in the node body block itself?
Up until now, I have found it most convenient and easy to place PHP code into my node by placing it in the node body and enabling the PHP filter. However, I have been informed that this is incorrect and unsafe.

Furthermore, I also know that it would be incorrect to place PHP code in node.tpl.php.

Could someone please tell me where the correct place to place PHP code for a node would be?

# Answer
One of two places, `hook_node_view()` or `hook_preprocess_node()`. They can both be used in a module file, but only the latter will work in your theme's template.php file.

`hook_node_view()` example:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_node_type') {
    $args = array(':nid' => $node->nid);
    $my_value = db_query('SELECT my_field FROM {my_table} WHERE nid = :nid', $args)->fetchField();

    $node->content['my_value'] = array(
      '#markup' => 'My value is: ' . $my_value,
      '#weight' => 10 // Controls the display order of this piece of content
    );
  }
}

```

`hook_preprocess_node()` example:

```
function MYMODULE_preprocess_node(&$vars) {
  $vars['content']['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

```
> 5 votes

---
Tags: 7, nodes
---


# Question
Title: Adding an auto-complete field to a custom module form
I am trying to add two auto-complete fields to a form I am using to generate two types of reports. What I have going on is that we have interfaced the CometChat chat system with Drupal using a custom module and now the customer wants reports for it. We realized that the best way for the user to narrow the result set is to let them use an auto-complete field for chatrooms by name and instant messages by individual.

Since I will be querying non-Drupal tables in the DB to do so I cannot just use a CCK field and the autocomplete widgets module (unless you know a trick on how to do that). I have never done an auto-complete field before in my life.

I know that I need to create the menu hook page callback, but I am not entirely sure how the JS and pingback should work to best do something like this. Does anyone know how to get started?

I am going over the code for the autocomplete widgets module to learn from it right now. But I would love any help with this.

Thanks!

# Answer
> 7 votes
There's a full example for Drupal 6 here: Textfield that uses autocomplete. The code will probably be useful to people on this site as well so I'll post i here:

*The following is based on a module with the name: 'cities'*

In your form function:

```
$form['city'] = array(
  '#type' => 'textfield',
  '#title' => 'City',
  '#maxlength' => 128,
  '#autocomplete_path' => 'cities/autocomplete',
);

```

In your module file:

```
function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' => 'Autocomplete for cities',
    'page callback' => '_cities_autocomplete',
    'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
    'type' => MENU_CALLBACK
  );
  return $items;
}

```

Also in your module file:

```
function _cities_autocomplete($string) {
  $matches = array();
  //search table `cities` for cities that begin with the letters the user enters in the form
  $result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%')", $string, 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->city] = check_plain($data->city);
  }
  // return for JS
  print drupal_to_js($matches);
  exit();
}

```

---
Tags: 6, ajax
---


# Question
Title: how to replace file with an empty file of the same name?
My Set-Up:

When a user uploads a file, it first gets uploaded to a folder on my local server, and then gets moved to an amazon s3 server for storage. Currently, when the file is moved to s3, the local file gets deleted.

What I would like to do:

Rather than delete the local file, I would like to replace the local file with a 0-byte file. Reason: so that if another user uploads a file with the same name, the system will know it needs to rename the second file.

My Question:

How can I replace a file ("myvideo.flv") with an empty file of the same name, so that "myvideo.flv" now contains 0 bytes?

# Answer
To replace a file with a zero byte file use a combination of `unlink()` and `touch()`:

```
unlink($file_path);
touch($file_path);

```

To move a file to a different folder use Drupal's `file_move()`:

```
file_move($src_file_path, $dest_file_path);

```

To rename a file use `rename()`:

```
rename($file_path);

```

All of the above make the assumption that your webserver user has read access over the source path, and write access to the destination path.

**EDIT**

Your original question asked about moving/renaming files as well, I'll leave the answer to those in just in case you're still wondering.
> 2 votes

---
Tags: files
---


title: Cannot disable or replace logo

text:
# Question
Title: Cannot disable or replace logo
I set up a subtheme of Bartik in Drupal 7. I also set up the private file system. I was styling everything and when I went to upload a logo, the logo broke. Now the logo url is `private://logo_0.png`. I cannot remove the logo, disable it via the checkbox, or set it back to `default`.

I tried some of suggestions from around the net such as using \[theme\]\_preprocess\_node. I also tried using a default bartik "template.php" file. (I renamed all the prefixes in it to match my theme name.)

Nothing seems to work and this is the weirdest bug I've EVER encountered in Drupal. Anyone have some suggestions or a push in the right direction to try and fix this?

# Answer
> 0 votes
I need to disable the Bartik theme completely to make the sub-theme work.

---
Tags: 7, media
---


# Question
Title: Setting up a download page requiring a user to fill a form before downloading anything
In the Drupal site I'm setting up, there's a Download page containing several links to download softwares.

1. What is the best way to "bind" the softwares to the page, put them anywhere online and place a direct link in the page?
2. Does anyone know a module that would show a contact form when a user clicks one of the "Download" buttons, preventing him from downloading unless he properly completes the form? Our goal is to receive the contact information of any person downloading our software.

# Answer
There is Webform Protected Downloads. But it will result to quite a different structure from yours. Webform Protected Downloads allows someone to download a "protected" file after filling out a webform. You can add more than one file and have the download links expire after a certain time.

When also looking for something like your issue I also found another module (don't remember the name) that added a page before redirecting you to a node. So maybe you could add a webform page to send the user before reaching the download page. But if he knows the link he could bypass it of course.
> 2 votes

# Answer
I created a module named jhmodule to handle the form submission and set session for a user, code is as follows

```
    <?php
//hook menu to handle form
function jhmodule_menu() {
    $items['downloads/pdf'] = array(
        'title' => 'Form submit',
        'page callback' => 'send_link',
        'access callback' => TRUE,
    );
    return $items;
}

function send_link(){
   if(isset($_SESSION['pdf_download_session'])){
       $pdf_download_session = set_session_for_download($_POST);
        $out = json_encode($pdf_download_session);
   }  else {
        $pdf_download_session = set_session_for_download($_POST);
    $out = json_encode($pdf_download_session);
}
    $clean_file_name = rawurlencode($_POST['file_name']);
    $out = json_encode('/sites/default/files/'.$clean_file_name);
  print $out;
    return ;
}

function set_session_for_download($argument_a){
    if(!isset($_SESSION['pdf_download_session']))
    {
    $_SESSION['pdf_download_session'] = array('fname'=> $argument_a['fname'], 'lname'=> $argument_a['lname'], 'new'=>'yes');
    $pdf_download_session =  $_SESSION['pdf_download_session'];
    }  else {
         $pdf_download_session =  $_SESSION['pdf_download_session'];
    }
return json_encode($pdf_download_session) ;
}

```

In page--contentType.tpl.php link to the form and checking if the session is set if the session is set jquery adds path to the filename:

```
//node--contentType.tpl.php
<span rel="#pdf_form" class="download_link download_link_one"><a file_name="<?php
        if (isset($content['field_application_sf_download']['#items'][0]['filename'])) {
            print $content['field_application_sf_download']['#items'][0]['filename'];
        }
        ?>" href=""><img src="/sites/all/themes/jhtheme/images/whitepaper_btn.png"/></a></span>

//page--contentType.tpl.php
<form action="downloads/pdf" method="POST">

    <input type=hidden name="oid" value="test">
    <input type=hidden name="retURL" value="http://**Insert Thank You Page Address Here**">
    <div class="form-sections-holder">

        <div class="frame">

            <div class="form-left-content"> <p class="formTitle">Lorem Ipsum sit dolor</p>

                <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In posuere felis nec tortor. Pellentesque faucibus. Ut accumsan ultricies elit. Maecenas at justo id velit placerat molestie.</p>

                <p>Donec dictum lectus non odio. Cras a ante vitae enim iaculis aliquam.</p>

            </div>

            <div class="form-right-content">

                <div class="row">

                    <div class="text">

                        <input type="text"  name="first_name" id="first_name" value="First Name" />

                    </div>

                    <div class="text">

                        <input type="text"  name="last_name" id="last_name" value="Last Name" />

                    </div>

                </div>

                <div class="row">

                    <div class="text">

                        <input type="text"  name="email" id="email" value="Email" />

                    </div>

                    <div class="text">

                        <input type="text"  name="company" id="company" value="Company" />

                    </div>

                </div>

                <div class="row">

                    <div class="text">

                        <input type="text"  name="city" id="city" value="City" />

                    </div>

                    <div class="text">

                        <input type="text"  name="state" id="state" value="State / Province" />

                    </div>

                </div>

                <div class="row">

                    <input class="submit" type="image" value="Submit" alt="Submit" src="/sites/all/themes/jhtheme/images/submit.png">

                </div>

            </div>

        </div>

    </div>

</form>
 <?php
            if (isset($_SESSION['pdf_download_session'])) {
                print '<div id="pdf_download_session"></div>';
            }
            ?>

```

JQuery to handle the form submission.

```
    //download link for pdf
jQuery('.download_link').click(function(){
    if(jQuery('#pdf_download_session').length >0){
        var file_name = jQuery('.download_link a').attr('file_name');
        jQuery('.download_link a').attr('href', '/sites/default/files/' + file_name);
        return true;
    }else
    {
        jQuery('#pdf_form, #fader_wrapper').show();
        //form overlay
        jQuery("span[rel]").overlay();
        jQuery('#pdf_form a.close').click(function(){
            jQuery('#pdf_form, #fader_wrapper').fadeOut(100);;
        });
    }
    return false;
});
//form validation
jQuery('#pdf_form').find('input').blur(function(){
    var blur_element = jQuery(this);
    if(blur_element.val().length == 0 ){
        jQuery(this).addClass('form_warning');
    }
});
jQuery('#pdf_form').find('form').submit(function(){
    var fields = {
        first_name: jQuery('#first_name').val(),
        last_name: jQuery('#last_name').val(),
        email: jQuery('#email').val(),
        company: jQuery('#company').val(),
        city: jQuery('#city').val(),
        state: jQuery('#state').val(),
        file_name: jQuery('.download_link a').attr('file_name')
    }
    jQuery.ajax({
        type: "POST",
        url: '/downloads/pdf',
        data: fields,
        dataType: 'json',
        success: function(pdf_location) {
            jQuery('#pdf_form').hide();
            jQuery('.ad-block .frame').append('<div id="pdf_download_session"></div>');
            window.location = pdf_location ;

        }
    });
    return false;
});

```

Later on as I get more time I will try to explain each step more. In my case form data was going to be handled by third party application that is the reason I am doing every thing manually. You should think about using drupal's form api.
> 2 votes

---
Tags: 7
---


# Question
Title: Custom validation for a custom field in comment form
I'm currently trying to set up a custom validation script to prevent spam on a comment form with hidden elements. The problem involves setting up the conditional for the submitted form values. I'm currently using the hook\_form\_FORM\_ID\_alter. Here is my existing code.

```
function STARTERKIT_form_comment_node_contact_page_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'comment_validation_function';
}

function comment_validation_function($form, &$form_state)
{
    if ($form_state['values']['field_website'] != 'http://') {
        form_set_error('field_website', t('Please do not change the value of this field.'));
    }
}

```

The problem is that $form\_state\['values'\]\['field\_website'\] isn't returning the value inside the text field. I've looked at so many pages showing a script very similar to this, yet I haven't been able to get this even close to working.

The field id is "field\_website".

# Answer
Assuming the field is a text type (and your site is monolingual) you'll find the value here:

```
$form_state['values']['field_website'][LANGUAGE_NONE][0]['value']

```

There's an explanation here.

Instead of doing this, though, you might want to have a look at the Field Validation module, which will let you add the same validation rule through the UI.
> 0 votes

---
Tags: forms
---


# Question
Title: Media Gallery module field settings stored in database?
I have installed the Media Gallery module for someone's site to upload fotoalbums with; it's need to add a file size restriction because quite a bit of pictures are coming in.
I can't tell what the exact error is in English; the site's language is Dutch. When I want to edit fields in my Media Gallery content type, I get a message that says the settings are stored in the database, locked and I can't change those settings anymore.

**Update:** There is a similar issue at Drupal.org; it looks like it isn't possible. Or is it?

# Answer
> 0 votes
You can make the 'dirty solution' from the link posted by @NikhilMohan into a more 'clean' one pretty easily:

```
function MYMODULE_form_media_gallery_node_form_alter(&$form, &$form_state) {
  if (arg(1) == 'add') {
    // Get the language code from the node object. Should be reliable.
    $langcode = $form['#node']->language;

    $form['settings_wrapper']['presentation']['media_gallery_allow_download'][$langcode]['#default_value'] = 0;
  }
}

```

If you're not comfortable writing a custom module you can easily drop this function into your theme's template.php file instead, but change the name of the function to `MYTHEME_form_media_gallery_node_form_alter`. Once you clear Drupal's caches the hook will start to be called.

Don't forget that Media Gallery is still in beta so you have to expect a few bugs/missing configuration options. Using hooks to alter the fields you need to is pretty much the only option you have here, without going directly into the database.

---
Tags: 7, media
---


# Question
Title: Change text on "Create new Account" button makes administration created user registration fail
In the form provided by `user_registration_form()`, I modified the text for the "Create New Account" button to "Sign me up!" via the following code:

```
$form['actions']['submit']['#value'] = t('Sign me up!');

```

Creating a new account as anonymous user from the main site works fine: new button text, customized validation and submission included. Now, if I want to create a new user as administrator via "People -\> 'Add User'," the form and button are correctly displayed, but NOTHING happens once I hit the button! Somehow, all validation and submission routines seem to be deactivated by renaming this button. Do you have any idea why this is happening?

# Answer
That code works without a problem for me. I hope you didn't change the code in Drupal's user module directly?

You should make this change by implementing hook\_form\_alter() in your own custom module or theme.

```
function MODULENAME_form_user_register_form_alter(&$form, $form_state, $form_id) {
     //your changes here
   }

```
> 1 votes

# Answer
Maybe submit and validation handlers in admin form expect specific name only.. you could profile / debug to be sure.

What u could probably do is instead of modifying label from form\_alter, you could use translate inerface feature and give it desired name that way, since the label is already going through t() function.
> 0 votes

---
Tags: 7, users, forms
---


# Question
Title: Apple-like button style carousels in Drupal 7?
I would like to build a carousel which supports Apple-like scrolling, like at http://www.apple.com/displays/ So you would have a carousel with small "buttons" at the bottom which allow for easy navigation. The jcarousel module seems the preferred module for carousels, however it does not seem to support this type of carousel? I can not find a way to get links to all images/nodes/... to realise this via a different jcarousel template. I did not find alternatives to carousel implementations in Drupal 7, but I might be mistaken of course :-)

# Answer
The Views Slideshow module can do this and is stable for Drupal 7.
> 1 votes

# Answer
NivoSlider looks pretty much like that, but neither NivoSlider module has a stable D7 release. I'm currently using it on my personal site without any module - take a look at http://nivo.dev7studios.com/
> 0 votes

---
Tags: views
---


# Question
Title: Drupal Registration Form In Lightbox With Ajax
I updated my post up top to pull in the user form created in Drupal, it now loads it in a lightbox correctly, how can I submit this using AJAX, validate this all in the Lightbox? any ideas?

Any help would be good help :)

```
    <?php
function ajax_register_menu() {
  $items['request'] = array(
    'page callback' => 'ajax_register_mypage',
    'page arguments' => array('ajax_register_form'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'title' => t('MY TITLE'),
  );

  $items['request/submit'] = array(
    'page callback' => 'ajax_register_submit',
    'type' => MENU_CALLBACK,
    'access callback' => FALSE,
  );

  return $items;
}

function ajax_register_mypage($form){
    print '<div style="background: #FFFFFF;">';
    print 'Hello World';
    print render(drupal_get_form('user_register_form'));
    print '</div>';
}

function ajax_register_submit() {
    $returnO = new StdClass();
    $returnO->status = true;
    $returnO->message = 'MY INFORMATIVE MESSAGE HERE';

    print drupal_json($returnO);

    die;
}
?>

```

# Answer
If I recall correctly, instead of calling render() for your drupal\_get\_form(), call drupal\_render() instead.

```
<?php

function ajax_register_mypage($form){
  print 'Hello World';
  print drupal_render(drupal_get_form($form));
}

?>

```

Hope this ends up solving your issue on this one.
> 0 votes

---
Tags: ajax, users, javascript
---


# Question
Title: Add a class to all title text fields in all content add forms
I'm using Twitter Bootstrap and I want to expand the length of all the title fields in the content forms by adding 'span6' to the class attribute for the title field's input element.

I've added the following function to my template.php file:

```
function ccom_field__title($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

Right now all I've done to it is change the name of the function according to the functions preceding comment. I'm not sure what I need to do, because I need to add the class to the input element directly, and not its parent div element.

Using JavaScript (including jQuery) is not an option.

TL;DR

How does one add a class to a specific field's input element?

# Answer
> 3 votes
The content title is a property rather than a field, so overriding `theme_field()` isn't the way to do this.

Instead you might want to use a `hook_form_FORM_ID_alter()` (which can also be used in your theme's template.php file):

```
function ccom_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#attributes']['class'][] = 'span6';
}

```

---
Tags: 7, theming
---


# Question
Title: Why is Views "Query Execute Times" so high?
I have a basic view that shows a list of members and their user points. The views query output show that this query takes over 1500ms to run.

Query build time 24.71 ms

Query execute time 1546.84 ms

View render time 88.29 ms

> SELECT users.picture AS users\_picture, users.uid AS uid, users.name AS users\_name, users.mail AS users\_mail, users.created AS users\_created, userpoints\_total.points AS userpoints\_total\_points, 'user' AS field\_data\_field\_motorcycle\_user\_entity\_type, 'user' AS field\_data\_field\_review\_count\_user\_entity\_type, 'user' AS field\_data\_field\_address\_user\_entity\_type
>
> FROM {users} users LEFT JOIN {userpoints\_total} userpoints\_total ON users.uid = userpoints\_total.uid WHERE (( (users.status \<\> '0') AND (users.uid NOT IN ('1')) )) LIMIT 10 OFFSET 0

When I copy and paste that query into myphpadmin and run it there it takes less than 5ms. What else is happening in the "Execute Time"? I coudn't find any good help about that on the web.

# Answer
> 7 votes
When testing be sure to turn off the query cache `SET SESSION query_cache_type = OFF`

Next step is to run `EXPLAIN` on the sql.

EXPLAIN SELECT users.picture AS users\_picture, users.uid AS uid, users.name AS users\_name, users.mail AS users\_mail, users.created AS users\_created, userpoints\_total.points AS userpoints\_total\_points, 'user' AS field\_data\_field\_motorcycle\_user\_entity\_type, 'user' AS field\_data\_field\_review\_count\_user\_entity\_type, 'user' AS field\_data\_field\_address\_user\_entity\_type

---
Tags: views, performance
---


# Question
Title: Entity alteration to prevent entity from being indexed by search_api
I'm using search\_api/search\_api\_solr, and would like to be able to exclude certain nodes from being indexed by Solr at all. In looking at search\_api.api.php, I see this text:

> Please be aware that generally preventing the indexing of certain items is deprecated. This is better done with data alterations, which can easily be configured and only added to indexes where this behaviour is wanted. If your module will use this hook to reject certain items from indexing, please document this clearly to avoid confusion.

I'm just getting into the whole entity API, so it's not so "easy" for me to do this. I'm thinking that he's referring to hook\_entity\_property\_info\_alter(), and I've used that to add a property to an entity so it is available as a facet and field available in search results. However, I'm not seeing how to alter the entity so that I can control whether it is indexed by search\_api or not. Can someone point me in the right direction?

Thanks.

# Answer
When he says "better done with data alterations" he is referring to the "Data Alterations" fieldset / section in the "Workflow" tab for each index in the UI and that is accessible in code through hook\_search\_api\_alter\_callback\_info().

You can see a patch that uses this (it doesn't use the hook but the original function because it is being added to the actual search\_api module but you get the idea) to not index unpublished nodes: http://drupal.org/node/1507882

I think his audience for this comment is other contributed module makers. You can imagine it would be extremely confusing for a user if certain items didn't get indexed because a module they turned on used that hook.

If you are trying to exclude nodes from being indexed (be aware that you can use the "Node Access" data alteration which will keep unpublished nodes from being returned for searches for users who don't have content editing access) you can use that hook checking for the node ids and unsetting them as in the example function.
> 3 votes

---
Tags: search
---


# Question
Title: Allow editing of only a single field of a node in Panels or a block
I am working with drupal 7. I have organic groups and cck set up. I want users to be able to only edit the group audience field in an organic group but nothing else. Is there a way where I can only add a group audience edit field to a panel or a block ?

I looked at the form block module, but that provides access to the complete content edit page.

Thanks.

# Answer
> 2 votes
You might be able to use the Field API Pane Editor. Though the name may be unusual, the module

> adds a contextual link to the Entity Field panel pane which allows that field to be edited without having to visit the entity's edit page.

Earl Miles introduced this module at DrupalCon 2012 (see 13:30 in the linked video).

# Answer
> 2 votes
Try the Field Permissions module:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you allow your users access to the group edit form, they will only see the fields that you have selected to be editable using Field Permissions.

Use that in conjunction with the form block module as you've suggested and you should get the effect that you're looking for.

# Answer
> 2 votes
Clive has suggested a good solution, but I will adress the Panels part of the question as this also comes up in the issue queue every now and then.

Unfortunately, the answer is that, "yes you can", but you should not. Panels will allow you to render a single form edit field, but form api will does not support this, and so saving will not behave as you intended.

---
Tags: blocks, panels, nodes
---


title: Confirm delete via AJAX

text:
# Question
Title: Confirm delete via AJAX
How can I have a JS confirmation button pop-up when a user clicks a button and then fire the #ajax defined for that button?

Right now, I have this button at the end of my form:

```
    //add an update button to the end of every row
    $form[$row_name][sizeof($data['columns']) + 1] = array (
        '#type' => 'button',
        '#value' => t('Delete Row'),
        '#name' => $row . '-_udr_delete_data',
        '#prefix' => "<td class='delete-button'>",
        '#suffix' => "</td>",
        '#ajax' => array (
            'callback' => '_udr_ajax_handler',
            'progress' => FALSE,
         ),
        '#weight' => 1001,
    );
  }
  $form['table_end'] = array(
      '#prefix' => '</table>',
  );

  //if the form has been changed, update the appropriate fields
  if ( isset($form_state['triggering_element']) ) {
    $callback = _name_to_callback($form_state['input']['_triggering_element_name']);
    if ($callback == "_udr_update_data") {
      _udr_update_data($form, $form_state, $data);
    }
    elseif ($callback == "_udr_delete_data") {
      _udr_delete_data($form, $form_state, $data);
    }
  }
  return $form;
}

```

I would like to make this button make a pop-up warning that asks the user if he/she would like to really delete the data. If yes, then delete. If no, then don't delete.

I have tried various methods such as:

```
'#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),

```

And also:

```
    // Add an delete button to the end of every row
    $form[$row_name][sizeof($data['columns']) + 1] = array (
      '#type' => 'submit',
      '#submit' => array('udr_submit_rebuild'),
      '#value' => t('Delete Row'),
      '#name' => $row . '-_udr_delete_data',
      '#prefix' => "<td class='delete-button'>",
      '#suffix' => "</td>",
      '#ajax' => array (
        'wrapper' => "row-$row",
        'callback' => '_udr_ajax_handler',
        'progress' => FALSE,
      ),
      '#weight' => 1001,
    );
  }

  if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == t('Delete Row')) {
    $form[$row_name][sizeof($data['columns']) + 1]['#value'] = t('Really Delete?');
    $form[$row_name][sizeof($data['columns']) + 1]['#submit'] = array('udr_submit_handler');
  }

  $form['table_end'] = array(
    '#prefix' => '</table>',
  );

  //if the form has been changed, update the appropriate fields
  if ( isset($form_state['triggering_element']) ) {
    $callback = _name_to_callback($form_state['input']['_triggering_element_name']);
    if ($callback == "_udr_update_data") {
      _udr_update_data($form, $form_state, $data);
    }
    //~ elseif ($callback == "_udr_delete_data") {
      //~ _udr_delete_data($form, $form_state, $data);
    //~ }
  }
  return $form;
}

function udr_submit_rebuild($form, &$form_state, $data) {
    $form_state['rebuild'] = TRUE;
}

function udr_submit_handler($form, &$form_state, $data) {
  $callback = _name_to_callback($form_state['input']['_triggering_element_name']);
  if ($callback == "_udr_delete_data") {
    _udr_delete_data($form, $form_state, $data);
    $form_state['rebuild'] = TRUE;
  }
}

```

# Answer
The correct way to fix this issue is to is to attach a JavaScript watch to the button and have the trigger make a confirm dialog pop up and then make a JavaScript request from the user's browser back to a URL with a parameter of the element to be deleted at the end of it, then fade out the rows from the HTML table and make sure the zebra striping is correct, then secure that second URL to have the same permissions as the original page, then receive the parameter at the called URL and process the callback you had originally intended to run:

PHP:

```
onclick="Drupal.dccAdmissions_confirm_delete('$rec->pi_firstname $rec->pi_lastname', '$rec->pi_id . ', '$rec->pi_id', jQuery(this) );

```

JavaScript:

```
( function($) {
  Drupal.dccAdmissions_confirm_delete = function( in_name, id, object ) {
    if ( confirm( 'Do you want to delete the application for ' + in_name + '?' ) ) {
      $.ajax({
        type: 'GET',
        url: '/admissions/application/delete/' + id,
        success: function(data) {
          if ( data == 'DELETED' ) {
            // Remove the specific row
            $(object).parents('tr').fadeOut( 1000 );
            $(object).parents('tr').remove();
            $('#dccadmissions-application-management-form tr:nth-child(odd)').addClass( 'odd' );
            $('#dccadmissions-application-management-form tr:nth-child(odd)').removeClass( 'even' );
            $('#dccadmissions-application-management-form tr:nth-child(even)').addClass( 'even' );
            $('#dccadmissions-application-management-form tr:nth-child(even)').removeClass( 'odd' );
          } else {
            alert( 'Delete failure: ' + data );
          }
        }
      });
    }
  }
  Drupal.dccAdmissions_confirm_reset = function( in_name ) {
    return confirm( 'Do you want to reset the application for ' + in_name + '?' );
  }
})(jQuery);

```

Make a menu hook:

```
function dccAdmissions_menu() {
  $items['admissions/application_management'] = array (
    'title' => t("Admissions Online Application Management"),
    'page callback' => 'dccAdmissions_application_management_content',
    'type' => MENU_CALLBACK,
    'access callback' => 'dccInGroup',
    'access arguments' => array( 'Admissions' ),
  );

```

Check your cases:

```
/*
 * Page callback for application management pages.
 */
function dccAdmissions_application_management_content( $arg1 = 'new', $arg2 = 0, $arg3 = '' ) {
  include_once "application-management.data.inc";

  $module_path = drupal_get_path( 'module', 'dccAdmissions' );
  $output = array(
    '#attached' => array(
      'css' => array( $module_path . '/css/application-management.css', ),
      'js'  => array( $module_path . '/js/application-management.js', ),
    ),
  );

  switch( $arg1 ) {
    case 'delete':
      $message = _dccAdmissions_application_management_delete( $arg2 );
      return drupal_json_output( $message );
      break;

```

Then delete your data:

```
function _dccAdmissions_application_management_delete( $id ) {
//... your delete code here...

```
> 3 votes

---
Tags: forms, ajax
---


# Question
Title: How do I hide nodes tagged with a specific taxonomy term in views?
I'm on d7. I have a multi taxonomy term vocabulary that I allow users to add up to three terms. I'm using the flag term module and have a global flag set up to flag a term as hidden. Ive set up a filter in my view that only shows nodes that have terms that are NOT flagged as "hidden". This is working when one a node only has one term that is hidden, but when it has two or more that are not, it shows the node in my view. How can I make it so that if a node has a term flagged as "hidden" it doesn't show up in my view list even if it has another term that is not flagged? Thanks.

# Answer
You need to add a new filter to your view.

* Filter criterion: Has taxonomy term
* Vocabulary: Corresponding vocabulary
* Operator: Is none of
* And select the hidden term in the dropdown
> 1 votes

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


title: Views grid - align fields

text:
# Question
Title: Views grid - align fields
I'm using Drupal 7, and I have a content type called Book, which consists of a picture and a title. I'm using Views (grid format) to display Books on a page, and it's working great. The only problem is that the titles always sit directly under the picture, which looks bad if the pictures are of different heights. Is there a way to horizontally align all fields within a grid?

This is what I currently have:

```
_____   _____   _____
|    |  |    |  |    |
|    |  |    |  |    |
|____|  |    |  |____|
title   |____|  title
        title

```

And this is what I want:

```
_____   _____   _____
|    |  |    |  |    |
|    |  |    |  |    |
|____|  |    |  |____|
        |____|
title   title   title

```

I've managed to achieve this by overriding views-view-grid.tpl.php (and adding a new row to the table for each field), but was wondering if there was a better way?

Update: I'm not interested in solutions that involve changing the layout / picture sizes. This is the second time a designer has given me a PSD that leaves me facing this issue, so I'd really like to find a good solution to this exact problem!

# Answer
> 1 votes
If the images are of different sizes, it might look a lil sloppy. You can use CSS to set a particular height and width for all the images so that they look uniform and I guess overriding views-view-grid.tpl.php just for this is not the best way.

# Answer
> 0 votes
This is the way I used to do it. http://www.advomatic.com/blogs/amanda-luker/table-free-gallery-grid-view-drupal-theming However this post is a bit dated. That said, same size images really is the way to go if you can, or set a definite height.

---
Tags: views
---


# Question
Title: How do I print the node add form in block.tpl.php?
I am using Microblog. How do I print the node add form in a block?

I tried `node_add('microblog')`, but it doesn't work for me; then, I tried `drupal_get_form('microblog_node_form')`, but I am still getting nothing.

# Answer
> 2 votes
Maybe you could look at the Form Block module, which will allow you to easily create blocks with node add forms for your content types.

# Answer
> 3 votes
The drupal\_get\_form approach is correct. Make sure you use

```
print drupal_get_form(....

```

Edit:

Take a look at function `node_add()`. You also need a `$node` parameter for this form. So like

```
<?php
  global user;
  $node = array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'foo', 'language' => '');
  print drupal_get_form('foo_node_form', $node);
?>

```

# Answer
> 2 votes
```
module_load_include('inc', 'node', 'node.pages');

$form = node_add('nodetype');

print drupal_render($form);

```

# Answer
> 1 votes
Placing this in a block works for me:

```
<?php
  module_load_include('inc', 'node', 'node.pages');
  print drupal_render(node_add('CONTENT_TYPE'));
?>

```

---
Tags: 7, forms, theming
---


title: Force comment form to show

text:
# Question
Title: Force comment form to show
I was trying to make my comments form show on a node type that has gallery assist but for some reason it doesnt have any options to change the value to make it show.

is there a module or some sort of way using hook form alter to force the default comments form to show on a node type?

# Answer
You should be able to go into the Edit Content type form simply turn on comments. Are you sure the option is not there?
> 0 votes

---
Tags: 6, media
---


# Question
Title: How can I make or render a website with wiki features(for e.g wikipedia) with Drupal?
The question is can I render wiki features in my website which is to be made with Drupal.For e.g if I make a website with tons of features how can Wiki feature be made functional with Drupal.If no should I make new themes.

# Answer
> 8 votes
To allow contributors to easily link between multiple pages, check out the Freelinking module.

To enable simple plain-text formatting, check out the Markdown module.

To allow editing subsections of text individually, check out the Edit Section module.

To automatically generate a Table of Contents for each node, check out the Table of Contents module.

To move comments to a separate page (similar to the Wikipedia "Talk" pages), check out the Talk module.

# Answer
> 4 votes
Have you tried http://drupal.org/project/wikitools ?
Drupal have a native revision system, so this is an essential part of a wiki.
Can you describe a little more what kind of features you're expecting ?

# Answer
> 1 votes
I'm working on a similar project and I make use of following combination

1. Installed the profile Corporative Site, as it contains the the rich text editor - "CKEditor" and the image upload option with IMCE preconfigured.
2. Enabled the "book" module which is a part of drupal core from *admin/modules*, as it contains the most of the wiki features by default.
3. Installed ACL and Content Access to give appropriate access to the types of users like - Administrator, Author(The one who will be responsible to add a book page), and Authenticated user(will just see the page and comment.
4. And created a sub-theme by following this procedure.

---
Tags: theming, nodes, features
---


# Question
Title: Importing products into Drupal Commerce and handling Tax
Im working on an integration module where I'm trying to import products externally and into Drupal Commerce. I revceive the product object externally like this: 2692604 (Object) stdClass id (Integer) 2692604 revision (Integer) 2 currencyCode (String, 3 characters ) NOK vatType (Integer) 3 name (String, 14 characters ) Produktkatalog priceCurrency (Integer) 235 priceIncVatCurrency (Integer) 294 number (String, 4 characters ) 1003 cost (Integer) 230

I've found a code snippet from the commerce\_example module where you can create a product programmatically like this:

```
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;

// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);

commerce_product_save($new_product);
return $new_product->product_id;

```

I have defined a tax type and a set of tax rates - including a mapping from the code found in the importing object.

I'm thinking the correct way of adding the tax part should be by modifying the code to something like this:

```
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => $product_obj->vatType,
  'data' => array('include_tax' => 'MVA_hoy'),
)));
$form_state['values']['commerce_price'] = $price;

// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);

commerce_product_save($new_product);

```

Problem is that when I import the products, the tax rate is not set as I would expect it to. Investigating the newly created product (or an old loaded product) does not give me much clue either...

# Answer
Found the solution it seems. It is apparently not enough to add a field under the data array, you also need to add the include\_tax field on the same level as amount and currency:

```
//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => $product_obj->vatType,
  'data' => array('include_tax' => 'MVA_hoy'),
  'include_tax' => 'MVA_hoy',
)));
$form_state['values']['commerce_price'] = $price;

```

Now, when importing products, the tax field is updated.
> 5 votes

---
Tags: 7, commerce
---


# Question
Title: Warning: Cannot use a scalar value as an array in _block_get_renderable_array() on hook_block_info / hook_block_view
I'm trying to create a module that creates a block to a specific region so I use this module on multiple sites instead of using the admin menu copy and pasting creating blocks with HTML code in it and putting it in the region that I want it to be.

Somehow the block doesn't even shows up in the blocks admin section. Maybe I'm overlooking something but I quite sure my code is correct for the hooks implemented below:

```
/**
 * Implements hook_block_info()
 */
function bannert_block_info() {
    $blocks['bannert'] = array(
        'info' => t('bannert'),
        'cache' => DRUPAL_CACHE_PER_PAGE,
        'region' => 'three_33_third',
        'status' => 1,
    );

    return $blocks;
}

/**
 * Implements hook_bock_view()
 */
function bannert_block_view(){
    $block['subject'] = t('');
    $block['content'] = _bannert_get_bannert();

    return $block;
}

/**
 * get banner
 */
function _bannert_get_bannert() {
    return include_once('banner.html');
}

```

The only thing I'm doubting about is the \_bannert\_get\_bannert() function but that doesn't prevent the block from being created, now does it?

I'm getting this error now:

> Warning: Cannot use a scalar value as an array in \_block\_get\_renderable\_array() (line 346 of /Users/Jack/Sites/drupal-7/modules/block/block.module). Fatal error: Unsupported operand types in /Users/Jack/Sites/drupal-7/modules/block/block.module on line 352

# Answer
> 2 votes
I changed the `_banner_get_bannert()` code to the following one:

```
function _bannert_get_bannert() {
    return "<div>push me</div>";
}

```

The error is gone, and the block is created.

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


# Question
Title: No 'read-more' to specific content type (eg page)
I've been making a content type page for my Drupal 7 website. I'd like to see an option to disable the 'read more' and the 'link' to the /node/x in the content type customization. I just want it to be displayed on the home 'as is'.

Is that possible?

# Answer
> 1 votes
You can do this by removing the "teaser" mode and tweaking node--your\_content\_type.tpl file.

To remove the teaser mode: Go to "Structure \> Content types \> your content type"; click on "Manage display" and "Custom display settings"; uncheck the "Teaser" checkbox.
This will display the content in the front page as is.

Now to remove the "read more" link, unset it in your node--your\_content\_type.tpl.

```
unset($content['links']['node']['#links']['node-readmore']);

```

This way you will not have "read more" link in your home and the whole content will be displayed for your content type.

# Answer
> 1 votes
You can use the Display Suite module, which allows controlling fields shown in different view modes for a content type.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

# Answer
> 0 votes
You can remove links just by using hook\_node\_view\_alter()

---
Tags: theming, nodes
---


# Question
Title: user registration redirect for custom form drupal 6
I have worked on a solution which will redirect from the user registration form to my own form. My own form can be reached by typing the website name testweb/my\_module/form. Here is the code of my module using a form\_alter. When I run the function it doesn't redirect to my own form. Could someone advice me why it is not working?

```
function redirect_custom_reg_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form_state['redirect'] = 'my_module/form';
  }
}

```

# Answer
It is `$form['#redirect']`, not `$form_state['redirect']` in this case because `user_register_submit()` unsets `$form_state['redirect']` (well, sets it to `''`) when it is confident that all is good with its part in the registration process...and hence allowing an alter to add in a #redirect.
> 1 votes

# Answer
Basing on the comment you left for this question, I get you want to show your own form; in this case, setting `$form_state['redirect']`, or `$form['#redirect']` is not what you want to do, as the redirection take place after the form has been submitted, which means the form validation handlers, and the form submission handlers have been already executed.
From the user's point of view what would happen is:

* The users see the default registration form used by Drupal.
* The users enter the required information.
* If they don't correctly fill the fields, the form is shown them again, together a list of error messages.
* If they correctly fil the fields, the data is saved, and they are redirected to the page that has been set through `$form_state['redirect']`, or `$form['#redirect']`.

What you want is altering the registration form, and for that there are two cases:

* You want to completely alter the existing registration form.
* You want to simply add some fields to the existing registration form.

### **Completely altering the existing registration form**

In this case, you implement \[hook\_menu\_alter()\]\[1\] to alter the menu callback used when the registration form is needed.
The menu callback for the registration form is defined in \[user\_menu()\]\[2\] using the following array:

```
  $items['user/register'] = array(
    'title' => 'Create new account',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access callback' => 'user_register_access',
    'type' => MENU_LOCAL_TASK,
  );

```

To alter it, you could use the following code in your module (replace "mymodule" with the short name if your module):

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

```

`mymodule_user_register_form()` is the form builder function that return your registration form. In this case, you are completely overwriting the default registration form, which means Drupal doesn't have control over the registration process, and your code needs to handle the full process.

### **Adding some fields to the existing registration form**

In this case, you implement \[hook\_form\_FORM\_ID\_alter()\]\[3\] to add new fields to the registration form. This is what done from the System module (part of Drupal), which uses the following code to add the field that allows the users to set they timezone.

```
function system_form_user_register_form_alter(&$form, &$form_state) {
  if (variable_get('configurable_timezones', 1)) {
    if (variable_get('user_default_timezone', DRUPAL_USER_TIMEZONE_DEFAULT) == DRUPAL_USER_TIMEZONE_SELECT) {
      system_user_timezone($form, $form_state);
    }
    else {
      $form['account']['timezone'] = array(
        '#type' => 'hidden',
        '#value' => variable_get('user_default_timezone', DRUPAL_USER_TIMEZONE_DEFAULT) ? '' : variable_get('date_default_timezone', ''),
      );
    }
    return $form;
  }
}

```

In Drupal 6, you would implement \[hook\_user()\]\[4\]; when `$op` (the first parameter) is equal to `'register'`, the registration form is going to be shown, and the hook implementation needs to return the form fields to inject in the form.
In Drupal 6, the function that has the same purpose of `system_form_user_register_form_alter()` is `system_menu()`.

```
function system_user($type, $edit, &$user, $category = NULL) {
  if ($type == 'form' && $category == 'account') {
    $form['theme_select'] = system_theme_select_form(t('Selecting a different theme will change the look and feel of the site.'), isset($edit['theme']) ? $edit['theme'] : NULL, 2);

    if (variable_get('configurable_timezones', 1)) {
      $zones = _system_zonelist();
      $form['timezone'] = array(
        '#type' => 'fieldset',
        '#title' => t('Locale settings'),
        '#weight' => 6,
        '#collapsible' => TRUE,
      );
      $form['timezone']['timezone'] = array(
        '#type' => 'select',
        '#title' => t('Time zone'),
        '#default_value' => strlen($edit['timezone']) ? $edit['timezone'] : variable_get('date_default_timezone', 0),
        '#options' => $zones,
        '#description' => t('Select your current local time. Dates and times throughout this site will be displayed using this time zone.'),
      );
    }

    return $form;
  }
}

```

The function uses a parameter list that is different from the one reported for `hook_user()`, which is `hook_user($op, &$edit, &$account, $category = NULL)`; what `system_user()` calls `$type` is called `$op` in `hook_user()` documentation.
> 1 votes

# Answer
Alternatively, you can utilize the LoginToboggan module. Here is a quote about it (from the module's project page):

> ... offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> * Allow users to login using either their username OR their e-mail address.
> * Allow users to login immediately.
> * Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> * The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> * Customize the registration form with two e-mail fields to ensure accuracy.
> * Optionally redirect the user to a specific page when using the 'immediate login' feature.
> * Optionally redirect the user to a specific page upon validation of their e-mail address.
> * Optionally display a user message indicating a successful login.
> * Optionally combine both the login and registration form on one page. Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
> * Integrates with Rules module to do various tasks when a user validates via email validation process.
> 1 votes

# Answer
you can use rules module to make actions after events, including redirect user after registration.
> 0 votes

---
Tags: forms
---


# Question
Title: my base_path is empty do I need to set this manually or is something else wrong?
I've tried putting in these values in my return:

```
base_path();

global $base_path;
$base_path;

$GLOBALS['base_path'];

```

They all end up returning nothing, while an appended string shows up just fine:

```
return '<div>' . base_path() . drupal_get_path('module','bannert') . "banner.html" . '</div>';

```

# Answer
> 1 votes
You haven't printed/returned any of your examples. It should be

```
print base_path();

global $base_path;
print $base_path;

print $GLOBALS['base_path'];

```

or

```
return base_path();

global $base_path;
return $base_path;

return $GLOBALS['base_path'];

```

Depending on the context.

A line with just a variable on it is valid PHP, but it won't do anything with the variable unless you tell it to.

**EDIT**

It's also worth considering what exactly you're expecting `base_path()` or `$base_path` to contain. The docs say this:

> Returns the base URL path (i.e., directory) of the Drupal installation.
>
> base\_path() adds a "/" to the beginning and end of the returned path if the path is not empty. At the very least, this will return "/".

Unless you have your Drupal installation in a sub-folder of the web root (e.g. http://localhost/drupal/), this function/variable will always give you the value '/'.

---
Tags: 7, uri
---


title: Searching for a pptx and pdf viewer

text:
# Question
Title: Searching for a pptx and pdf viewer
I'm using Embedded Google Docs Viewer but it's not what I need exactly.
I searched for a while but I could not find my answer.
I need a module that displays the .pdf or .ppt file like in this image.

Can anybody suggest me a module?

# Answer
> 1 votes
You can convert your PDF to a series of images and show them as slideshow, using the PDF To ImageField module.

> The PDF To ImageField module provides automatic conversion of uploaded PDF files to images. It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.
>
> The module is implemented as CCK widget for FileField where PDFs are uploaded to. It places generated images into a CCK ImageField on the same content type.

---
Tags: 7
---


# Question
Title: Module for getting what is visible from user's webcam
I need a module that allows users to show what is visible from their webcam. Is there a module that can do this?

# Answer
> 3 votes
I don't think there is exactly what you want at the moment, but the following module might help you on your way:

Webcam field \- This is still in development

> Webcam field provides dynamically updating webcam image fields. This module is compatible with Colorbox.

Videochat \- Has no recommended release, although seems to have a full 3.6 version

> The Video Chat module adds a fully hosted free video chat to a Drupal website. The chat application and video hosting are courtesy of Camamba and ad-supported. We hope it provides an alternative to all the payware chat modules out there.

Media: Webcam \- This is in beta

> This project (still under active development) will add a Webcam capture tool for video and images to FileField. Video requires a Red5 or Flash Media server to also be available; documentation for this coming soon enough.

Video conference \- This requires some further set up of server components, but if you want live video streaming I should imagine you're aware that you will most likely need a RTMP protocol set up.

> VideoWhisper Video Conference is a modern web based multiple way video chat and real time file sharing tool. It can be used stand alone or integrated as extra feature to existing sites. Internet based video conference software is great for bringing physically distant people together in meetings, trainings, conferences, live events, recruiting, consultations, coaching and of course casual community chat.

**Paid solution**

AVChat

This comes at a price of $285 plus $49 for the Drupal module

---
Tags: 7
---


title: Ecommerce Subscription

text:
# Question
Title: Ecommerce Subscription
How to setup subscription for a particular role using the ecommerce module. I want certain users to only be able to access certain content using a role. On registration I want the user to have to pay for a subscription to access special content.

# Answer
> 1 votes
This answer is based on the tutorial http://www.stonemind.net/blog/2008/02/07/tips-for-implementing-a-subscription-based-drupal-site/. Here is further information in EC subscriptions:Role products http://drupal.org/node/88239

Firstly the user needs to install various modules

* All modules in the E-Commerce Core package.
* Your payment gateway choice.
* Generic Product
* EC Recurring.
* EC Role.

It is important to note that subscription are intangible. They are not solid objects and therefore don't have an arrival time. For this reason the type of product is a "Non Ship able product" E-Commerce configuration (at /admin/ecsettings)

The tool mentions that the way rebelling is achieved is due to the cron tasks. So therefore its imperative that is can be achieved.

Multiple roles can be purchased to achieved so there can be different types of subscriptions. To enable only certain users to access certain content the node option premium module. http://drupal.org/project/nopremium. This is the replacement for the module premium that was used in drupal 6.

If you want different types of roles to be only able to see a teaser. You can use the contemplate module to achieve this task. This means that you could have content that certain users will not be able to see. A good example is news site which give a teaser and ask you to register to find out more information.

http://drupal.org/project/contemplate

---
Tags: 7, commerce, notifications
---


# Question
Title: jQuery working twice after click load more
I'm using Drupal 7.0 and Views 3 module. And my pager setting: Views Load More.

And i listing my thumbnail images via this extensions. Like this:

My thumbnail get number, mouseout shadow and hover jQuery effect. I added this codes in main.js and view\_load\_more.js

Hover code:

```
    var hoverImg = '<div class="hoverimg"></div>';

$(".thumb").each(function(){
    $(this).children("div").each(function(){
        $(this).find("a").append(hoverImg);
    });
});

$(".thumb div").hover(function() {
    $(this).find(".hoverimg").animate({ opacity: 'toggle' });
});

$(".thumb").hover(function() {
    $(this).find("div").each(function(){
        $(this).find(".shadow").fadeOut(500);
    });
});

```

Number code:

```
var c = '';
var d = '';
$('.view-content div.views-row').each(function(){
    c = 0;
    d = 0;
    var i = 1;
    d = $(this).find('.thumbimg').length;
    $(this).find('.thumbimg').each(function(){
        sayi=i++;
        $(this).append('<div class="img_no">0'+sayi+'</div>');
    });
});

```

View Load More js:

```
/**
 * @file views_load_more.js
 *
 * Handles the AJAX pager for the view_load_more plugin.
 */
(function ($) {

  /**
   * Provide a series of commands that the server can request the client perform.
   */
  Drupal.ajax.prototype.commands.viewsLoadMoreAppend = function (ajax, response, status) {

    // Get information from the response. If it is not there, default to
    // our presets.
    var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
    var method = response.method || ajax.method;
    var effect = ajax.getEffect(response);

    // We don't know what response.data contains: it might be a string of text
    // without HTML, so don't rely on jQuery correctly iterpreting
    // $(response.data) as new HTML rather than a CSS selector. Also, if
    // response.data contains top-level text nodes, they get lost with either
    // $(response.data) or $('<div></div>').replaceWith(response.data).
    var new_content_wrapped = $('<div></div>').html(response.data);
    var new_content = new_content_wrapped.contents();

    // For legacy reasons, the effects processing code assumes that new_content
    // consists of a single top-level element. Also, it has not been
    // sufficiently tested whether attachBehaviors() can be successfully called
    // with a context object that includes top-level text nodes. However, to
    // give developers full control of the HTML appearing in the page, and to
    // enable Ajax content to be inserted in places where DIV elements are not
    // allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
    // content satisfies the requirement of a single top-level element, and
    // only use the container DIV created above when it doesn't. For more
    // information, please see http://drupal.org/node/736066.
    if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
      new_content = new_content_wrapped;
    }
    // If removing content from the wrapper, detach behaviors first.
    var settings = response.settings || ajax.settings || Drupal.settings;
    Drupal.detachBehaviors(wrapper, settings);
    if ($.waypoints != undefined) {
      $.waypoints('refresh');
    }

    // Set up our default query options. This is for advance users that might
    // change there views layout classes. This allows them to write there own
    // jquery selector to replace the content with.
    var content_query = response.options.content || '.view-content';

    // If we're using any effects. Hide the new content before adding it to the DOM.
    if (effect.showEffect != 'show') {
      new_content.find(content_query).children().hide();
    }

    // Add the new content to the page.
    wrapper.find('.pager a').remove();
    wrapper.find('.pager').parent('.item-list').html(new_content.find('.pager'));
    wrapper.find(content_query)[method](new_content.find(content_query).children());
    if (effect.showEffect != 'show') {
      wrapper.find(content_query).children(':not(:visible)')[effect.showEffect](effect.showSpeed);
    }

    /** thumbnail number **/
var c = '';
var d = '';
$('.view-content div.views-row').each(function(){
    c = 0;
    d = 0;
    var i = 1;
    d = $(this).find('.thumbimg').length;
    $(this).find('.thumbimg').each(function(){
        sayi=i++;
        $(this).append('<div class="img_no">0'+sayi+'</div>');
    });
});
/** thumbnail number end **/

var shadowImg = '<div class="shadow"></div>';

$(".thumb").each(function(){
    $(this).children("div").each(function(){
        $(this).append(shadowImg);
    });
});

var hoverImg = '<div class="hoverimg"></div>';

$(".thumb").each(function(){
    $(this).children("div").each(function(){
        $(this).find("a").append(hoverImg);
    });
});

$(".thumb div").hover(function() {
    $(this).find(".hoverimg").animate({ opacity: 'toggle' });
});

$(".thumb").hover(function() {
    $(this).find("div").each(function(){
        $(this).find(".shadow").fadeOut(500);
    });
});

    // Attach all JavaScript behaviors to the new content
    // Remove the Jquery once Class, TODO: There needs to be a better
    // way of doing this, look at .removeOnce() :-/
    var classes = wrapper.attr('class');
    var onceClass = classes.match(/jquery-once-[0-9]*-[a-z]*/);
    wrapper.removeClass(onceClass[0]);
    var settings = response.settings || ajax.settings || Drupal.settings;
    Drupal.attachBehaviors(wrapper, settings);
  }

  /**
   * Attaches the AJAX behavior to Views Load More waypoint support.
   */
  Drupal.behaviors.ViewsLoadMore = {
    attach: function (context, settings) {
      if (settings && settings.viewsLoadMore && settings.views.ajaxViews) {
        opts = {
          offset: '100%'
        };
        $.each(settings.viewsLoadMore, function(i, setting) {
          var view = '.view-id-' + setting.view_name + '.view-display-id-' + setting.view_display_id + ' .pager-next a';
          $(view).waypoint(function(event, direction) {
            $(view).waypoint('remove');
            $(view).click();
          }, opts);
        });
      }
    },
    detach: function (context, settings, trigger) {
      if (settings && Drupal.settings.viewsLoadMore && settings.views.ajaxViews) {
        $.each(settings.viewsLoadMore, function(i, setting) {
          var view = '.view-id-' + setting.view_name + '.view-display-id-' + setting.view_display_id + ' .pager-next a';
          $(view, context).waypoint('destroy');
        });
      }
    }
     };
})(jQuery);

```

All jQuery effects is working. But when i click Load More button, next thumbnails working normal but jQuery effects seen twice previous thumbnails. Like this:

What's problem?

# Answer
> 5 votes
The `Drupal.behaviors.ViewsLoadMore.attach()` function is called multiple times (each time `Drupal.attachBehaviors()` is called, so each time more content is loaded) over the same portion of the DOM tree. So the same element can be processed multiple time by the same code. The easiest solution to prevent this is to use the jQuery once plugin (which is provided by Drupal 7) like this:

```
$(selector, context).once('behavior-name').doSomething();
$(selector, context).once('behavior-name', function(){ /*do something*/ });

```

# Answer
> -1 votes
You need to implement those using `Drupal.behaviors` to stop it being executed twice or more.

Hover:

```
(function($){
  Drupal.behaviors.myHoverImg = {
    attach: function(context, settings) {
      var hoverImg = '<div class="hoverimg"></div>';

      $(".thumb", context).each(function(){
        $(this).children("div").each(function(){
          $(this).find("a").append(hoverImg);
        });
      });

      $(".thumb div", context).hover(function() {
        $(this).find(".hoverimg").animate({ opacity: 'toggle' });
      });

      $(".thumb", context).hover(function() {
        $(this).find("div").each(function(){
          $(this).find(".shadow").fadeOut(500);
        });
      });
    }
  };
})(jQuery);

```

Number:

```
(function($){
  Drupal.behaviors.thumbNumber = {
    attach: function(context, settings) {
      var c = '';
      var d = '';
      $('.view-content div.views-row', context).each(function(){
        c = 0;
        d = 0;
        var i = 1;
        d = $(this).find('.thumbimg').length;
        $(this).find('.thumbimg').each(function(){
          sayi=i++;
          $(this).append('<div class="img_no">0'+sayi+'</div>');
        });
      });
    }
  };
})(jQuery);

```

---
Tags: views, javascript
---


# Question
Title: How to pull in dynamic content in hook_filter_FILTER_process?
I'm creating a custom input filter to replace a placeholder html comment with a simple form. However, calling drupal\_get\_form within a hook\_filter\_FILTER\_process function causes the php memory limit to be exceeded.

Elsewhere I tried to do a node\_load within one of these functions and the same thing happened. I was able to work around that but this indicates it's nothing to do with the form (which is displayed elsewhere on the site anyway, and only contains a couple of fields).

The memory limit is hit whether I actually perform any filtering or just return the unfiltered text.

Any ideas what I'm doing wrong?

Thanks

# Answer
Ok, solution was simple enough in the end :) I just added a static var to the start of the function to prevent infinite loop

```
    static $donethisalready;

if (!$donethisalready){
    $donethisalready = true;

    // do whatever
}

```
> 0 votes

# Answer
Depending on your settings, `hook_filter_FILTER_process()` will be invoked (albeit in a round-about way) from within the `drupal_get_form()` and `node_load()` functions.

So at the moment you're simply creating an infinite loop that PHP cannot escape from (`node_load()` calls `hook_filter_FILTER_process()`, which then calls `node_load()` again), hence the out of memory error.
> 0 votes

---
Tags: 7, input-formats
---


# Question
Title: How to run Drush commands on a schedule?
I'm deploying content to Drupal remotely (I'm in an Enterprise environment) and I need something to run Drush commands based on a schedule. E.g on a cron task, read commands from the database table or file, execute the commands and record the result.

I've looked at the Rules and Job Schedule modules, but they don't really work because I need to enable Features.

I was thinking of creating a module which reads commands from a database and executes the commands in php. But is there a better way to do this?

# Answer
> 2 votes
Yes, you can use Jenkins, which could be described as an advanced version of cron, though it is more powerful than that. John Smith made a slideshow about integrating Drupal with Continuous Integration practices.

If you're in an enterprise environment, hopefully you have the resources to get a Jenkins server set up. You can then also use this to run automated tests, etc. too.

# Answer
> 1 votes
If you want to use Drush with cron, please read drush topic docs-cron. `drush topic` has a lot of interesting information, and is a good place to look when you have questions.

---
Tags: drush, cron
---


# Question
Title: Reviewing and displaying node reviews in Drupal 7
I have to create a Movie content type that's going to be submitted by the Admin, but where anonymous users will have the possibility of adding a review.

As I'm using D7 (making NodeReview not an option), I was thinking of using the Vote API and fivestar.

My actual question is (and please excuse my n00bness): can I somehow embedded a "Review" content type (that's going to have fivestar, author name and a short text) in the Movie nodes and expose that to anonymous users?

Could someone point me what the Drupal way would be in this case?

# Answer
If you wanted to do this very simply, you could just add a fivestar field to Drupal's built-in comments. Comments already provides the author name and a description field (the comment), and enabling comments on nodes is easy (you can do it from structure/content types).
> 2 votes

# Answer
If you don't want use Drupal comment for any reason: Use this modules:

1. starrating instead of fivestar, I think in this case it is better
2. references

create content type "Review", rename title field to Author, rename body field to note and configure it to accept just plain text, create a rate field of `starrating` type

finally create field\_movie of `Node reference` type and set cardinality to 1.

use /node/add/review/xxx as Review creation link and alter Review creation form and set field\_movie to xxx. xxx is Movie ID.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to create a user listing page with a tpl.php
I would like to create a listing page of users of a particular role.

Inside this view, there should be another view which shows the related content for each user.

When I try to create a view the system gives me the option to use just fields, but I need to be created like a node so I can use a tpl.php file.

How can I get a tpl.php file for this?

If I create a view for the users and one with the contents(contextual filter uid), can I embed the second view inside the view-unformatted.tpl.php?

# Answer
Here I create similar page with views: http://cgart.ir/en/members

as you can see there is a list of users and 5 last uploaded image. the page created with views and latest artworks is another views.

to do that:

1. create first view for list users and in `Format` select `Show:Rendered entity | Settings`
2. create second view and configure `CONTEXTUAL FILTERS` and add `Content: Author uid`

edit `user-profile.tpl.php` and render second view there:

```
$account = $variables['elements']['#account'];
<?php print views_embed_view('second_view', 'page_1', $account->uid); ?>

```
> 2 votes

---
Tags: 7, views, users
---


title: Content Access Help

text:
# Question
Title: Content Access Help
Are there any modules for 7.x that will allow users to select whether content they create will be for authorized users only or anonymously viewable?

# Answer
> 1 votes
Something like this is usually best solved with a bit of indirection.

Have a look at the Taxonomy Access module. It allows to control access who can view content based on the assigned tags.

You can then add two tags, one for All and one for authenticated only, configured them and let your users chose which one they want for a node.

The advantage of this over e.g. a checkbox that allows to make it visible to all or authenticated only is that it is very easy to extend. For example, if you decide to add another role to your system, and want to limit access to only that role, it's as easy as adding another tag.

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


# Question
Title: Drupal theme layout - recommendation based on example needed
I am going to create a website that will have a layout similar (almost identical) to this one: http://www.statoilfuelretail.com Meaning:

* position of all the menus/elements
* picture in the background two
* columns in the middle

All the graphics will be made by graphic designer - **all I need is the theme (template) with layout I could use**. Would be great if it was a Drupal 7 theme.

My question is: **Which themes can you recommend (free and paid) that could be easily configured to match the layout presented on the website above?**

# Answer
> 0 votes
If it were me I'd start with Bartik and go from there. It's very solid and flexible. It has the main elements you'll need.

But that's just me. Take a look at http://drupal.org/project/corporateclean

If you are looking for something *extremely* quick and easy, your best bet is just browsing the different template websites that offer Drupal designs. These have some themes similar to what you're looking for:

# Answer
> 0 votes
if you have HTNL/CSS Implemented version of your template. its very easy to convert it to Drupal theme. http://drupal.org/documentation/theme

---
Tags: theming
---


# Question
Title: Unflagging (by rule) doesnt show rightaway
I have 3 flags in my custom content type "Movie" Seen , Unseen , Want to see...

these 3 flags are mutually exclusive , that is if a user has "seen" a movie he cant "unseen" the movie..

To make the flags mutually exclusive I have added rules , so whenever one of the flags are flagged, the other 2 are unflagged.

Now my problem is, when i flag a movie with say "seen" , the other 2 flags "unseen" and "want to see" are unflagged internally, but that unflagging effect is not visible on that page right away. When i refresh the page , then i can see those changes.

How can , i see the changes right away ??

# Answer
> 0 votes
I am assuming you are using flag's javascript toggle to set these flags, and if that's correct, you could hook into flag's `flagGlobalAfterLinkUpdate` event and refresh the portion of the page where your flags are set. More details are here: http://drupal.org/node/336122. If you don't want to do this, you could always set the flag link to a normal link, which would refresh the page for you in of itself.

---
Tags: ajax, javascript, rules, flags
---