# Question
Title: What is the "Category" argument in user_save for?
I'm working on a custom module that edits the user's details. I'm using

```
user_save($user_entity,$new_field_values);

```

But I see there is a third argument in user\_save called "category". What exactly is it for?

# Answer
> 1 votes
`$category` is one of the strings returned from any implementations of hook\_user\_categories(). Think of them as a different tab that is visible in the form for editing a user profile.

By default, the User module defines just the "account" category, which contains all the data about the user account.

```
function user_user_categories() {
  return array(array(
      'name' => 'account',
      'title' => t('Account settings'),
      'weight' => 1,
    ));
}

```

Other modules can define new categories. In Drupal 6, the Profile module was one of those modules, which implemented `hook_user_categories()` with profile\_user\_categories().

```
function profile_user_categories() {
  $result = db_query("SELECT DISTINCT(category) FROM {profile_field}");
  $data = array();
  foreach ($result as $category) {
    $data[] = array(
      'name' => $category->category,
      'title' => $category->category,
      'weight' => 3,
      'access callback' => 'profile_category_access',
      'access arguments' => array(1, $category->category),
    );
  }
  return $data;
}

```

# Answer
> 1 votes
As you see in user\_save function it tells that

> category: (optional) The category for storing profile information in.

It basically used in below lines of code inside user\_save function

```
user_module_invoke('presave', $edit, $account, $category);
user_module_invoke('update', $edit, $account, $category);
user_module_invoke('insert', $edit, $account, $category);

```

So, the information is just passed to all presave, update, insert hooks so that they can take contextual actions.

In user\_module\_invoke function $category is defined as

> $category: The category of user information being acted upon.

So, from above it clarifies that is used as a value to tell all hooks that we are saving user details and on which part of user information we are acting upon. Something like if we change the user organic groups that he belongs to then we can specify that $category as "organic\_group" .

For Example if you see hook\_user\_presave in user module

```
/**
 * Implements hook_user_presave().
 */
function user_user_presave(&$edit, $account, $category) {
  if ($category == 'account' || $category == 'register') {
    if (!empty($edit['picture_upload'])) {
      $edit['picture'] = $edit['picture_upload'];
    }
    // Delete picture if requested, and if no replacement picture was given.
    elseif (!empty($edit['picture_delete'])) {
      $edit['picture'] = NULL;
    }
    // Prepare user roles.
    if (isset($edit['roles'])) {
      $edit['roles'] = array_filter($edit['roles']);
    }
  }

  // Move account cancellation information into $user->data.
  foreach (array('user_cancel_method', 'user_cancel_notify') as $key) {
    if (isset($edit[$key])) {
      $edit['data'][$key] = $edit[$key];
    }
  }
}

```

You can see the use case of $category above where they check for account or register !

In your case just make it as an optional and don't assign any value :-)

---
Tags: 7, users
---


# Question
Title: Render default value of views exposed filter
I have a view in Drupal 7 using an exposed filter. When I access the view without any ($\_GET) values in the URL I want to display all items. The drop down selection has the value -Any- as I want it, but the view is still empty, even the empty result text will not shown. If I hit the submit-button all items appear. Already tried different things from post I found about this, but nothing worked so far. I have no Idea why it is rendering nothing at all by default and why I can't make it render something...

Here are my settings for the filter:

* Exposed: YES
* Type: SINGLE
* FILTER Operator: IS ONE OF
* Options: -nothing\_selected- (already tried selecting everything)
* Checked options: Reduce duplicates

I'm using View 7.x-3.5 and have CCK 7.x-2.x-dev enabled. Hope anyone has an idea. Thanks a lot!

Saduras

# Answer
This may cause by the *Exposed form style* setting: Change it to *Basic* if it is *Input required*.

>
> 2 votes

---
Tags: 7, views
---


title: Overriding theme_links__main_menu()

text:
# Question
Title: Overriding theme_links__main_menu()
I have the following call in page.tpl.php.

```
 theme('links__main_menu',array(...));

```

How can I override the theme function that is being called from that code?

# Answer
In a theme, you just declare the `mytheme_links__main_menu()` function in the template.php file. (Replace `mytheme` with the actual name of the theme.)

In a module, you declare the `mymodule_links__main_menu()` function, and implement hook\_theme() to define the theme function. (Replace `mymodule` with the actual name of the module.)

The argument passed to the function are the same passed to theme\_links().

`$variables`: An associative array containing:

* links: An associative array of links to be themed. The key for each link is used as its CSS class. Each link should be itself an array, with the following elements:

+ title: The link text.
    + href: The link URL. If omitted, the 'title' is shown as a plain text item in the links list.
    + html: (optional) Whether or not 'title' is HTML. If set, the title will not be passed through `check_plain()`.
    + attributes: (optional) Attributes for the anchor, or for the tag used in its place if no 'href' is supplied. If element 'class' is included, it must be an array of one or more class names.

If the 'href' element is supplied, the entire link array is passed to `l()` as its `$options` parameter.

+ attributes: A keyed array of attributes for the UL containing the list of links.
    + heading: (optional) A heading to precede the links. May be an associative array or a string. If it's an array, it can have the following elements:

    1. text: The heading text.
        2. level: The heading level (e.g. 'h2', 'h3').
        3. class: (optional) An array of the CSS classes for the heading.
> 2 votes

# Answer
This is a theme hook pattern of the form \[base hook\]\_*\[context\]. When links are themed with theme('links*\_main\_menu', $vars), theme() will search for and use theme\_links\__main\_menu() if it has been defined. If not, it will use theme\_links().
> 0 votes

---
Tags: theming, routes
---


# Question
Title: How can i attach my content type to level 1 taxonomies in multilevel taxonomy in drupal 7?
I am using the default taxonomy of Drupal 7. I have a taxonomy like the following one:

* Multilevel taxonomy (Vocabulary)
    + level 1 taxonomy (Term)
        1. level 2 taxonomy (Term)

I want my blog post have a field type of level 1 taxonomy.

Is there any module for this?

# Answer
> 0 votes
Checkout Hierarchical Select module. It offers many features.

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

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


# Question
Title: Create a connection using FileTransferFTP
I want to create a FTP connection using the `FileTransferFTP` class.

How can I do it?

# Answer
The code used to create an FTP connection is similar to the following one.

```
try {
  $ftp = FileTransferFTP::factory($jail, $settings);
  $ftp->connect();
  // Copy the files.
}
catch(Exception $e) {
  // An error happened.
}

```

`$jail` is the directory to which the operations are restricted. Any tentative to write files externally to this directory will raise a FileTransferException exception.

`$settings` contains:

* `$settings['username']`: The username
* `$settings['password']`: The password
* `$settings['advanced']['hostname']`: The hostname for the FTP server (default to localhost)
* `$settings['advanced']['port']`: The server port (default to 21)

FileTransferFTP::factory() returns the instance of the sub-class that takes care of the file transfer, if there is one, or raises an exception, if there aren't sub-classes.

The code currently executed from `FileTransferFTP::factory()` in Drupal 7 is the following one.

```
  $username = empty($settings['username']) ? '' : $settings['username'];
  $password = empty($settings['password']) ? '' : $settings['password'];
  $hostname = empty($settings['advanced']['hostname']) ? 'localhost' : $settings['advanced']['hostname'];
  $port = empty($settings['advanced']['port']) ? 21 : $settings['advanced']['port'];

  if (function_exists('ftp_connect')) {
    $class = 'FileTransferFTPExtension';
  }
  else {
    throw new FileTransferException('No FTP backend available.');
  }

  return new $class($jail, $username, $password, $hostname, $port);

```

Future versions of the class could implement the method differently, and create different instances of the FileTransferChmodInterface interface basing on different conditions.

In Drupal 8, the class has been renamed Drupal\Core\FileTransfer\FTP.
> 5 votes

---
Tags: 7
---


# Question
Title: How to merge two different vocabulary in one auto-complete text-field?
I have two taxonomies like below:

```
Content--- editor pick
       --- recommended
       --- today high
Sources--- sky
       --- earth
       --- water

```

to attach these with blog-post i need to make 2 different auto-complete text-box. I want to make a single text box and both the taxonomy should be suggested in that.

# Answer
> 5 votes
You can do it using Entity Reference module. You can able to reference multiple vocabulary terms using this module.

See the screenshot of field settings of field type "Entity Reference" and Widget types "Auto-complete (Tags Style)"

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


# Question
Title: How to update Drupal securely using GUI/web interface
The admin/reports/updates/update page lists updates, and there's what looks like a handy button **Download these updates** at the bottom.

And then you're asked for your SSH user and password.

Now unless you're running over SSL, this is a massively daft thing to do. Provide your **server credentials** over plain http?

