# Question
Title: How can a user access only one specific node, and not all nodes of that type?
I have a user with view and edit rights to a specific content type. This give the privilege to all users to view and edit all the nodes of that type. But actually, I want to create for each user a unique node, so that only that user may view and edit it. How can I do this in Drupal 7 ?

# Answer
> 11 votes
Using an existing module, you can do that with Content Access, which (when used together ACL) allows to set the permissions to access a node for each user.
This means that you need to set the access permissions manually for each node.

If you manually create the nodes, and then you want to be sure that only the user who is set as owner of the node is able to view (and edit) it, then you can create a custom module (which means a module that is used for your site), and implement `hook_node_access()` as follows (the code has been written to make it easier to read):

```
function mymodule_node_access($node, $op, $account) {
  // We are interested to existing objects. When the node is being created, Drupal passed the node type instead of the node object.
  if (is_object($node)) {
    $bool = (
      ($node->type == 'the node type you need to check') &&
      (($op == 'view') || ($op == 'update'))
    );
    if ($bool) {
      if ($account->uid == $node->uid) {
        return NODE_ACCESS_ALLOW;
      }
      else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}

```

Using this hook implementation, you don't need to manually edit the access permissions given for each node of that content type you create. Changing the owner of the node would also be easier, as you don't need to change the access permissions of that node; the code would automatically grant the update and view permissions to the user set as owner (or author) of the node.

# Answer
> 5 votes
You don't need any special module or custom code to do this. Just create manualy those nodes, set appropriate users as owner (author) of the nodes and set permissions to this contentype to edit own content only (not edit any content of this type) and you are done.

# Answer
> 2 votes
What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather course, and to control access to view a node by role, you must use some sort of node access control module. There is a page at Drupal.org listing all node access modules, with a capsule review of each. I suggest you take a look at that page to see if you can find a suitable module to control access.

The Flexi Access module seems to be the module that is the closest match to your requirements, as its *primary function* is to let you control access for individual users, rather than by role or by taxonomy term.

It is a small module that let you set up ACLs (access control lists) for individual users. It is basically a user interface for the ACL module, so you need to install that as well.

It lacks some of the features of the more advanced access control modules, such as Content Access, but it is actively maintained and there are currently no open bugs in its issue queue.

Disclosure: I am the maintainer of Flexi Access.

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


# Question
Title: How to save file uploaded with plupload integration module, and make it managed?
As described here, I can use Plupload integration module to upload my files to server. They go there, I can see them in temp directory, and that's the point I'm stuck.

Code I'm using for a field is:

```
'DownloadFile' => array(
  '#title' => t("Download's download"),
  '#title_display' => 'invisible',
  '#type' => 'file',

  '#upload_validators' => array(
    'file_validate_extensions' => array( /* extensions */ ),
    'file_validate_size' => array(variable_get('max_size', 300 * 1024 * 1024)),
  ),
  '#upload_location' => 'public://mymodule/download',
  '#plupload_settings' => array(
    'runtimes' => 'html5',
    'chunk_size' => '10mb',
    'max_file_size' => variable_get('max_size', 300 * 1024 * 1024) . 'b',
  ),
),

```

In form validation function I get thus in `$form_state['values']`:

Since the Views for Drupal 7 got reasonably stable, I was using Drupal 7 and managed files. I have literally no idea how should I take this file and plug it into managed table for other functions to use. As you can see from the time difference, it been some time between the moment I was able to upload and now - all this time with no idea. Tried to treat it as `'#type' => 'file'`, but functions for unmanaged don't get it. They require specific name and even if I add `'#name'` to plupload form element, it still fails.

Is there any way to add file to managed table knowing it's location in `temporary://`?

# Answer
I didn't really checked all links in this email but I have used Plupload very extensively and worked very well.

```
<?php

  $form['upload'] = array(
    '#type' => 'plupload',
    '#title' => '',
    '#description' => t('Maximum file size allowed: 10MB'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('zip rar 7z odt doc docx xls xlsx png jpg pdf rtf txt'),
    ),
    '#plupload_settings' => array(
        'runtimes' => 'html5,flash', // Also consider the order of technologies.
        'chunk_size' => '10mb',
        'unique_names' => TRUE,
        'flash_swf_url' => file_create_url(_plupload_library_path() . '/js/plupload.flash.swf'),
      ),
    );

  return $form;

  // Submit handler:
  //function ..._submit($form, &$form_state) {
  if (!empty($form_state['values']['upload'])) {
    $form_state['uploaded_files'] = quotes_file_save_files($form_state['values']['upload']);
  }

  // }

function quotes_file_save_files($files) {
  $saved_files = array();
  $scheme = 'private://'; // Change to "public://" if you want to move to public files folder.
  foreach ($files as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      // Check the $file object to see if all necessary properties are set. Otherwise, use file_load($file->fid) to populate all of them.
      // $file = file_load($file->fid);
      $saved_files[] = $file;
    }
  }

  return $saved_files;
}

?>

```

I think the point is, plupload does not save the files to the managed files folder by default, but populates all the data in the $form\_state array for you to process and save.

Edit: In relation to the other answer that mentions file object's status should be permanent. I'm sure you already know that the status must be 1. But `plupload_file_uri_to_object` function sets the $file object's status to 1, so it's not done in the example.

Good luck!
> 4 votes

# Answer
I did a multiple gallery plugin that integrated with Ubercart and allowed users to upload multiple images with Plupload, per each attribute option.

Below is the part of the code that I used for uploading files. It goes in the `_submit()` handler function. The files were saved in the managed files table as permanent files and then were listed in orderable table view.

```
// Upload files.
foreach ($element['images']['#value'] as $uploaded_file) {
  $source = $uploaded_file['tmppath'];
  $filename = filefield_sources_clean_filename($uploaded_file['name'], array());
  // Move the file to a temporary destination using final base file name.
  $temp_destination = file_stream_wrapper_uri_normalize('temporary://' . $filename);
  $temp_filepath = file_unmanaged_move($source, $temp_destination, FILE_EXISTS_RENAME);
  // Save the files to their final destination.
  if ($file = filefield_sources_save_file($temp_filepath, array(), 'public://your-path/' . $form['nid']['#value'] . '/')) {
    $file->oid = $element['oid']['#value'];
    // Set status to 1, meaning this is a permanent file and should not be
    // cleaned up upon cron run. IMPORTANT!
    $file->status = 1;
    file_save($file);
  }
  else {
    drupal_set_message(t('An error occurred during upload. Please try again.'));
  }
}

```

**Important**
You must set `$file->status = 1`, otherwise the file will be treated as temporary file and will be deleted upon next cron run.

If you need more code/working example, let me know and I'll clean the custom module a bit and post it.

Hope this helps.
> 1 votes

---
Tags: files
---


# Question
Title: How to validate file using hook_file_validate?
I want to validate my file, I'm using

> hook\_file\_validate

```
function test_file_validate($file) {
  $errors = array();

  if (empty($file->filename)) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (retstrlen($file->filename) > 255) {
    $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  }
  return $errors;
}

```

But, when I am going to `print_r($file)` I am not getting any values, please let know how to use this function

# Answer
> 0 votes
In Drupal 7 just use **drupal\_set\_message**

```
/**
 * Implementing hook_file_validate
 * @param type $file : Object
 * @return type : array of error messages
 */
function hook_file_validate($file) {
    drupal_set_message("<pre>" . print_r($file, 1) . "</pre>");
    $errors = array();
    if ($file->source == 'field_article_file_und_0') {
        if ($file->filesize > 290081) {
            $errors[] = t("The file's exceeds upload limit. Please try again.");
        }
    }
    return $errors;
}

```

