# Question
Title: Add an boolean attribute to a text field?
I need to add a boolean attribute in the form of a check-box to a ordinary multivalued text field attached to a node. In this case, the text field will be used to list arguments for functions, which can either be required or not-required. So, in a node-edit form, I envision it to look something like the screen below. What's the best way to go about this?

Edit: adding links to suggested options, and also some that I found while checking these out:

1. field collection - https://drupal.org/project/field\_collection
2. field collection table - https://drupal.org/project/field\_collection\_table
3. double field - https://drupal.org/project/double\_field
4. tablefield - https://drupal.org/project/tablefield
5. multifield - https://drupal.org/project/multifield (dev)

# Answer
> 3 votes
You can write your own field type and widget form. A good example can be either filefield or imagefield.

Or try Field collection module.

So you can create a new type of field in field\_collection UI.

Here are tutorials: https://drupal.org/node/1353926

# Answer
> 2 votes
Field Collection module is what you looking for. **OR**, if you don't want to use field collection module for any reason, you want to make your own field type. You can follow this tutorial from Phase2 and suit it to your needs:

http://www.phase2technology.com/blog/compound-fields-in-drupal-7/

---
Tags: 7, entities
---


# Question
Title: How can I override the default forums and container pages with a view?
I need to override the default pages that come with forums with views. I need to still include the default info as per the screenshots. I can't seem to get the right relationships and the correct aggregation for the counts. Any insight would be appreciated.

# Answer
You can use Advanced Forum module, which provides many advanced features, and overrides the default forum listing with views and panels. It is not a replacement module for core forum but an enhancement.

If you don't want to use it, you can at least take a look at how they've overriden the core forum listing and make your own implementation.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Is it possible to use a Display Suite Code Field in Views?
I've created a code field in Display Suite to to manage the display of a file (the file entity has a few fields per file).

Is it possible to use this same Display Suite code field in Views when creating a list of nodes for display? I know I can do the same thing in a php field, but I'd rather not have to manage different code in different places to get to the same end result.

# Answer
> 3 votes
Instead of using Views fields, just use the Content -\> Display Suite view modes in the view, that way you can just render the DS view mode with the custom field of the returned nodes in views.

---
Tags: views, display-suite
---


# Question
Title: How to restore form values from $form_state['values']?
I save the `$form_sate['values']` in a data base. When my users come back to the form I want to show the values that they put before. Something like:

```
function my_form($form, &$form_sate) {
  $form_state_saved = get_form_state_values_from_db();

  $form['my_field'] = array(
    ...
    '#default_value' = $form_state_saved['my_field'];
    ...
  );

  return $form;
}

```

With a `textfield` seems that works fine, but I have some custom fields. Is there a way to set the `default_value` from *db*? Or should I implement the `default_value` independently for each field?

# Answer
Finally, what my colleague did was a combination of `field_default_form` and `field_form_set_state`.

```
$field_state = array(
  'field' => $field,
  'instance' => $instance,
  'items_count' => $count,
  'array_parents' => array(),
  'errors' => array(),
);
field_form_set_state($parents, $field_name, $language, $form_state, $field_state);

```

`$items` is an array with the form values stored in a database.

```
$form_field = field_default_form('node', NULL, $field, $instance, $language, $items, $form, $form_state);

$form[$field_name] = $form_field[$field_name];

```
> 0 votes

# Answer
Use Form default value:

```
'#default_value' => variable_get('sitename_textfield', ''),

```

If you use system\_settings\_form() you don't need to manually save your variables using a custom form submit function. Note: The variable must have the same name as the form item.

Function details: https://api.drupal.org/api/drupal/modules!system!system.module/function/system\_settings\_form/7

```
/**
 * Creates/returns a form to configure the variables.
 *
 * @param array $form
 * @param array $form_state
 * @return array
 */
function sitename_custom_form($form, &$form_state) {
  $form['sitename_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom Textfield'),
    '#default_value' => variable_get('sitename_textfield', ''),
  );

  // Use system_settings_form() to automate saving configuration variables.
  return system_settings_form($form);
}

```
> 1 votes

# Answer
**You need to use variable\_set() if you only want to set the previous value There is no harm in storing independent values for each fiels element using variable\_set()**

```
  function my_form($form, &$form_sate) {
      $form['my_field'] = array(
        ...
        '#default_value' = variable_get('my_field','');
        ...
      );

  return $form;
}
function my_form_submit($form, &$form_sate) {

      variable_set('my_field',  $form['my_field']['#default_value']);

}

```
> 0 votes

---
Tags: 7, forms, database
---


# Question
Title: Expose Custom DB Tables to Drupal Views Error
I am trying to display an already existing table to Drupal Views. This table exists within my current Drupal Database, along with my Drupal tables.

The table's name is `ACCOUNT_PNL` and I would like to expose the fields in this table to Drupal Views.

I've followed the instructions here, but when I go and enable this module, I get the following error from my site:

```
DatabaseSchemaObjectExistsException: Table <em class="placeholder">ACCOUNT_PNL</em> already exists. in DatabaseSchema->createTable() (line 657 of /var/www/drupal7/includes/database/schema.inc).

```

I understand that the table already exists, but isn't the tutorial code supposed to only "expose" it to Views so I can then use Views to display it?

Perhaps there is an error in my understanding, any help would be appreciated.

# Answer
The tutorial you linked to implements `hook_schema()` which means Drupal will want to take care of the table implementation for you.

I don't know this for definite but I think Views requires that the table be under Drupal's control when you're exposing custom data.

I don't know of a way to tell the installer to ignore the schema installation, so the simplest thing to do would probably be to rename the custom table temporarily, install the module (allowing Drupal to create the table), then import the data from the temp table into the newly created one.

If you then uninstall the module (not just disable), your custom table and the data will be lost so it's worth keeping a backup if you think that's likely to happen.
> 1 votes

# Answer
> The tables declared by `hook_schema()` hook will be automatically created when the module is first enabled, and removed when the module is uninstalled.

As there is already `table` in your Drupal database, so you are getting the error that `table already exist` when you install the module.

There is no need of implements `hook_schema()` function in your installation file, if you have already `table` in your database with record.

Or you can implements `hook_schema_alter()` in your module to alter your existing table.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Omega subtheme - Dropdown menus not working properly
When on http://demo.drupalizing.com/?theme=corporateclean the source for About menu item is:

```
<li class="expanded"><a title="About" href="/corporateclean/node/3">About</a><ul class="menu"><li class="first leaf"><a title="Our Team" href="/corporateclean/node/3">Our Team</a></li>
<li class="last leaf"><a title="Our Vision" href="/corporateclean/node/3">Our Vision</a></li>
</ul></li>

```

However, on my site, when on the homepage, the source for Privacy (a menu item which has pages hanging off it) is as follows:

```
<li class="collapsed"><a href="/content/privacy">Privacy</a></li>

```

It's only when I am ON the Privacy page, that the dropdown menus appear when I hover over the Privacy menu item. The source now is:

```
<li class="expanded active-trail"><a class="active-trail active" href="/content/privacy">Privacy</a><ul class="menu"><li class="first leaf"><a href="/content/advice-0">Advice</a></li>
<li class="last leaf"><a href="/content/complaint-management">Complaint management</a></li>
</ul></li>

```

What am I doing wrong, and why aren't the dropdown menus being displayed when on the homepage for example, but instead only when I am ON that page?

# Answer
The usual behavior is for sub-menus to only expand when you are on the parent item; so if you have a tree like the one below, you would only see a dropdown containing "Child" when you are on "Parent":

* Home
    + Parent
        - Child
        - Child
        - Child

**SOLUTION:**

1. Go into the menu list links which is admin/structure/menu/manage/main-menu for the main menu and edit the item you want expanded ("Parent" in this case)
2. Check the checkbox "Show as expanded"

That item will now be expanded no matter where you are on the site.
> 1 votes

---
Tags: theming
---


# Question
Title: I just want to move this login button up above the create new account and request new password. How?
I want to move login button up above other two options create new and request new password links. what I do I have to do. I am new to drupal

# Answer
> 5 votes
You can use hook\_form\_FORM\_ID\_alter in your custom module and change the weight of the links

```
function MYMODULENAME_form_user_login_block_alter(&$form, &$form_state){
  $form['links']['#weight'] = 100; //define weight as such the links moves below  submit button.
}

```

Replace "MYMODULENAME" with the name of your custom module.

---
Tags: users
---


# Question
Title: Drupal 6 does not like it when an image tag's absolute path contains “http:”
I'm using Drupal 6.28 and there's something i don't understand.

i have a page that contains an image tag pointing to an absolute path. e.g.

```
<img alt="google logo" src="http://www.google.com.sg/images/srpr/logo11w.png" style="height:190px; width:538px" />

```

when the content is saved, drupal returns a "Page Not Found" error.

i found out that if i remove the "http:" at the start of the src attribute, there wouldn't be any problem. everything would be ok. i.e.

```
<img alt="google logo" src="//www.google.com.sg/images/srpr/logo11w.png" style="height:190px; width:538px" />

```

is there some setting that i may have messed up that causes this?

Thanks

# Answer
> 1 votes
the issue i reported was caused by a mod\_security setting. my host fixed it after i spoke to them.

---
Tags: media
---


# Question
Title: What is the execution sequence of functions while rendering a form?
I have a form in my website with id: `sample_test_custom_form`. I have used hook\_form\_alter in a custom module to alter this form. I also have a preprocess function (`mytheme_preprocess_sample_test_custom_form`) to do a little preprocessing.

However the alter function and the preprocess function are a little dependent on each other.

So I ask, what is the execution sequence of these function? Which of them is executed first?

# Answer
> 7 votes
Here's a diagram of the form build workflow in Drupal 7

More info: https://drupal.org/node/165104

---
Tags: theming, forms
---


# Question
Title: Check if user has access to a certain page
How can I determine whether a user has permission to access to a certain page?

# Answer
> 25 votes
If you want to verify if the currently logged-in user has access to a page, you can use the following code:

```
if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    // The user has access to the page in $path.
  }
}

```

`$path` is the path of the page you want to check (e.g. node/1, admin/user/user).

The code works in Drupal 6 and higher versions, and it is the one used from menu\_execute\_active\_handler().