If Drupal *really* needs to do an SSH loopback (as the help text explains, it's highly likely that the webserver is the SSH server it will connect to) in order to run updates, then surely there ought to be a way to provide the webserver's user with a DSA key so that users don't need to pass credentials in plain text.

Is there a way? Or is this really as insecure as it looks!

(I generally use SSH and drush to do updates, but as there's a GUI there, which looks nice, I feel it ought to work)

# Answer
**Got it! Here's how to update your site at example.com over http, with your normal user name and password, but without sending these unencrypted.** You will need access to SSH and to your (local) hosts file.

1. Edit your local hosts file (`/etc/hosts` on Linux) adding `example.com` after the `127.0.0.1 localhost` line. This will mean that when you access example.com, you're actually just accessing your own machine. Therefore, after doing this, you should not be able to access this website. Try it.
2. At the command line, log on to your server with SSH, setting up a local port forward: `ssh user@example.com -L 10022:localhost:80`.
3. You should now be able to access your site at `http://example.com:10080`. You can do the updates, and happily supply your username/password because although it's running over http, this traffic is being tunnelled over SSH to the server, so as long as example.com is the webserver, the only unencrypted bit is between SSH and (e.g.) Apache on the same machine; i.e. nothing goes across the internet unencrypted.
4. Finally, exit the SSH session, and re-edit your hosts file.

Nb. editing the hosts file is necessary so that Apache (or whatever) knows which website you're accessing. If it only serves one site, you can probably skip the hosts bit and access the site at `http://localhost:10080` instead.
> 0 votes

# Answer
I think you are right that it's asking you to enter your important credentials over a potentially non-encrypted channel. This feature is a trade-off between doing things an optimally secure way and making it easy to get updates done. If updates are hard to do people won't do them and that is also an insecure situation.

Entering your credentials over a non-encrypted channel is only insecure if you think someone is sniffing your traffic. You can mitigate that by using a vpn or ssh tunnel (especially one that goes to the server).

Your idea to upload your private ssh key to the webpage to avoid using credentials seems at least partially flawed to me: the private key has the same value to an attacker as your ssh username/password. If you send the key on a non-encrypted channel that can also be intercepted and abused.

If you are concerned about security you can:

1. Add a full or self-signed ssl certificate to your webserver
2. Use a vpn or ssh tunnel to encrypt your non-encrypted (http) browser traffic
3. Just keep using ssh+drush to get the updates done
> 7 votes

---
Tags: 7, updating, security
---


# Question
Title: How to 'store' email templates in the site?
On certain events, defined in code, specific mails are sent to certain users in the site (such as on node\_save if some value has changed etc).

The content managers need access to those mail templates in order to be able to change literals.

I've thought about having the mail's body inside the node as a field with a 'dummy' default value, but that seems a bit crude. Is there a better way to have my mail templates stored somewhere in the site and access them from code?

# Answer
"There is a module for that!"

Well of course there is :)

http://drupal.org/project/pet worked wonders for my case. Supports tokens, and provides a hook for aditional tokens, you just need to invoke `pet_send_mail` with the correct arguments and having set up a mail template before hand it will do the work for you. No need to invoke `hook_mail` manually.
> 0 votes

# Answer
It all depends on usage patterns of that feature.

For example if you only need one master template and edits are global (e.g apply to all events) then the "correct" storage could be inside the `variable` table.

You can expand on the above design by suffixing those `variable` keys with the node type (or whatever differentiates one template from another). So you could have entries such as:

* mail\_template\_event
* mail\_template\_publication
* mail\_template\_press\_release

or in the case of "typed" events:

* mail\_template\_event\_internal
* mail\_template\_event\_external
* mail\_template\_event\_generic

Keeping the mail template on a node field will be easier in terms of programming though. Because if you fetch the template from an "external" source (such as the `variable` table) you'll need to handle presentation within the node edit screen and update of the template in case it was altered.
> 1 votes

---
Tags: 7, emails
---


title: Token in Shortcuts

text:
# Question
Title: Token in Shortcuts
Does anybody know of a way to use tokens in a shortcut link? Background: I would like to link to a users IMCE Browser at `http://DRUPALSITE/user/[current-user:uid]/imce` from the shortcuts bar.

# Answer
> 0 votes
I found a way to solve my problem: The me aliases plugin replaces a defined placeholder (normally "me") with the uid of the current user:

Example: `user/me/imce` for the admin aliases to `user/0/imce`.

It's not very flexible though, as it can only replace the uid.

---
Tags: 7, tokens
---


# Question
Title: Passing a number via page arguments in hook_menu()
I am generating the return value for a hook\_menu() with values from a query.

```
 $items[$record->path_prefix . '/my_path/%'] = array(
     'title' => 'Topic Redirect',
     'page callback' => 'my_callback',
     'page arguments' => array($record->id,2),
     'access callback' => TRUE,
     'type' => MENU_CALLBACK
   );

```

This will automatically pass the argument that is the record id to the callback function. I would like it to pass the value. Is there an easy way to do this?

# Answer
I normally just wrap the value in quotes, that should convince the router system to leave it alone:

```
'page arguments' => array("$record->id", 2)

```
> 4 votes

---
Tags: 7, routes
---


# Question
Title: Remove search form from search results page
I have a search box in a sidebar and I'm happy with it. I don't want Drupal to output another one on the results page. So far I've managed to remove it with the following code

```
function mythemename_preprocess_page(&$variables) {
    if(array_key_exists('page', $variables)) {
        if(array_key_exists('content', $variables['page'])) {
            if(array_key_exists('system_main', $variables['page']['content'])) {
                if(array_key_exists('search_form', $variables['page']['content']['system_main'])) {
                    unset($variables['page']['content']['system_main']['search_form']);
                }
            }
        }
    }
}

```

but it doesn't look very clean to me. Is there another way?

# Answer
> 5 votes
Write a form alter:

```
function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "search_form") {
     $form['#type'] = 'hidden';
  }
}

```

# Answer
> 4 votes
There is the exact same question in drupal.org, and your solution seems to be similar - but with more code - with this. Keep in mind that there is always the option of using css to target specific elements and make them not display (i.e. display: none;).

# Answer
> 3 votes
`search_view()` is the function that builds the search page. So Another way is to implement the`hook_menu_alter()` and change page callback from `search_view` to your own function. You can copy the `search_view`'s body to your function and remove the following line:

`$build['search_form'] = drupal_get_form('search_form', NULL, $keys, $info['module']);`

Of course, this also doesn't seem to be very clean!

# Answer
> 1 votes
In Drupal 7 You can use hook\_page\_alter: http://drupalcontrib.org/api/drupal/drupal%21modules%21system%21system.api.php/function/hook\_page\_alter/7

```
/**
 * implements hook_page_alter()
 *
 * Alter the page output before render.
*/
function NAME_OF_YOUR_THEME_page_alter(&$page) {
  // kpr($page); //use this to find the item you want to remove - you need the devel running.
  // Remove the search form from the search results page.
  if (arg(0) == 'search') {
    if (!empty($page['content']['system_main']['search_form'])) {
      hide($page['content']['system_main']['search_form']);
    }
  }
}

```

---
Tags: theming, search
---


# Question
Title: How can I float a specific field to the right of another field
For example, I have one field in my content type that is a boolean value of "Is this employee certified" next to this field I'd like a Pop-up Date that shows the expiration field. I've created both fields for my content type but I have not seen anything in the CSS that allows my to float or align fields. Any help would be greatly appreciated.

Can I do this with Views? Or with CSS? Thank you

# Answer
You can use Token Field Or computed Field but the easier way it's to use token field.

You should create a token field then use replacement patterns (each field of your content type has a replacement pattern to print it's value) for example:

I have integer field (field\_int), it's replacement pattern should be \[node:field\_int\].

With that you can print the fields between each other.
> -1 votes

# Answer
You can just use CSS for this. You will need to find the specific element ID or class for the containing element (div for example) for each of the fields (you can find this out using Firebug with Firefox), then create a CSS rule for each of those elements such as:

```
#field1 {
  float:left;
  width:150px;
}

#field2 {
  float:left;
  width:150px;
}

```

You will probably need to then use the CSS rule `clear:left;` for the field or element that follows after them.
> 1 votes

---
Tags: views, entities, nodes, theming
---


# Question
Title: Editing user submission of user registration form with hook_user_insert() and $edit
I recognize there is a similar question here:

drupal.stackexchange.com/questions/38124/hook-user-insert-get-form-values

but I've got Eclipse and XDebugger setup so I can see the variables and I am still stuck.

I provide the variables below, please note `field_foo` is a field the system has taken care of properly without my interfering, after the user submits it, `field_bar` is a field I want to change the submitted value of, it has the value `303031` when the system handles it from form submission, where the variables show "value `300501` " is my attempt to edit that value - clearly I'm editing something wrong)

```
$edit   Array [37]
[0...30]
    uid 63
    field_foo   Array [1]
        und Array [1]
            0   Array [1]
                value   asdasd
                    length  6
                    0   61
                    1   73
                    2   64
                    3   61
                    4   73
                    5   64
    field_bar   Array [2]
        und Array [1]
            0   Array [1]
                value   303031
        value   300501

```

Here is my code to try and set it...

```
function MY_MODULE_user_insert(&$edit, $account, $category) {

    $newBarValue = 300501;
    $edit[field_bar][value] = $newBarValue;

}

```

**PLEASE NOTE:**

I don't know if this is the case for all field\_data\_field Core fields but I had to use the following to get it to work:

`$edit[field_bar][und][0][value] = $newBarValue;`

This might be unique as I am working on someone else's work atm.

# Answer
`hook_user_insert()` is invoked after the user object and all it's fields have already been committed to the database; that's why your code isn't taking effect at the moment.

There are a couple of ways you could go:

1. Use exactly the same logic in `hook_user_presave()`, which gets called before the data is committed to the database.
2. Implement `hook_form_alter()` for the registration form, add a custom validation function, and manipulate the field values in there.
> 3 votes

---
Tags: users, forms
---


title: Comparing a clicked views-row in a loop

text:
# Question
Title: Comparing a clicked views-row in a loop
When I loop through my `.views-row` divs in jQuery, I need to 'grab' the one that is clicked on, needing to uniquely identify it and put only the selected fields from that particular div in my modal frame. Now I have the selected fields of all the divs within that loop in my modal frame.

I don't think I'm too far off with the following here below. I think the only thing that's missing is that I haven't been able to properly 'say' to drupal which `div` is being clicked and see to which `views-row-number` it corresponds to in order to display only that one in the modal frame.

obviously `jQuery(".views-row .views-row-" + index).click()` isn't the way but I'm sortof out of ideas which one that would be then.

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

    row = jQuery(".views-row");

    row.each(function(index){
        forModal = jQuery('.forModal');
        forModal.hide();
        jQuery(".views-row").click(function(){

                if (jQuery(".views-row .views-row-" + index) ==
                                jQuery(".views-row .views-row-" + index).click()){
                                 forModal.modal();
                }

        });
    });

});

```

# Answer
I think you're making that a bit harder than it needs to be...if I understand you right anytime a row is clicked you want to identify that row, extract a field from it and display it in a modal?

If so something like this would be a bit simpler:

```
(function($) {
  $(function() {
    $('.views-row').click(function() {
      // Find the modal within this row and show it.
      $(this).find('.forModal').modal();
    });
  });
})(jQuery);