# Answer
> 0 votes
`hook_file_validate()` is called by `file_validate()`. It lets you supply custom validation to supplement the validators that already exists. You need to give it valid file object to work with. Here is an example of how to use. In this example, it *always* produces an error message (so you don't have to type in absurdly long filenames, etc. to test).

```
/**
 * Implements hook_file_validate().
 */
function MYMODULE_file_validate($file) {
  debug('hook_file_validate was called');
  // Add your custom validation code here. E.g.:
 $errors = array();
 if (!mb_detect_encoding($file->filename, 'ASCII', true)) {
   $errors[] = t("Please don't use non-ASCII charcters in filenames.");
  }
  $errors[] = t("This error is always added, just to test that it works.");
}

```

Now, most of the stand upload functions that comes with Drupal already calls `file_validate`, so you should see any errors generated by it.

However, if you're creating a custom upload method, you need to call `file_validate` somewhere in your code, for instance in your form validation code:

```
// Load the file object:
$fid = $form_state['values']['image'];
$file = file_load($fid);
// Use one of the existing validator callbacks to check if it is an image.
$validators = array(
  ' file_validate_is_image' => array(),
);

// When this function is called, hook_file_validate is also called.
$errors = file_validate($file, $validators);
foreach ($errors as $key => $error) {
  drupal_set_message($error);
}

```

Note that instead of using `hook_file_validate()`, you can write your own validation callbacks and add those to the `$validators` array. I prefer to use this method instead of `hook_file_validate`.

# Answer
> 0 votes
Hello Sachin I think the problem is that you are not watching output at right place. If you are uploading a file at a node's edit then you will see your message there only. For example I tried it for you by uploading a file with file name larger than 25 characters then at time of uploading I found the this message:

I have also used this print\_r($file) in my code and found details about file being uploading in Ajax pop up. And my code as as follows :

```
 function common_file_validate($file) {  print_r($file);exit;
  $errors = array();

  if (empty($file->filename)) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (strlen($file->filename) > 25) {
    $errors[] = t("The file's name exceeds the 25 characters limit. Please rename the file and try again.");
  }

  return $errors;
}

```

---
Tags: hooks, files
---


# Question
Title: Is there any API to get corresponding field in a custom content type?
I have drupal 7 and created a custom "content type" with several fields. just imagine i have:

1. title field
2. subtitle field

I need to search the data. I want to search titles and when i found my certain title I want to get **corresponding** subtitle (in the same row of that title)! I know I can do it by going to directly to my database and do it by db\_query(and i have to know the structure of my database as well). but is there any API in this regard?
i need to get them inside my custom module

# Answer
In this instance using db\_query is appropriate...

```
$nids = db_query("SELECT nid FROM node WHERE title LIKE :title", array(':title' => '%'.$title.'%'))->fetchCol();

$nodes = node_load_multiple($nids);

foreach($nodes as $node) {
    $subtitle = $node->field_subtitle[LANGUAGE_NONE][0]['value'];
    // do things with the subtitle....
}

```

What has happened here is we are using db\_query to search the node table for nodes with matching titles. Once we have the nids we call node\_load\_multiple and that loads the whole node(s). Drupal uses caching here so we don't have to necessarily connect to the DB at all to do this.

The resulting $node object has all of the fields already attached to it so knowing where they are actually stored in the DB at this point is irrelevant.

As Clive has pointed out we shouldn't really access field items directly as using field\_get\_times or EntityMetadataWrapper will ensure that we always load the field items in the correct language (the language of the current user).

To use field\_get\_items you could:

```
foreach($nodes as $node) {

    // using field_get_items here automatically loads the field in the correct language
    $field_items = field_get_items('node', $node, 'field_subtitle');
    $subtitle = $field_items[0]['safe_value'];

    // do things with the subtitle....
}

```
> 2 votes

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


# Question
Title: How to change image size and position when uploading to article in tb_rave_starter
I want to change image size and position How could this be done, please help me.

# Answer
To edit the size of the image:

Go to `/admin/structure/types/manage/YOUR_CONTENT_TYPE/display` and click the edit image style button shown in the image below.

This will open a drop down and then you can choose the image size you want:

To change the location of the image you have several options...

You can edit your themes CSS file, however this will require understanding the underlying HTML and CSS.

An alternative is to use a module like Panels that allows you to create custom layout and apply them without actually doing any coding. I've not actually used it before myself but have heard good things about it and there are lots of tutorials online - just Google it.
> 0 votes

---
Tags: 7, media
---


# Question
Title: hook_permission and control access [how to redirect to the login page if user not logged in]
How does one limit "what" can access a page. I have little understanding on how to use `hook_permission()` to set user permission based on a role to control access to `hook_menu()` items. However, what if I have a `hook_menu()` item that is to be used solely by the system itself? For example, say I have a registration page in a custom module: `module/register` \- Anyone can access that page. Then, say I have an another page which is only for admin. So, I register another item in hook\_menu(), call it `module/register/reg_user_details` \- I do not want anyone to be able to browse to `module/register/reg_user_details`

Instead I want page to be visible only when user is logged in, I have already created a `hook_permission`

```
/**
 * Implements hook_menu()
 *
 */
function video_subtitles_menu() {
  $items = array();
  $items['video_subtitles/upload'] = array( //this creates a URL that will call this form at "video_subtitles_test/upload"
    'title' => 'Upload Subtitle', //page title
    'description' => 'Uploading subtitle for videos',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, drupal_get_form need to be used
    'page arguments' => array('video_upload_subtitles_form'), //Name of the Uplaod Form
    'access callback' => 'user_access',
    'access arguments' => array('administer video_subtitles module'),
  );

  $items['player/video_subtitle_status'] = array(
     'page callback' => 'video_subtitle_status',
     'access callback' => 'user_access',
     'access arguments' => array('administer video_subtitles status'),
  );
  return $items;
}

/**
 * Implements hook_permission.
 */
function video_subtitles_permission() {
  return array(
    'administer video_subtitles module' => array(
      'title' => t('Administer video_subtitles module'),
      'description' => t('Access the video_subtitles upload module Page'),
     ),
    'administer video_subtitles status' => array(
      'title' => t('Administer video_subtitles module status'),
      'description' => t('Access the video_subtitles module status Page'),
  ));
}

```

So User is not able to access my page unless user is logged in, but what I need user should be redirected to the login page when he is not logged in as admin , if he successfully login it should be redirected to my page.

1. visit url `d-7/example/my-module`
2. if already logged in show the page
3. if not logged in redirect to the login page
4. if user logged in successfully redirect to `d-7/example/my-module` page

What is best way to achieve this

**Similar Question**

using-hook-menu-with-hook-permission-access-denied

using-hook-menu-and-hook-permission-to-control-access

can-someone-explain-access-arguments-in-drupal

# Answer
> 2 votes
Easiest way will be specifying this logic in `page callback` function. example:

```
function SOME_PAGE_CALLBACK($someArg) {
  if(user_is_anonymous()) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }

  // do_something();
}

```

another way is checking the user in `hook_preprocess_page` function:

```
function MY_THEME_preprocess_page(&$variables) {
  if(curent_path() == 'SOME_PATH' && user_is_anonymous()) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }
}

```

Access callback function checks the user's access to the request and returns boolean value, TRUE or FALSE, if you want to check if the user has an access to the page, you can do somthing like this:

```
$path = current_path();
if ($router_item = menu_get_item($path)) {
  if (!$router_item['access']) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }
}

```

# Answer
> 1 votes
Allow access to all users in hook\_menu:

```
$items['player/my_page'] = array(
    'title' => t('My Page'), // note this is a required parameter
    'page callback' => 'my_page',
    'access callback' => TRUE,
);

```

And then in your page callback function redirect users that are not logged in:

```
function my_page() {

    global $user;
    if(!$user->uid) {
        $dest = drupal_get_destination();
        drupal_goto('user/login', $dest); / this remembers where the user is coming from
    }

    //  Carry on with rest of code...

}

```

An alternative approach here pointed out by Clive is to do this checking in the access callback function and then leaving the page callback function for logic associated with building the page. I think this is a better approach as separates these 2 distinct tasks into their own functions.

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


# Question
Title: Is it possible to approve an Enitity Form?
Is it possible to approve a submitted Entity Form by a specific user/role ?

For example, I have a Leave Request Entity form to be submitted by the employee(role). The manager(role) will approve or disapprove the leave request.

Thanks for those who can give me some ideas. (Im a beginner and learning drupal)

# Answer
> 3 votes
* Define a field called "Approval Status" in your entity form with two values Approved / Unapproved
* Be Default set it to "Unapproved"
* Use Views to list your custom entities see below post for reference

How do i use views with a custom entity?

* Update "Approval Status" using VBO. See this article to find out how to create simple action.

---
Tags: entities
---


title: Widget type radio buttons and N/A

text:
# Question
Title: Widget type radio buttons and N/A
I have a field so-called "Status" in my custome contact type. It is a List (integer) and widget type is "Radio buttons". I added two values for allowed values list:

```
 0|Sold
 1|Available

```

Default value is "Available". But Drupal lists this as below:

```
 () N/A
 () Sold
 () Available

```

Why does Drupal add this unnecessary "N/A" to the radio buttons? I encountered this problem since D6. Now, I'm using the latest version 7.14. I'm still seeing this.

I know I can remove the "N/A" by writing a hook from a custom module. Nonetheless, I don't want to write additional codes for this kind of small thing. When I use "Select list", it is ok with an option "-None-", but the radio button is ideally suited for the two options.

How can I remove it without installing additional module? Am I missing some functionalities from Drupal core interface?

# Answer
> 2 votes
**When your field is required, no `N/A` options should show up** (and you said you need this field to be required).
To show you an example,

1. I created a new content type named "First test content type" (with the machine name `first_test_content_type`)
2. Went to *"Manage fields"*, and added a field with radio buttons (with the machine name `field_test_radio_buttons`)
3. Added the mentioned options:

```
0|Sold
1|Available

```
4. I checked the *"Required field"* checkbox (**this is the key** for not seeing `N/A` as a separate option!!)
5. Made "Available" the default option
6. So, on `/admin/structure/types/manage/first-test-content-type/fields/field_test_radio_buttons`, the following shows up: SCREENSHOT
7. When adding a new "First test content type" content, I can see the following radio buttons (click on the image to see the whole page):
8. So this is the result.

# Answer
> 3 votes
Something like this should help.

```
(function($) {
  $('.form-radio[value=_none]').parent().hide();
})(jQuery);

```

http://drupal.org/node/1623360

# Answer
> 2 votes
If your field is not required and not multiple then there's no way to remove the *N/A* without writing some custom code I'm afraid.

It's hard-coded into the `_options_properties()` function:

```
// Add a 'none' option for non-required radio buttons.
if (!$required && !$multiple) {
  $properties['empty_option'] = 'option_none';
}

```

Your only choice is to write a small form alter hook unfortunately; this was obviously a design decision made by the core developers when they were implementing that module's functionality. I'd imagine the justification would be UX-based but I don't know for sure.

# Answer
> 1 votes
It's implemented that way, because otherwise users don't have any way to deselect a radio button, and for some (government) sites that's a requirement.

To change it use:

* a form\_alter in a custom module
* javascript inside your theme to hide the N/A option.
* theme\_options\_none

# Answer
> 0 votes
```
unset($form['fieldname'][$form['fieldname']['#language']]['#options']['_none']);

```

should do it in a form\_alter hook. replace "fieldname" with your field's name. this should work for all select fields no matter what widget is used.

cheers, j

# Answer
> 0 votes
You can remove this "N/A" radio button option for all fields, or just specific fields, using the following `hook_field_widget_WIDGET_TYPE_form_alter()` implemention:

```
<?php

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function modulename_field_widget_options_buttons_form_alter(&$element, &$form_state, $context) {
  if (!isset($context['field']) || !isset($context['instance'])) {
    return;
  }
  $field = $context['field'];
  $field_instance = $context['instance'];

  if (!isset($field['field_name']) || !isset($field_instance['entity_type'])) {
    return;
  }
  $field_name = $field['field_name'];
  $entity_type = $field_instance['entity_type'];

  if (isset($element['#type'])
      && $element['#type'] === 'radios'
      && isset($element['#options'])
      && is_array($element['#options'])
  ) {
    $options =& $element['#options'];
    unset($options['_none']);
  }
}

?>

```

To limit this to change only selected fields, check on the `$field_name` and `$entity_type`.

# Answer
> -1 votes
One of the interesting Features of Drupal 7 is the Field API. Prior to Drupal 6, to make a custom field the Core Profile Module and Content Profile Modules are used. Now in Drupal 7 we can make any custom field to appear in User Registration Form. When Adding Custom Fields Such as Gender usually we use Radio Button Input. However there is a small Problem with the core module as it displays the third option N/A in the input. To Remove the N/A option the field needs to be set as mandatory. To Remove this option there is another way. Go to modules/field/modules/options/options.module and comment the the code $properties\['empty\_option'\] = ‘option\_none’ as shown below under buttons.

```
case ‘buttons’:
$properties = array(
‘filter_xss’ => TRUE,
);
// Add a ‘none’ option for non-required radio buttons.
if (!$required && !$multiple) {
//$properties['empty_option'] = ‘option_none’;
}
break;

case ‘onoff’:
$properties = array(
‘filter_xss’ => TRUE,
);
break;
}

```

However the proper way to achieve it would be to override this function in custom module. But for a quick fix we can also follow this method. \[blog\]: http://yamafm.wordpress.com/ "click here for updates"

---
Tags: entities
---


# Question
Title: Module Rules-> PHP Code, trying to use a Form Handler from Pardot, but Pardot is not receiving the info
I am trying to use the Rules module to send a form-handler to Pardot using a PHP script when a user logs in. I tested my variables to make sure they were valid by seeing them in a message and they appear fine. The problem I am having is that Pardot does not seem to be getting the form.

**The Rules module information**

* Event: 'User Logs in'
* Condition: none
* Action: Execute custom PHP Code.

**Pardot given form handler link**

(similar to)

`<form action="http://go.pardot.com/5/38543/2014-03-31/xyz" method="post">`

Pardot has a link explaining that I could use an IFRAME instead a Form Action to POST.

**Custom PHP Code:**

```
$name = [account:mail];
$FName = [account:profile-user:field-profile-last-name];
$LName = [account:profile-user:field-profile-last-name];
echo '<iframe src="http://go.pardot.com/5/38543/2014-03-31/xyz?name='.$name.'&FName='.$FName.'" width="1" height="1"></iframe>';

```

Any help?

# Answer
It seems the reason why was, that the Iframe was loading and then the page would redirect to wherever the onSuccess page would be set as. So this worked instead.

1- Created a module that hooked the `user_login(&$edit,$account)` function.

Within the function I defined my variables needed for the form handler, (this example will be email, first name and last name). In my case the First name and Last name were found in the Profile page so I had to get the Profile Id to find them.

```
$uid = $account->uid;
$mail = $account->mail;
$Fname;
$Lname;
$pid = db_query('SELECT pid FROM {profile} WHERE uid = :uid', array(':uid' => $uid))->fetchField();
$Fname= db_query('SELECT field_profile_first_name_value FROM {field_data_field_profile_first_name} WHERE entity_type = \'profile2\' and entity_id = :pid', array(':pid'=> $pid))->fetchField();
$Lname= db_query('SELECT field_profile_last_name_value FROM {field_data_field_profile_last_name} WHERE entity_type = \'profile2\' and entity_id = :pid', array(':pid'=> $pid))->fetchField();

```

2- After I used the `user_cookie_save(array())` function so I can send the info to the IFRAME after the page loads. (this is still in the user\_login function)

```
user_cookie_save(
      array(
        'pardotParams' => '?Email='.$mail.'&FName='.$Fname.'&LName='.$Lname.'&RequestUpgrade='.$RequestUpgrade.'&Serial='.$Serial.'&Industry='
        .$Industry.'&Country='.$Country.'&USFedOrg='.$USFedOrg.'&State='.$State.'&Company='.$Company.'&Phone='.$Phone ,
        'pardotUrl' => $url
      )
    );

```

3- Lastly, I added this bit of code in the page.tpl.php file found in my template. This will create the iframe off screen but still give it time to load.

```
<?php

  // Comparing the login time to the current timestamp to see if the user just logged in
  if (property_exists($GLOBALS['user'], 'login')
      && (time() - $GLOBALS['user']->login) < 5 ) {
    // Show the ParDot hidden iFrame. Added some css positioning to move the iframe off the screen
    // as it was throwing off the page alignment regardless of where it was shown in the template.
    echo('<iframe src="http://go.pardot.com/l/38912/2014-03-31/cz7' .
     $_COOKIE['Drupal_visitor_pardotParams'] .
     '" width="1" height="1" style="position: absolute; top: -999px; left: -999px;"></iframe>');
  }
?>

```
> 1 votes

---
Tags: rules
---


# Question
Title: Why do site visitors end up with two sessions after logging in?
I have an up and running Drupal 6.30 (latest) site, but some users are having problems logging in. This is due to the user having two rows in the sessions table, one for uid 0 and one for their uid (this one appears after logging in). The session for uid 0 should be removed from the database after authentication, but it is not.

**Question: How could a user end up with two sessions or why is the uid 0 not removed?**

Steps to repeat and further background:

1. Truncate sessions table
2. Delete all cookies in browser
3. Visit site homepage. This gets a new session for uid 0.
4. Login Successful login is seen in the watchdog table. uid x appears in the session table. The uid 0 session is not deleted, but I think it should be.

I believe that this causes the browser to send both sessions and Drupal only expects one, so if the uid 0 session is seen by Drupal then the request is seen to be from an anonymous user.

The user is redirected back to the homepage and is presented the login form again and is not logged in. Ironically, the user's name appears in the footer of the homepage as a logged in user.

Additional info: I managed to get some debug info from a user. After logging in the browser also has two sessions. Both have the same SESSxxxxxx name but different values. So it seems the old session is not being destroyed properly.

Full disclosure: I've posted this question on the Drupal Community Forum but haven't had any response after 48h, I hope it's ok to cross post it here.

# Answer
User always have one session at a time. Every time he logs in or out, new session is created.

Drupal 6 does not clean session table. I don't know if it is supposed to or not, but both my experience and simple Google search reveals it fails to do it.

So you have current session of an logged-in user, and outdated session data he left behind when he stopped to be anonymous.

If this really bothers you, consider moving sessions to APC or Memcached, it's much faster than database way, and unused data will be purged by the storage system even if Drupal will not trigger cleanup.

> The user is redirected back to the homepage and is presented the login form again and is not logged in. Ironically, the user's name appears in the footer of the homepage as a logged in user.

This behaviour I experienced only once - when database was misconfigured, and it reported inserts to session table as successful, but next request failed to read freshly inserted data. Apparently it was database caching, but unable to fix it, we ended up with sessions in RAM, as noted above.
> 1 votes

---
Tags: 6, users, sessions
---


# Question
Title: How to stop menu links being disabled after saving nodes?
A localised Drupal 7 site I'm working on has a navigation menu along the top. Each node is provided with a menu link with a given weight. Nodes are translated into three (non-English) languages (the admin language is English). The nodes show on the menu correctly depending on the current language.

Whenever I edit a node (eg edit the title, body) and click Save, its links disappears from the menu.

The same thing happens if I edit a node but don't actually change anything, then click Save.

I can re-enable it by:

1. Edit the node again
2. Untick the menu link
3. Save
4. Edit the node yet again
5. Tick the menu link (re-filling the title/weight)
6. Save again

Or:

1. Go to admin/structure/menu/manage/main-menu
2. All the other menu links are enabled, but the recently saved is not and has "(disabled)" after its name
3. Tick the box to re-enable
4. Save configuration

But how can I stop menu links from being disabled when a node is edited?

# Answer
It's a bug in the latest version 1.8 of i18n Martins Bertins' patch fixed this for me.

But its parent bug has been released in the latest dev version, and installing that fixed it as well.
> 1 votes

# Answer
Here's a quick fix:

1. Download version 1.7 of i18n.
2. Unzip it and find the folder named i18n\_menu
3. Go to your site's modules directory (could be /sites/all/modules/) Find the folder i18n
4. Replace the subfolder i18n/i18n\_menu with the version from version 1.7 you downloaded in step 1

You can also check this bug report: http://drupal.org/node/1905268
> 2 votes

---
Tags: 7, routes, navigation, i18n-l10n
---


title: Method to partially duplicate a node

text:
# Question
Title: Method to partially duplicate a node
What I need to do is save a node and then add another node that uses some of the data in the saved node. I have figured out how to add another button onto the form that will save the node first and then do something else.

In my form alter I have added a second submit button to the original form:

```
   // Check for a particular content type's node form.
   if (($form_id == 'content_node_form')) {

   $form['actions']['submit_another'] = array(
   '#type' => 'submit',
   '#name' => 'save_another',
   '#value' => t('Save, and Add Another Submission.'),
   '#submit' => array('node_form_submit','create_partial_duplicate_handler'),
   '#weight' => 20,
   );

   }  //endif

```

It saves the node then, runs another function that will load some information from the just saved node into a new node.

Should the create\_partial\_duplicate\_handler() function go to a menu item that calls another function or could I load the node form and the values directly in the function?

I have been reading lots of examples that create a menu item with a different url, but have not seen it done any other way. I don't want to waste time trying another method if the menu item method is the only way to do it.

Please let me know. Thanks.

ETA: I am using a second button because the user will have the choice of saving the node with the information entered into the form or saving the node and having another form appear with partial data from the saved node. The user enters the rest of the information into the partially filled form and again has the option of saving or saving and adding another.

# Answer
> 0 votes
I think there are no need of any menu or other submit button.

You can use hook\_node\_insert for create a different node form partial data of a node upon creation on node.

The statement is like:

```
function MODULENAME_node_insert($old_node) {

 if($old_node->type === 'article'){ // check node type

    $new_node_title =  $old_node->title; // get partial data from old node

    $node = new stdClass(); // We create a new node object
    $node->type = "page"; // Or any other content type you want

    $node->title = $new_node_title; // Assign partial data of old node to new node

    $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
    $node->path = array('alias' => 'your node path'); // Setting a node path
    node_object_prepare($node); // Set some default values.
    $node->uid = 1; // Or any id you wish
    // Let's add standard body field
    $node->body[$node->language][0]['value'] = 'This is a body text';
    $node->body[$node->language][0]['summary'] = 'Here goes a summary';
    $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

    $node = node_submit($node); // Prepare node for a submit
    node_save($node); // After this call we'll get a nid
 }

}

```

If this not fullfil your requirement then use some other HOOKS provided by Node API

---
Tags: 7, nodes
---


title: Drush Open-Source License

text:
# Question
Title: Drush Open-Source License
What open-source license is Drush licensed under?

I've checked GitHub including the README (https://github.com/drush-ops/drush/blob/master/README.md) and it isn't stated anywhere.

# Answer
The last version of Drush on drupal.org has a GPL v2 license in it. The license itself is not in the repository. Modules and themes on drupal.org automagically get LICENSE.txt added by the packaging script (the automated process that creates the tarballs and zips from central git repo).

This means that drush is technically still GPL v2, even though it doesn't have an explicit license in it. There is talk about relicensing drush, though.
> 2 votes

---
Tags: drush
---


# Question
Title: Keep custom theme when using AJAX submit
I am using the following code to switch to a custom theme based on the URL

```
function job_agent_custom_theme() {
  if (arg(0) == 'vista') {
    return 'vista';
  }
}

```

This works great and will switch to my "vista" theme when "vista" is in the URL. The problem is that one of my pages has a form that is submitted via AJAX. I created the form using the standard Drupal form API and creating my submit button like so

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('class' => array('submit')),
  '#ajax' => array(
    'callback' => '_display_form',
    'wrapper' => 'ajax_wrapper',
    'effect' => 'fade',
    'event' => 'click',
  ),
);