The reason I am not suggesting to directly call the access callback is because the arguments that need to be passed to that function.

The code used by \_menu\_check\_access() is the following one (Drupal 7):

```
$arguments = menu_unserialize($item['access_arguments'], $map);
// As call_user_func_array is quite slow and user_access is a very common
// callback, it is worth making a special case for it.
if ($callback == 'user_access') {
  $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
}
elseif (function_exists($callback)) {
  $item['access'] = call_user_func_array($callback, $arguments);
}

```

The code, which needs to be as much generic as possible, doesn't directly handle a user object. This means that is not possible to replace the user object for the currently logged-in user with another user object.
The code must be generic enough to handle menu definitions such as the following ones:

```
$items['node/add/' . $type_url_str] = array(
  'title' => $type->name,
  'title callback' => 'check_plain',
  'page callback' => 'node_add',
  'page arguments' => array($type->type),
  'access callback' => 'node_access',
  'access arguments' => array('create', $type->type),
  'description' => $type->description,
  'file' => 'node.pages.inc',
);

$items['node/%node'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  // The page callback also invokes drupal_set_title() in case
  // the menu router's title is overridden by a menu link.
  'page callback' => 'node_page_view',
  'page arguments' => array(1),
  'access callback' => 'node_access',
  'access arguments' => array('view', 1),
);

```

In both the definitions, the access arguments don't include a user object, and node\_access() in this case uses the user object for the currently logged in user. In the second case one of the argument is the node object that is obtained from the URL; for example, if the URL is example.com/node/1, then the second argument passed to the access callback is the node object for the node with node ID equal to 1.
Writing code that handles these cases too would mean to duplicate code already existing in Drupal. Even if you duplicated that code, there would be still the problem of the access callbacks that are checking the access against the currently logged-in user.

If you want to check if a user that is not the currently logged-in user can access a menu is to first change the value of the global variable `$user`, use the code I reported at the beginning of my answer, and then restore the value of `$user`. For how to change the value of the global `$user`, you can see Programmatically impersonating another user without causing the currently logged-in user to log out. The difference is that, instead of using the value returned from drupal\_anonymous\_user(), you use the value returned from user\_load().

# Answer
> 15 votes
Try drupal\_valid\_path().

The function returns `TRUE` is the path passed as argument exists and the current user has access to it. So, if you are working on Drupal 7 and you need to check the access on the currently logged in user, it's the easiest way to go:

```
if (drupal_valid_path('my/path')) {
  // Your code here...
}

```

# Answer
> 3 votes
Call the `access callback` that is specified in the menu entry that is responsible for the page. That menu entry is usually created by Drupal calling the implementation of `hook_menu` and is stored somewhere in the database. Beware that the data returned by `hook_menu` might be changed by a module implementing `hook_menu_alter`.

Beware that some modules might not pass the user as a separate argument (as specified by the `access arguments` key of the menu entry), but might instead use the global `$user` object instead. You will have to check this for each module that you use.

# Answer
> 2 votes
Check out the `user_access()` function. See the link for the specified parameters for each version of Drupal. From the documentation page for Drupal 7-8:

> **Parameters**
>
> $string The permission, such as "administer nodes", being checked for.
>
> $account (optional) The account to check, if not given use currently logged in user.
>
> **Return value**
>
> Boolean TRUE if the current user has the requested permission.
>
> All permission checks in Drupal should go through this function. This way, we guarantee consistent behavior, and ensure that the superuser can perform all actions.

# Answer
> 2 votes
If you need to know if a user can access a particular node, and are using a node access module, you can use node\_access(). (without a node access module they just need the 'access content' permission.)

If you want to figure out if a user can access an arbitrary path that is defined by a hook\_menu() implementation, you may have to retrieve the menu entry from the database and evaluate its 'access callback' parameter.

# Answer
> 2 votes
```
    $node = node_load(123);

    $account = user_load(456);

    if (node_access("update", $node, $account) === TRUE)
   {

         print "access";
    }

```

---
Tags: users
---


# Question
Title: Ajax reloading a view with ajax mini pager
I have this view, a 'block' display that has ajax enabled and have a mini pager that loads next page content through ajax.

As a requirement I have to reload the current view content through ajax along with some custom sort/filter.

After going through some forums, I did something like below.

in .module page callback :

```
$view = views_get_view('vdlibrary');
$view->set_display('block');
$view->set_use_ajax(TRUE);

$settings = array(
    'views' => array(
        'ajax_path' => url('views/ajax'),
        'ajaxViews' => array(
            array(
                'view_name' => $view->name,
                'view_display_id' => $view->current_display,
                'view_args' => check_plain(implode('/', $view->args)),
                'view_path' => check_plain($_GET['q']),
                'view_base_path' => $view->get_path(),
                'view_dom_id' => 1,
                //'pager_element' => $view->pager['element'],
            ),
        ),
    ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

```

in JS I am calling below ajax function on a click event to load the new views content based on the condition.

```
for (var key in Drupal.settings.views.ajaxViews[0]) {
  data[key] = Drupal.settings.views.ajaxViews[0][key];
}
// I add additional filters/sort params to var data.
$.ajax({
  url: Drupal.settings.views.ajax_path,
  type: 'GET',
  data: data,
  dataType: 'json',
  success: function(response) {

    $(".vdr_container").html(response[1].data);

  },
  error: function() {
    // handle error response.
  },
});

```

Not surprisingly, after it loads the content, the ajax pagination feature not working instead it reloads the page along with params. How do I keep the old context or make the new loaded views to rebind pager click event to work with ajax pager.

NOTE: my descriptions might not be good enough, let me know where I could explain in better way.

Thanks

# Answer
> 0 votes
After going through ajax\_views.js and understanding view-dom-id element structure, finally I could able to get this done.

In ajax response object, there are 3 callbacks, In the last 'insert' callback, I got data with command to 'replacewith' and a DOM selector (unique dom for views wrapper with '.view-dom-id-xxxxx'). So I did replace the new content like :

```
$(".view-dom-id-" + vDomId).replaceWith(response[2].data);

```

Then I got the content with existing context, all I had to do then is re-attach the 'ViewsAjaxView' behavior as found in ajax\_view.js

```
Drupal.attachBehaviors('ViewsAjaxView');

```

This attachBehaviors function will take care of binding ajax pagination to my newly altered views data.

I still feel, as if this can be more simpler like running all callbacks I get in response variable in success. I will post more if I get into. Hopefully someone gets some help from this.

Anybody have idea to run those commands?

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


# Question
Title: Show block only in user own page and for administrator role users
What I'm trying to achieve:

1. User can see block only on his own "user/\[uid\]/my-page" - he cant see that block on other users my-page.
2. Users who belong to administrator role can see user block on user own page.

Right now my code shows block for user himself and also to administrator role users BUT for administrator role users it shows block on every page - not only in "my-page".

How to modify code to show block only in "my-page" also for administrator role users?

Here is the code:

```
<?php
global $user;
if (in_array('administrator', ($user->roles))) {
return TRUE;
}
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == "my-page" ) {
return TRUE;
}
else {
return FALSE;
}
?>

```

I used this code as a base: https://drupal.org/node/134433

# Answer
> 2 votes
This is almost a replica of your code with a small change. I hope it helps.

1. If you want to allow the admin to see the block on every other user profile page

```
global $user;
if (arg(0) == 'user' && ($user->uid == arg(1) || in_array('administrator', ($user->roles))) && arg(2) == "my-isn10") {
  return TRUE;
}
else {
  return FALSE;
}

```
2. If admin or normal user do not have a difference both can see only on their profile page.

```
global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == "my-page" ) {
  return TRUE;
}
else {
  return FALSE;
}

```

---
Tags: 7, blocks, users
---


# Question
Title: Node Update not showing to anonymous user even after clear cache
I have a live site , when i update any node, it is not reflected for anonymous user.Even I clear the cache.This domain has SSL certification but we use it only for few pages.But if we use https for the updated content for anonymous user, It show the updated content. We have used cache for bloack and anonymous user and minimum cache lifetime and cache expiration is 1 hour.

# Answer
> 0 votes
You have set the value of `Expiration of cached pages` to `1 hour`

Expiration of cached pages tells the External Caches for how long they can server the old version of a page.

In your case browser is the External Cache and it assumes that it can show old content for an hour. So it doesn't even make a call to you website when you request the page.

You can see the changes after an hour or clear all your browser caches to see the new changes.

More Explanation

---
Tags: nodes, caching, updating
---


# Question
Title: what benefit is it to clearing the Drupal cache now that I have Varnish in front of Drupal?
Our site has Varnish in front of Drupal for anonymous user page requests so that these pages are cached. I know how to clear the Varnish cache within Varnish but my question is what benefit is it to clearing the Drupal cache now that I have Varnish in front of Drupal?

# Answer
Whenever Varnish Cache expires it asks Drupal to give it the rendered page. Drupal in turn sees if it can server the page from the Cache. If yes it will server from the cache, else it will regenerate the page.

In short, when you clear the Drupal Cache,

1. No changes are visible to end users for whom the content is served from Varnish.
2. When the Varnish Cache expires, it will fetch the content form Drupal. Now that you had cleared the Drupal cache, instead of serving from the cache the page will be rebuilt.
> 0 votes

---
Tags: caching, proxies
---


# Question
Title: Get locations search: Show all markers by default
I played around with the get locations module for drupal escpecially with the `get locations search` part.

Finally I got the thing working but I'm wondering now if it's possible to display by default all markers on the map and not only the result markers after a search.

A blank map till I searched something is very confusing to the user.

Thx for any advice in advance.

**EDIT**

Okay I try to write a patch on my own. My research is based on version `7.x-1.10` The essential part ist to load the lat/longs of the location nodes and also the min- / maxes into the array in `getlocations_search.module` line `290:291` which is

```
$minmaxes = '';
$latlons = array();

```

For the "normal" map they are loaded in the function `getlocations_nids()` on line `828` in the file `getlocations.module`.

# Answer
Try using Open layers Module which has an option for adding multiple locations n single map...

**OpenLayers:**

> The OpenLayers core code stores map's object configurations: maps, layers, styles, sources, controls, interactions and components. It combines them to create maps using the OpenLayers JavaScript library on any Drupal site.
> 0 votes