```

Sorry if I've mis-understood what you're looking for, I wasn't 100% sure.
> 1 votes

---
Tags: 7, views, javascript
---


# Question
Title: What is the proper way of retrieving and handling sessions when making multiple calls to the API?
I can't log in consistently via Services 3 in Drupal 7.

```
POST http://<mydrupaldomain>/services/user/login.json
{
"username":"admin",
"password":"password"
}

```
* The first time I make this request I get a session name and id back. Which is what I want. I use the session information to make successive calls such as update user.
* The second time I make this request the response comes back as HTML for the login screen.
* The third time I get

> 401 Unauthorized: Access denied for user anonymous

* And at the forth time I get am able to login again with a NEW session name and id.

I make these requests within seconds of each other. I will have an application which will be making multiple API calls to Drupal per second. This includes creating a user and updating a user both of which requires that I get a user session id in order for the request to be served by the API.

Questions: Why the inconsistent behavior? On each login attempt I expected to get either a new session info back or, if the user is already logged in, the current session.

What is the proper way of retrieving and handling sessions when making multiple calls to the Services API?

# Answer
> 2 votes
Apparently the Services module submits a form in order to log a user in. I expected /login to purely go through the backend.

Having said that, I disabled a module which hooked into my login form and now I am getting the expected results.

---
Tags: services
---


# Question
Title: The requested URL /node was not found on this server
I am setting up Drupal locally in my Ubuntu. I used drush to download and install Drupal 7. (using mysqladmin to create the database and the user)

All worked well, I have the default homepage, but when I try to do any action (logging in, registering) I get a 404. I imagine the mod\_rewrite doesn't work..

I installed the Apache module and enabled it, restarted the server, but no lack...

I am guessing mod\_rewrite needs more parameterization...?

update: I can access correctly the page with this url:

```
http://localhost/index.php?q=user

```

so I guess my mod\_rewrite clearly doesn't work as it should..

# Answer
I just realized I had not restarted apache2 service after enabling mod\_rewrite... It works fine.
> 2 votes

# Answer
Have you verified that the .htaccess file from the Drupal 7 core package is in the website root?

You can easily download and extract that file from drupal.org base package: http://drupal.org/project/drupal
> 2 votes

---
Tags: 7, uri
---


# Question
Title: Accessing html.tpl.php variables from outside
The Drupal 7 has it's default html.tpl.php looking similar to this:

```
<!DOCTYPE html>
<html>
<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

How can I access those variables ($styles, $scripts, etc.) from outside the html.tpl.php? (suppose from page.tpl.php)

Thank you in advance!

# Answer
> 1 votes
Direct answer to your question - you can populate the variables you need by emulating the same functions that the processing function for html.tpl.php uses to render the page:

http://api.drupal.org/api/drupal/includes%21theme.inc/function/template\_process\_html/7

```
function template_process_html(&$variables) {
  // Render page_top and page_bottom into top level variables.
  $variables['page_top'] = drupal_render($variables['page']['page_top']);
  $variables['page_bottom'] = drupal_render($variables['page']['page_bottom']);
  // Place the rendered HTML for the page body into a top level variable.
  $variables['page']              = $variables['page']['#children'];
  $variables['page_bottom'] .= drupal_get_js('footer');

  $variables['head']    = drupal_get_html_head();
  $variables['css']     = drupal_add_css();
  $variables['styles']  = drupal_get_css();
  $variables['scripts'] = drupal_get_js();
}

```

So to access the styles variable, you would just need to call the same function the template engine is using:

```
$mystyles = drupal_get_css();

```

However - just to check, these values are already on your page because the html.tpl file is a wrapper for page.tpl.php. Sure you want to print it twice?

---
Tags: theming
---


title: User role specific login link

text:
# Question
Title: User role specific login link
This may sound like a strange question but it is desired functionality from a client. They would like to have a login screen that only staff members can log in through. What I mean by that is if an anonymous user logs in, and if their role is staff (or admin) then they are logged in. If it is any other role, then they are not logged in and redirected to a 'normal' login page.

I know this seems unorthodox but is there a way to accomplish this?

Thanks.

# Answer
Which ever role you want to allow to login give the role the permission.

**Drupal 6**

Please change the permission to an appropriate one. This is just for test purpose.

```
function modulename_perm() {
  return array('allow modulename login');
}

function modulename_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'login') {
    if (user_access('allow modulename login') == FALSE) {
      drupal_set_message('Member logins have been temporarily disabled. Please try again later.', 'warning');
      user_logout();
      exit;
    }
  }
}

```

**DRUPAL 7**

```
function modulename_permission() {
  return array(
    'allow modulename login' => array(
      'title' => t('allow modulename login'),
      'description' => t('allow modulename login.'),
    ),
  );
}
function modulename_user_login(&$edit, $account) {
 if (user_access('allow modulename login') == FALSE) {
      drupal_set_message('Member logins have been temporarily disabled. Please try again later.', 'warning');
      user_logout();
      exit;
 }
}

```
> 1 votes

---
Tags: 6, users
---


# Question
Title: Add/Edit Taxonomy Terms directly from add content form
I've hunted around for a while trying to find a solution to what I believe is a common user interface in the world of data entry but appears to be missing from Drupal.

What I want to be able to do is add/del/edit taxonomy terms for a given content type directly from the Add Content page where the terms show as a multiple select. This is often done with a multi-select box and a simple + - icon next to the multi-select that would bring up an ajax form to manipulate the taxonomy terms and then refresh the multi-select box when the ajax dialog is closed.

For example, say I have a content type for keeping track of books. Fields for Title, ISBN, etc, and a multi-select taxonomy field for book genre (drama, educational, horor, children's, etc) Ideally I want the user to be able to add genre's without having to leave the add book form to do it. I know it can be done with freetagging but then you open up the taxonomy to duplicates and misspellings and other garbage. The multiselect gives a firmer set of choices first and then allows for editing once the user has browsed the list to make sure what they want to add isn't in there already. I would settle for just adding terms from that screen but edit and delete would be nice too.

Taxonomy Other module is ALMOST what I'm looking for, except it doesn't support multi-selects. Are there other modules out there that do this? What about CCK? Any options for using CCK to achieve the same result? I'm using Drupal 6.

# Answer
Take a look to the Hierarchical Select module.

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
> 2 votes

---
Tags: taxonomy-terms, entities
---


# Question
Title: How to change the default mail template for subscriptions module
It's probably a silly question but I just can't find the answer: Where can I change the default email template for the Subscriptions email? I'm using Drupal 7 and installed the module Subscriptions.

I would expect to change the mail templates at `http://[mydomain]/admin/config/system/mail-edit`. However at this location I only can add language translations for 4 languages which I've enabled but not the default email templates.

Can anybody point me to the right direction?

# Answer
> 1 votes
There is no template but you can solve this by adding the mail\_edit module to your site. Here's the notes from the documentation:

http://drupal.org/node/344030#Configuration

(scroll down to "Mail Templates")

> If you have installed and enabled the mail\_edit module then you can go to admin/build/mail\_edit to edit the mail templates.

---
Tags: 7, emails, notifications
---


# Question
Title: how to show contents tagged under a parent taxonomy term
I have contents that can be tagged per taxonomy terms (with hierarchies in content type), say,
Events \> weddings
Events \> birthdays
Events \> public \> national day celebration

The events (which is a vocab) actually turns into a menu (using taxonomy menus) and I want it so that when users click 'Events' menu all contents tagged weddings, tagged birthdays, tagged national day celebrations will show up on the page.

This content type (Events) has a field called 'Type' which is a hierarchical taxonomy list from the vocab 'events'. I had it set so that the term lineage will be save in the hierarchical select settings, I was under the impression that for any content tagged 'weddings' for example, this same content will also be tagged as 'events' by the system due to 'save term lineage' settings...

When I go to http://mysite/events (which i already configured using pathauto, and used views to display taxonomy terms related to nodes) none show up, as if none is being tagged 'events' at all. But when going http://mysite/weddings i get all contents tagged under weddings only (which is right).

Thanks!

EDIT: This content type (Events) has field called 'Type' which is NOT a hierarchical taxonomy list but a select list. Sorry for that.

# Answer
Try Hierarchical Select module.

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 1 votes

# Answer
I believe you may need to have the content tagged in both terms, "Events" and "Type" for this to work without custom coding.

You can get this through a view or custom module quite easily, though. If no answers posted later on, I will post you an update when I get home as I am writing this from mobile.

Good-luck
> 1 votes

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


title: Drupal 7 Bartik theme drop down menu

text:
# Question
Title: Drupal 7 Bartik theme drop down menu
> **Possible Duplicate:**
> Drop down menu in drupal 7

How can I add the drop down menu item to the navigation menu in the Bartik theme?

# Answer
You can able to do it using Nice Menus module. Check here for detailed step by step tutorial on how to use nice menus module.

> Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)
> 1 votes

---
Tags: theming
---


title: How to print a Panel Page?

text:
# Question
Title: How to print a Panel Page?
I am using the Print module.

I have enabled the node/%node template in panels and used a selection rule to select my specific node type and added fields into the panels regions etc. That all works fine.

I need to be able to use the Print module to see a print-friendly version of this node. However when I go to /print/\[nid\] I just get a completely blank page.

So is it possible to have a printer friendly version of a panels page? i.e in a template file or another method?

# Answer
> 1 votes
Thanks for the help above.

Coding was the last option I wanted to take here. In the end I achieved what I needed without it.

Firstly, I configured the Print module to also print non-standard node pages (so panel pages and views as well). Still would not work.

So, I created a copy of my panel with the url 'node/%node/print-friendly' and used panels stylizer to style it very bland. Then I was able to link to the copy panel as '/print/%node/print-friendly' and it works perfectly!

# Answer
> 2 votes
Checkout the piece of code here. Just copying it here for reference

Create a function as follows in template.php

```
function get_panel_view(&$node) {
    // Load my task plugin
    $task = page_manager_get_task('node_view');

    // Load the node into a context.
    ctools_include('context');
    ctools_include('context-task-handler');
    $contexts = ctools_context_handler_get_task_contexts($task, '', array($node));

    $output = ctools_context_handler_render($task, '', $contexts, array($node->nid));
    if ($output !== FALSE) {
        return drupal_render($output['content']);
    }
    // Otherwise, fall back.
    return drupal_render(node_view(node_load($node->nid)));
}

```