```

So the problem is that when I submit the AJAX form, the page switches to this weird hybrid of the default theme and my custom theme. It's like they are both loaded. Am I missing something? How do I preserve the custom theme when submitting an AJAX form. It also seems really weird to me that the entire page would refresh and switch to a different theme anyway. I would think that defeats the whole purpose of AJAX. I can understand the contents of my ajax\_wrapper changing, but not the entire page. Anyway, does anyone know of a way to preserve my theme when submitting via AJAX?

EDIT: Oh and I forgot a big piece to this puzzle. This ONLY happens with anonymous users. If I am logged in, it works as expected and when submitting the form, the custom theme is preserved, but if I am NOT logged in I get the mish mash theme.

THANKS

# Answer
> 1 votes
The form AJAX callback uses /system/ajax as the default. The menu router item for /system/ajax implements a theme callback to try and render the ajax contents in the same theme. For example, perhaps this is a node edit form and you have set node forms to use the same theme as the admin theme. The callback will find that. In your case, it is likely rendering in what it thinks is the default theme. Fortunately, you can specify your own ajax path like so:

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('class' => array('submit')),
  '#ajax' => array(
    'callback' => '_display_form',
    'wrapper' => 'ajax_wrapper',
    'effect' => 'fade',
    'event' => 'click',
    'path' => 'vista/system/ajax'
  ),
);

```