---
Tags: location, google-maps
---


# Question
Title: View mode template for user-profile.tpl.php?
I can set up a view mode for the user profile, but I don't know how to create a template targeting it. user-profile.tpl.php is the template used, but I can't figure out how to make a view-mode targeted version of it.

Any suggestion?

# Answer
> 3 votes
You already figured out how to create an additional view mode for the user entity:

```
/**
 * Implements hook entity info alter
 * Adds additional view mode for user entity
 */
function MYCUSTOMMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['view modes']['teaser'] = array(
      'label' => t('Teaser'),
      'custom settings' => TRUE,
  );
}

```

Now you can define theme suggestions for that view mode using HOOK\_preprocess\_user\_profile:

```
/**
* Implements HOOK_preprocess_user_profile()
* Adds theme suggestions for the user view mode teaser
*/
function MYCUSTOMMODULE_preprocess_user_profile(&$vars) {
  if ($vars['elements']['#view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__teaser';
  }

```

After clearing the caches Drupal will search in the theme folder for a file called user-profile--teaser.tpl.php, which could look like this example\*:

```
<section class="user-teaser">
  <?php print render($user_profile['field_last_name'][0]); ?>
  <div class="user-image">
    <figure><?php print render($user_profile['field_user_picture'][0]); ?></figure>
  </div>
  <div class="user-body">
    <?php print render($user_profile['field_biography']); ?>
    <?php print render($user_profile['field_birthdate']); ?>
    <?php print render($user_profile['field_nationality']); ?>
  </div>
</section>

```

(\* actual code will depend on the fields you defined for the user profile)

---
Tags: 7, users, entities
---


# Question
Title: Conference registration form/site with limited places available
I have to build a little conference-site with a registration-form.

The conference is 1 day and has different sessions in the morning and different sessions in the afternoon. Those sessions have limited spaces available.

Users should be able to register for the conference by the registration-form and if there are no more spaces available for a specific session, they should get a message that this is no longer available, so that they have to choose another session.

What is the best solution for this, knowing that my client wants **1 registration form** for the entire day. Otherwise I was considering **entity\_registration**. With the "1 registration form" in mind, I was considering to use **webform** and **webform\_validation** or **webform\_rules**, but there is no standard solution for the limited spaces available.

Is there a good solution for this problem?

Can someone help me?

# Answer
Session = content\_type.

One session = one node of type session

Every session has a field "available spaces"

Create a custom form programatically which you pass the session id in a field of type "value". https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#val

In the validate function of the form check if the field "available spaces" for the session with that id is greater than 0, otherwise decrease it and in the submit function store the user id with this session id.

Regards.
> 0 votes

---
Tags: rules, webforms
---


# Question
Title: Blank page when trying to add new content
I've to cope with something very odd: I can't add any type of content anymore. For example: when I go to Content \> Add content \> Article, I navigate correctly to the 'add acticle' page, but I simply get a white screen. I didn't have this before and I can't remember installing new modules. I already tried to flush all caches, but that didn't solve anything. Even when I add

```
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
?>

```

to my index.php or settings.php file, no erros are displayed. Please help!

Edit 1: going to the Configuration screen doesn't result in a WSOD. There's only a white screen when I try to add content.

Edit 2: I discovered that I also get a WSOD when I try to edit already existing content. Please help me! I really can't do anything anymore!

# Answer
There was something wrong with my database. I had to delete it and reinstall my backup.
> 2 votes

# Answer
Open your "settings.php" file and add the following at the top:

```
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
?>

```

Update your question to include the errors that show up when you get the white screen.
> 0 votes

---
Tags: 7, wsod
---


# Question
Title: How do I make the content of one user not accessible to other
I have created separate dashboard for each student using login destination module. I am able to redirect the student to their profile page. There are some other pages (score card, attendence etc) which are different for each student. how do I make the details of one student not accessible for other?

# Answer
You have two option to do it as per my experience. But it depends upon kind of information which you want them to see related to them.

One option is with help of VIEWS :- If you find your content somehow related to the current user then you can make a relation or use contextual filter. In most cases, I do the same. I try to relate the content to user somehow.

But you have to keep in mind. Views is tricky & very broad. You can see some complicated things in action by following some free tutorials online like - Johan Folk at nodeone.se.

Other way is at theme level:-

You fetch the current logged in user in `template.php` in template\_preprocess\_page(). Use UID to fetch the info which is required(either by query or user\_load(), which ever suits you). Pass those value to some variable which can be used at `page.tpl.php`.

Now use them at `page.tpl.php` & values will be always for current user. You can even make `page.tpl.php` for specific user page like - `page--user.tpl.php`. Maybe it looks complicated but it's very easy. For me, easy than using views :)

EDITED - About not letting one accessing others profile. Just set the apropriate permission. Find in users permission section & you have option for it.
> 0 votes

# Answer
For nodes check Content Access module. It has video tutorials.
> 1 votes

---
Tags: users
---


# Question
Title: Loop through entities chosen by Views Bulk Operations
I successfully created a new action using hook\_action\_info() and a corresponding hook\_action(). However, I want to find the method which loops through the elements chosen by Views Bulk Operations, as I wanted to combine some pages for a pdf.

What method loops through the entities chosen by VBO?

# Answer
> 0 votes
Quoting the VBO Development guide, you can use the `aggregate` option to get a list of all chosen entities.

> **implement hook\_action\_info()**
>
> ***aggregate (optional)***: boolean. If TRUE, all selected objects' IDs (oids) will be packed in an array and passed as the first argument to the action function, instead of passing each object one by one. This is useful to implement aggregate functions that perform a single operation on the whole selection set.

Note this guide is only for D6. I have created a D7 version but could not add an aggregate example yet.

However, in your hook\_action\_info() implementation, set `aggregate` to TRUE (defaults to FALSE) and VBO will send a list of entity IDs (for you to perform additional related tasks).

---
Tags: views
---


# Question
Title: EntityMalformedException: Missing bundle property on entity of type commerce_customer_profile
I was doing some work on my custom module which hooks into and modifies Drupal Commerce, and all of a sudden the checkout page wont load and I get this error:

```
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /var/www/test.dev/htdocs/includes/entity.inc).
EntityMalformedException: Missing bundle property on entity of type commerce_customer_profile. in entity_extract_ids() (line 7693 of /var/www/test.dev/htdocs/includes/common.inc).
```

and I have no idea how to fix it! I commented out what I had changed and nothing worked. I even did a git stash on all of my work to revert the changes and still nothing. My only guess is that somehow the database got messed up. How can I fix this? If I have to mess with the database, where do I start?

# Answer
I figured out the issue. I debugged in the common.inc file and I was able to determine that there was an issue with the User entity. I looked back into my code and saw that I had written

```
global $user;
```
twice inside of one hook. I took this out and the page loaded again
> 0 votes

# Answer
When you declare an entity and function `entity_get_info($entity_type = NULL)` is called, the next function `cache_set("entity_info:$langcode", $entity_info)` is also called which stores the entity info in the cache table, so probably your change is cached in the database.

If you're executing `drush cc all` and you have the same message error again, you can try several more things:

* You can call this function `entity_info_cache_clear()` https://api.drupal.org/api/drupal/includes!common.inc/function/entity\_info\_cache\_clear/7.
* Try executing `SELECT cid FROM cache WHERE cid LIKE 'entity_info%'` from MySQL command line and then `DELETE FROM cache WHERE cid="entity_info:en"` -\> "en" or whatever depending or your language config.
* Try truncating the cache tables:

You can do:

`drush sqlc` with

`SHOW TABLES LIKE 'cache_%';`

`TRUNCATE cache_tablename;`

in order to remove the cached data where entity info is stored. The content of this tables are regenerated programatically when you make a request.

That probably should works
> 2 votes

---
Tags: commerce, entities
---


# Question
Title: Ubercart shipping API, get the package object with php to send the tracking number to the client as email
I have an online shop implemented in Ubercart 6.x-2.4 and Drupal 6.19

All cool everything works but I'm struggling to do custom things