Template should be called print--node--.tpl.php and you can print it as

`print get_panel_view($print['node']);` in place of `print $print['content'];`

Rebuild theme cache

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


# Question
Title: Why isn't the user #1 able to edit the user details?
I have one site in Drupal 6. When I log in as user #1, and I visit the page at user/\[uid\]/edit, I am not able to access this page. I get an access denied error.

Can any one please tell me what may be the problem, and the solution?

# Answer
This is probably a conflict/misconfiguration of some module (or permissions) you have installed on the site and that deals with users or permissions.

Super user (uid: 1) has all privileges, whether or not the admin role exists.

Make a dev version of the site and start disabling modules one by one to find which one caused this.

Which modules do you have installed? Any custom modules? Is there anything in the database/error log?
> 1 votes

# Answer
You have to make sure the the permission " Administer users " is checked for Administrator role in your permission page.

*update*
> -1 votes

---
Tags: 6, users
---


# Question
Title: Show menu link as expanded when on node pages for a content type?
I need to show a menu link as expanded when you are on the node page of a certain content type.

These nodes don't actually have menu link but are navigated to, through a menu link and taxonomy terms.

# Answer
> 0 votes
Menu Trail By Path modules does this is the node's paths are children of the parent. http://drupal.org/project/menu\_trail\_by\_path

---
Tags: 7, routes
---


title: How to start views list at specific ID

text:
# Question
Title: How to start views list at specific ID
I have a list of images(nodes) displaying horizontally and I would like to start from a certain id in this list. The way I have it now it starts at most recent added image(node).

Is there a way to start at a specific id in views?

NOTES: Would like it to look like the second image on page load. You can see in the first image there is white space to the left. I want this to be filled by an image. The navigation is fixed.

# Answer
> 0 votes
I would suggest perhaps using a Nodequeue - http://drupal.org/project/nodequeue.

This way you can order the images in whichever order you like.

Alternatively, if it is just one node that you want to appear first and then sort by something else you could perhaps utilise the 'sticky' feature?

OR do you want the order to start from ID 5 and continue 6, 7, 8 etc?

---
Tags: 7, views
---


# Question
Title: Before saving a node how to get the file path
For a content type "TEST" which has a field "upload file", I want the file path before saving the node. hook\_node\_presave can be used to do anything before saving the node. I want to rename the file before it get saved into database.

but my file is getting saved first into the database.

How to do rename a file before it gets saved into database in a custom module.

# Answer
Check out `hook_file_presave()` function.

You might have to additionally rename/move the file after it has been uploaded.

See also this thread and check the File (Field) Paths module as it might have already the functionality you need.
> 1 votes

---
Tags: 7
---


# Question
Title: How to move blog to a custom path in drupal?
I want to move default blogs to a custom URL i.e. blog are by default present at ./blog but i want them to be at ./share/blog I don't want to use path aliases. I want a permanent move.

# Answer
For a 'permanent' move you'll need to write a custom module and implement `hook_menu_alter()`, to copy the settings for the original path over to the new one, and remove the old page from the system:

```
function MYMODULE_menu_alter(&$items) {
  if (isset($items['blog'])) {
    $items['share/blog'] = $items['blog'];
    unset($items['blog'];
  }
}

```

That will just do the core 'blog' page, the blog module defines 4 paths (see `blog_menu()`), each of which you'll need to override if you want make this change fully. You might also need to do some further digging into the code the blog module produces as I'm not sure if any of those paths are hard-coded into URLs or anything like that.
> 2 votes

---
Tags: routes, nodes
---


# Question
Title: hook_user_presave at user registration, how to get field_data_field (set to auto increment) to take a new and unique value
I'm trying to force a parallel identifier (to match up legacy system requirements) to correlate to `uid` by means of a `field_data_field_foo` table.

The `field_data_field_foo` was created in the Field UI and because I couldn't see any `UNIQUE` and `AUTO_INCREMENT` options I set them both for the column `field_data_field_foo.field_foo_value` in phpMyAdmin.

I assumed this would be enough to force the issue, but in development I setup a `hook_user_presave()` function in my custom module and with a break point inside it, for `$account->field_foo` I just get undefined....

```
field_foo   Array [1]
    und Array [0]

```

Because this is something that *must* be assigned uniquely and I'd *like* to assign at the point of registration should I be using a different hook? Or is there something else I'm missing?

Btw, it might be something more basic in Drupal that I'm missing as I'm not that experienced with it atm - i.e. due to the nature of this project, I've yet to spend time learning nodes and the like.

# Answer
Here's what I did in the end...

First I added the field to the user registration form, as one thing Drupal is great at is processing information - I did notice errors being caught so I might have to check that out.

Then I used hook\_user\_presave() and (managing the unique id creation seperately) passed that, overriding any existing value or adding a value if none existed.

(full details are here: Editing user submission of user registration form with hook\_user\_insert() and $edit)

I will still have to manage away the users ability to insert an identifier by hiding it through CSS/JavaScript etc. but because hook\_form\_alter() wouldn't edit the user registration form after repeat attempts this seems the most expedient way of solving the problem.
> 0 votes

---
Tags: users, entities
---


# Question
Title: Drupal assuming admin created user, when user registered normally
This is something that I'm pretty sure worked when in beta, but doesn't work now anymore.

I have setup the user registration to be allowed by visitors, but a confirmation by the admin is required. Email verification isn't required. I have composed all the necessary emails.

Now, when a user registers, two things go wrong:

* no mail is sent to the admin
* the wrong mail is sent to the new user

The new user receives a mail stating that the admin created his account and that he can use the one-time login link to change his password. When he clicks on this link, he doesn't have access to the page, because the account isn't active yet.

The user should receive the mail telling him he registered succesfully and his registration is waiting for approval. The admin should receive the mail that a new user was created.

Sometime, the admin will create the users, so both mechanisms will be used. But I get the impression Drupal thinks it was always the admin that created the user, even if it was a normal user registration.

I have a rule setup (from the Rules module) for when a new user registers, to add him to certain roles. But this worked in beta, now it doesn't anymore. Also, disabling this rule, or disabling the rules module entirely didn't help.

Any ideas where I can start looking?

# Answer
As it turns out, a custom-made module conflicted with the normal behavior in a sneaky way.

In D7, when you create a user as an admin, the checkbox to send an email with a one-time login link is not selected by default. As the person creating users is not a technical person, I thought it might be user friendly if this was checked by default.

After a bit of searching, I found a small module that could help. What this piece of code did was:

```
if ($form_id == 'user_register_form') {
    $form['account']['notify']['#default_value'] = TRUE;
}

```

However, as you can see there is no check if the current user is the admin. So Drupal assumes the admin is creating the user, even for a normal registration by a visitor. Subsequently, the visitor gets a mail that the admin created his/her account.

I explained this for the author also, and hope someone fixes it (or I'll try myself when I find the time).
> 0 votes

---
Tags: users, emails
---


# Question
Title: How to implement less than / greater than in views contextual filters
I want to filter my view like

`field_opening_hour_start_time > <?php date("g"); ?>`

How can I make this happen? The filter criteria does not let me to use PHP and the contextual filter does not let me to use less than (or greater than), but only equal (=) comparison. Is there a way around this? Or a way to use PHP in filter criteria box?

edit. I am using Office hours module

# Answer
> 5 votes
Have you tried using the regular filter (granularity of hour) and selecting the 'relative date' instead of the hard-coded date? You could use 'now' to do a greater than or or equal to the current time, which is the same as

Screenshot attached:

# Answer
> 5 votes
You could use `hook_views_query_alter()` for this. Look example. Use `print_r()` or devel functions such as `dpm()` to view how your field is called.

```
/**
 * Implements hook_views_query_alter()
 */
function occ_search_views_query_alter(&$view, &$query) {
  if ($view->name == 'restaurants') {
    if (isset($query->where[0])) {
      if (trim($query->where[0]['conditions'][0]['field']) == 'field_data_field_max_group_size.field_max_group_size_value = :field_data_field_max_group_size_field_max_group_size_value') {
        // Use '>=' condition instead of '='
        $query->where[0]['conditions'][0]['field'] = 'field_data_field_max_group_size.field_max_group_size_value >= :field_data_field_max_group_size_field_max_group_size_value';
      }
    }
  }
}

```

# Answer
> 2 votes
you could use this sandbox project views arguments in filter. It permit to use arguments in filter criteria and then all the operators of the filter criteria with the arguments.

---
Tags: 7, views
---


# Question
Title: Can I show the answers to a previous round of questions in webform?
I built a questionnaire on Survey Monkey and had 75 people fill it in. I now need people to repeat the same questionnaire (which I am rebuilding in Webform) BUT I have to show the option they previously selected and the average across the entire survey.

I have all previous answers in a mysql database, so what I would like to do is to drop the user-specific answers in.

i.e. Last time you answered ....

Is there any way to get Webform to do this (i.e. with the Markup feature possibly?) or is this beyond its remit? I have people who are willing to help me with this, but wanted to see whether the Drupal community had any ideas first.

**EDIT**

Perhaps I can give you an example. Say for the first round of the questionnaire you ask people:

How do you feel about cats? 1) Love them 2) Like them 3) Dislike them 4) Hate them.

A week later, you then ask people to repeat that same question, except the question looks like this.

How do you feel about cats?

Last time you selected 'Love them'

In the survey overall people made the following choices: 1) Love them 25% 2) Like them 40% 3) Dislike them 25% 4) Hate them 10%

Please now re-answer.

1) Love them 2) Like them 3) Dislike them 4) Hate them

Thanks for your help. I hope this is a bit clearer!

# Answer
Your question is not completely clear, but as I understand you want to load a custom set of dropdown options as a webform element.

You can do that from a custom module with the following example code:

```
/**
 * Implements hook_webform_select_options_info().
 *
 * Defines a custom dropdown form element to be used with the Webform module.
 */
function YOURMODULE_webform_select_options_info() {
  $items['last_time_answered'] = array(
    'title' => t('Last time you answered'),
    'options callback' => '_YOURMODULE_get_options',
  );
  return $items;
}

/**
 * Generate "Last time answered" options for the current user.
 *
 * Used for sample webform element.
 */
function _YOURMODULE_get_options() {
  // Your query goes here
  // Return should be an array with $value => $label structure.
  return array(
    1 => 'Option 1',
    2 => 'Option 2',
    3 => 'Option 3',
  );
}

```