You'll then have to create a menu item for 'vista/system/ajax', which I guess would be a duplicate of 'system/ajax' without theme callback. Perhaps something like this:

```
/**
 * implements hook_menu
 */
function mymodule_menu() {
  $items['vista/system/ajax'] = array(
    'title' => 'AHAH callback',
    'page callback' => 'ajax_form_callback',
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE,
    // 'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
    'file path' => 'includes',
    'file' => 'form.inc',
  );
  return $items;
}

```

Don't forget to clear cache so the new menu item takes affect.

Also, I wanted to bring your attention to the ThemeKey module which is great way to change themes based on path.

---
Tags: forms, ajax, theming
---


# Question
Title: Would redirecting users in hook_menu's access callback have any undesirable effects?
This answer led to a discussion about the best way to redirect a user to a specific page if they shouldn't have access to the page they are trying to access.

One option is to set the access callback to true and then redirect users in the page callback. Whilst this seems valid I think it is mixing access functionality with page building functionality in the page callback.

E.g.

```
function hook_menu() {
    $items['player/my_page'] = array(
        'title' => t('My Page'), // note this is a required parameter
        'access callback' => TRUE,
        'page callback' => 'some_function',
    );
    return $items;
}

function some_function() {
    global $user;
    if(!$user->uid) { // here checking if the user is logged in but could be checking for a specific permission or field value
        $dest = drupal_get_destination();
        drupal_goto('user/login', $dest); // this remembers where the user is coming from
    }
    // carry on building rest of page
}

```

Another option is to set the access callback function to call a function that checks if the user has access, but then instead of returning false it would redirect the user to another page. This is good as it is separating access logic and page building logic. However the purpose of an access callback is to return a boolean value, so this is breaking that logic by redirecting the user.

E.g.

```
function hook_menu() {
    $items['player/my_page'] = array(
        'title' => t('My Page'), // note this is a required parameter
        'access callback' => 'check_access',
        'page callback' => 'some_function',
    );
    return $items;
}

function check_access() {
    global $user;
    // here checking if the user is logged in but could be checking for a specific permission or field value
    if(!$user->uid) {
        $dest = drupal_get_destination();
        drupal_goto('user/login', $dest);
    }
    return TRUE;
}

```

Are there any undesirable effects from redirecting users in the access callback that I'm not aware of?

What do you think is best practice here?

# Answer
> 6 votes
I think you could do this by altering the delivery callback function. If the access callback returns `FALSE` that's what's passed to the delivery callback. If you wanted this redirect behaviour just on specific pages you could modify the delivery callback just for those pages via `hook_menu()` or `hook_menu_alter()`. If you want the behaviour to be global, you can use a `hook_page_delivery_callback_alter()` to change it.

Here's an example delivery callback.

```
function custom_deliver_html_page($page_callback_result) {
  if ($page_callback_result === MENU_ACCESS_DENIED) {
    drupal_goto('<front>');
  }
  drupal_deliver_html_page($page_callback_result);
 }

```

Btw this is untested, and I've never actually altered the delivery callback myself previously.

# Answer
> 3 votes
I would not do it in the access callback. If another developer want to alter the `page_callback` at some point in the future, they will end up scratching their heads as to why the callback is not working when you are redirecting in access callback.

---
Tags: users, redirection, routes
---


title: Change data on form submit handler

text:
# Question
Title: Change data on form submit handler
I have a form alter handler like this.

```
function toyotaec_form_webform_client_form_seleccionar_alter(&$form, &$form_state) {
    $concesionarias = concesionarias();

    $form['actions']['submit']['#value'] = 'Enviar';
    $form['submitted']['concesionaria']['#options'] = $concesionarias;
    $form['#validate'][] = 'toyotaec_form_webform_client_form_seleccionar_validate';
    $form['#submit'][] = 'toyotaec_form_webform_client_form_seleccionar_submit';
}

```

Actually, this code is not a hook\_form\_alter but a function called by the actual hook. The hook calls this function passing &$form and &$form\_state also by reference.

After this, I have the corresponding handlers. Both handlers are called as expected. The handler I want to focus in is as follows:

```
function toyotaec_form_webform_client_form_seleccionar_submit(&$form, &$form_state) {
    $values = $form_state['values']['submitted_tree'];
    $input = &$form['submitted'];

    $concesionaria = trim($values['concesionaria']);
    $redirigir = trim($values['redirigir']);
    $modelo = trim($values['modelo']);

    //obtenemos cual es la concesionaria (por marca, descartamos las ciudades)
    $mconcesionaria = current(explode('-', $concesionaria));

    //las redirecciones diferidas van a tener una salvada incluyendo la url.
    //las redirecciones directas no van a tener salvada.
    $form_state['values']['submitted']['3'] = _redirect_bystore($mconcesionaria, $redirigir, $form_state, $concesionaria, $modelo);
}

```

For the last line, I also tried assigning $form\_state\['values'\]\['submitted\_tree'\]\['url'\]. This url field is the 3rd field and I have to keep track of it, but even when the data is stored in the array (confirmed by using `dpm()` on it), **the form result has a blank url field**.

For this, I'm using Webforms in Drupal 7.

My **question** is: how can I alter the submitted data? It seems that - for the submit handler - form state is not passed by reference.

# Answer
> 4 votes
You're *accepting* `$form_state` by reference, so the changes you make will definitely persist onto the incoming variable when your function loses scope. The variable/calling function doesn't control whether it's a reference here, your function signature does. The FAPI doesn't use the old pass-by-reference style (e.g. `foo(&$bar)`, which has been deprecated and removed), so you're in control of that.

Chances are the webform submit handlers are running before yours, so the changes you make aren't actually used by anything, despite being correctly added to the array.

To get around it, simply use a validate handler instead. This will run before the form submission, and changes you make to `$form_state['values']` will be available to the webform's submit handlers (as well as your own if you need to do extra processing).

I think you can probably use exactly the same code as in your submit handler.

---
Tags: 7, webforms, forms
---


title: 7 Increase the "Expires" header

text:
# Question
Title: 7 Increase the "Expires" header
I am trying to optimize a Drupal 7 site. I noticed the `Expires` header is set to just 6 hours, although according to my `.htaccess` file, it should be 2 weeks. Then i found out `mod_expires` module is not enabled. Now i have two questions:

1. Since i don't have the necessary rights, is there a way to set the `Expires` header without enabling `mod_expires`?
2. What is setting the header to 6 hours?

EDIT: Another strange thing is that the header is not there at all for some of the css files.

Also the settings in my `/admin/config/development/performance` is as follows, if related to this:

`Cache pages for anonymous users: checked
Cache blocks: checked
Minimum cache lifetime: none
Expiration of cached pages: 1 day`

# Answer
> 1 votes
Here is some boilerplate Apache rules I came up with for this question based off of the rules found in the advagg readme. The inverted files match is untested but based off this post: https://stackoverflow.com/questions/12926604/inverted-filesmatch; got what needed to be excluded by looking at core's .htaccess

```
<FilesMatch "(?<!\.php)$">
  # No mod_headers
  <IfModule !mod_headers.c>
    # No mod_expires
    <IfModule !mod_expires.c>
      # Use ETags.
      FileETag MTime Size
    </IfModule>
  </IfModule>

  # Use Expires Directive.
  <IfModule mod_expires.c>
    # Do not use ETags.
    FileETag None
    # Enable expirations.
    ExpiresActive On
    # Cache all files for 2 weeks after access (A).
    ExpiresDefault A1209600
  </IfModule>

  <IfModule mod_headers.c>
    # Do not use etags for cache validation.
    Header unset ETag
    <IfModule !mod_expires.c>
      # Set a Cache-Control header to 2 weeks.
      Header set Cache-Control "max-age=1209600, no-transform, public"
    </IfModule>
    <IfModule mod_expires.c>
      Header append Cache-Control "no-transform, public"
    </IfModule>
  </IfModule>
</FilesMatch>

```

In your case the best you can do is to use ETags.

Note: If you happen to be serving all you static file assets from a CDN then you could enable far-future headers in the CDN module. Doing it this way will route almost all static file traffic through PHP (on a origin request) so it can be extremely damaging to the sites performance if you are not using a CDN.

---
Tags: 7, caching, .htaccess
---


# Question
Title: Limit taxonomy terms that can be selected to 2nd level terms only?
Is it possible to limit taxonomy terms that can be added to a node to 2nd level tags only?

So if my taxonomy is as follows:

Open

-forum1

-forum2

Closed

-forum3

-forum4

How can I limit the selections to forum1, forum2, forum3 and forum4, and exclude Open and Closed?

This may need to be a separate question but I also need to limit tags that can be created to 2nd level only. So a new tag would need to be a child or either Open or Closed. Thanks

# Answer
> 2 votes
One way would be to install the Hierarchical Select module which gives you the option to limit selections to lowest-level terms only:

The module overrides the default widget for the hierarchy on the default taxonomy page as well, so it might even take care of your second question for you (although I haven't tried that myself before).

# Answer
> 1 votes
A simple module that does that exact thing is Taxonomy container. Once enabled, change the widget type for your taxonomy field to `Select list (with groups)`. The module will use `OPTGROUP` tags to list the top-level taxonomy terms. See the screenshot for an example.

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


# Question
Title: Is Migrate module supposed to be used for imports too?
I am in need of an entity import functionality so I started to write my own. But then I started to think if I'm not reinventing the wheel and it occurred to me that maybe Migrate module will be used for this(beside it's main purpose)?

I mean, since all entity fields are objects with their own specifications regarding data they work with, Migrate will probably handle all of this. So am I correct to assume this or should I continue to work on my module? Because right now I started to think about the field objects(FieldDefinition for core fields and FieldInstanceConfig for field API fields) and I would need to write a lot of data handlers for each type of field and data-type it's working with(boolean, text, file/image, float,...) which will be a lot of work.

On the other hand Migrate would probably have all this data-handlers already in place so they could be reused?

---

By entity import I mean creating data from csv, xls, xml... files.

# Answer
Of course! That's why we split migrate\_drupal and migrate. The latter is the API, it has the destinations, like the entities you are asking for. Handbook page is at https://drupal.org/node/2127611 useful article at http://webikon.com/cases/migrating-to-drupal-8
> 1 votes

# Answer
Also github.com/larowlan/default\_content for module provided entities
> -2 votes

---
Tags: entities, importing-exporting, 8
---


# Question
Title: How to set the default values of "Included Export Components" for a Drupal Webform
I'm trying to figure out how to set the default values of the Webform Results \> Download \> Included Export Components Field to exclude certain fields.

The webform module defaults to a state for that field in which all the webform's fields are checked. They can be manually unchecked before each download but we've run into a business requirement by which we would require 3 fields (IP Address, Draft, and UID) to be unchecked on the page load.

I've looked through the configuration pages for the webform module and for the specific webform node and have come up empty handed. I've considered writing an additional module which will override the module which sets the checkboxes. Before I went that route though, I was wondering if anyone has dealt with this requirement before and/or can share some insight/point me in the right direction.

Thanks!

# Answer
> 3 votes
I remember having to do that once, and though I looked at how the values were initially set, I still ended up using hook\_form\_alter to change them. I don't remember why exactly, but presumably due to fact I couldn't reach them as easily.

Just use a hook\_form\_alter in a custom module to get to the form, and unset the defaults you don't want.

This should pretty much do it in a hook\_form\_alter or hook\_form\_ID\_alter ( example is for hook\_form\_alter ) :

```
if ($form_id == 'webform_results_download_form') {
  /**
  * default ( and named ) components are :
  * - serial: Submission nr
  * - sid: Submission ID
  * - time: Time
  * - draft: Draft
  * - ip_address: IP Address
  * - uid: User ID
  * - username: User Name
  */
  $excludes = array('serial', 'sid');

  foreach ($form['components']['#default_value'] as $cid => $component) {
    if (in_array($component, $excludes)) {
      unset($form['components']['#default_value'][$cid]);
    }
  }
}

```

This will uncheck both the Submission Nr & Submission ID checkbox. Adjust the `$excludes` array accordingly to your needs

---
Tags: webforms, importing-exporting
---


# Question
Title: Why use constuctor injection in controllers or forms?
Documentation is proposed to use injection in constructor instead of using `\Drupal::service()`. Why?

Example with injection:

```
class MyController extends ControllerBase implements ContainerInjectionInterface {
  protected $database;
  public function __construct(Connection $database) {
    $this->database = $database;
  }
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }
}

```

Example without injection (it is easier):

```
class MyController extends ControllerBase {
  protected $database;
  public function __construct() {
    $this->database = \Drupal::service('database');
    // or
    $this->database = \Drupal::database();
  }
}

```

# Answer
As soon as you start to test MyController you will run into problems

The test harness must be able to instantiate the minimum amount of stuff around your class to still be able to put it through its paces.

It is easier to mock up and inject a simple container.. rather provide \Drupal::service as it will rapidly spiral out of control and your test harness will have to provide a full drupal environment.

In more formal language you have just "tightly coupled" MyController to the drupal eco-system, and so you have made your code less reusable.
> 1 votes

---
Tags: 8
---


# Question
Title: How to display the average rating of a node as stars in a view?
The users on my website can rate an article with the Fivestar module while they comment. I'd like to create a view with the 5 articles that have the highest average score.

I've nearly been able to achieve what I want with a 'Vote results' relationship and a 'Vote results: Value' field. The problem is that the average score is displayed as a number, but I'd rather like it to be shown as stars. I achieved this in the past without custom coding (thanks to a deleted video that was situated here), but I forgot how to do it.

Can you help?

# Answer
> 0 votes
I finally rediscovered how I achieved this in the past. First, follow each step in this article and call the Fivestar field 'Stars'. Next, import the following view:

```
$view = new view();
$view->name = 'best_content';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Best content';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'node';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['required'] = TRUE;
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'percent',
  'tag' => 'vote',
  'function' => 'average',
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Field: Stars */
$handler->display->display_options['fields']['field_stars']['id'] = 'field_stars';
$handler->display->display_options['fields']['field_stars']['table'] = 'field_data_field_stars';
$handler->display->display_options['fields']['field_stars']['field'] = 'field_stars';
$handler->display->display_options['fields']['field_stars']['label'] = '';
$handler->display->display_options['fields']['field_stars']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_stars']['click_sort_column'] = 'rating';
$handler->display->display_options['fields']['field_stars']['settings'] = array(
  'widget' => array(
    'fivestar_widget' => 'sites/all/modules/fivestar/widgets/basic/basic.css',
  ),
  'expose' => 0,
  'style' => 'average',
  'text' => 'none',
);
/* Sort criterion: Field: Stars (field_stars:rating) */
$handler->display->display_options['sorts']['field_stars_rating']['id'] = 'field_stars_rating';
$handler->display->display_options['sorts']['field_stars_rating']['table'] = 'field_data_field_stars';
$handler->display->display_options['sorts']['field_stars_rating']['field'] = 'field_stars_rating';
$handler->display->display_options['sorts']['field_stars_rating']['order'] = 'DESC';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

```

Done!

---

PS: This comment might explain why this didn't work before.

# Answer
> 0 votes
This is what I came up with:

Create a Views template for this specific field and put it in your theme (or module if you have Views templates already there and enabled via the Views api hook).

In my case it was called `views-view-field--top-content--page-1--value.tpl.php` for just the included and now enabled top content View.

In there, do the following:

```
<?php
  $data = $row->{$field->field_alias};
  $path = drupal_get_path('module', 'fivestar');
  print theme('fivestar_static', array('rating' => $data, 'widget' => array('name' => 'basic', 'css' => $path . '/widgets/basic/basic.css')));
?>

```

And if all is well in the world of copy and paste, you should now have a View with basic stars displayed instead of the number. If you don't like the basic stars, just look in the widgets directory and you can take your pick of any of the other styles there.

---
Tags: 7, views, rating
---