What I want to do is after saving the shipment data (i'm insterested in sending the Client that the package has been sent and he has to receive by email the tracking number)

So I added a predicate that does just that, but I don't know how to get the shipment object associated with the order and get that tracking number. I just know that there is an API somewhere...

# Answer
Are you managing to save the tracking number to the order? With a bit of preprocess magic you could probably get the number as a variable to the invoice template that already gets sent out.

EDIT:

Something like the below would work, that I did to get extra data displayed in an invoice. I did this in my theme, so replace that with your own theme name (and the other capitalised bits).

```
    function [THEMENAME]_preprocess_uc_order(&$variables) {
        $variables['tracking_number'] =
           db_fetch_object(db_query("QUERY TO GET TRACKING NUMBER"))->COLUMNNAME;
    }

```

Then if you put uc\_order.tpl.php (needed as a dummy file so your theme can override other templates) and your own custom template into your theme directory then you are able to reference it in the template with a simple call like `print $tracking_number;`
> 0 votes

# Answer
This question needs an update for Drupal 7. I created a module for drupal 7 and a patch for UberCart that accomplish adding Tokens for shipment tracking that can easily be used in email.
> 0 votes

---
Tags: ubercart
---


title: Embed Views remove pager

text:
# Question
Title: Embed Views remove pager
I have embedded view in a node with following code:

```
<?php
 $view = views_get_view('articles');
 $view->set_items_per_page(1);
 $view->set_offset(2);
 print $view->preview('page');
 $view->destroy();
?>

```

I just need to display only one specific row (that's why I'm using offset). I couldn't find a way to retrieve one specific row with any other method.

This code is acceptable but it has pager because that view has more than one row. Is there a way to remove pager like in Views UI? In Views there is a option to not use a pager but "Display a specified number of items".

I would like to remove it completely from code without CSS.

# Answer
I ended up having to hide the specific pager with css in the case I did what you are trying to do...
> 0 votes

---
Tags: views, paging
---


# Question
Title: users see all replies to a message sent by admin [Privatemsg module]
I (admin) sent a message to couple of users by their username (not by role) . If "user1" replies back to the admin , user2 and user3 will see the message too ,

that's why the module is called PrivateMessage right :)

any clue ? thanks

# Answer
This is by module design and works as expected.

If you add multiple recipients to a message, Privatemsg treats it as a "conference" discussion and notifies everyone in the group when someone replies.

If you want to keep the conversation only between you and a particular user, you must send it only to that particular user.

---

What you need to do is to hook into the submit function of the form and instead of generating messages for all recipients at once, loop through them and do that for each separately.

You should not modify source code, as that might make it work incosistently and will create maintenance problems for you later on.

What I suggest is to create a custom module, add your submit callback for `privatemsg_new()` form and process the messages separately. Check out `privatemsg_new_submit()` function in the source. Also make sure the default privatemsg submit handler does not get executed - just unset it form the `$form['actions']['submit']['#submit']` array.
> 1 votes

---
Tags: privatemsg
---


title: Menu link to block or div

text:
# Question
Title: Menu link to block or div
Is it possibile to link menu links to the div or block on the certain subpage? If yes what is the method to do this?

# Answer
> 0 votes
One way of doing that using the **#id** of that block or div in the path of menu link pointing to the page like below:

```
PAGE-PATH-URL/#ID-OF-BLOCK-OR-MENU

```

basically you can link the menu to any div, block or anything having **id attribute** by appending the **#ID** at the last of the page path.

# Answer
> 1 votes
This is not *completely* straight forward. If you try to create and save a menu link like book/page#anchor-id, Drupal will give this error

> The path 'book/page' is either invalid or you do not have access to it.

You will need the node ID. Drupal wants the link to look like this: node/55#block-you-want.

The easiest way to do this is

1. Save the menu link without the anchor id. ex: /book/page
2. Drupal will create the menu link like this: node/55
3. Edit your menu link to: node/55#anchor-id. Save again.

---
Tags: routes, blocks
---


# Question
Title: Disable all notice errors on a drupal 6 site
I'm updating a drupal 6 site and getting hit with alot of notice errors. how can i silence these non vital errors. Usually just get undefined index and warning/notice messages

# Answer
Its not so much a Drupal 6 question, but a PHP question.

In your settings.php file I sometimes do the following on my Drupal 7 sites:

```
// Drupal Bootstrap is overriding even htaccess values for this. I want the
// notices but not for them to display in production.
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');

```
> 3 votes

---
Tags: 6
---


# Question
Title: Show related nodes of a specific type when looking at a node of a different type
I have a custom content type `Topic`, another custom content type `Sub-Topic`, and a taxonomy `Topic Tags`. I'd like to be able to display the sub-topics on the page for each topic that has any of the same topic tags.

I'm using panels to define how pages look topics, and I was trying to use a view for the sub-topics. I can make a view that filters by a specific tag, but I can't figure out how to pass the tags that the topic node has to the sub-topic view.

Thanks!

# Answer
> 0 votes
I would look into using the "context" module for this.

With it you would be able to set "conditions" and "reactions". The condition, being if your `topic` node is visited, `react` by showing a view block of the sub-topics. You can configure said block view to show the taxonomy tags based on certain criteria.

---
Tags: views, panels
---


# Question
Title: How do I pass multiple values to the command line?
My module will be run from the command line. The Drush command would be something like this:

```
drush create-denver-type --name="some title" --title="some title" --options="apple" --userid="myid"

```

`--options` can have one option or five. I'm using a `switch` statement and only passing one value through `--options`. What do I need to do to pass two or three values to `--options`, for example `--options="apple, pear, orange"`?

Basing on the values passed in `--options`, different functions will be called.

When gathering multiple values, how do I pass them to my function, and call the correct functions based on the value passed in `--options`?

# Answer
```
$options = drush_get_option_list('options');

```

This will return something like `array('apple')` or `array('apple','pear','orange')`.

Yeah, Drush does everything.
> 1 votes

---
Tags: drush
---


# Question
Title: cannot create taxonomy terms using hook_enable solved!
i want to create 1 taxonomy vocabulary and 1 taxonomy term using drupal's hook\_enable. but when i enable the custom module, it create only the taxonomy vocabulary. And if i disable and enable the module, the taxonomy term will be created without problem. the code is as below:

```
 $sql = "SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name='article_type'";

$vid = db_query($sql)->fetchField();
    if (!$vid) {
      drupal_set_message(t("Created article type vocabulary"));
      // No vocabulary exists, we'll create one.
      $vocab = (object) array(
          'name' => 'article type',
          'description' => t('Automatically created by the custom_block module'),
          'machine_name' => 'article_type',
          'multiple' => '0',
          'required' => '0',
          'hierarchy' => '1',
          'relations' => '0',
          'module' => 'custom_block',
      );
      taxonomy_vocabulary_save($vocab);
      $vid = $vocab->vid

}

  $terms = (object) array (
          'name' => 'News',
          'vid' => $vid,
          'vocabulary_machine_name' => 'article_type',);

 $term_name = $terms -> name;

  $tid = db_query("SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid and name = :name", array(
    ':vid' => $vid,
    ':name' => $term_name,
  ))->fetchField();

if ($vid && !$tid) {

    taxonomy_term_save($terms);
}

}

```

PS:i've figured it out! it's a stupid mistake. i did not get the vid after saving the vocabulary to the database. i just need to add $vid = $vocab-\>vid after taxonomy\_term\_save.

# Answer
> 2 votes
$vid remains FALSE throughout the entire first run. You need to set it after the vocabulary object is saved:

```
...
taxonomy_vocabulary_save($vocab);
// Add this next line
$vid = $vocab->vid;

```

---
Tags: taxonomy-terms
---


# Question
Title: How can I make a curl type http request after a node submission?
Basically I have a node type which I've named "rss". Its purpose is exactly as I'm sure you guessed, all of these nodes are available as an rss view at a specific url (ex: `http://mysite/rss/feed`).

When a node of that type gets created (or updated I suppose) I need to make an http request to a specific url (the details to that are irrelevant to this question).

So lets say I create a new "rss" post on my drupal site, after it gets submitted I need an http request to the url ex: `http://myapplication/blog?status=fetch`

I know that I can make such a request happen with the visit url function in actions core module, and "trigger" it on node creation (not of a specific type though) but I think it does exactly that, and actually VISITS the url, whereas I just need it to make a curl type request.

I'm also using the scheduler module, so posts of this type can be scheduled, so I would need to trigger the action in sync with the schedule, if it is scheduled to be posted at a certain time/date, that is.

I'm guessing I need to use some sort of hook functionality and make my own module, true? Or is there any other way of doing this?

# Answer
> 2 votes
There's no pre-configured action for making a back-end request like that, so you will need to write some code. It's not going to be terribly hard to accomplish, though. Drupal has a function called drupal\_http\_request() to hit the external URL. You'll execute that function within a hook\_nodeapi() implementation, which runs at various times in the node creation process.

Drupal 6:

```
<?php
/**
 * Implements hook_nodeapi().
 */
function MODULENAME_nodeapi(&$node, $op) {
  // In D6, this hook is executed at various points in the node creation/render process.
  // We only want to run code during the node's "insert" operation.
  if ($op == 'insert') {
    // Only run for RSS nodes.
    if ($node->type == 'rss') {
      // Make a back-end HTTP request to an external resource.
      $url = 'http://my-url.com';
      $response = drupal_http_request($url);
    }
  }
}
?>

```

---
Tags: nodes, 6, feeds
---


# Question
Title: In Ubercart auction final bid amount adds sell price instead of highest bid amount in the cart?
In uber-cart after auction has been won, the buyer will get add-to-cart button to add and buy the product. After clicking on add-to-cart button, it adds sell price value in the cart page instead of highest bid amount.

**How to make it add highest bid amount in cart page instead of sell-price.**

Any suggestions? Thanks in advance.

# Answer
> 0 votes
```
/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your bid product

    $items[$index]->price = 100;
  }
}

```

For reference:

http://www.ubercart.org/docs/api/hook\_uc\_cart\_alter

---
Tags: 7, ubercart
---


title: User submission/restriction

text:
# Question
Title: User submission/restriction
Beginner drupal user here, I know how to assign permissions to users to add/create content etc., my problem is I am trying to create a specific page where users can go to (from the main menu) to upload content whether it be images, video, etc. and the content is then displayed in its own page, for example, all images are displayed in a separate page called "images" and videos go in "videos", based on what file they uploaded. Is there a module that accomplishes this or am I just

# Answer
If I understand correctly your requirement, then you want to provide a functionality to user to upload `images` or `video` and then save the `images` or `video` respectively.

I have already implemented similar functionality in one of my recent project with following concept:

* Create a new `content type` as `upload`
* Add a list (`select`) field `Filter type` with options `image` and `video`
* Add two fields `image` as 'image' field type
* Installed Media module and add `video` field as 'Media file selector'
* Installed Conditional field module and set condition that `image` field be only visible if user select 'image' as Filter type options and `video` field be only visible if user select 'video' as Filter type options
* Set the permission to user to create content of `upload` content type.
* Now Create two views to display image and video separately.

I hope that it will solve your problem.
> 1 votes

# Answer
You should use Media module for adding media (images and video) into any textarea and it (requires Wysiwyg module). After adding image and video field you can create a node containing these two fields. When you save the node using submit you will get a view of all the image and video file generated.
> 0 votes

# Answer
If you are asking...

> Is there a module that can look at a file upload field in a specific content type, and then, based up the extension of the file uploaded, sort and display the various files on separate pages?

...the answer is most probably `No. Not out of the box anyway.`

However, the Views module is quite powerful, and with a bit coding it could be done.
> 0 votes

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


# Question
Title: Hide block on specific page through custom contextual link
We usually require to hide some blocks on specific pages for which we need to goto configure block page and add the URL of the page where we do not want to display a block.

Instead of going to configure block page, I want to add a contextual link " Don't display on this page"

which should add the path of the current page in the list on which the block should not appear.

# Answer
You can use context module which has good number of contextual filters that can be used dynamically to display/hide a block.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
> 0 votes

---
Tags: navigation, blocks
---


# Question
Title: How to add Profile2 form to ctools multistep wizard
I've been basing this off of Grashmash's article over building a multistep registration with Ctools, and I can't seem to get the Profile2 form in. I don't want to use the Field Group multistep option as I need to add additional forms to the wizard, but I'd like to get past this first.

I can successfully get past the initial account creation, but then the profile doesn't show up. Any ideas?

```
    $form_info = array(
    // Specify unique form id for this form.
    'id' => 'multistep_registration',
    //Specify the path for this form. It is important to include space for the $step argument to be passed.
    'path' => "user/register/%step",
    // Show breadcrumb trail.
    'show trail' => TRUE,
    'show back' => FALSE,
    'show return' => FALSE,
    // Callback to use when the 'next' button is clicked.
    'next callback' => 'kidb_register_subtask_next',
    // Callback to use when entire form is completed.
    'finish callback' => 'kidb_register_subtask_finish',
    // Callback to use when user clicks final submit button.
    'return callback' => 'kidb_register_subtask_finish',
    // Callback to use when user cancels wizard.
    'cancel callback' => 'kidb_register_subtask_cancel',
    // Specify the order that the child forms will appear in, as well as their page titles.
    'order' => array(
        'register' => t('Register'),
        'profile' => t('Complete Profile'),
        ),
    // Define the child forms. Be sure to use the same keys here that were user in the 'order' section of this array.
    'forms' => array(
        'register' => array(
            'form id' => 'user_register_form'
            ),
        'profile' => array(
            'form id' => 'profile2_edit_main_profile_form',
            // Be sure to load the required include file if the form callback is not defined in the .module file.
        ),
    ),
);

```

# Answer
I found the answer in a similar thread, works perfectly with ctools.

How to display a profile form using profile2 module
> 0 votes

---
Tags: users, chaos-tool-suite
---


# Question
Title: How to support .dcm image format file for uploading in an article?
I want to upload .dcm image format file into Drupal7 article, but it's not allowed.

Suggestions about how to get this to work?

# Answer
Unfortunately, it is not possible to allow image extension that cannot commonly displayed by a browser. You would have to use a filefield instead.

This has been discussed at:

https://drupal.org/node/1081060

https://drupal.org/node/1014816

And for D6 at:

https://drupal.org/node/515152
> 1 votes

# Answer
You can set allowed file types at the field settings page of that image field.

Go to `admin/structure/types/manage/article/fields/field_image` and add the file extension to the comma separated list of allowed file types.
> 0 votes

---
Tags: 7, nodes, media, files
---


# Question
Title: How to use jquery ui tooltip in Drupal7?
I want to use jQuery UI tooltip in my Drupal7 website.

I have installed 'jquery-update' and 'jquery-plugins' module and added

```
$(function() {
   $("a").tooltip();
});

```

in js file of my template. But firebug gives this error to me:

```
$(...).tooltip is not a function

```

that show the website doesn't find tooltip js file.

Should I do something more to use tooltip jquery ?

# Answer
Try adding:

```
drupal_add_library('system', 'ui.tooltip');

```

in your theme template.php file

```
/**
 * Implements hook_preprocess_html
 */
THEME_preprocess_html(&$variables){
  drupal_add_library('system', 'ui.tooltip');
}

```

That should ensure the library is available. You can add various conditions to make it page specific as required.
> 6 votes

---
Tags: 7, javascript, tooltips
---


# Question
Title: How to get a field value in form validate
i have a custom form validate function. what is the correct/reliable way to get the field value and why? below two lines get the same value from a Select List.

a) $form\['field\_a'\]\['und'\]\['#value'\]