I also suggest to drop in a custom validator to the webform:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    // Sample webform custom validation
    case 'webform_client_form_1':
      $form['#validate'][] = '_YOURMODULE_validate_custom_field';
      $first = array_shift($form['#submit']);
      array_unshift($form['#submit'], $first, '_YOURMODULE_validate_custom_field');
      break;
  }

}

/**
 * Custom validation function for webform component.
 */
function _YOURMODULE_validate_custom_field() {
  foreach ($form['#node']->webform['components'] as $element_id => $element) {

    if ($element['form_key'] == 'last_time_answered') {

      // Perform the check here
      if ($element['value'] != 'Sample value') {
        form_set_error('', t('Validation message.'));
      }

    }

  }
}

```

To use this custom field, create a new webform element (select options) and choose your new list from the "Load a pre-built option list" dropdown.
> 0 votes

---
Tags: webforms, database, theming
---


# Question
Title: Trying to edit the breadcrumbs for views using Custom Breadcrumbs module
I'm trying to use the custom breadcrumbs module with Drupal 7, and I'm having issues generating a custom breadcrumb - it only seems to want to let me edit nodes/add custom bread crumbs to nodes.

How would I go about adding a custom breadcrumb to a view?

# Answer
The stable Drupal 7 version of Custom Breadcrumbs is currently in the 1.x branch; support for Views has only been added in the 2.x branch, for which there is no stable release for either version (there's an RC available for Drupal 6 but only a dev version for Drupal 7).

I think your options are:

1. Try the 7.x-2.x-dev branch and report any problems you find back to the module issue queue
2. Implement `hook_preprocess_views_view()` for your view and set the breadcrumb in there programatically (with code similar to the below).
3. Add custom PHP code to the header of your view (not advised):

```
$breadcrumb[] = l('Home','<front>');
$breadcrumb[] = l('View Name', 'path/to/view');
drupal_set_breadcrumb($breadcrumb);

```
4. A number of other 'hacky' methods that involve overriding the `theme_breadcrumb` function and making changes based on the path of a View (see this post for some examples).
> 8 votes

# Answer
This is a functional example of #2 which is hooked to view 7.x-3.x that has contextual filters on two displays based on term ID (base-path/%). The base-path is not valid, so this masks it out to just "Home \> TERM NAME"

```
/**
 * Implements hook_views_post_execute().
 */
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'products') {
    switch ($view->current_display) {
      case 'by_occasion':
      case 'by_type':
        $breadcrumb[] = l('Home', '<front>');
        if (!empty($view->args)) {
          if ($term = taxonomy_term_load(current($view->args))) {
            $breadcrumb[] = check_plain($term->name);
          }
        }
        drupal_set_breadcrumb($breadcrumb);
        break;
    }
  }
}

```
> 1 votes

# Answer
I did it with hook\_page\_alter, checking current page url against views page url.

```
/**
 * Implements hook_page_alter().
 */
function mymodule_page_alter(&$page) {
  /* ----- set breadcrumb for some view pages ----*/

  if (request_path() == 'announcement') {
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l(t('Announcement'), 'announcement');
    drupal_set_breadcrumb($breadcrumb);
  }
  ...
}

```
> 0 votes

---
Tags: 7, views, breadcrumbs
---


title: Relationship in View

text:
# Question
Title: Relationship in View
I need to have two content type: "book" and "article". Then I want to make a view that shows the title of the book (which is in the content type book) and the titles of each article (found in the content type article). Which field should I add to the content type "article" to make sure it is plugged into a certain book? And how do I set the View?

# Answer
Although your question seems a bit less detailed than it should be, I assume that you need some way to connect a node type (article) to another node type (book). For this you can use References module or Entity References will be even better.

You can add an entity reference field to book content type. Then, when you create a book, you can select relevant articles. If you want to have two-way relationship (book \<--\> article) then you can also use this module: drupal.org/project/cer A good addition can be this module also: http://drupal.org/project/inline\_entity\_form which allows you to create or select your articles when you create a book.

Then in your view, you can show book's titles as fields. Add a relationship with your entity refrence field. Add a field "title" but select relationship you just added. Group the results by first field (title only)
> 1 votes

---
Tags: views, 7
---


title: Get the invalid URL which throw a 404

text:
# Question
Title: Get the invalid URL which throw a 404
I have a catalog of products in one of my website, each year there are new products and some old products are unpublish (never deleted). Some websites put links to the products, so when a product is unpublish, all those referents links becomes invalid and are redirect to a 404 pages.

Now i don't want that, i want a custom redirection to parent category of the product. For that i catch the 404 event, and then i tough i could just make a dbquery on my node items to found the parent's category, and create a redirection.

I catch the 404 in the template.php file like that :

```
 function myTheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  if (!empty($node)) {
    $headers = drupal_get_headers();
    if (preg_match('@HTTP/1\.[01]\x20+404@', $headers)) {
      //want to do my redirection here

    }
  }

```

but when i try to get my url, i get in fact the url of the 404 pages but in the url bar, it's still the product url.

So how can i get that url or simply the invalid nid?

# Answer
> 1 votes
My bad, i had one of those blind drupal moment :)

Yes it seem that drupal can't find the url because of the 404 which become the current node, but with some PHP we can still get it.

```
  $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
  print $pageURL;

```

\[that is not my code, so thank you Google.\]

---
Tags: 6, uri
---


# Question
Title: How to import multiple values in a text field with Feeds module?
In my content type, I have a text field that allow an illimited number of values.

How do I configure Feeds to import multiple datas in this kind of field?

# Answer
Feeds Tamper will do this for you.

> Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below. Additional plugins can be added in separate modules or through the issue queue.

One of the default plugins is explode. Just set up a feed tamper to take your multivalued field from your CSV and explode it based on whatever delimiter you fancy. This will import it as multiple field values.
> 7 votes

---
Tags: feeds, importing-exporting, entities
---


# Question
Title: Change style for the reply link in comment.tpl.php
How could I style the "reply" link in comment.tpl.php?

I have this line of code inside:

```
<?php print render($content['links']) ?>

```

With this I get something like the following:

```
<ul class="links inline" thmr="thmr_249"><li class="comment-reply first last"><a href="/?q=comment/reply/28/1" thmr="thmr_250 thmr_251">reply</a></li></ul>

```

I manage to get the exact URL with `<?php print render($content['links']['comment']['#links']['comment-reply']['href']) ?>`, but for some reason it doesn't work perfectly: It loses the "/?q=" part.

# Answer
> 2 votes
Just use the following code:

```
<?php print url($content['links']['comment']['#links']['comment-reply']['href']); ?>

```

If you pass node/1 to `url()`, it will return /?q=node/1 when clean URLs are not enabled, and /node/1 when clean URL are enabled.

---
Tags: comments, navigation
---


# Question
Title: How can I let users register for a certain node type?
In Drupal 7.15, I use the Webforms module to allow guests to sign up to courses. I therefore created a content type *Registration Form*.

Courses themselves are individual content nodes, of the type *Course*.

Now, I'd like the user to be able to select a course to sign up for, and save that in the web form as well. How can I do that?

It seems that the Webform Associate module does exactly that:

> The Webform Associate module is designed to allow attaching webforms to particular node types. The example would be event registration. Event node types might need starting and ending dates, descriptions, etc. With Webform Associate a new webform node is automatically created, and the webform itself is appended to the bottom of the event node.

However it says that "Webform 3.0 Obsoletes this module and is not compatible in any way." Haven't found out how, though.

# Answer
> 2 votes
I was finally able to associate the event using the Node Registration module.

> Allows (authenticated and/or anonymous) users to register for events. Events are nodes with certain node types. You can enable registration for any node type and add fields and manage display per type and per node.

The module depends on Value is and Entity as well as Views and CTools.

---

What you'll have to do after installation:

* Go to `admin/structure/types/manage/<course>/edit`, where `<course>` is your course
* Enable registrations at the bottom under *Registration Settings*
* Go to `admin/structure/node_registration/manage/<course>/fields` and add fields to your registration form, as required.
* Don't forget to enable the right permissions too for anonymous users.

---
Tags: 7, forms
---


title: Headless Web Browser During Cron?

text:
# Question
Title: Headless Web Browser During Cron?
I need a headless web browser with JS support to use during cron. It seems like the simpletest module does what I need, but how could one initiate a browser and hand it a DOM?

Outside the context of Drupal cron, it would go like this:

```
require_once('simpletest/browser.php');

$browser = &new SimpleBrowser();
$browser->get('http://php.net/');

```

But, is there a way I can use the code that the simpletest module already provides?

# Answer
SimpleBrowser does not support Javascript. I'll have to use a headless browser like Phantom or Zombie or script something to execute the JS more directly with a given DOM.
> 1 votes

# Answer
If you want a PHP headless web browser, you might look at Mink.

Gherkin/Behat seem to be getting some traction in the Drupal community and in the PHP community more broadly for Behavioral Driven Development. Mink also supports browser emulation systems (like Selenium), which you typically need in order to interact with Javascript.
> 4 votes

---
Tags: 7, javascript, cron, testing
---


# Question
Title: Get the master parent node id for a node reference field
I have 3 content type "A" , "B", "C". B has a node reference to A. C has a node reference to B.

```
B->A
c->B

```

Using simple query I want to get the master parent node Id of C. which is A node id

```
c->B->A

```

How to do this.

# Answer
> 2 votes
If you are looking for a DB query within a custom module, you could do something like the following example function that recursively goes through the reference tree to get to the top for a node. It will work for N levels, (but not for multi-valued references or nodes with multiple node reference fields).

```
function mymodule_getTopReference($nid){
    $top_nid = 0;
    //load the node
    $node = node_load($nid);
    //get all reference fields
    $node_reference_fields = array();
    $field_infos = field_info_instances('node',$node->type);
    foreach ($field_infos as $field_name=>$value){
        $field = field_info_field($field_name);
        if (($field['type'] == 'node_reference')){
            if ($field_value = field_get_items('node',$node,$field['field_name'])){
                $top_nid = $field_value[0]['nid'];
                break;
            }
        }
    }

    if ($top_nid && ($parent_nid = mymodule_getTopReference($top_nid))){
        $top_nid = $parent_nid;
    }
    return $top_nid;
}