# Question
Title: Horrible permissions bug, anonymous users can edit products
I have a Drupal Commerce site. I'm using `Content Access` to only allow users with the role "Vendor" to "Edit own product." Nobody else is allowed to edit any products. This is the only module I'm using afaik that controls permissions.

And yet.... **everybody** is able to edit **all** products! Even guests! This bug is horrifying.

I've tried

* clearing all caches
* emptying the node\_access DB table
* Rebuilding permissions from the status report
* completely disabling editing products for anyone
* disabling and uninstalling the Content Access module

Here is my access control for the Product content type (it was originally called Produce, hence the machine name being `produce`)

And yet when I go to view a product, even as an anonymous guest, it shows the "View" and "Edit" tabs. And when I click "Edit" I can actually change the content and save the node!

One node example is node id 78. If I look at the `node_access` table in the DB, it shows this:

```
nid   gid   realm   grant_view   grant_update   grant_delete
78    0     all     1            0              0

```

If rebuilding permissions doesn't work, disabling Content Access doesn't work, then.... I have no idea where to go from here.

**Update**

I've installed Devel and am checking which modules implement `hook_node_access`

```
$ drush fn-hook node_access
Enter the number of the hook implementation you wish to view.
 [0]  :  Cancel
 [1]  :  commerce_marketplace
 [2]  :  node
 [3]  :  features

```

# Answer
Node access rights can be a little hard to debug. You need to enable the Devel module, and the Devel Node Access submodule.

Then goto your block configuration. There will be two new blocks: Devel Node Access and Devel Node Access By User. Add these to your page, and configure them for your admin role(s). Also goto the Devel settings (admin/config/development/devel) and enable Devel Node Access debug mode.

Then visit a page with access problems. Look at the debug info.

The Devel Node Access block will show you the `{node_access}` rows for the node in question.

The Devel Node Access By User block will show you who has permission to do what, and why.

Then you need to do some sleuthing. If it is a permission, then you need to find that permission and edit it. If it is a `hook_node_access()`, then you need to find the module that is implementing it. If it is a grant, then you need to use the realm/gid and track down who is implementing a `hook_node_access_records()` with that pair.

The `module_implements()` function can be used to track down who is implementing what. I typically do this with

```
drush php-eval 'print_r(module_implements("node_access"))';
drush php-eval 'print_r(module_implements("node_access_records"))';

```

My *guess* is that one of your features has a rogue `hook_node_access()` in it. You could also try disabling your features one by one and seeing what happens.
> 4 votes

---
Tags: users
---


title: How to undo the achievement of a goal?

text:
# Question
Title: How to undo the achievement of a goal?
I have 2 goals on my website: 'Published 1 article' and 'Published 2 articles'. I have according rules that record the tasks for these goals when new content is published by a user.

Now, assume that a user published exactly 2 articles. That means he/she completed 'Published 2 articles'. How can I undo this goal (programmatically) when one of his/her articles are removed?

PS: I've already found this post, but as there aren't any answers, it wasn't that helpful... :)

# Answer
Unfortunately, this isn't possible yet. A request has been made here. Hopefully, the maintainers will provide this feature in the future.

If someone gives a working solution later on, I'll mark it as answer instead.
> 0 votes

---
Tags: rules, 7
---


title: How do I define a JavaScript library?

text:
# Question
Title: How do I define a JavaScript library?
In Drupal 8 some JavaScript changes were introduced: All JavaScript scripts should be defined using `hook_library_info()` and added to the page only with `#attached` attribute of the render array.

What should I do to define external libraries? Should I create a *libraries* directory and upload the library there, or should they be managed by the module using Composer?

# Answer
Since you posted this question, hook\_library\_info was replaced with \*.libraries.yml files.

An example of a simple library declaration looks like this:

```
jquery.form:
  remote: https://github.com/malsup/form
  version: 3.39
  js:
    assets/vendor/jquery-form/jquery.form.js: {}
  dependencies:
    - core/jquery
    - core/jquery.cookie

```

Once declared, this library can be attached to a render array like this:

```
$element['#attached']['library'][] = 'core/jquery.form';

```

Now Drupal should take care of adding the library and all required dependencies to the page. Even though the library declaration can contain a remote url, Drupal will not automatically download the library for you.

If I'm not mistaken, you will always need a module or a theme with a .libraries.yml file to act as the provider of your library. However a module can be really simple, you only need a .info.yml file to declare a module.
> 3 votes

---
Tags: javascript, 8
---


# Question
Title: MigrateSQLMap with multiple same-name source keys?
I'm using migrate module 7.x-2.5 with a MySQL source database. My records are defined by the intersection of two tables, so I need two keys in my $source\_key parameter to MigrateSQLMap(). I've done this before, no problem. But in this case, the columns have the same name, both "id". Because the column name is used as the key in the $source\_key array, the second "id" would replace the first "id".

I tried defining an alias for one of the columns with addExpression() and using the alias (type\_id) as one of the keys. This correctly registers multiple source keys and shows the correct record count on drush ms, but fails on drush mi with a SQL error: "Column not found: 1054 Unknown column 'type\_id' in 'on clause'".

In the short term, I can just create a new column in one of the tables and duplicate the "id" values, but I'd like to know if there's a way to do this entirely in migrate code without altering the source database.

# Answer
> 0 votes
I'm not aware of a solution without altering the source database -- although there are in my opinion clean ways of altering the source DB; and it's not a ton of code:

In either your migration module hook\_install() function or a pre/post Import hook call (https://drupal.org/node/1343112) simply using a custom db\_query() such as:

```
db_query("CREATE TABLE foo LIKE other_table; INSERT INTO foo FROM (intersection query); ALTER TABLE foo (change id to type_id);");

```

You can drop/recreate the table as apart of a pre/post import call.

You just have to get the SQL right and it's all of 3 SQL statements, and 1 or 2 Drupal hook functions to make it all repeatable using Migrations.

---
Tags: 7, migrations
---


# Question
Title: Programmatically printing from field_collection array
Is there any simple way to print a certain number of elements from a field collection?

Say I have an array of 8 elements and want to just print 4 at the top of a page; then, print the other 4 at the bottom.
Right now I'm attempting it in the node.tpl I am theming.

```
print render($content['field_my_elements_of_whatever']);

```

# Answer
You can use Entity View Modes to solve the first part.

Install/enable the module, then configure some new view modes for field collections.

Then, goto the Field Collections config, and do the Manage Display for your collections. Configure the new view mode(s).

Now, goto the Manage Display for your nodes. Click the settings gear for the field collection field, and choose your view mode.

That should set you up for your second part, which is rendering out a field twice. There are several ways to do this, like this and this. You would just need to make sure your duplicated field uses your other view mode.
> 1 votes

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


title: 404 Not Found Error

text:
# Question
Title: 404 Not Found Error
I am trying to transfer my drupal 7 website from share-hosting to VPS. If I do a fresh install of drupal on my VPS everything works fine, but as soon as I upload/migrate my database, the front page works fine, but if I click on any link on my website I keep getting this error. For example if I click on login I get:

> 404 Not Found
>
> The server can not find the requested page:
>
> xx.xxx.xx.xxx/~xxx/user/login (port 80)
>
> Please forward this error screen to XX.XXX.XX.XXX's WebMaster.

# Answer
> 2 votes
I found the answer over at StackOverflow https://stackoverflow.com/questions/13280015/apache-404-error-drupal

All I had to do was add `RewriteBase /~YourCpanelUserNameGoesHere` into the .htacess file

---
Tags: migrations
---


# Question
Title: Version 5.9: Which components does "drush site-alias --local" look for in ~/aliases.drushrc.php?
In version 5.9, "drush site-alias --local" returns what I consider to be non-local sites, because they each have a remote-host and a remote-user component set in ~/aliases.drushrc.php.

I don't understand part of this excerpt from "drush help site-alias":

--local Only display sites that are available on the local system (remote-site not set, and Drupal root exists).

What does "remote-site" refer to -- some other component in ~/aliases.drushrc.php?

Thanks,

Glo

# Answer
> 1 votes
The filtering is done in the `_drush_sitealias_user_specified_list()` function with

```
if ((array_key_exists('remote-site', $one_site)) || (!array_key_exists('root', $one_site)) || (!is_dir($one_site['root']))) {
  unset($site_list[$site_name]);
}

```

So it looks like the `remote-site` option is used. But the documentation for the alias settings does mention a this option. So this looks like a bug.

Note: the same condition is still used in the latest version (see https://github.com/drush-ops/drush/blob/master/commands/core/sitealias.drush.inc#L164).

---
Tags: drush
---


title: How to add RDFa to fields in a view?

text:
# Question
Title: How to add RDFa to fields in a view?
I have installed a Drupal 7 views module called Islandora Solr Views and I can create views from the Islandora solr search results. My next goal is to add some semantic data to these fields but after searching around several days, I still can't find a way to do that.

At the moment the HTML for one of the fields look like this:

```
<div class="views-field views-field-mods-name-Author-ms">
  <span class="views-label views-label-mods-name-Author-ms">Author: </span>
  <span class="field-content">Mr LLoyd Marshall</span>
</div>

```

I want to add the following RDFa data the to the field:

```
<span property="dc:creator" href="http://www.example.com/people/R12345">
    <span vocab="http://xmlns.com/foaf/0.1/" typeof="Person"
             about="http://www.example.com/people/R12345">
        <span property="name">Mr LLoyd Marshall</span>
    </span>
</span>

```

Is there a module to do that? If not how should I go about achieving this?

According to the post *Allow custom attributes on Semantic Field wrapper tags*, I wonder if there is a module to do this at the moment.

# Answer
> 0 votes
Look at the Fences modules to change the output of a field to a span as you have here. Then use https://drupal.org/project/semanticviews to wrap the span field with semantic markup. I'm on my phone gluck

---
Tags: 7, views, rdf
---


# Question
Title: Views show table of titles of last nodes for each content type
I want to show a table (using views) displaying a list of the last node (latest pub date) for each content type.

Any ideas?

# Answer
Use a View and code to embed that View for each content type.

To get the same View as what I created, import the View I've pasted here: http://pastebin.com/2xQx7BPs

Instead of having anything hardcoded, you can achieve this as follows:

## Quick and Dirty

* Enable the "PHP filter" module.
* Create a Basic Page.
* Use "PHP code" as the Text format in a Basic Page with this Body

Paste this:

```
<?php
    $content_types = node_type_get_names(); // get all content types
    $ct_machine_names = array_keys($content_types); // we just need machine names
    foreach ($ct_machine_names as $ct_name){ // loop through, adding them as an argument to the View
      echo views_embed_view('latest_node_by_type', 'block', $ct_name);
    }
?>

```

## Proper Way

There are a few ways to achieve this instead of using the "PHP filter". Using a custom block in your own module isn't difficult. My favorite resource that explains this is located here: http://kahthong.com/2013/06/create-your-own-custom-drupal-block-programmatically

Follow the directions, and replace the last block with something like this:

```
<?php
    function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
      $output = '';
      $content_types = node_type_get_names(); // get all content types
      $ct_machine_names = array_keys($content_types); // we just need machine names
      foreach ($ct_machine_names as $ct_name){ // loop through, adding them as an argument to the View
        $output .= views_embed_view('latest_node_by_type', 'block', $ct_name) . '<br/>';
      }
      return $output;
    }
?>

```
> 1 votes

# Answer
Just create a view, add the "Node: Title" Field and sort your nodes by date added.
> 0 votes

# Answer
1.) In your views Fields include content type
2.) Then set Format as Table and group them by content type
3.) Sort them by date desc
4.) on Pager select "Display a specified number of items" and enter 1 for it to show only 1 link for the node