b) $form\_state\['values'\]\['field\_a'\]\['und'\]\[0\]\['value'\]

# Answer
Refering to form API Drupal 7 for #value

```
$form['field_a']['und']['#value']

```

> Used by: button, hidden, image\_button, submit, token, value
>
> Description: Used to set values that cannot be edited by the user.

For `$form_state['values']['field_a']['und'][0]['value']`

> **$form\_state** is one of the arguments passed to a form submission handler, or a form validation handler; its main usage is to retrieve the values entered from the user in the form see the content of $form\_state\['values'\])

So you should use `$form_state['values']['field_a']['und'][0]['value']`
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Easily theming Form Fields - How to get minimum HTML required for form field in Drupal 7
I'm using my own templates to modify forms, i.e. user registration form. In my custom template, I call `drupal_render($form['field_email']);` to get output for a **text input** used for taking *user's Email*.

However, this function returns so many outputs (including a Label which definitely I don't want, and a lot of divs) that break my design. What I require is a single `<input name = "appropriate-name" />` but I'm getting:

```
<div class="field-type-email field-name-field-user-email field-widget-email-textfield form-wrapper" id="edit-field-user-email"><div id="field-user-email-add-more-wrapper"><div class="text-full-wrapper"><div class="form-item form-type-textfield form-item-field-user-email-und-0-email">
  <label for="edit-field-user-email-und-0-email">Email <span class="form-required" title="This field is required.">*</span></label>
 <input type="text" id="edit-field-user-email-und-0-email" name="field_user_email[und][0][email]" value="" size="60" maxlength="128" class="form-text required" />

```

A lot of HTML!

Is there a way to get minimum HTML required for a form input field to work properly?

Perhaps, I may end up with editing the `#theme` property for this field, to specify a custom theme function. But That's a lot of work to do, I think. Besides, I have many other fields for which I may need to write custom theme functions to get simple HTML for the input. **Is there a quick way to get minimum HTML for a form field?**

# Answer
I can't advise that you remove the labels as your website will instantly become inaccessible and fall foul of disability discrimination guidelines.

That being said, you can override the output for all form elements by implementing an override of the `theme_form_element` function. The easiest thing to do would be to copy that function in its entirety into a function in your site's theme called `MYTHEME_form_element(&$variables)`, and then step through the code trimming out the elements that you don't want to be output.
> 4 votes

# Answer
You should take a look at semantic fields. Its lets you control the structure of HTML generated and helps you remove the clutter.

On the module page it says

> The user can also choose to remove all (or some) markup for any field.
> 0 votes

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


# Question
Title: Getting og membership type in template.tpl.php
I want to obtain the organic groups role-id of a node/comment-author in node.tpl.php and comment.tpl.php.

I can't find an array that provides this information.

I want to add a class based on the authors membership type.

Dummycode:

```
<div id="header" class="<?php if ($author->rid == 7): print 'class-7'; endif; ?>">

```

How to do this for nodes and comments?

Note: for normal (non-organic-group) roles I use:

```
<?php if(in_array('administrator', $user->roles)): print 'admin-type'; endif; ?>

```

Which works ok, I want similar usage for organic group roles.

# Answer
> 1 votes
Found the anwser: This goes in node.tpl.php (tested on Drupal 7, Organic groups 7.x-2.3)

```
<?php if (og_context()) {
  $group = og_context();
  $userid = user_load($node->uid);
  $roles = og_get_user_roles('node', $group[gid], $uid = $userid->uid, $include = FALSE);
  }
?>

```

Then use it with something like:

```
<?php if(in_array('test member', $roles)): print '<span>Testuser</span>'; endif; ?>

```

For comments it's a little different:

```
<?php if (og_context()) {
  $group = og_context();
  $roles = og_get_user_roles('node', $group[gid], $uid = $comment->uid, $include = FALSE);
  }
?>

```

Works only on pages where groupcontext is available!

---
Tags: theming, users, organic-groups
---


# Question
Title: field_info_instance returns empty in hook_uninstall
In a custom module, I'm creating a new field and instance for a custom entity type like this:

```
function mymodule_install() {
  if (!field_info_field('mymodule_field')) {
    $field = array( .... );
    field_create_field($field);
  }
  if (!field_info_instance('mymodule_entity','mymodule_field', 'bundle1')) {
    $instance = array( .... );
    field_create_instance($instance);
  }
}

function mymodule_uninstall() {
  if ($instance = field_info_instance('mymodule_entity','mymodule_field', 'bundle1')) {
    field_delete_instance($instance);
  }
  if (field_info_field('mymodule_field')) {
    field_delete_field('mymodule_field');
  }
  field_purge_batch(100);
}

```

...and the field and instance gets created properly. However upon uninstalling the module, only the field tables are being deleted while the field instance is still there in the `field_config_instance` table **still having** *deleted = 0*.

Debugging the uninstall process reveals that `field_info_instance` (and `field_read_instances`) is returning NULL...

Anyone knows what I'm doing wrong? I'm on a fresh Drupal 7.23 install...

# Answer
You don't need `field_delete_instance` separately, because `field_delete_field` has it inside.

According to `deleted` column in field\_config (you can skip this value in field\_config\_instance if you're deleting whole field) debug `field_delete_field` function.
> 0 votes

---
Tags: entities, installation
---


# Question
Title: Redirect after login from custom login block
I have added the login form to a page using `drupal_get_form`. Now, I would like to redirect the users back to that page after login. Note: I don't want to redirect users that logged in somewhere else (e.g. user/login), and I also don't want to use a contib module for that.

B.T.W Maybe if I'll Ajaxify the login form it will have the same effect?

I'll appericiate any help and/or examples.

Thanks!

# Answer
> 5 votes
You have to add form\_alter and add custom #submit handler to user\_login form if current\_path() is correct for you and set `$form_state['redirect']` there.

Check this post Redirect to a custom page after a node has been added or edited.

Also it can be achieved via custom rule, if you don't want to write any custom code.

# Answer
> 0 votes
You should save the current path and use that current path in the redirect path of the form

```
$redirect_url = current_path();
$form['#redirect'] = $redirect_url;

```

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


# Question
Title: Reoccurring weekly billing that only a user can see, based on a schedule in another node
I need to setup a timed event, weekly, that will create a node or "billable event" based on a given pricing schedule (values on another node) and based on a date in another field on a different content type. And now if that wasn't confusing enough, I need for only the specific user to be able to see it. I'm open to any ideas as I really have no idea where to begin.

# Answer
> 0 votes
I will suggest using these modules: https://drupal.org/project/nodeaccess (to restrict node access per role or per user) https://drupal.org/project/elysia\_cron (flexible cron jobs)

Create separate cron job with flexible schedule where you can put all you custom logic with related nodes.

---
Tags: 7, users
---


# Question
Title: How do I create a text field in registration that only shows up if a checkbox is checked?
I am making a registration process in which there needs to be a text field that only appears if a checkbox is "on". I would think "parent" fields would do this, but whenever I click the "parent" dropdown under account settings, the only option is "none". If I am being too vague, feel free to let me know and I will clarify.

Thank you,

Alex

# Answer
Conditional Fields seems to be what you are looking for.

> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

Especially their example use case seems to match exactly your checkbox - text field need:

> When editing a node (or any other entity type that supports fields, like **users** and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" **field that is shown only if a** "Has teaser" **checkbox is checked**.

Emphasis mine.
> 1 votes

---
Tags: forms
---


# Question
Title: How to fill form fields based on other fields values using AJAX
I have 3 fields. On blur on any of them I want to look for empty ones - if blurred one has value and any of the others does not, I want to copy value.

Obtaining value is easy, simply `$form_state['triggering_element']['#value']`, but setting it elsewhere gets tricky.

Changing `$form['item']['#default_value']` does not work if field is empty after user's edit. Changing `$form['item']['#value']` makes Drupal ignore any further user input. Changing `$form_state['values']` seems to do nothing. What is the correct approach that should work? When I'll know that, I'll be able to debug.

# Answer
> 0 votes
The solution was, as Clive suggested, to simply use:

```
$form_state['input']['item'] = '...';

```

For elements that got replaced by AJAX, works like a charm.

If that's not enough, using AJAX commands might be needed.

# Answer
> 1 votes
I had the same issue and this workaround did the trick. Basically you clear up `$form_state['input']` value **and rebuild the form**.

Form builder:

```
<?php
$form['test'] = array(
  '#type' => 'textfield',
  '#title' => t('Test'),
  '#ajax' => array(
    'callback' => 'my_test_callback_func',
    'wrapper' => 'edit-test2',
    'progress' => array(
      'message' => '',
      'type' => 'throbber',
    ),
  ),
);

$form['test2'] = array(
  '#type' => 'textfield',
  '#prefix' => '<div id="edit-test2">',
  '#suffix' => '</div>',
  '#title' => t('Test2'),
);
?>

```

**Ajax callback function: This is the trickier part.**

```
<?php
function my_test_callback_func($form, &$form_state) {
  unset($form_state['input']['test2'], $form_state['values']['test2']);
  $form['test2']['#default_value'] = 'Auto Filled!';
  $form_state['input']['test2'] = 'Auto Filled!';
  return form_builder($form['#id'], $form['test2'], $form_state);
}
?>

```

We unset the user input (or check if it's empty), set a default value and then rebuild the form.

---
Tags: 7, forms
---


# Question
Title: Sending message body to email with PrivateMsg module
PrivateMsg Module sends email notifications that you have received a message to users. How to send the "Message Body" to the user in the email. So no need to login and see the message .

Any clues ? thanks

# Answer
If you navigate to `admin/config/messaging/privatemsg`, you will find the template of mail which get send by system when somebody private message to message some user.

You can modify the template. If you navigate to tokens below, you will find several tokens, one is - **\[privatemsg\_message:original:body\]**. You can insert it in above template to send it in mail according to your need.

I think you need Token module for all this & I hope you must have this installed in your instance.
> 2 votes

---
Tags: privatemsg
---


title: Live Drupal page editing

text:
# Question
Title: Live Drupal page editing
Is there any module or a way for live editing Drupal's HTML Markup. I want to add few CSS classes to various fields.

Thanks

# Answer
You said you want to add classes to fields, maybe this module will get that job done: https://drupal.org/project/field\_formatter\_class

You can find others as well, like block class module and I think there is one for menus or menu items (advanced menu module?), just search around.
> 2 votes

---
Tags: 7
---


# Question
Title: How to implement properly a view of nodes displaying other referenced nodes with no duplications?
I know that this has been asked several times with different variations, but I cannot seem to find an optimal solution, so here we go again:

I have a content type 'Parent' and a content type 'Child'. The relation between the two is one-to-many i.e. there is a field within the 'Parent' CT called 'children' which is of type 'Entity Reference' and allows for multiple values. Now, I want to create a view that will fetch 'Parent' nodes and for each resulting row I want to display the respective children nodes. Something like this:

```
    -----------
    Parent 1
    - Child 1
    - Child 2
    -----------
    Parent 2
    - Child 3
    - Child 4
    ----------

```

Solutions I have found and explored so far:

**1.** Use a **Relationship** for the 'Child' nodes within the 'Parent' view

OK, I can now use the 'Child' node fields, but instead of having them grouped within the 'Parent' node row, I end up with one row per relationship and duplicate content

```
    -----------
    Parent 1
    - Child 1
    -----------
    Parent 1
    - Child 2
    ----------

```

How should I remove the **duplicate** content?

**1.1** Use a 'distinct' in query options. Naturally, it does not work, because distinct is applied to the whole row and since parent-child field tables are joined, each row IS actually distinct

**1.2** Use aggregation. Again the desired result cannot be achieved, since by grouping by Parent nid I will only get the first Child node reference

**1.3** Use module views\_distinct. OK, this seems to do the job, but it breaks the pager and the results counter as processing is done after the respective view queries have been executed

**2.** Use a **views\_field\_view**, so that respective 'Child' nodes are fetched by a separate view (via Contexual filter) and embedded gracefully within the 'Parent' node row.

OK, this definitely does the job, and I get no duplicates since the child field tables no longer participate in the Parent view query, BUT:

* it is not performance optimal
* performance gets worse considering that my project has 30 different views (for different content types) that need to function similar to the 'Parent' view in this example
* since I already have 30 "main" views, I would hate to create another 30 ones only to be used as field views for the "main" ones

**3.** Do the job **manually**: use a 'Global: Custom text' field, use the template "*views-view-field--parents--nothing-1.tpl.php*" and implement the whole logic there i.e. re-load the Parent node, get the Child node ids, load the Child nodes and print their desired fields. OK, this does the job too, BUT:

* it is not exactly the "Drupal way" of coding against views
* once again, there are performance issues since I bypass Drupal and load stuff on my own
* once again, I will have to implement 30 template files named like "\*nothing\_1" for each of my views

So, my question is the following:

Is there a solution for this issue other than the ones that I mention here? If not, then which one should I choose and how to overcome its disadvantages?

# Answer
You can fetch the 'Parent' nodes with their 'Children' nodes with the default functionality of views and without the use of Relationships, Aggregation or other modules.

The Steps Are:

* Create a view of 'Parent' content type.
* In the 'Fields' section add the field 'Content: Title' and the field 'Content: Children(Appears in: node:parent)'.
* In the 'settings' of the 'Format' section select as 'Grouping field Nr.1' the 'Content: Title' field.
* In the field 'Content: Children' select the display format that you want.
* Finally 'Exclude' from display the 'Title' field.

Enjoy
> 1 votes

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


title: Upload picture in custom register form

text:
# Question
Title: Upload picture in custom register form
I'm building a multistep register form in a custom module. I'm using profile2 module to save other custom fields. I want to let the users choose an image from their computers. This is the code that I use to upload the picture that saves in the file\_managed Drupal table but without the user uid because at this point I don't create the user.

```
$form['empresa']['logo_empresa'] = array(
        '#title' => t('Logo de la empresa.'),
        '#type' => 'managed_file',
        '#description' => t('Tamaño máximo 3Mb y formato aceptado jpg,jpeg o png'),
        '#upload_location' => 'public://',
        '#upload_validators' => array(
        'file_validate_extensions' => array('png jpg jpeg'),
        'file_validate_size' => array(3*300*300),
        ),
);

```

When all fields are OK I submit the form and create the user as follows:

```
function empresas_registration_signup_form_submit($form, &$form_state) {

$nombre = $form_state['storage']['field_nombre_contacto'];
$apellidos = $form_state['storage']['field_apellidos_contacto'];
$mail = $form_state['storage']['email'];
$comunidad_autonoma = $form_state['storage']['field_comunidad_autonoma'];

$provincias = $form_state['storage']['field_provincia'];
$razon_social = $form_state['storage']['field_razon_social'];
$cif_nif = $form_state['storage']['field_cif_dni'];
$telefono = $form_state['storage']['field_telefono'];
$web = $form_state['storage']['field_web'];

$municipios = $form_state['storage']['field_municipio'];
$poblacion = $form_state['storage']['field_poblacion'];
$direccion = $form_state['storage']['field_direccion'];
$codigo_postal = $form_state['storage']['field_codigo_postal'];

$razon_social = $form_state['storage']['field_razon_social'];
$clave = substr($razon_social, 0, 3);
$cif_nif = $form_state['storage']['field_cif_dni'];

$usuario = $clave.$cif_nif;
$password = password(8);
//$imagen = $form_state['values']['field_logo_empresa'];

$roles = user_roles();
$newuser = array(
        'name' => $usuario,
        'pass' => $password,
        'mail' => $mail,
        'status' => 1,
        'roles' => array('7' => 'empresa'),
        'access' => time(),

);
$existing_user = user_load($usuario);
if (!$existing_user->uid) {
    $account = user_save(null, $newuser);

    $profile = entity_create('profile2', array('type' => 'empresa'));
    $profile->uid = $account->uid;

    //Datos a guardar para el perfil

    $profile->field_nombre_contacto[LANGUAGE_NONE][0]['value'] = $nombre;
    $profile->field_apellidos_contacto[LANGUAGE_NONE][0]['value'] = $apellidos;
    $profile->field_razon_social[LANGUAGE_NONE][0]['value'] = $razon_social;
    $profile->field_cif_dni[LANGUAGE_NONE][0]['value'] = $cif_nif;
    $profile->field_direccion[LANGUAGE_NONE][0]['value'] = $direccion;
    $profile->field_codigo_postal[LANGUAGE_NONE][0]['value'] = $codigo_postal;
    $profile->field_telefono[LANGUAGE_NONE][0]['value'] = $telefono;
    $profile->field_web[LANGUAGE_NONE][0]['value'] = $web;
    $profile->field_poblacion[LANGUAGE_NONE][0]['value'] = $poblacion;
    $profile->field_comunidad_autonoma[LANGUAGE_NONE][0]['value'] = $comunidad_autonoma;
    $profile->field_provincia[LANGUAGE_NONE][0]['value'] = $provincias;
    $profile->field_municipio[LANGUAGE_NONE][0]['value'] = $municipios;

    $profile->save();

    $account->profiles['empresa'] = $profile;
    entity_save('user', $account);
    drupal_goto('user');

}
}

```

My question is: How could I set the fid from the table and assign it to the user?

# Answer
> 1 votes
@Luism, you should use field widget for it. `field_attach_form` attaches fields to form, `field_attach_form_validate` validates all attached fields, `field_attach_submit` prepared entity to be stored. Regarding values in `$form_state['values']` you will have big structure inside `$form_state['values']['FIELD_NAME'][LANGUAGE][INDEX]` but you need only `$form_state['values']['FIELD_NAME'][LANGUAGE][INDEX]['fid']`, it will contain File ID from file\_managed table (with status=0) for uploaded files and after `profile2_save()` file will be activated or deleted otherwise.

---
Tags: forms, users, media
---


# Question
Title: Hide content types in administration for certain user
I created a user role who can only create and edit a certain content type, this works as it should.

When they log in however, they can click the content box in the admin bar to see all content. I want them to be able to click there and get all the content that they have the permission to create, but other content types should not appear.

I can't find any setting for this is the user role and permissions setting, but perhaps I'm mistaking? How can I fix this?

# Answer
> 1 votes
You should use Content Access module

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

# Answer
> 0 votes
You can just create a custom view and filter it to the desired content. This also allows you to completely customize which options they have available to them.

---
Tags: nodes, users
---


title: why ajax not work in this code

text:
# Question
Title: why ajax not work in this code
In callback of custom menu wrote function , in function I want to use node\_add , I have a field that I want add AJAX to it, but when change the field nothing happened where is the problem? I am using Drupal 7

```
 module_load_include('inc', 'node', 'node.pages');
    $form = node_add('pre_register');
$form['field_course_display_ref']['und']['#value'][]=$nid;
    $form['field_course_display_ref']['#ajax'] = array(
      'callback' => 'myfunction_ajax_change_course',
      'event' => 'change',
      'wrapper' => 'course-schedules-div',
      'method' => 'replace',
      'effect' => 'fade',
    );
    $form['field_course_schedules']['#prefix'] = '<div id="course-schedules-div">';
    $form['field_course_schedules']['#suffix'] = '</div>';

```

I also try

```
 module_load_include('inc', 'node', 'node.pages');
    $form = node_add('pre_register');
$form['field_course_display_ref']['und']['#value'][]=$nid;
    $form['field_course_display_ref']['und']['#ajax'] = array(
      'callback' => 'myfunction_ajax_change_course',
      'event' => 'change',
      'wrapper' => 'course-schedules-div',
      'method' => 'replace',
      'effect' => 'fade',
    );
    $form['field_course_schedules']['#prefix'] = '<div id="course-schedules-div">';
    $form['field_course_schedules']['#suffix'] = '</div>';

```

but nothing happened :(

**EDITED** I have two field, one `field_course_schedules` (will wrap) and `field_course_display_ref` The field that I want but changing it ajax will be trigger.

**type mistaked in code corrected but not worked again**

# Answer
> 0 votes
You're trying to modify a form which is already got built/processed!!

node\_add function is internally calling drupal\_get\_form which will return the processed form, so even if you change anything it wont take any effect. i.e. Drupal will consider the things which are available when the form is being built/processed.

To overcome this you should use drupal\_retrive\_form instead of drupal\_get\_form.

The same problem is discussed here with different context, sadly the OP took part in that discussion :(

---
Tags: ajax
---


# Question
Title: How to hide Fivestar rating field after first comment?
The accepted answer on How to limit a user to one vote when using Fivestar? doesn't work for me, but the author hasn't provided a solution yet, so I felt this is worth a new question.

My goal is exactly the same as the one in the article mentioned above: I'd like to hide the Fivestar rating field (called *field\_stars*) in the comment form when a user comments on a node on which he/she's already commented.

Is there another solution (for example with the Rules and Flags modules)?

---

**Edit:** I already have a flag called *Commented* on my site and a rule that flags a node on behalf of the commentator when someone commented on it (which works perfectly). I'd really like to use it to fix this problem. I tried something, based on the information I found here:

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $flag = flag_get_flag('commented') or die('no "commented" flag defined');
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid OR $flag->is_flagged($form['#node']->uid, $user->uid)) {
      unset($form['field_stars']);
    }
  }
}

```

Unfortunately, it doesn't change anything (I don't get any errors either).

# Answer
> 0 votes
I nearly had the answer in my **edit**. The code should have been

```
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $flag = flag_get_flag('commented') or die('no "commented" flag defined');
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid OR $flag->is_flagged($form['#node']->nid, $user->uid)) {
      unset($form['field_stars']);
    }
  }
}