```

For example, if your node reference field was called "my\_reference" and your example nodes had the following nids:

* A = 1
* B = 2
* C = 3

and your references are as you said:

* B-\>A (2-\>1)
* C-\>B (3-\>2)

Then for node 'C'(3) you'd call this function like so:

```
$top_nid = mymodule_getTopReference(3);

```

which then would set $top\_nid to 1 (A's nid).

---
Tags: 7, nodes
---


title: Group of References

text:
# Question
Title: Group of References
i am working on a site for a association with employees (mostly voluntary) on three "Levels":

1. Nation wide
2. Districts
3. Local

The locals are bound to a district.

The positions for the employees are almost the same on all levels.

* Person1 -\> PR nation wide (like a manager for the districts and locals)
* Person2 -\> PR in the district
* Person3 -\> local PR

The positions should have a kind of priority so that for example the leading person should be on the top of every listing of nation/district/local.

I created 3 content types for NATION, DISTRICT, LOCAL. LOCAL with an entity reference to DISTRICT. And because the listings should be sorted by the priority, I created a JOB content type.

Another content type I created is the PERSON. Now here is the problem: a PERSON can have more than one position and that could be twice (or 3,4,5...) in a LOCAL or LOCAL and DISTRICT.... So that the position he is having should be group of references (NATION/DISTRICT/LOCAL & JOB).

The thing is that I want to see all the persons working for NATION/DISTRICT/LOCAL (simple view)

A view listing all LOCALS bound to a DISTRICT.

PROBLEM: A listing of all JOBs and places (NATION/DISTRICT/LOCAL) a PERSON is having.

Edit: Drupal 7

# Answer
So to set up the view that displays all jobs and levels a person has, you just have to use the correct relationships in your view. So if a job is already listed as 'local' or 'regional' by containing **a reference field** (entity or node reference) to the correct level, you can get to that in a view by making sure the view is created as a listing of jobs.

So if you are doing a 'Jobs' listing, set up a filter under the 'Advanced' section to be able to filter by person. If the 'Person' content type has a field that's a reference to this 'job' content, you should be able to add a '**reverse** reference' in the '**Relationships**' section, so you can filter on that (the Person) to limit the jobs to just a particular person. You can set that up as a regular filter (hard-coded or exposed so anyone looking at the view can change it) or as a contextual filter that's based on the current person logged in or the person whose profile is being viewed.

Then you can, with each job that pops up in the view, after you've filtered by person, simply display the 'level', since I'm assuming the job will have the level as a reference field already. You should be able to easily and without any more relationships display all the fields that are associated with the job, such as the job's level.

Does that help at all? Or did I misunderstand your question?
> 0 votes

---
Tags: entities
---


title: user specific menu tab

text:
# Question
Title: user specific menu tab
I have a menu tab on nodes which is visible to everyone on the site. But I want it to be user specific. If the logged in user is the one who created that node, only he should be able to see the menu tab. Is it possible to do this using views ?

# Answer
Using Views, you can add tabs and set argument (aka contextual filter) validators.

user will not see the tab if the argument is invalid.

See this post. You will need to set arguments as described in this post.
> 0 votes

# Answer
You can always add access argument "edit own page content" replace page with you content-type name. If you want more complex permissions you can add your own access callback to a menu item which will return true or false. For further information check http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7
> 0 votes

---
Tags: 7, users, routes
---


# Question
Title: Address book problem when user edit the billing address
i just installed commerce address book module but i noticed that when authenticated users try to edit their billing address they have some options in the bottom that seems very strange and not necessary.

The fist one is : The user is able to change the owner of the account and the second is : The user can change the status from active to disabled.

I think that these options should not be there.

Do you know how can i disable?

# Answer
> 0 votes
I found this patch which worked for me: http://drupal.org/node/1774932

---
Tags: 7, commerce
---


# Question
Title: PDOException: SQLSTATE[42000]: Syntax error or access violation
> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1118 Row size too large. The maximum row size for the used table type, not counting BLOBs, is 8126. You have to change some columns to TEXT or BLOBs:

Database storage Engine : Innodb

Do we have to switch over for MyIsam?

# Answer
> 6 votes
Sounds like a case of InnoDB File Format issues.

# **SUGGESTION #1**

If you are not using **innodb\_file\_per\_table**, you may need to export all the data with mysqldump, delete ibdata and ib\_logilfe0 and ib\_logilfe0. Then, reimport that data. I wrote a *detailed step-by-step process* for this 2 years ago.

# **SUGGESTION #2**

Increase the size of your InnoDB Log Files. Each file (ib\_logfile0,ib\_logfile1) needs to be more than **10 times as big as the biggest BLOB** in your dataset:

Here are several links discussing this scenario

MySQL's maximum size of innodb\_log\_file\_size for a log group of of 2 files is 2047M. Should you ever need InnoDB Log Files that can exceed the 4GB combined barrier, you must upgrade to Percona Server.

I also wrote a *detailed step-by-step process* for resizing InnoDB Log Files.

# **SUGGESTION #3 (OPTIONAL)**

You may want to switch the **innodb\_file\_format** to Barracuda. *Bill Karwin's answer in the DBA StackExchange* and links thereof explains why.

---
Tags: 7, database
---


title: Caching Panel page variants

text:
# Question
Title: Caching Panel page variants
I don't believe I have never run into this before, but I have a Panels page with a few variants based on selection rules. Is there a way that you can serve up cached results for the whole page (not just the individual panes) after the selection rules have run? I am not seeing any options or other modules to get Page Manager to do this.

# Answer
Did you try any off the following module

Panels Page Cache

> This plugin can cache panels based on the path/url (arg() structure).
>
> This is needed if a panel has content which is dynamically per page (eg ad-tags, content related items).

Panels Hash Cache

> This module provides a hash-based cache for Panels and other Chaos Tools powered displays. This support caching based on any combination of:
>
> ```
> Contexts (node, term, user etc)
> Arguments
> Drupal Path (args) (same as the Panels Page Cache Module)
> Full URL (including domain and query string)
> Users
> Roles
>
> ```
> 3 votes

---
Tags: panels, caching, chaos-tool-suite
---


# Question
Title: Remove contributor role when user deletes all of his content
I have the following problem that I don't seem to be able to solve myself:

Today user BRIAN feels like creating some content, let's say 5 articles. I created a rule using the RULES MODULE that automatically assigns him the role CONTRIBUTOR after creating the first article.

Tomorrow Brian will realize that 4 of his articles weren't that great, and he decides to delete them. No problem, there is still one article out there authored by him and Brian is still a contributor! HOWEVER, as soon as Brian also deletes his very last piece of contributed content, I want him to lose his contributor role.

How do I put this into a rule?

On Brian's user profile, there is a VIEWS block listing all of Brian's content. The RULES BONUS PACK (http://drupal.org/project/rb) would let me check the number of results of this block and remove his contributor role as soon as the number of results drops down to 0. However, the module is still in development and I really don't want to use a dev-version on a productive website.

I read somewhere that the VIEWS BULK OPERATIONS module could do the job, but I really wouldn't know how. Could someone give me a hint, please?

# Answer
> 1 votes
Checkout the rules bonus pack

> Conditions
>
> * Check number of results from a view: This condition loads a view and checks the number of results – condition is passed if it is at least as many results as you set. You can pass on arguments to the view.

---
Tags: users, views, rules
---


# Question
Title: Specifying the default database to store new field tables in
I have a few Drupal 7 sites running on a multisite setup. They each have their own database, and there's a "shared" database used by all of them, which contains user data, date formats, filters and some other data that is shared across all of the sites.

Nodes and taxonomy are not shared, but I am looking at changing that so they are, and using a taxonomy vocab as a means of specifying which site each node is associated with.

I don't have a problem setting that up as I have a nice little database include that handles database credentials and prefixing, but there is one drawback with this setup and that is controlling which database any given module should create new tables in. I know that in order to have all sites use a single `node` table, I should also share the content types and fields - but I am going to run into issues when creating new fields on content types, as their respective tables will naturally be created in the site's default database and not the shared one.

So, I suppose my question is: **how can I specify what the default database should be on a per-module basis?**

P.S. I did consider using Domain Access to achieve this, but that doesn't seem to be suitable in this case as each site uses a separate database already, and I'm not looking to share themes, site config, blocks, views, panel data, paths, etc.

# Answer
> 2 votes
Unfortunately, Drupal was not designed to work this way. The only way to figure out where to put each table would be to carefully inspect each new module and adjust your settings in advance of enabling the module. Even if you manage to do this, you are likely to run into problems with modules that stores critical information in the variables table. Clearly you cannot share the entire variables table, so you would instead need to figure out how to synchronize individual values that must be shared, avoid race conditions, etc.

You should strongly consider using domain access or subdomain to share node content between different sites. You will have some work ahead of you in converting from your current site format to one that will work for you; the migrate module may help with this task.

---
Tags: database, multi-sites, domain-access
---


# Question
Title: Display the flag link only for the node author
I'm trying to display the flag link only for the node author, and I'm using the following code:

```
global $user;
if ($node->uid == $user->uid) {
  //print your flag
}

```

The link doesn't appear.

Do you have any idea on what is causing this?

# Answer
> 2 votes
You may use hook\_flag\_access(), as in the following code.

```
 function crystal_qa_flag_access($flag, $entity_id, $action, $account) {
   // Only the author of the question has right to use flag "Accepeted" on answers.
   if (($flag->name == 'accepted') && ($flag->content_type == 'node')  && ($node = node_load($entity_id))) {
     if ($node->type=='answer') {
       // The content type machine name must be answer.
       $question_nid = $node->field_answer['und']['0']['target_id'];
       $question = node_load($question_nid);
       return ($question->uid == $account->uid);
     }
   }
 }