That should be it..
> 0 votes

# Answer
You can achieve this by using aggregation. In the views edit screen (considering you have already configured your content type filters and fields), look under advanced (right side). Near the bottom of the list locate "aggregation:No", set it to yes. Go back to your fields and change aggregation settings according to your needs.
> 0 votes

# Answer
Use attachments. Create a view display that shows only 1 of a certain content type. Create 2 more attachment displays, using the same settings but change the content type on each one to whatever you need, then attach those to the original display.
> 0 votes

---
Tags: 7, views, css-js-aggregation
---


title: How can I redirect properly?

text:
# Question
Title: How can I redirect properly?
Long story short I replaced an outdated site with a Drupal site at its previous url, let's say oldsite.org. But the old site was also accessed from oldsite.org/THIS, I think because it was a subdirectory of a larger site or something. But there are old links around that use oldsite.org/THIS and we want those to go to the homepage of the new site.

What is the proper Drupal way to do this redirect? I have thought of a handful of possible hacks, but I want to do it right. Maybe a small module to handle the redirect. Or even htaccess somehow?

# Answer
**301 redirects** are considered the best way to handle redirected pages, for they inform search engines to update their databases with the new paths. Edit your .htaccess file in a text editor. \[Note: Be sure to save the file in "UTF-8" format.\]

In the file, you will find the commands:

```
# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  # Modify the RewriteBase if you are using Drupal in a subdirectory and
  # the rewrite rules are not working properly.
  #RewriteBase /drupal
RewriteBase /

```

Immediately after that code -- and before the Drupal-provided "Rewrite old-style URLs" commands -- add your rewrite rules using the following format:

```
#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects

```

For detailed discussion https://drupal.org/node/38960
> 2 votes

# Answer
You can use Redirect module for this. You can set redirection path with status such as 301 etc..

For `.htaccess` redirect, you can take help from this documentation.
> 1 votes

---
Tags: redirection
---


# Question
Title: How to convert a unix timestamp field in views
I'm keeping a Unix timestamp in a text field. In Views, I want to convert it to a readable date. This is a commerce view, and the field is a custom field of an order.

Can I use hook\_field\_formatter\_view() to use as my own formatter? Something like:

```
function mymod_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    if ($entity_type == 'commerce_order') {
          // figure out field type and instance
    }

```

}

If that is a way to do it, I want to look at the params through Devel, so what can I return until I'm ready to operate on them?

# Answer
You can use hook\_views\_pre\_render to change the output of your field..

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.
>
> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after. Altering the content can be achieved by editing the items of $view-\>result.

```
function MYMODULE_views_pre_render(&$view) {

   if ($view->name=='viewyouarelookingfor') {

      // do whatever you want

   }

 }

```
> 2 votes

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


# Question
Title: Drupal 7, Is there a module that detects file structure changes?
Recently one of my clients sites was hacked and hackers uploaded a few directories and files into the web root folder.

I'm looking for a module or a method that has the ability detect file structure changes in the web root of drupal and any sub folder. In the end I want it to be able to email me when files get added or directories get made.

# Answer
> 5 votes
There is quite a few:

I've included those abandoned and seeking new maintainers, in case you want to revive them or use them as starting points for your own project.

However, as noted by *Clive*, this is easier to set up and maintain outsite of Drupal. Here is a broad outline of what you need:

First, recursively run through every file and sub-folder on the server within the current directory of the script and generate a file containong the "master" hash for each. Repeat this whenever you update your site by installing new modules, etc. or updating old ones.

Create a script (in your favourite scripting language) to do the following, and activate it with cron at regular intervals. Make sure that it is not remorely executable (store it outside the web root).

1. Load configuration file (list of files to exclude from scan, etc.)
2. Recursively run through every file and sub-folder on the server within the current directory of the script.
3. Generate a hash for each file and compare with the master hash
4. Alert (e.g. by email) if different.

Based on: How to detect if your webserver is hacked and get alerted. They also have a script (*WebsiteCDS*) that does this taht you can download. I haven't used it, and can't vouch for the quality of their code.

# Answer
> 4 votes
I prefer using git for that task.

Simple way is to:

```
cd /whatever/your/drupal/directory/is
git init
git add .
git commit -m 'Initial commit'

```

Then, in system's CRON, add

```
git add . #To add files that appeared in the meantime
git commit -a -m 'Nightly commit' # -a to  automatically stage files
                                  # that have been modified and deleted

```

And you're done. You might need to investigate `--git-dir` and `--work-tree` options to make git work in scripts, but it's not hard.

That's it. It will scan, record changes, and to add to that, it will allow you to rollback whatever you need to have rolled back, if something will go awry. And you can use git hooks to mail you the list of changes. It is described in many places, like here and here \- but this is a bit out of the scope of Drupal Answers.

---
Tags: 7, security
---


# Question
Title: How to wrap first word of page title in span in drupal 7
I want to implement it with theme\_preprocess function. Every my attempt fails.

```
function mdrupal_mono_preprocess_page(&$variables) {
  $variables['title'] = drupal_get_title($variables['node']);
  $title = $variables['title'];
  if($title) {
    $words = explode(' ', $title);
    $words[0] = '<span>' . $words[0] . '</span>';
    $title = implode(' ', $words);
  }
}

```

# Answer
> 1 votes
in my case this is working perfectly in `bartik_preprocess_page()` (bartik theme):

```
  $pageTitle = drupal_get_title();
  $pageTitleArr = explode(' ', $pageTitle);
  $firstPart = '<span>' . $pageTitleArr[0] . '</span>';
  $pageTitleArr[0] = $firstPart;
  $title = implode(' ', $pageTitleArr);

  drupal_set_title($title, PASS_THROUGH);
  $variables['title'] = $title;

```

# Answer
> 1 votes
Not really a Drupal question, but you're setting the wrong variable

```
$title = implode(' ', $words);

```

should be

```
$variables['title'] = implode(' ', $words);

```

Or, change

```
$title = $variables['title'];

```

to

```
$title = &$variables['title'];

```

instead. Either will work

# Answer
> 1 votes
You can add some `pseudotags` like `[span]` or `[i]` in your node title and can use below `function` in your `template.php` file.

```
function bb2html($text) {
  $bbcode = array(
                  "[strong]", "[/strong]",
                  "[b]",  "[/b]",
                  "[u]",  "[/u]",
                  "[i]",  "[/i]",
                  "[em]", "[/em]"
                );
  $htmlcode = array(
                "<strong>", "</strong>",
                "<strong>", "</strong>",
                "<u>", "</u>",
                "<em>", "</em>",
                "<em>", "</em>"
              );
  return str_replace($bbcode, $htmlcode, $text);
}

```

You need to use `<?php print bb2html($head_title); ?>` in your `page.tpl` file.

For more reference, you can check this.

---
Tags: theming
---


# Question
Title: Rewrite the field label text on node dispaly
I created a content type. In the content type I have field called ingredients. Machine name is "field\_ingredients".

When a user see the output of the node (not in form and not in views), the label is: "ingredients:". I want the remove the ":" or even change the label to something else.

How can I do that?

I tried the "preprocess\_node" function, but it didn't succeed.

# Answer
You need to override field.tpl.php to do this (the colon is hard coded into that template file).

Create field.tpl.php anywhere in your theme folder, copy the code from the above link into it, tweak it (remove the colon etc), then clear your caches: all will be well!

I found Answer from Here
> 1 votes

---
Tags: 7, entities
---


title: Keep left menu in every event node

text:
# Question
Title: Keep left menu in every event node
I created the event calendar using calendar view module. suppose If I click the particular event in calendar it will goes to particular event detail page but suddenly the left menu is disappear. How do I keep my left menu in all the event details pages?

Please assist me on this

# Answer
You can use the Context module to set the block active on content types and url wildcards (ex. /event/\*). There are also much more conditions available with Context.
> 1 votes

---
Tags: views, 7
---


title: How to clone regions from panel?

