Attach file grammatically to a node in Drupal 7

The below code shows how to upload a file to the field of the node programmatically

$file_path = 'sites/default/files/'.$fname;

$node = node_load($nid);
$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.

// We will save file under this location. public:// if it is a public file
$destination = 'private://';

// Make sure destination directory exists before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_attachement[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_attachement[$node->language][0]['display'] = 1;
$node->field_attachement[$node->language][0]['description'] = 'Description of the file';

// Save node to make the attachment effective.

You need to upload your file to the server first then run the code after setting the path of the file on your server.
$file_path = ‘sites/default/files/’.$fname;
Just change the $nid variable to your variable

Using drupal 7 field collection programmatically

Insert field collection

//Create the Field Collection entity
$item = entity_create('field_collection_item', array('field_name' => 'myfieldcoll_machine_name'));
//set the hosting node 
$item->setHostEntity('node', $myNode_object);

//Fill your fields
$item->field_myfield[LANGUAGE_NONE][0]['value'] = 'My Value;

//Save the entity
$myNode_object->myfieldcoll_machine_name[LANGUAGE_NONE][]['value'] = $item->item_id;

Continue reading

Using Drupal 7 Real name module with user reference autocomplete

To use the Real name module with the User reference autocomplete field you have to implement hook_form_alter and add the autocomplete path to the user reference field


 * Function mymodule_form_alter()
 * Implements hook_form_alter() 
function mymodule_form_alter(&$form, &$form_state, $form_id) { 

  if($form_id == 'formname_node_form') {
    $form['fieldname'][LANGUAGE_NONE][0]['uid']['#autocomplete_path'] = 'realname/autocomplete';



Redirect Anonymous users to Login Page in Drupal 7

To redirect the anonymous users to the login page we need to implement hook_init() in our own module, inside the init function we add the redirect code


 * Implements hook_init().
function mymodule_init() {

  // Check if user is anonymous
  if (user_is_anonymous()) {
    $redirect = FALSE;

    // Detect whether this request is for cron or site installation or xmlrpc
    // request.
    foreach (array('cron', 'install', 'xmlrpc') as $task) {
      // Generate a path for the task
      $path = base_path() . "{$task}.php";
      // See if we have a match
      if (substr(request_uri(), 0, strlen($path)) == $path) {
        // Stop here

    // Proceed if the request is not coming from the command-line
    if (!drupal_is_cli()) {

        // Determine the current path
        $path = drupal_strtolower(filter_xss($_GET['q']));

        // Convert the path if this is the home page
        $path = $path ? $path : '<front>';

        // Continue only if we're not on the login page
        if ($path != 'user/login') {
         $redirect = TRUE;

        // See if we're going to redirect
        if ($redirect) {
          // See if we have a message to display
          if ($message = variable_get('anonymous_login_message', NULL)) {

          // Redirect to the login, keeping the requested path
          drupal_goto('user/login', array('query' => drupal_get_destination()));

How to display only the non empty fields in the Webform email?

To display only the non empty fields in the Webform email use the theme_webform_element_text() function in the template.php file of your theme
Copy the following code to your template.php file.

function themename_webform_element_text($variables) {
  $element = $variables['element'];
  $value = $variables['element']['#children'];

    // Check if there is any value to print out at all, if not, return an empty string.
  if (strlen(trim($value)) == 0) {
    return '';
  // Call the default theme function if there is a value.
  return theme_webform_element_text($variables);

How to reload current page without losing any form data

The best way to keep form values after reloading the page is using Sysyphus.js javascript library.

It is easy to use:

First include the library in your pages:
<script src="js/sisyphus.min.js">

Then you need to call yourform.sisyphus(); function Suppose we have a form with id=”my-form”, here is an example showing how to use the library to keep form values:

<script src="js/sisyphus.min.js"></script>

<form action="" id="my-form" method="get">
  <input id="my-form-name-field" name="name" type="text" value="">

// Here we'll persist the form's data into localStorage on 
// every keystroke 
$( function() { 
  $( "#my-form" ).sisyphus(); 
  // or you can persist all forms data at one command 
  // $( "form" ).sisyphus(); 

Note: to use it in drupal you have to include the library in hook_init() and use it inside your module or to include it and use it in your theme

Adding Javascript to Drupal 7 Module

If you want to add javascript to your module you can do that several ways.

Starts with adding the following line to your MYMODULE .info file

scripts[] = MYMODULE.js

Where you can choose any name for your .js file

The next step is to create the MYMODULE.js file. The general template of the javascript file looks like:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      // Your Javascript code goes here


Continue reading

How to change value of a field in node view

We can alter field value to show it in node view without changing the actual value in database by implementing template_preprocess_field(&$variables, $hook)

Here is an example to check the node type then change the value of a field in that node before rendering the node


function THEMENAME_preprocess_field(&$variables, $hook) {
  if ($node = menu_get_object()) {
    if ($node->type == 'car') {
      if($variables['element']['#field_name'] == 'field_price') {
        $variables['items']['0']['#markup'] = $new_value; //new value;