```

# Answer
> 0 votes
Perhaps by declaring `$user` to be a blank variable right before you use it, you're overwriting Drupal's variable?

---
Tags: views, flags
---


# Question
Title: How to save the URL of anonymous user on a webform?
Using Webform 7.x-3.18, I'd like to save the referring URL of an anonymous visitor on a webform. I added some code to MYTHEME\__preprocess\_page() in template.php to save the info as a cookie: user\_cookie\_save(array('webform\_referrer' =\> $\_SERVER\['HTTP\_REFERER'\]));

On my webform I added a hidden component, with a default value of %cookie\[Drupal\_visitor\_webform\_referrer\].

I'm testing with safari/chrome/ff on a Mac and on Windows. I can get this to work on my local testserver, but only about 10% of the time on the production server, and never from Windows to the production server. The production server has hardware load balancing. I'm suspecting this is a caching issue. I've also read that server vars may not be available as webform default values for anon users (http://drupal.org/node/296453#comment-2397674) - is this the issue? Why then would it be working for anon users coming to my local server?

I can't think of another way to integrate this easily into webform as a hidden field. Perhaps I have to write some kind of custom hander to save the referrer?

# Answer
So you can achieve this using form alter,

create a text field namely 'refer\_url' for saving referring url, then using following snippet in your module you can save the referring url. You can hide this field in display using css or form alter.

```
function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_27') {
    $form['submitted']['refer_url']['#default_value'] = $_SERVER['HTTP_REFERER'];
    }
}

```
> 1 votes

---
Tags: webforms, cookies
---


title: Get text field value before saving node

text:
# Question
Title: Get text field value before saving node
I have a a custom module in which I am implementing hook\_node\_presave() for a content type "ABC".

I want to get the value of a text field say 'field\_test' before saving the node.

How to do this.

# Answer
> 1 votes
Use the following code,

```
$value = $node->field_test[$node->language][0]['value']

```

This to get the value for the text field alone for other fields format will chage.

---
Tags: 7, hooks
---


title: Customizable labels in custom fields

text:
# Question
Title: Customizable labels in custom fields
For a new website I have a list of products with specs, but most of the time the specs are different for each product, because there are a lot of types of products.

Right now I just have a new field for every type of spec, but I want the client to be able to do this themselves. Is there a module that enables me to customize the label for each field?

So let's say the client can add a field, fill in the label and value himself?

# Answer
> 1 votes
You can use 'Field collection' in your content type for products, In your field collection field keep one field as label and other for the value. This approach will suit your needs

---
Tags: 7, entities
---


# Question
Title: if i have no right use the flag "Accepted",please hide it
when user have no permission use flag "Accepted",how to hide it instead of when clicking and tell them "you have no permission"?

I found a function on flag.module: function template\_preprocess\_flag(&$variables) ,

but it seems not a hook to reuse...

# Answer
I just added this to my sites/all/themes/mytheme/template.php file and it worked after clearing the theme registry:

```
function mytheme_preprocess_flag(&$variables) {
  // Do something here
  dpm($variables);  // Pretty print $variables if you have the Devel module installed
}

```

That should give you a nudge in the right direction.
> 1 votes

# Answer
```
/**
 * If I have no right use it, please hide it.
 * @see druedu_preprocess_flag in theme level.
 */

 function crystal_qa_preprocess_flag(&$variables) {
  $flag = flag_load('accepted');

  if (!$flag->access($variables['content_id'])) {
    $variables = NULL;
  }
}

```

We needed to override the flag.tpl.php file to avoid errors in the log:

```
if (isset($flag) && !is_null($flag)) {
  // Render.
}

```
> 0 votes

---
Tags: flags
---


# Question
Title: How can I switch menus after a user logs in
I'm trying to create a register/login links in the format "Register or Login" which is display for anonymous users and switched out with the user menu when a user is logged in.

I know I can preprocess those links as variables in template.php but am not sure how to access the user menu from template.php in order to write an if statement.

Ultimately, if I could do something like Forrst (images below), then tahts what I would love to end up with, but for now just trying to keep it sweet and simple.

From This:

To This after login:

# Answer
You could create the menu using UI at *admin/structure/menu*, control menu visibility by using Menu Per Role module and then style it with CSS to get this to work.

Menu Per Role module features:

> This module allows you to restrict access to menu items based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.

Screenshot of the settings which you get on menu create/edit form:

Also to create the dropdown menu you could use DHTML Menu module, or Superfish module.
> 2 votes

# Answer
You might do that with a simple block, rather than creating a menu, preprocess it to add the word between and check if the user is logged in.

Simply select anonymous/authenticated user under the "Roles" in block visibility settings.
> 2 votes

---
Tags: theming
---


title: Deactive link in h2

text:
# Question
Title: Deactive link in h2
I created a custom node.tpl.php file with the following code:

```
<?php
 /**
  * @file
  * Default theme implementation to display a node.
  */
?>

<div<?php print $attributes; ?>>
  <?php print $user_picture; ?>

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

  <?php print render($title_prefix); ?>
  <?php if (!$page && $title): ?>
    <h2<?php print $title_attributes; ?>><?php print render($title_link); ?></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <div<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>
  </div>

  <?php print render($content['links']); ?>
  <?php print render($content['comments']); ?>
</div>

```

Everything works, but the `<h2>` tags come with link I don't want.

Instead of `<h2 datatype="" property="dc:title"><a href="/node/10">NEWSSSSS</a></h2>`, I want `<h2 datatype="" property="dc:title">NEWSSSSS</h2>`.

How can I achieve this?

# Answer
> 1 votes
I changed this line and worked!

`<h2<?php print $title_attributes; ?>><?php print render($title_link); ?></h2>`

change to

```
<h2<?php print $title_attributes; ?>><?php print render($title); ?></h2>

```

`($title_link)` ----\> `($title)`

---
Tags: 7, nodes, navigation
---


# Question
Title: Scheduling unpublish too complex for existing modules
I need a specific node type to automatically unpublish 3 months after publishing, but the date of unpublishing needs to remain constant even if the user unpublishes and republishes the node, unless the date is passed in which case it should start again.

Whenever the timer is reset a notice should be sent to the admins, and the date of scheduled unpublishing should be editable by the admins.

Needless to say this is too complex for any current modules, and when I think of writing a module to do it I don't know how to use the drupal api to schedule things with cron, or how to create an administration settings interface to handle the unpublish dates.

# Answer
Drupal Scheduler will provide the proper infrastructure. Then in a hook\_form\_FORM\_ID\_alter(), you can set the date as follows:

```
global $user;
$roles = $user->roles;

$plusThreeMonths = date("Y-m-d H:i:s", strtotime("+3 months"));
$form['scheduler_settings']['unpublish_on']['#default_value'] = $plusThreeMonths;
// Disable setting of unpublished date unless admin or user 1
if ($user->uid != 1 && !in_array('administrator', $roles)) {
  $form['scheduler_settings']['unpublish_on']['#disabled'] = TRUE;
  $form['field_package_winning_bid']['#disabled'] = TRUE;
}

```

Then if you need to update the unpublish date, you can use a function similar to the following:

```
function _republish_node($nid, $time) {
  $node = node_load($nid);
  // Add time to the publish date
  $unpub = date("Y-m-d H:i:s", strtotime($time));  // pass in a string like "+2 weeks"
  $node->unpublish_on = strtotime($unpub);
  // Set published to true
  $node->status = 1;
  node_save($node);   // Re-save node with updated status
  scheduler_node_update($node); // update publisher fields
  // Add watchdog or other method to alert admins (or use rules)
}

```
> 1 votes

# Answer
Checkout the module scheduler, This module allows nodes to be published and unpublished on specified dates. If you want to do any other associated tasks related to publishing and un publish of nodes like sending mails etc can achieve by rules
> 0 votes

---
Tags: 7, cron
---


# Question
Title: View only content created by that particular user
I want the user to view only the content created by him.

Used "content access module". And change permissions for the user to "Grant own Content Access".

But other users also able to see the content created by other users. Below is my permissions page:

Not able to find what went wrong. Please correct me.

If any other module is there please suggest me.

# Answer
> 0 votes
Follow below steps to resolve the issue !

* Enable Content Access Module
* Clear Cache
* Go to Edit Content Types, and Select Access Control
* Set Access Control As shown below. Remove checkbox view any article content for anonymous and authenticated users.
* Save Settings
* Go to "admin/reports/status/rebuild" and rebuild permissions
* Create a Content of content type that you set access permissions.
* Logout and Login as another normal user and check for access.

Let us know if still fails :-)

---
Tags: 7
---


title: Regex Jquery in Drupal 7 not working

text:
# Question
Title: Regex Jquery in Drupal 7 not working
(I have posted this on Stack Exchange as well)

I have a Drupal 7 page on which I need to remove text bracketed by "Keywords:" and "Description:", there are a number of text blocks all with the class .feedDesc

Page is here: http://www.cafe.gen.nz/node/236/feed-items

I have this working on a plain html page with this Jquery below but can not for the life of me make it work in the Drupal setup:

```
  $('p.feedDesc').html( function (index,text) {
    var regex = /Keywords(.*)Description/;
    return text.replace(regex,"");
  });

```

On the site the below does work indicating the whole stack is good.

```
  $('p.feedDesc').html( function (index,text) {
    return text.replace("Keywords","Foobar");
  });

```

Help !

Any ideas?

Update:

This works to do the find/replace:

```
    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      return text;
    });

```

However I also need to trim whitespace and $.trim does not work:

```
    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      text = $.trim(text);
      return text;
    });

```

# Answer
> -1 votes
If that's the exact code, then

```
var regex = /Keywords(.*)Description/;

```

should be

```
var regex = '/Keywords(.*)Description/';

```

---
Tags: javascript, 7
---


# Question
Title: Creat new menu items link in menu like create new Content Type does
When create a new Content Type, several new menu links will created and show in the management menu, such as `node/add/article` and `admin/structure/types/manage/article`.

```
Add content
    -- Article
    -- Page

```

How can I implement similar functionality within my custom module?

```
Sites
  -- Site Name A  (link to site/1)
  -- Site Name B  (link to site/2)