text:
# Question
Title: How to clone regions from panel?
Is it possible to copy (clone) regions (or at least blocks) with their settings from one panel to another panel? I have two different panel pages, but some of the regions are the same in both panels. Could I just set such common regions once and then "copy" them to another panel?

thanks for advice Tomas

# Answer
> 2 votes
Panels supports cloning/exporting the whole panel page, as well as individual page variants. It doesn't support cloning/exporting individual content panes (afaik)

However, you could potentially do it manually manipulating the panel export code.

e.g:

* Export source page with new panes to clone
* Copy desired pane definition from code export
* Export target page to save into
* Copy pane definition back into the desired section of the export code
* Reimport the exported target page.

Manual, but something like that would work. You could also do it programmatically with the ctools/panels api.

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


# Question
Title: use xmlrpc to authenticate and create a node via services module 3.x and drupal 7
I want to use services module 3.x, drupal 7 and xmlrpc to create a node from a php client. However, I don't know how to deal with the authentication. I enable the session authentication but I don't know what I should do and I get error: HTTP/1.0 401 Unauthorized: Access denied for user anonymous.

ps: I can get session name and session id from user.login

# Answer
> 1 votes
Note: this is valid after SERVICES 3.5 (lower version are deprecated, anyway)

```
// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

// GET TOKEN
$token = xmlrpc(url($this->endpoint, array('absolute' => TRUE)), array('user.token' => array()), $this->headers);

//INSERT TOKEN INTO HEADERS
$options['headers']['X-CSRF-Token'] = $token['token'];

```

At this point you should be authenticated and could create nodes at will.

# Answer
> 0 votes
Please go through the below given link and I am sure it will help

How do I POST a new node using the Services module?

Before doing please read https://drupal.org/node/1354202 Services 3 - POST node.create with custom fields ...test your services first on various tools. link browser add-ons and other apps. after that you can use this services in any flatforms like PHP, JAVA ....etc

# Answer
> 0 votes
As you said After logging in using web service ,you are getting a response with session name and session id.For making a request to create a node ,you should specify the session name and session id in the header of the request. The session name and id are used for authentication,If it does not match with the current session,then you will not be authorized

---
Tags: 7, services
---


# Question
Title: URL to access a private file within Drupal 7
I want to be able to have my Drupal 7 site allow both public and private downloads (see below configuration screen shot).

>

It appears that the private directory at: sites/default/files/private is preventing direct access to the files which is what I want and is allowing direct public access to the files within: sites/default/files which is also what I want.

My question is what URL do I use to call the private files so that my function hook\_file\_download($url) it called and then can decide based on a combination of the directory within the /private directory and the requesting users role whether they have access to view this file?

# Answer
> 1 votes
The function you want to use is file\_create\_url().

You pass a stream wrapper path to your file, in this case it starts with 'private://'.

The value that you pass to the function is 'private://relative/path/to/file.txt'.

The relative path is based on the private files folder.

# Answer
> 1 votes
You can not downlaod the files directly via URL, when files is in private directory structure, This module will help you provide the permission to users to download the private files, hope this will help! https://drupal.org/project/private\_files\_download\_permission

---
Tags: files
---


title: hook_form_FORMID_alter not working

text:
# Question
Title: hook_form_FORMID_alter not working
```
function send_xml_form_user_profile_form_alter(&$form, &$form_state){
    $form["#submit"][] = 'send_xml_edit_account_submit_function';
    drupal_set_message('<pre>' . print_r($form['#submit'], TRUE) . '</pre>');
}

function send_xml_edit_account_submit_function($form, &$form_state) {
    drupal_set_message(t("ahoy"));
}

```

the modules name is `send_xml.module`.

this code `drupal_set_message('<pre>' . print_r($form['#submit'], TRUE) . '</pre>');` displays

```
Array
(
     [0] => user_profile_form_submit
     [1] => send_xml_edit_account_submit_function
)

```

but this code `drupal_set_message(t("ahoy"));` isnt displaying...

anyone ring a bell?

it's quite annoying to have problems which you cant find the reason why... does anyone experience this before? if yes, would please so kind to share your solutions to me. thank you very much! :)

# Answer
> 0 votes
Can you try

```
function send_xml_form_user_profile_form_alter(&$form, &$form_state, $form_id){
    $form['actions']['submit']['#submit'][] = 'send_xml_edit_account_submit_function';
    drupal_set_message('<pre>' . print_r($form['#submit'], TRUE) . '</pre>');
}

```

Try clearing Drupal cache before you see the changes..

# Answer
> 0 votes
There are many ways to fix this problem @Anil sagar has aslo gave the right answer. Another approach you can take is :

```
/**
 * Implements hook_form_alter().
 */
function send_xml_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_profile_form') {
          $form['#submit'][] = 'send_xml_edit_account_submit';
   }
}

function send_xml_edit_account_submit($form, &$form_state) {
    print '<pre>';print_r($form['#submit']);  die;
}

```

Do not use ***function*** keyword in a declaration of **function** on send\_xml\_edit\_account\_submit\_**function**

Try it, I tried its works for me.

---
Tags: hooks, forms
---


# Question
Title: Random default image for a CCK image field
Is it possible to use a random default image for a CCK image field, if the user doesn't provide an image?

# Answer
Module called image field random does the job you specified.

> Description:
>
> Populates an image field with a random image on save.
> 2 votes

# Answer
CCK imagefield provides settings to have a default image when user doesn't provide any input image. Checkout page `admin/content/node-type/[my-content-type]/fields/[my-image-field]`, `Default image` fieldset.

For random images check devel generate module.
> 1 votes

# Answer
The module that implements that CCK field has a setting for the default image to use for the field, but it's not randomly chosen; the image will be the same, when the user doesn't provide an image.
As far as I know, there aren't modules that alter the settings of ImageField, and add a "Use a random image" option.
> 1 votes

# Answer
You could configure this with a view and some node template changes.

Set up a view for the random image display with sort \> global \> random

Have the view choose from a library of images

Have node template check if the user uploaded a file for the imagefield; if so, it prints the image; if not, if prints the view:

```
<?php if (field_imagefield_name[0]['view']): ?>
    <?php print field_imagefield_name[0]['view'] ?>
<?php else: ?>
    <?php print views_embed_view('random_image_view_name','view_display') ?>
<?php endif; ?>

```

However, the random global display does not work with page caching turned on (at least in D6), so you may instead want to use a views slideshow that does not rotate, but does display a random image each time the page is loaded (those are all settings within views slidehow). That should work with page caching.
> 0 votes

---
Tags: entities, media
---


# Question
Title: How can I let users rate content with half stars in Fivestar?
This is a quite regular feature request on the Drupal website (see for example this article), but there hasn't been provided a full answer anywhere and the answers only cover Drupal 6.

Instead of rating content with whole stars, I'd like my users to be able to vote with half stars (0.5, 1, 1.5, 2, etc.). On my website, voting on nodes happens via comments.

How can I achieve this? Which CSS and/or PHP changes do I eventually have to make to the Fivestar module?

# Answer
I've written a module that alters the fivestar module to allow halfstar voting:

Halfstar

After installing the module an option is added to the field instance setting form allowing half star voting:

Which then allows voting with half stars:

There is a rounding bug that occurs occasionally at the moment when using the *Stars (rated while editing)* widget. If you have 9 stars and then vote 5.5 is display as 5.6.
> 7 votes

---
Tags: 7, rating
---


# Question
Title: Views format: faster fields or rendered entity?
I'm building some views that returns many content types that have different fields, so I'm choosing to display results as "rendered entity" instead of "Fields". I would like to know if there are perfomance reasons to use fields or rendered entity.

# Answer
If you are able to cache the views output, you should not need to think about that problem. If it is not cachable:

I would say rendered entity will cause more overhead due to rendering each field of the content you selected while with fields you could limit it to the needed fields. If rendered entity and fields equal, I would go for rendered entity with display suite.

For actual performance benchmarking try using apache's benchmarking tool for both solutions.

```
ab -n100 -c1 http://domain.tld/path/to/view

```

remember to disable caches while running the tests.
> 1 votes

# Answer
I came across this thought as well when working on increasing performance on a site recently. On that particular site and view, using fields instead of rendered entity cut the time in half.

Rendered entity: 3500ms

Fields: 1500ms

This, ofcourse, can be a matter of complexity in regards to the entities. We're also using DS on that site, which might influence the results. In either case, it seems like fields is preferable *if* there are performance issues. It will be a hassle to maintain several different views with fields instead of maintaining one view mode.
> 0 votes

---
Tags: views, performance
---


title: Customize webform-fields error messages

text:
# Question
Title: Customize webform-fields error messages
I'm using Webforms module and, in particular, a Date field. Using built-in validation and intentionally triggering the validation error, the message looks like follows:

```
The entered date must be 04/04/1914 or later.

```

Have no error here. **What I need** is to customize that error message (I need to show (1) a different message, and (2) in a different language).

**Question**: How can I alter the webform to override the message with my custom one?

# Answer
> 3 votes
Go ahead and download this https://drupal.org/node/1209450 module in zip. there are two zips you can download any one. here is the code can you use now

```
function modulename_message_alter(&$message) {

    if(isset($message->messages['error'])){
       foreach($message->messages['error'] as &$val) {
        if(preg_match('@The entered date must be \w+/\w+/\w+ or \w+.@',$val)){
            $val='This is not correct date';
        }
       }
    }
}

```

---
Tags: 7, webforms
---


# Question
Title: I just want to add a radio buttons to my content type
I am creating a new content type in Drupal 7 and I would like to add some radio buttons as content types. This is surprisingly difficult to do. I have enabled field and options modules but I have yet to see radio buttons show up as an option for numeric or text fields. How do I do this?

Update: I do not have 'select option' or 'list' as a select-able field type

# Answer
> 2 votes
You can choose the `list` field type - this will display radio buttons. `List` core module will need to be enabled.

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