```

So, the only thing that was wrong was `$flag->is_flagged($form['#node']->uid`. It should have been `$flag->is_flagged($form['#node']->nid`.

Many thanks to @jerdiggity on Stackoverflow!

# Answer
> 0 votes
In your node.tpl.php you should have the following code

```
hide($content['field_fivestar']);
print singlerating_print_rating($node->nid, $content['field_fivestar']);

```

I presume field\_fivestar is the fivestar field you are using and not field\_fivestar\_rating

---
Tags: 7, rules, comments, rating
---


# Question
Title: How do I enable private messages for normal users, and not just administrators?
Only Administrators can see the "Messages" link when logged in. Non-administrator users cannot. What can I do to alleviate this?

I've tested by looking at the site when logged in as Bobby, who is normally non-administrator user. No "Messages" link. However, if Bobby is ticked off as an administrator and I log back in as Bobby, I can see the "Messages" link between "My Account" and "Log out" in the upper right corner of the screen. I even get a notification that I have "1 new message".

I've looked through the Private Messages module configuration and can't seem to find setting that corresponds to what I'm experiencing.

I'm using Drupal 7.22 and Privatemsg 7.x-1.4.

The Private Message module is enabled, and all users have a tick in their "Enable private messages " setting.

# Answer
You need to set up permissions to use Privatemsg.

Go to example.org/admin/people/permissions (Home \> Administration \> People, Permissions tab) and check privatmsg boxes for Authenticated User role.

It might be also convenient to create "Messenger" role with these permissions, and grant it to all users by default. That way, you will be able to ban someone from messaging by simply taking role away from him.
> 1 votes

---
Tags: users, privatemsg
---


# Question
Title: Facebook Comments Widget disappears for logged in users
EDIT: I would clarify that this only affects Chrome, works in IE\Firefox\Opera.

I am using the following code after the opening `<body>` tag

```
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/fi_FI/all.js#xfbml=1&appId=409074972499544";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

```

Then in my module I've created a block for the FB Comments, so that I can add it via Panels to the pages I'd like commenting to be enabled in like this (omitting the typical block code required):

```
function _fb_comment() {
  $url = "http://" . $_SERVER['HTTP_HOST'] . request_uri();
  $comment = '<div style="text-align: left !important;" class="fb-comments" data-href="' . $url . '" width="720" data-num-posts="10" colorscheme="light"></div>';
  return $comment;
}

```

Visitors on my site are able to see the Comment widget, but for logged in users it's not visible and I just can't determine why. It feels like FB is hiding the widget due some problem, but there are no errors in the Console to help debug the issue. Inspecting the actual dom shows us that when it works, the markup is following (visitor):

```
<div style="text-align: left !important;" class="fb-comments fb_iframe_widget" data-href="http://url-to-the-current-page-here.com" width="720" data-num-posts="10" colorscheme="light" fb-xfbml-state="rendered">
  <span style="height: 160px; width: 760px;">…</span>
</div>

```

And for logged in users it shows up like this:

```
<div style="text-align: left !important;" class="fb-comments fb_iframe_widget" data-href="http://url-to-the-current-page-here.com" width="720" data-num-posts="10" colorscheme="light" fb-xfbml-state="rendered">
  <span style="height: 0px; width: 0px;">…</span>
</div>

```

As we can see, FB for a reason or another decides to hide the widget -- what causes this I have no idea, I have tested disabling contextual filters so as not to fiddle with the markup of the block in any way and not aggregating JS, not caching blocks and just about everything.

As we traverse further down to INSIDE the Facebook iframe, the logged in users one has

```
<html lang="en" id="facebook" class="no_js">..</html>

```

This might be key, but I've not the slightest clue what may cause it. Was hesitating over asking this in StackOverflow instead of Drupal, but since it's a problem with being logged into Drupal, I might not be the first one to tackle the issue.

# Answer
> 1 votes
This bug, in the end, was a MODERATOR specific bug in the Facebook Commenting widget itself. FB has now fixed it.

---
Tags: social-network
---


title: Filter view from $_GET parameters

text:
# Question
Title: Filter view from $_GET parameters
I have a classic view with fields from classic nodes. I have made a custom form that reload the view with parameters :

```
mypage?nid=168

```

But to display only the wanted data, my view use **CONTEXTUAL FILTERS** and need this format :

```
mypage/168

```

How can I filter my view from **$\_GET** parameters.

# Answer
> 2 votes
Hope this will help you,

In Drupal 7 you can achive it by using **views php** module.

* Add contextual filter
* Select the field using which you want to filter. I'm using **Content NID** as filter parameter
* Add the PHP code for filtering
* PHP code

```

if(isset($_GET['nid']))
    return $_GET['nid'];
else
    return;

```
* Just add the param in the URL

Note :

* check the permission of views\_php module
* Make the changes as per your requirement.

# Answer
> 2 votes
Use "**Global: PHP**" field to get the required parameter value. If **views\_php** is not installed, then use this link, **views\_php** to install the module and give the permission using **admin/people/permissions**.

Go to your Views -\> CONTEXTUAL FILTERS -\> ADD -\> Select "Global: PHP" then you can retrieve the parameter using **$\_SERVER\[QUERY\_STRING\]** and retrieve the value.

And also you can use **$\_GET\['nid'\]** to get the value.

---
Tags: views
---


title: Opposite to theme_get_setting To Set

text:
# Question
Title: Opposite to theme_get_setting To Set
In the template.php file, we grab the theme settings:

```
if(theme_get_setting('fix_sidebar')){
...
        variable_set('fixed_navbar',1);
    }

```

Based on the theme setting(i.e fix\_sidbar'), we want to reset another theme setting(i.e fixed\_navbar) as you see above. However, it does not appear to be working. It is not showing up theme settings that has:

```
 $form['style']['fixed_navbar'] = array(
        '#title' => t('Fixed Navbar'),
        '#default_value' => theme_get_setting('fixed_navbar'),
        '#type' => 'checkbox',
    );

```

How to do the opposite of theme\_get\_setting API to reset the setting with new value? Thank You

# Answer
> 0 votes
If I understand you correctly, you should be doing this

```
$form['style']['fixed_navbar'] = array(
    '#title' => t('Fixed Navbar'),
    '#default_value' => variable_get('fixed_navbar', 1),
    '#type' => 'checkbox',
);

```

---
Tags: theming
---


title: How do I put an article in a block?

text:
# Question
Title: How do I put an article in a block?
I don't think I understand Drupal too well yet. I have an article. In the theme I chose it has the various blocks. How do I put an article on a given block area of a theme?

I see the modules I can assign to a block in a specific region, but I have things articles I want to put in the block. I don't need who's online, recent comments, etc.

# Answer
> 6 votes
If you want to put a node, where in your case it will be a node from an article content type, you can use the node as block module.

You also have other module options, including:

These modules allow you to add your nodes inside a block. Afterwards, you can configure which block to show in which region on the block administration page. For example if you want to hide the 'who is online block' simply set the region for the block to none and it will not show up any more.

# Answer
> 9 votes
I don't know if there is any shortcut to put the article into Block, but usually I use Views for that. After installing Views Module

1. create new Views and select ***content*** of type ***Article***
2. Check on **Create a Block** and *Continue and Edit*
3. In Fields, Select the fields you want to display eg: Article Title, Description, etc.
4. Use the **Filter** to filter results.

If you want to display only the latest Article, then use **Sort** by ***Post Date Desc*** and in **Pager** settings display max items to ***1*** with ***No Pagination*** option.

Go to **Structure-\>Blocks** and select your theme and you can enable/disable what blocks you want to display and where. If you are unsure about the regions in theme then click **Demonstrate Block Regions**

This looks one heck of a task, but playing around **Views** would make you more comfortable with Drupal.

# Answer
> 0 votes
If you decide to dive into the "panels module way" of layouting your pages, then you will find that it comes closer to your way of thinking. Traditionaly, blocks are not for "putting the article content into my theme". Blocks are for the fluff around your content. (like e.g. Who is online) But the "panels approach" will replace the "classic block way of doing things" in your drupal. Panels will instead support your approach of "put the article's content here -- like I would place a block."

---
Tags: blocks, nodes
---


title: Display quiz results for users

text:
# Question
Title: Display quiz results for users
I am developing an e-learning portal for a client; the client wants to be able to create quizzes and view the results of individual students, and probably draw a graph to give an overview of student performance. I am using the Quiz module to create quizzes.

The "quiz score" is not available if you use node as the view base or quiz.

I am able to list username, level, and quiz.

# Answer
> 2 votes
You would need to add a relationship which would be the Quiz Result : User.

Then you would find the quiz result : score in the fields

# Answer
> 2 votes
Use quiz as the base for view. If you want to create a chart. Im using views dataviz module

Code Karate have a tutorial on it here.

My view page ended up looking like this:

which created a chart based on the individual scores of the users answers (not the overall quiz:score)

---
Tags: views, quiz
---


# Question
Title: Find out which fields to modify on drupal view for a module
I would like to implement a hook on a view that grabs the fields that would be displayed and modifies one of the slightly before displaying it. However, I am stuck at the first part which is just finding out how to view/see the fields that I can manipulated. Based on a couple of other post I have read it seems like I should use the parseurl\_views\_pre\_render which seems to make sense. But, I don't even only how to see what the data looks like.

Any pointers or help would be greatly appreciated.

Thanks, Derek

# Answer
> 0 votes
I think you can do what you need with hook\_views\_pre\_render.

Here is what you can do to find out what the data you need to manipulate looks like:

1. Install & enable the devel module - https://drupal.org/project/devel
2. Create a custom module (if you haven't already)
3. Add a function based on HOOK\_views\_pre\_render(&$view)
4. In your function, use the dpm function like so: dpm($view);
5. Reload the page with the view you want to alter
6. Explore the data rendered through Krumo which is provided by devel

So, ultimately, your function will start something like this:

```
function your_module_views_pre_render(&$view) {

  if (($view->name == 'viewname') && ($view->current_display == 'displayname')) {

    dpm($view);

```

---
Tags: 7, hooks
---


# Question
Title: how can I change digits from latin to persian digits
I am using Drupal with localization module, in persian language, I want in persian show persian digits instead latina digits?

# Answer
You can use `persiantools` module, it change digits from latina to persian and some another features.....

persiantools
> 1 votes

---
Tags: 7, i18n-l10n
---


title: Only sort views after selected

text:
# Question
Title: Only sort views after selected
I am looking to sort nodes in a view, but only after the user has selected the sorting value.

So the nodes are currently listed in posting order, but I would like to provide the user to sort by price, but only once selected the price sorting?

Creating a standard sort by price, sets this from the initial page load and does not give the use a chance to see recently posted items.

How could this be achieved?

# Answer
Two ideas:

(1) Expose the sort to the user to allow them to control sorting. You need to enable "Expose this sort to visitors, to allow them to change it" for the sort criterion in views. See below for more detail on how to get the two sorts grouped together.

(2) Present the data in a table and make the columns you want the user to be able to sort, "sortable". You'll find this option under Format: table \> Settings.

With both approaches, you can set an initial sort, so the user will see content in the order you wish when the page first loads.

Edit: more detail for #1: by default, views will sort the output based the first sort criterion, and clutter the exposed form with sort order controls. To get the default sort you want, and to clean things up, you can try:

1. Add both sort fields and expose to visitors (post date first)
2. Under exposed form options: enable autosubmit and hide the submit button
3. Under exposed form options: disable "Expose sort order"
4. Adjust exposed sort labels if needed for clarity

(exposed form options are in the Advanced section of the view)

When the view loads, the user will see a single select list that contains both sort options, and no submit button. The view will be sorted according to the first option.
> 2 votes

---
Tags: views
---


# Question
Title: Node PHP function causing CRON not to run properly
Below is my code. I have two fields.

By default, "$staticPath" equals the path of the "field\_static\_ad" field, and "$flashPath" equals the path of the "field\_flash\_ad" field.

However, when there is nothing uploaded to "field\_flash\_ad", I want "$flashPath" to equal the path of "field\_static\_ad" instead.

This code WORKS for me know, but something is going wrong when I run CRON! I don't get an error, but I can't index my site.

```
<?php
if ($node = menu_get_object()) {  $nid = $node->nid; }

$staticPath = file_create_url($node->field_static_ad['und'][0]['uri']);

$flashPath = field_get_items('node', $node, 'field_flash_ad');

if ($flashPath) { $flashPath = file_create_url($node->field_flash_ad['und'][0]['uri']); }

else { $flashPath = file_create_url($node->field_static_ad['und'][0]['uri']); }
?>

```

Is there something wrong with my php?

# Answer
Try debug\_cron module to debug the cron issue.Also I am not sure if the mentioned code is even executing on cron run. This module provides debugging of

```
 fail due to programming or runtime errors
 time out (PHP, server, database)
 are very slow

```

> Cron Debug will also allow you to test run specific cron functions while not running others. This can be nice for developing cron functions where you don't want to run a full cron.php with all maintenance, alerts and other tasks every time you test your own function.

Also why not you putting the complete code inside the first if conditions like'

```
if ($node = menu_get_object()) {
  $nid = $node->nid;
  $staticPath = file_create_url($node->field_static_ad['und'][0]['uri']);
  $flashPath = field_get_items('node', $node, 'field_flash_ad');
  if ($flashPath) {
    $flashPath = file_create_url($node->field_flash_ad['und'][0]['uri']);
  } else {
      $flashPath = file_create_url($node->field_static_ad['und'][0]['uri']);
   }
}

```
> 0 votes

---
Tags: entities
---


title: Hiding Menu Links Based on URL

text:
# Question
Title: Hiding Menu Links Based on URL
Is there a way to hide menu links on the main menu based on the URL?

For instance, if my URL is 'example.com/undergraduate', the main menu links would be different than if I were to go to 'example.com/graduate'.

This obviously can't be too hard? A module would be awesome.

# Answer
> 0 votes
If you want to have page specific menu system, you can create different menu blocks and put them appropriately.

Considering your example

Main menu is nothing but a menu block, so instead of using main menu block you can have two different menu blocks let say Menu block A and Menu block B

So in block configuration for Menu block A you will put the block visibility to show on "undergraduate" only and similarly put for Menu block b put it as "graduate"

Remember to put the menu blocks in same region as your main menu. You are just toggling menu block visibility on basis of URL.

---
Tags: 7, routes
---


# Question
Title: How do I sort two different date content-types in a view?
I have a view that filters two content-types (*single event*, and *serial event*) by date. The content-types have their own date-field (one with, one without date-repeat option).

The view shows all the "serial events" first, and afterwards the "single events".

How can I change this order?

Is it because I use two different date-fields?

The sort criteria are the following:

* **Format**
Format: Unformatted list | Settings
Show: Fields | Settings
* **Fields**
Content: single event
Content: serial event
* **Filter criteria**
Content: Published (Yes) AND Content: Category (exposed) | Settings AND Content: Type (in single event, serial event) OR Date: Date (node) (Content: single event (field\_serialevent) OR Content: serial event (field\_singleevent) \>= now)

I am using Drupal 7.14, with the latest versions development snapshots of the Views, Calendar, and Date API modules.

# Answer
> 2 votes
Are you sure you are only have one sort field? It sounds like you are also sorting on "Type". If you are sorting on type, make sure the "Date" is the **first** in the sort fields. The order of the sort fields, makes the top ones dominant.

# Answer
> 0 votes
In case anyone comes across this looking for sorting on two different date fields, please see the summary of possible solutions I wrote here: https://drupal.org/node/2133879

The best solution I found was to use hook\_views\_query\_alter() function to alter the sort criteria to use a CASE ... WHEN conditional in the orderby filter.

---
Tags: views
---