```

My `hook_menu()` implements code:

```
$items['site/%'] = array(
  // ...
  'page callback' => 'mymodule_site_view',
  // ...
);

```

I have tried to use `_load()` and `_to_arg()`, but doesn't work or maybe I just not use them correctly.

```
function mymodule_menu() {
    $items['site/%mymodule_site'] = array(
        // ...
        'page callback' => 'mymodule_site_view',
        // ...
    );
}

function mymodule_site_load($sid) {
    // load site object from database
    $site = ...
    return $site;
}

function mymodule_site_to_arg($site) {
    // I guess here I can use site object, but just get %
    return $site->name;
}

```

Can anybody give me on example?

---

I know I can create/delete menu links when create/delete my site object manually. I just want to know if I can user `_load()`, `_to_arg()` or others to implement it.

# Answer
> 0 votes
You do not need to use php code just to create a menu with menu links. You can do it with Drupal Core itself.

See below detailed tutorials that may help you.

How to create a menu and add links to it in Drupal 7

Advanced Drupal 7 menu settings, how to create parent child menu links

Create Drop Down Menus in Drupal 7 Using Nice Menus module

If you want to do it specifically using Custom Code then your callback function should call drupal\_goto with link as an argument.

---
Tags: 7, routes
---


title: Views News slider

text:
# Question
Title: Views News slider
I have this design:

E.G. Click "Structure" header, open contents and come img.

Created content type and installed Views. Seperate image, header, content fields via block.

Like our design but site now static. I want dynamic structure but i don't know. Well, how can i do it?

# Answer
You can able to do it using "Views Module" and "Views Slideshow Module" . Below Steps may help you.

* Create a Content Type.
* Add all necessary fields.
* Create content
* Create a view that lists all above content and use views field option to display above content type fields.
* Select the Views Style as "Views Slideshow".
* Configure settings and select pager as title field.
* That's it ! With little bit of CSS and Positioning you are good to go :-)
> 0 votes

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


# Question
Title: Image link in views exposed filter gallery
I created a content type which contains among other infos, some pictures

I'm using views with exposed filters to render them on the page (the images are thumbnails)

How can i create a link on the thumbnails that will start a gallery (big pop-up modal img slider) that include only the pictures in each content?

Here is what i can link pictures to atm (i'm looking for some other options for this drop down menu)

# Answer
> 1 votes
Try the Colorbox module; it is great and very configurable, and it has also an image-format option for the Views module.

# Answer
> 0 votes
You can use Colorbox module to do this. -Install Color Box -Edit your view image field formatter to be Colorbox not Image. -Choose node style which would be displayed in the normal page -Choose Colorbox style which would be displayed in the pop-up modal (colorbox, lightbox ...) -In the Gallery Option (image grouping) Choose per page gallery ...

That's it

---
Tags: views, navigation, media
---


# Question
Title: Prepopulate from link in content only visible to users tagged within that content
I have two content types, Parent and Child. Parent contains a list of tagged users which may create Child. Child contains the tag of the Parent.

On the Parent page I need a link, which is only visible to people tagged in it, to create a new Child with the Parent already tagged in it.

I know I need to use something like **Entity Reference Prepopulate** but my problem is that I can't figure out how to make the link.

This seems like it should be a simple thing to do but I can't for the life of me figure out how!

The requirement is that this should only use the UI and **without editing any .php files** as there is no guarantee that other devs will be able to code and allows easy visual recognition of what has changed.

Any advice would be greatly appreciated.

# Answer
> 0 votes
So here is how to do it.

1. Install and activate Entity Reference Prepopulate and enable it within the Entity Reference of Parents field in Child. You can now populate that field by **example.com/node/add/child?field\_parents=\[parent nid\]**.
2. Install and activate Views PHP.
3. Create a new View without any pages or blocks called "Create new Child"
4. Click "+Add" and select "Content Pane"
5. Apply the following settings:
    * Filter critera
        + Content: Published (Yes)
        + Content: Type (= Parent)
    * Pane settings
        + Link to view: Yes
        + Argument input: From context\>Node Content ID
    * Contextual filters (under advanced)
        + Content: Nid
6. Set Format - Show: Fields and then add a field - Global: PHP
7. In the configuration for Global: PHP, in the Output code section write: `<?php print '<a href="http://example.com/node/add/child?field_parent=' . (string)$data->nid . '">Create new child</a>'; ?>`. (N.B. You need title field/NID field added as well for the `%data->nid` to work, hide it if you wish)
8. Add a Global: PHP in "Filter Criteria" and add the following code

`$uid = $GLOBALS["user"]->uid;`
`$node = node_load($data->nid);`
`$info = field_get_items('node',$node,'field_users');`
`$uids = array();`
`foreach($info as $user)`
`{`
`$uids[] = $user['target_id'];`
`}`
`return in_array($uid, $uids) ? FALSE : TRUE;`
9. Save everything. In in Pages now, you can add this into Panels via "View Panes".

---
Tags: 7, entities
---


# Question
Title: The module Node Embed does not work for a custom user role
I am trying to use the Node Embed module with WYSIWYG editor in Drupal 7 to embed a node. I can do this as an Admin but cannot do it as a custom user role. It says Access Denied when I go to the WYSIWYG editor and the Node Embed plugin. I did check for the permissions for WYSIWYG profiles and also text formats. The custom role has permissions to use/access both. Any thoughts on this? Any help would be appreciated.

# Answer
> 1 votes
In the Module Documentation for both CKEditor Integration and WYSIWYG Integration it says:

"Enable the default view 'ckeditor-node-embed' (if its not already enabled). This view provides the content of the 7plugin dialog box."

The access to this view is "Permission | Administer Content"

If your custom roles do not have this permission it won't work.

I altered the access to be by Role and selected roles I wanted to be able to use Node Embed and it then worked.

---
Tags: nodes, users
---


# Question
Title: create layouts without the use of embedded regions
from my experience with Drupal, I could understand, that you can thematize the page.tpl.php file, adding the appropriate html / css and entering regions with php. So far so good .... but my approach I'm following this project is to thematize the file. tpl.php corresponding to each of my content type. Now I need a page to bring them all together, I did it successfully using the "Panel". But I would adopt the approach in my opinion the most flexible layout with html / css. On which page should gather instances of my various themed content type?

# Answer
Your best option really is Panels, especially once you get comfortable making your own panel layouts (which is actually quite easy). Along with using preprocess hooks to attach classes (particularly to body) as needed, the combination of the three lets you do pretty much anything you want. I have yet to been given a design treatment from my creative director (and they are all complex) that I have not been able to tackle this way.
> 1 votes

---
Tags: theming, 7
---


# Question
Title: Save xml file produced by views data export module to a different location
I am using "views data export" module. And I am able to download the xml file.

I want to place a button "save to D:\\" such that when I click on button it directly get saved to "D:\\" drive .

I want to do something like this: if XML path is given

```
http://localhost/drupal/exhibti-dataexport.xml

```

I want to download the file.

If XML path is given

```
http://localhost/drupal/exhibti-dataexport.xml/savetoD

```

I want to directly save to D drive.

What I observed is when I am giving the path like this also

```
http://localhost/drupal/exhibti-dataexport.xml/savetoD

```

the file is getting downloaded.

Not able to understand the views data export module code.

Where should I modify the code in views data export module such that if xml path has arguments It should save the file to D drive.

Any help is appreciated.

# Answer
You will not be able to save anything automatically expecially to a particular path

Some browsers allow you to remember the action (Save/ Open) for each file type. If the user had chosen to "Remember my Answer", then the browser saves the file automatically. You can not force a similar it on all users using your site.

Regarding the path, it again depends on the browser config. If the user had configured a download directory, some browsers save the file in the download folder by default. Else will ask the user to select the path showing the last saved path.

If browsers allowed websites to save files directly to d:\ on your machine without your consent at the click of a button, your machine would have been full of stuff that you never intended to download!!!!
> 2 votes

---
Tags: 7
---


# Question
Title: How can I get the length of a list in Rules?
If there is another way to check if a list is empty, that is fine too.

# Answer
> 2 votes
Make a custom module eg. customrules and create customrules.rules.inc in this module. In customrules.rules.inc place following code:

```
/**
 * Implements hook_rules_action_info().
 */
function customrules_rules_action_info() {
  return array(
    'customrules_list_length' => array(
      'label' => t('Get length of list'),
      'group' => t('Data'),
      'parameter' => array(
        'list' => array(
          'type' => 'unknown',
          'label' => t('List'),
        ),
      ),
      'provides' => array(
        'list_length' => array(
          'type' => 'text',
          'label' => t('List length'),
        ),
      ),
    ),
  );
}

/**
 * The action for 'customrules_list_length'
 */
function customrules_list_length($list) {
  return array(
    'list_length' => is_array($list) ? count($list) : NULL,
  );
}

```

Now you should be able to use this action to get the list length

# Answer
> 1 votes
1. You might be able to doing without any coding using a view to just return the count of your list and if you have different lists you might want to use the views argument (D6) or the contextual filters (D7) to only use one view for all of them.
2. Using Rules and Views Integration if D6 or Views Rules if D7 you will be able to access the view from rules.

---
Tags: rules
---


# Question
Title: disable date field (only update with datepicker)
I am using drupal 6, im my form I put the date field as

```
$form['myform']['from_date'] = array(
    '#type' => 'textfield',
    '#title' => t('From date'),
    '#size' => 8,
    '#default_value' => (arg(5) == null)? '0':arg(5),
    '#attributes' => array('onclick' => 'GetdatePicker(this);'),
);

```

i want that user can not edit this field without using date popup(populated from date picker). any suggestion.

# Answer
Add 'readonly' =\> 'readonly' attribute to your field,

ie:

```
$form['myform']['from_date'] = array(
'#type' => 'textfield',
'#title' => t('From date'),
'#size' => 8,
'#default_value' => (arg(5) == null)? '0':arg(5),
'#attributes' => array('onclick' => 'GetdatePicker(this);', 'readonly' => 'readonly'),
);

```
> 2 votes

---
Tags: forms, datetime
---