# Question
Title: Drupal 7 Weform 4 attach file message stays even though correct size file is updated
I have set a file size limit of 4mb for the file type field.

Current behavior When a file greater than 4mb is attached (10mb.jpg) and upload button is clicked, there is a message shown that mentions. "The specified file 10mb.jpg could not be uploaded. The file is 10 MB exceeding the maximum file size of 4 MB..

Now when a file size of less than suggested limit and extensions ( 182kbs - 800px-pizigani\_1367\_chart\_10mb.jpg) is attached and upload button hit, the message still stays and does not go away.

Expected Behavior:
On attaching and hitting the upload button for the file of correct size, the error message should not be displayed.

Let me know if this has been rectified in a later release or is still occurring for others.

Note: If the upload button is not hit and directly the webform is submitted, the functionality does work fine. Thus there seems to be an issue in client side validation.

# Answer
Have you checked PHP's own maximum upload file size?

Default in php.ini is usually this:

```
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M

```

You can check your own site's setting at your sites `/admin/reports/status/php`
> 0 votes

---
Tags: webforms, files
---


title: Field Collections & Checkboxes

text:
# Question
Title: Field Collections & Checkboxes
I am trying to alter a field collection which has a couple of select/ textfields and a checkbox. When the checkbox is checked and another item is added to the form, in the previous instance the checkbox remains checked. This is the correct behavior and also this is the desired behavior in my case.

If, on the second instance added with "add another item", the user checks the associated checkbox then what I would like to accomplish is to have the previous checkbox unchecked.

Is there way to configure/ alter the checkbox so if we have multiple field collections items added when the user selects a checkbox all the other checkboxes are unchecked ? Code that alters the field collections part of the form:

```
        $tenant['field_org_tn_ud']['und']['add_more']['#ajax']['progress']['type'] = null;
        $tenant['field_org_tn_ud']['und']['add_more']['#ajax']['progress']['message'] = null;
        //$tenant['field_org_tn_ud']['und']['add_more']['#attributes']['class'][] = 'add-more-button';
        $tenant['field_org_tn_ud']['und']['add_more']['#value'] = t('Add');
        foreach ($tenant['field_org_tn_ud']['und'] as $delta_k => $user) {
            if (is_numeric($delta_k)) {
                $user['field_org_tn_ud_cp_pre']['und'][1]['#prefix'] = t('<div style="background-color: rgb(254, 255, 220); border: 1px solid rgb(204, 204, 204); line-height: 23px; height: 21px; width: 40px;">');
                $user['field_org_tn_ud_cp_pre']['und'][2]['#suffix'] = t('</div>');
                $user['field_org_tn_ud_cp_pre']['und'][3]['#attributes']['style'] = t('margin-left: 5px');
                if ($delta_k > 0) {
                    $user['field_org_tn_ud_email']['und'][0]['value']['#title'] = null;
                    $user['field_org_tn_ud_actions']['und']['#title'] = null;
                    $user['field_org_tn_ud_permission']['und']['#title'] = null;
                    $user['field_org_tn_ud_cp_pre']['und']['#title'] = null;
                }
                $user['field_org_tn_ud_email']['und'][0]['value']['#autocomplete_path'] = t('vf-users-autocomplete');
                $user['field_org_tn_ud_email']['und'][0]['value']['#attributes']['style'] = t('background-color: #FFFFD6; ');
                if ($delta_k > 0) {
                    $user['remove_button']['#prefix'] = t('<div class="clearfix" style=" z-index: 1; background-color: none; display: table-cell; ">');
                    $user['remove_button']['#suffix'] = t('</div>');
                }
                else {
                    $user['remove_button']['#prefix'] = t('<div class="clearfix" style=" z-index: 1; background-color: none; display: table-cell; vertical-align: bottom; pading-botom: 3px;">');
                    $user['remove_button']['#suffix'] = t('</div>');
                }
                $user['remove_button']['#ajax']['progress']['type'] = null;
                $user['remove_button']['#ajax']['progress']['message'] = null;
                $user['remove_button']['#weight'] = '3';
                //$user['remove_button']['#attributes']['class'][] = 'remove-button';
                $user['remove_button']['#attributes']['style'] = t('');
                $user['remove_button']['#value'] = t('Del');
                if ((isset($form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_cp_pre']['und'][4])) &&
                    ($form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_cp_pre']['und'][5] ==
                    1)) {
                    $duplicate_delta = $delta_k;
                    //dpm($duplicate_delta);
                }
                if (isset($duplicate_delta)) {
                    $user['field_org_tn_ud_actions']['und']['#default_value'] = $form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$duplicate_delta]['field_org_tn_ud_actions']['und'];
                    $user['field_org_tn_ud_permission']['und']['#default_value'] = $form_state['input']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$duplicate_delta]['field_org_tn_ud_permission']['und'];
                }
                // add custom class to select tags for user
                $user['field_org_tn_ud_actions']['und']['#attributes']['class'][] = t('field-custom-select-user');
                $user['field_org_tn_ud_permission']['und']['#attributes']['class'][] = t('field-custom-select-user');
                // add custom class to input tag for user
                $user['field_org_tn_ud_email']['und'][0]['value']['#attributes']['class'][] = t('field-custom-input-user');
                // hide the parent node field as we are not using it within the Plex demand form
                $user['field_parent_nodes']['#access'] = false;
                $tenant['field_org_tn_ud']['und'][$delta_k] = $user;
            }
        }

```
1. field\_org\_tn\_ud\_cp\_pre - is the checkbox
2. Initial
3. After another item is added
4. Undesired behavior: If the user checks the Copy checkbox for the second item in this field then the 'Copy' checkbox on/ for the first item should uncheck.

On the last image when the second Copy checkbox is selected i would like that the first one to become unchecked.

Thank you

# Answer
I have solved this using Drupal behaviors:

1. Created file plex.js and attached to the form in hook\_form\_alter()

```
$form['#attached']['js'] = array(drupal_get_path('module', 'plex') . '/plex.js', );

```
2. added a custom class to the checkbox e.g.: form-checkbox-custom. (The checkbox has a default class .form-checkbox so we need to apped it to the 'class' array)

```
$instance['field_org_tn_ic_cp_pre']['und'][1]['#attributes']['class'][] = t('form-checkbox-custom');

```
3. Drupal.behaviors.plex code (paste inside plex.js attached to form in 1. above)

```
(function($) {
  Drupal.behaviors.plex = {
    attach: function(context, settings) {
      $(".form-checkbox-custom, .form-checkbox").on('change', function(e) {
        e.preventDefault();
        //if ''this' checkbox is checked uncheck all the other checkboxes
        if (this.checked) {
          $(".form-checkbox-custom, .form-checkbox").not(this).prop('checked', false);
        }
      });
    }
  };
})(jQuery);

```
4. Done. Whenever a check box is checked all the other checkboxes will be unchecked. The nice part is that the behavior work for dynamically generated form (field collection) elements (add another item).

Thank you & I hope this helps someone
> 0 votes

---
Tags: entities
---


# Question
Title: How to add placeholders in customized module?
I am new to drupal, currently I am creating a new module for forms. Inside of module I have added the code as follows .

```
$form['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    );

```

In this case I wanted to use place holders for text fields. So how can I do ?

# Answer
what do you mean by placeholders? a default value that prefills the textfield or some watermark text that disappears when you focus the textfield? for a default value you can use the `#default_value` key in the text field definition.

for a watermark i recommend the Placeholder module. the module enables you to use a `#placeholder` key in your field definition.

cheers j
> 1 votes

---
Tags: 7
---


# Question
Title: How can I add custom markup with a theme function?
I have a simple form as follows

```
function MY_MODULE_form($form, &$form_state) {
  $form['MY_MODULE']['message'] = array(
    '#type' => 'markup',
    '#markup' => 'My Heading',
    '#tree' => true,
  return $form;
}

```

But I want the markup to change depending on some factor which will be defined inside a function.

So how would I call a function to do this for the #markup ?

# Answer
> 1 votes
To do this the drupal way, you should use a theme function:

```
function MY_MODULE_form($form, &$form_state) {
  $form['MY_MODULE']['message'] = array(
    '#theme'    => 'mymodule_markup',
    '#var1'     => $var1,
    '#var2'     => $var2,
  );
  return $form;
}

```

Then implement hook\_theme:

```
function MY_MODULE_theme() {
return array(
  'mymodule_markup' => array(
    'variables' => array('var1' => NULL, 'var2'=>NULL),
  ),
);

```

}

Then implement your theme function

```
function theme_mymodule_markup($var1, $var2) {
    return 'some string';
}

```

You also could use a template to render your markup. That way themers can overwrite your markup without having to dig into your module files.

# Answer
> 0 votes
Can you please try following:

```
function MY_MODULE_form($form, &$form_state) {
  $form['MY_MODULE']['message'] = array(
    '#type'    => 'markup',
    '#markup'  => some_custom_function(),
    '#tree'    => true,
  );
  return $form;
}

function some_custom_function() {
    return "Test string";
}

```

---
Tags: forms
---


title: How to save images using Services 3

text:
# Question
Title: How to save images using Services 3
I have found some very detailed tutorials about Services 3. I appreciate them very much here is a small list.

http://drupal.org/node/1354202

How to add multiple images to a node using node.save service?

http://drupal.org/node/1699354

But i cant find a way to upload images from the mobile app to the server. Is that possible ? Where can i get some example ?

Is there in Services core to accomplish this ? Every solution looks like i need o code something to get it work.

# Answer
> 6 votes
I had a requirement once like this where, using web service I have to create a node that will also save image. The following code uploads and saves image using web service.

```
// File validator.
$validators = array(
  /**
   * Defaults already allow png, jpg etc. If more needed to be supported,
   * edit here.
   */
  'file_validate_extensions' => array(),
  'file_validate_size' => array(),
);

foreach ($_FILES['files']['name'] as $field_name => $file_name) {
  // Save the file and get file object.
    $file = file_save_upload($field_name, $validators, file_default_scheme() . "://");

  // Check whether image is uploaded.
  if ($file->fid) {
    $node = new stdClass();
    $node->type = 'CONTENT_TYPE';
    $node->title = 'TITLE';
    $node->language = LANGUAGE_NONE;
    $node->uid = 'USER_UID';
    node_object_prepare($node);

    $node->field_custom[$node->language][0]['value'] = 'SOME_VALUE';
    // File upload here..
    $node->field_image[$node->language][0] = (array)$file;

    $node = node_submit($node);
    node_save($node);
  }
  else {
    return services_error(t('File upload failed'), 406, t('File upload failed'));
  }
}

```

NOTE: Following code was tested using services 3. Also it was an iOS app that was consuming this web service, and it worked there.

NOTE: File uploaded with POST request.

I tested the above code using a Google Chrome plugin called **REST Console**. To install the plugin search for "rest console" in Chrome Web Store and install the first plugin you get in result (with up green and down blue arrow)

Hope this helps!

# Answer
> 3 votes
First of all, make sure to in your endpoint is enable the File --\> Create resource.

And in the "client side" i did something like this:

```
/**
 * Upload a file using services 3.X
 *
 * @param the path of the local file
 * @return bool|int the fid of the file.
 *
 *
 * With the fid you can attach this file in the node object before to be send.
 * ej.
 * $node->title = 'My remote node';
 * $fid = node_upload_image('/The_path/to_the/local_file.jpg');
 * $node->file_field[0] = array(
 *    'fid' => $fid,
 *    'list' => 1,
 *    'data' => array()
 * );
 * // Other fields related with the node.
 * ...
 *
 * // Sending the node.
 * $data = http_build_query($node, '', '&');
 * $response = drupal_http_request('myremotesite.com'. '/node', array(
 *   'Accept' => 'application/json',
 *   'Cookie' => 'auth_cookie_info'
 * ), 'POST', $data);
 *
 * Done.
 */
function node_upload_image($image_path) {
  $file = array(
    'filesize' => filesize($image_path),
    'filename' => basename($image_path),
    'file' => base64_encode(file_get_contents($image_path)),
    'uid'  => 1  // This should change it by the user who use the service.
  );

  $data = http_build_query($file, '', '&');
  $response = drupal_http_request('myremotesite.com/myservice-endpoint' . "/file", array('Accept' => 'application/json', 'Cookie' => 'auth_cookie_info'), "POST", $data);

  if ($response->code == 200) {
    return json_decode($response->data)->fid;
  }

  $this->error =  $response->status_message;
  return false;
}

```

I did this from another Drupal, and is for Drupal 6, port the code to D7 should be easy, and i think you get the general idea about how do it.

# Answer
> 2 votes
The regular services 3 has a 'file' endpoint. You can just enable file creation and post something like this; the file itself is base-64 encoded:

```
{
    "filename": "user993.jpg",
    "target_uri": "pictures/user993.jpg",
    "filemime": "image/jpeg",
    "file": "/9j/4AAQSkZJRgABAQELIiyoy0pUQRoFjAVVGAAMACiigBaKKKAP/2Q==...",
    "filesize": "5356"
}

```

# Answer
> 2 votes
For uploading an image you would need only a filename and a file - which would be base64 encoded.

You could check my repo here, where you could find a simple class for working with Drupal 7 Rest Services and an examples.php file where there are some examples on how to use the class. There you could find also an example on how to upload an image, which I added recently.

https://github.com/flesheater/drupal\_rest\_server\_class

---
Tags: files, services
---


title: Drupal vs Options Indexes?

text:
# Question
Title: Drupal vs Options Indexes?
I have an `.htaccess` file with `Options Indexes FollowSymLinks`, my `/apache2/sites_available/default` file also has these options and `AllowOverride All`.

If I do these things outside of Drupal it's working (if I go to a directory without an index file, I see a file directory listing), but inside Drupal I'm getting

> The requested page "/sites/default/files/" could not be found.

Also, I am able to to access files within the files directory. For example if I went to /sites/default/files/someFile.pdf... it would be able to access it fine. I want to have it so that if I link to a directory within the files directory and that directory does not have an index file... it will display a directory listing of all the files/folders within. Something like:

http://3.bp.blogspot.com/\_rhuioznu6Us/TBmeWAr\_G2I/AAAAAAAAAFE/tKCclPXdq2M/s1600/apache.png

I think Drupal is doing something based on the fact that I get my Drupal headers above the message that the page couldn't be found. How do I stop this?

The files below show some of the things I've tried...

`apache2/sites_available/default` contains:

```
DocumentRoot /var/www/default
<Directory />
  Options Indexes FollowSymLinks
  AllowOverride All
</Directory>

<Directory /var/www/default/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  Allow from all
</Directory>

```

`default/files/.htaccess` contains

```
Options +FollowSymLinks
Options +Indexes
RewriteEngine Off

```

# Answer
You don't need the Indexes on your web server. Its actually not recommend on a live environment. For testing purpose it can be useful sometimes.

If you don't have your files directory I would recommend you to created a files directory

```
sudo mkdir sites/default/files # Creating files directory
sudo chmod a+w sites/default/files # Permissions

```

After that you can you try this on your default configuration file...

```
<DIRECTORY />
      Options FollowSymLinks
      AllowOverride None
 </DIRECTORY>

 <DIRECTORY /var/www/drupal_site/>
     Options +FollowSymLinks
     AllowOverride All
 </DIRECTORY>

```

Source: https://github.com/darol100/lazydubuntu/blob/master/bin/includes/skeleton

And then re-start your server.

If this does not solve your problem here is a similar question (with the same error)

And here is the answer.

> This is a known problem, a natural result of clean URLs
>
> So, when you use clean URLs the file links must have a front slash (and possibly a path if Drupal's home page contains an URL path). The browser sees the absolute path "/files/filename" and resolves it using the bare domain name. You need to edit all the file paths in the content and add a front slash.
>
> Alternatively, try the http://drupal.org/project/pathologic module which tries to be smart about it (or one of the other modules mentioned there).
> 1 votes

---
Tags: .htaccess
---


# Question
Title: Change Log in or register to post comments for content type
We are using the comments for a particular content type to post reviews for that content type. I have searched the web but can't find a proper solution how to change the text

"Log in or Register to post comments" to something like "Log in or Register to add Review"

only for this one content type. Any suggestions how this can be done, also happy if I can figure out how to hide this for this content type.

I don't believe I can alter comment\_links() via template file or custom module (in drupal 7)

Thanks

# Answer
Go through this link will give you a nice work around

https://www.drupal.org/node/170065

Then, you need to change code: Find your **modules/comment/comment.module** file, open it in a text-editor (like wordpad or the like), and search for the text you don't want to see on pages. You need to comment out (or delete) a bit of code, something like: //

```
 if (variable_get('user_register', 1)) {
//      return t('<a href="@login">Login</a> or <a href="@register">register</a> to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('<a href="@login">Login</a> to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

```

The added 'return' is just for case, to ensure nothing to show - I didn't test this.

You can either edit the original file (**which is quick but unclean, and requires you to redo the change after every unpgrade**), or **override that function in your theme** properly by placing its **copy into your template.php** file (whole function!), renaming it to "**phptemplate\_\[name\]**", and changing as needed. I think **(not tested!)** that it should look like this (added to '**template.php**' in your theme's folder / create the file if not existing yet, with

```
function phptemplate_comment_post_forbidden($nid) {
  global $user;
  if ($user->uid) {
    return t("you can't post comments");
  }
  else {
    // we cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages
    if (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
      $destination = "destination=". drupal_urlencode("comment/reply/$nid#comment_form");
    }
    else {
      $destination = "destination=". drupal_urlencode("node/$nid#comment_form");
    }

//    if (variable_get('user_register', 1)) {
//      return t('<a href="@login">Login</a> or <a href="@register">register</a> to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('<a href="@login">Login</a> to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

  }
}

```

But still, you'll probably need to check on every upgrade, whether this copied code is in sync with core's possible new changes.
> -1 votes

---
Tags: nodes, comments
---


# Question
Title: Does a sub-theme needs the main theme enable?
Just to clarified a doubt. But when creating a sub-theme, is it necessary to have the main theme enable ?

Thanks

# Answer
No, it is not necessary. You need to have your base theme installed, but you don't need to enable it: https://www.drupal.org/node/225125#comment-7716513

**EDIT**: Note that if you want to access the settings for your base theme, you will need to enable it, as noted by @MPD in a comment below.
> 9 votes

---
Tags: theming
---


# Question
Title: How do I delete the Edit Delete buttons suddenly showing above pictures?
All of a sudden when I insert a picture into a page, it shows an edit and a delete button above the image to the end user. These buttons take you to the default page. Also, now when I edit a page from the edit button at the top of each page and save, I get the following type of message after a lengthy wait.

Fatal error: Allowed memory size of 356515840 bytes exhausted (tried to allocate 523800 bytes) in /data/www/luna/sites/all/modules/token/token.module on line 767

I can edit and save if I select the page under Content.

See http://lunahq.com/content/luna-rox-v8-simple-smarter

# Answer
> 0 votes
you need to increase the memory limit size in php.ini

That indicates that Drupal needed more memory than PHP was allowed to give it.

Drupal 7

> ```
> Memory increase to 128M:
> (This has worked every-time; and used to always work for D6 as well)
>
> Create a new file php.ini, and add the code...
> php_value memory_limit = "128M"
> and put that file in your Drupal 7 (or D6) root folder.
>     For step-by-step details, see comment below...
>     Drupal 7 "Fatal error: Allowed memory size of ...".
> If you need more than 128M:
>
> Add the line
> ini_set('memory_limit', '512M');
> to your [Drupal 7 root]/sites/default/settings.php file.
>
> I have yet to need this much memory, but I did achieve
> a memory increase to 512M using this slightly more complicated
> process that involved temporarily changing the permission level
> for that file.
>     For step-by-step details see the comment below Drupal 7 memory increase to more than 128M.
>
> ```

refer this link

https://www.drupal.org/node/76156

---
Tags: 7, media
---


# Question
Title: How to calculate the sum of the values of a multi value field without page reload
For a content type with a decimal field with unlimited values (rows), how can I have another field in that same content type that shows the sum of all of the decimal values from the multi value field?

The goal is to keep a tally of the decimal values as the user enters them so they know the total before hitting save on the node.

When the node is saved, the final sum should also be saved in the database.

Modules used are Entity Api and Field Collection.

# Answer
I was going to recommend researching the AJAX in hook\_form\_alter function(), but when I read that you were using Field Collections I got a little nervous.

*The problem with Field Collections is they can be little finicky when you try and do more complex field "stuff" like the scenario you're proposing. I have yet to try using AJAX in combination with Field Collections and I definitely would not want to be the developer who was tasked with it.*

However, if you feel like you want to tackle such a problem you are most certainly going to have create a custom module specific to your situation.

Below is the basic layout for a Node Form Alter using AJAX. Ultimately you want to add an AJAX Event function on your select list, so when the value changes it will call a function that adds the values together.

That's even before you factor in the Field Collections module, which is going to add another layer of complexity to the whole operation.

https://api.drupal.org/api/examples/ajax\_example!ajax\_example\_node\_form\_alter.inc/7

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    ),
  );
  $form['container'] = array(
    '#prefix' => '<div id="ajax-example-form-node">',
    '#suffix' => '</div>',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ? $node->ajax_example['example_2'] : $form_state['values']['ajax_example_2'],
    );
  }
}

```

**ajax\['event'\]**

Description: When this event occurs to this element, Drupal will perform an HTTP request in the background via Javascript.

Values: String. Possible values: Any valid jQuery event, including 'mousedown' (for submit, imagebutton, and button), 'blur' (for textfield and textarea), 'change' (for select). Note that #ajax\['event'\] does not need to be explicitly specified. Although it can be manually set, usually the default value will be sufficient.
> 2 votes

# Answer
There is a module to have field that are based on computation : Drupal Computed Field

See this page for a detailed explanation. You can set the computation code in a module which is great for maintenance and version control.

I have not used the module myself, but it seems used on a lot of sites so i should be quite stable.

Then for the "without page reload" thing, you could add a custom javascript to display/update the computation when the source field are changed. I don't think ajax is necessary as you don't need to save the information to the database live, right ?
> 0 votes

---
Tags: entities
---


# Question
Title: How to get ordered list display for Top Emails in Forward Module?
I'm using the Forward module for keeping track of article content being emailed thru my site. I've been looking thru the module files to see where it is rendering the top5 (I modified it to Top10, instead) entries as an unordered list and have been unable to locate where this is.

Can anyone help with this?

Below is a sample of a basic unordered list showing from the Forward module block (I need this to render as an ordered list, instead):

# Answer
Found Go to `forward.module`

search for this "function forward\_top5\_list(" and change

```
"$query->range(0, 5);" from 5 to 10

```

this will work
> 0 votes

---
Tags: emails
---


title: Taxonomy view problems

text:
# Question
Title: Taxonomy view problems
I have a taxonomy list (sector), linked with differtent content, for example:

Company 1 has taxonomy Security & Computers.
Company 2 has taxonomy Security
Company 3 has taxonomy Computers

I created a view, but, in my view I get the following result:

Security
Company 2

SecurityComputers
Company 1

Computers
Company 3

Is it possible to get:

Security
**Company 1**
Company 2

Computers
**Company 1**
Company 3

So, that he show 2 times the company who is linked with different taxonomy?...

# Answer
> 0 votes
You should group your view by Taxonomy and for the taxonomy field in the view you should uncheck "Display all values in the same row".

These are the steps:

Add a taxonomy field to your view and uncheck "Display all values in the same row" and exclude this field from display.

Use the taxonomy field to group your view (Format settings of the view)

Of course add title field or other field to your view to have your content displayed (e. g. Company 1, 2, 3).

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


# Question
Title: Why view is not firing hook_views_query_alter?
I'm using Commerce Kickstart 2 and I want to modify the query of the included view collection\_products.

As a start, I've added a `mymodule_views.inc` file with this code:

```
function jch_utilities_views_query_alter(&$view, &$query) {
  dpm($view->name);
  if ($view->name == 'collection_products') {
    // my code goes here;
  }
}

```

`dpm()` fires for 3 times for each view on the page, but **not** for the collection\_products view. Obviously, `hook_views_query_alter()` is firing, but why isn't that view showing up?

Just to be clear: The view / page display renders fine.

I saw this issue and I wonder if it applies.

Is there another way to modify the query?

# Answer
Please read `hook_views_query_alter()` API, which say:

> This hook should be placed in `MODULENAME.views.inc` and it will be auto-loaded. `MODULENAME.views.inc` must be in the directory specified by the 'path' key returned by `MODULENAME_views_api()`, or the same directory as the `.module file`, if 'path' is unspecified.

So double check that you're placing the hook in the correct place either in the main module file or `MODULENAME.views.inc` (not `mymodule_views.inc`) and make sure that you've `MODULENAME_views_api` function defined (unless it's already defined by Feature). After all that clear your all caches (including memcached if in it's in use).

See also: How do I use hook\_views\_query\_alter()?

If there is still a problem, that means your view is implementing different query handler and possibly it implements `views_plugin_query` (which by default doesn't provide any alter code), so you have to find the right plugin query handler (a query class) and see which hooks they're using instead.

To find which plugin is in use.

Method 1: If view is already exported, check `base_table` name and which module is dealing with that table. If it's `search_api_`, then it's Search API module.

Method 2: Edit `views/includes/view.inc`, find the code which executes the query alter: `$this->query->alter($this);` and dump the `$this->query` object to see what class is used for that view.

Then find that class and its `alter()` method to see how it's implemented.

Here are few examples:

Views (`class views_plugin_query_default extends views_plugin_query`):

```
function alter(&$view) {
  foreach (module_implements('views_query_alter') as $module) {
    $function = $module . '_views_query_alter';
    $function($view, $this);
  }
}

```

Search API (`class SearchApiViewsQuery extends views_plugin_query`):

```
public function alter(&$view) {
  parent::alter($view);
  drupal_alter('search_api_views_query', $view, $this);
}

```

YQL Views (`class yql_views_query_plugin_query_yql extends views_plugin_query`):

```
function alter(&$view) {
  foreach (module_implements('yql_views_query_query_alter') as $module) {
    $function = $module . '_yql_views_query_query_alter';
    $function($view, $this);
  }
}

```

So as you can see, you need to use different hooks for different views types.

In your particular case `collection_products` views is handled by Search API, so you need to define `hook_search_api_views_query_alter` instead.
> 3 votes

---
Tags: 7, views, commerce, database
---


# Question
Title: How to execute request-specific tasks after page response is returned. Does hook_exit() actaully do this?
I'm trying to figure out if it's possible to "hide" the perceived execution time of some end-of-request logging tasks that are page specific and depend on the availability of the Drupal DB API. Essentially I'd like to run these tasks after the page response is returned in full to the browser. I've always just assumed that hook\_exit() was the right choice for this kind of thing but after looking at its invocation within drupal\_page\_footer() in some detail, I'm not so sure. Here's the notable snippet from drupal\_page\_footer():

```
module_invoke_all('exit');

// Commit the user session, if needed.
drupal_session_commit();

if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
drupal_serve_page_from_cache($cache);
}
else {
  ob_flush();
}

```

So it looks like both cached and un-cached responses are not sent to the browser until after all hook\_exit() implementations run (flushing the buffer and executing `drupal_serve_page_from_cache()` both happen **after** `module_invoke_all('exit')`). This seems a bit contrary to the hook\_exit() documentation which states that, "This hook MUST NOT print anything because by the time it runs the response is already sent to the browser."

Am I perhaps misinterpreting the way hook\_exit() implementations work in relation to the response delivery? If not, is there some alternative way to trigger custom logging logic later in the response (while DB access is still available)? Perhaps by registering a shutdown function or something to that effect?

# Answer
You're looking for fastcgi\_finish\_request(). Recommend using it inside of a shutdown function. If you need something else the HTTPRL module should be able to do what you need with threading.
> 1 votes

# Answer
I want to follow-up on this with an answer to my own question. This just expands on the already accepted answer.

For anyone wanting to achieve this in a reusable module, that may be implemented on multiple environments, a simple call to `fastcgi_finish_request()` will of course not be possible as there is no guarantee that FastCGI is being used. That said, it still looks like `fastcgi_finish_request()` is the best option for this when available.

To still leverage some advantage when FastCGI is not available, I've found it's useful to at least attempt to flush all content to the client before running the logging task. This would allow the browser to begin displaying content, start fetching any render-blocking js, etc., before the logging happens. It would **not** allow the connection to be closed, as `fastcgi_finish_request()` would do (so DOM ready events would still be held up), but it still seems better than not doing anything at all.

Here's what I've been testing in my shutdown function (this would only be applicable in a shutdown function and would not work in any hook implementations):

```
/**
 * Shutdown function used for logging purposes.
 */
function mymodule_shutdown() {
  // Try to ensure that our logging happens after the page content has been sent
  // to the browser, and ideally after the connection is closed.
  // fastcgi_finish_request() is our best option as it's designed for exactly
  // this purpose, but php may not always be running under FastCGI. As an
  // alternative we just force buffers to be flushed (this will not close the
  // connection but it will at least get the page content pushed out).
  if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
  }
  else {
    flush();
  }
  run_expensive_logging_task();
}

```

There is some useful info in this post about all this as well. I can't be too sure if calling `flush()` alone will always do the job as there are some indications that output buffering must be explicitly killed (`ob_end_flush()`) as well. However, in the context of a Drupal shutdown function it seems like this is unneeded as wrapping-up all the output buffering stuff was likely handled by core already. Of course if `fastcgi_finish_request()` is used it takes care of all this in one line.
> 0 votes

---
Tags: 7, hooks, performance
---


# Question
Title: Can I put batch api callbacks in an include file?
I have a .module file that is getting quite lengthy, and I added some batch functionality to it. I put the form and batch callbacks in a separate .inc file, and added the appropriate `file` directive to the menu array.

I was able to get the form submission to work, but the batch api threw the error `Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_my_batch_callback' not found or invalid function name in _batch_process()`. I got this error until I moved the batch callbacks into the .module file.

Is it possible to put the batch callbacks into a separate include file? Or have I just done something wrong?

# Answer
Actually, there is a file directive in the batch array. I found it was necessary to include `drupal_get_path` to fully reference the file's path.

```
'file' => drupal_get_path('module', 'MY_MODULE') . '/includes/my-batch.inc'

```
> 6 votes

---
Tags: batch-operations
---


# Question
Title: integration Webform and registration module
I want integrate Webfoem and registration user module.so , When a user fill a webform, some fields in that webform put in user table , and he/she insert in user list in my site. and I should active it our delete from users.

I have multiple Webform for registrations, and I want for each form change user role.

# Answer
> 1 votes
`webform module` in Drupal 6 implements a number of hooks upon submission.
One of which is `hook_webform_submission_insert($node, $submission)`. This hook is invoked when a form (webform) is submitted.

*`$node` is node object that holds webform, `$submission` hold data submitted via form to be inserted into database.*

You can implement this hook to get submission data and then process manually and create a user using `user_save()`

```
function custom_module_webform_submission_insert($node, $submission){
    $user = array(
       'name' => $submission['user_name'],
       'mail' => $submission['user_mail'],
    );
    user_save($user)'
}

```

# Answer
> 2 votes
There are two contributed modules that may provide what is needed (quotes included are from their project pages):

* Webform register:

> ... adds a Webform component that collects user registration details and creates a new account. This is useful when you only want authenticated users to submit webforms, but you do not want to create an extra hurdle for people before they fill out your webform.
>
> Webform Register can help you keep the flexibility of Webform, while reducing duplicate entry for your visitors. Because the user registration page can be extended through Drupal's built-in user profile fields or with the help of Content Profile, the Webform Registration can help you collect user-specific, oft-repeated information such as Name, Address and Organization information and store it in a profile entry for each visitor. Meanwhile, information that's only pertinent to the individual webform, such as survey data or preferences for a single event, are collected by standard Webform behavior.
* Webform Registration:

> ... born from the need to allow visitors that came to the site to fill out a sweepstakes from which needed to not only submit values to Eloqua, using the eloqua module, but also create a new user.
>
> At the time the Webform register module did not provide enough flexibility for what we needed to do. Which was have many different field names (used for eloqua mapping) and still keep track of which ones held the values for email, username and password.
>
> How is this module different from Webform register:
>
> + Maximum webform integration and flexibility
>     + You can add and fully customize every field that will be used for registration.
>     + If you are in a hurry, just add en email field and this module will handle the rest via a very user friendly and intuitive interface.
>     + Only the email field (webform component) is required, all the other components can be either generated by this module or omitted depending on your needs.
>     + Optionally you can specify all the labels and descriptions for all five fields (components): email, username, password, password confirmation and email confirmation

# Answer
> 1 votes
@Shuab Nawaz :

Note that hook\_webform\_submission\_insert() is called after a submission has been saved to the database, as explained in webform.api.php file.

If one wants to modify the submission before the data has been saved in the database, hook\_webform\_submission\_presave() should be used.

# Answer
> 0 votes
Was looking for this to mimic the invite or registration codes which are heavy and need complex configuration. Finally ended up with this article and implemented it.

For assigning a role create separate webform for each role or create a select list having role as items.

Not tested but you can also try entityform which supports drupal fields and that means you can attach any field including role though you need custom module

---
Tags: webforms, users
---


# Question
Title: What permissions affect fields attached to taxonomies that don't affect fields attached to content types?
On a D7 site, I created a Description field (using filtered text with ckeditor) and a Geolocation field using a Googlemap widget.

I attached them to a content type called Accommodation, and they behaved as I expected - ie, I got a rich text editor on Description, and a map on the Geolocation field, when logged in with any role that would allow me to edit a node of that content type.

I attached the same fields, with the same settings, to a Taxonomy, and found that I could only see the map and ckeditor if logged in as an administrator.

If I logged in with another role, the googlemap and rich text editor would not appear, although I was still able to create a taxonomy item, and they did appear on the same fields shown on a node create form - just not on the taxonomy item create form.

I have all taxonomy permissions turned on for authenticated users.

# Answer
> 0 votes
Leaving an answer in case it's useful to anyone else.

The permission that was affecting the display of taxonomy ckedit and geolocation fields was 'View the administration theme' - it looks like the Open Framework theme has a small issue when displaying taxonomy edit field forms.

I should have just changed to a default theme to test this.

---
Tags: entities, taxonomy-terms, wysiwyg, location
---


title: Comment ID in Comment field

text:
# Question
Title: Comment ID in Comment field
I've added a custom static field to comments. This static field is custom php code but I need to access the specific comment ID using php code in it. So how can I get the comment ID for every comment in the static php field?

Thanks

# Answer
In Drupal 7 you can use the below code to get all the comments of a node using node ID

```
 $nid = 2;
 // you can get nid
 // $node = menu_get_object();
  //  $nid = $node->nid;
    $comments = db_select('comment')
              ->fields('comment', array('cid'))
              ->condition('nid', $nid, '=')
              ->execute()
              ->fetchAssoc();
    foreach($comments as $comment) {
        print your comments here
    }

```

Also you can check below links https://api.drupal.org/api/drupal/includes%21common.inc/function/entity\_load/7 https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/comment\_get\_thread/7

In Drupal 6 you can use the comment\_render() ;
> 1 votes

---
Tags: entities, comments
---


# Question
Title: D7: How do you get the name of a module?
I am using **module\_list()** to get a list of all modules, but I want the names of the modules, not their machine name. Anyone know how to do that?

# Answer
> 3 votes
You can use the `system_rebuild_module_data()` function to get a list of all module data in the system:

```
$module_list = system_rebuild_module_data();

```

Each entry in the array returned from that function contains all the details about the module, e.g.:

It's the same function used by the system modules admin page so I think it's safe to assume this is the best way to get this particular data.

# Answer
> 3 votes
```
$info = system_get_info('module', 'example_module');
if ($info) {
   // Print human-readable name of the module
   print $info['name'];
} else {
   print t("No such module found.");
}

```

---
Tags: 7
---


# Question
Title: First page load/execution slow, login slower Drupal 7
Drupal 7 site experiencing slow execution/load time for first page visit and slower execution/load time for login. The web server and database servers are dedicated and well resourced, the site has no traffic currently.

Settings already in place

* JS/CSS compression enabled
* Cron is run via crontab every hour and disabled in Drupal
* Cache warming 2 times a day with min, max cache expiry time at 1 day for anon
* APC is set to 192MB and using about half memory
* Database is on another dedicated box lots of RAM
* Update manager disabled
* Content translation disabled
* No missing modules

Setup info

* About 100 modules: 70 contrib, 30 custom
* Drupal core and modules are on NFS server
* apc.stat=1 , apc.stat\_ctime=Off, apc.ttl=3600
* php.ini - realpath\_cache\_size=512k
* settings.php - database set via IP (not hostname)
* Mysql - query\_cache\_size no effect with both enabled or disabled
* Mysql - innodb\_flush\_log\_at\_trx\_commit =2
* Mysql - innodb\_buffer\_pool\_size=4G #current DB is 100mb total

DB queries are \< 110 ms. XHprof snapshots below.

**Update1: Login after few silent hours**

**Update2: Update.php XHprof timing**

**Update: NFS info**

%nfsstat -m Flags: rw,nosuid,nodev,relatime,vers=3,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=xx.xx.xx.xx,mountvers=3,mountport=xxxx,mountproto=udp,local\_lock=none,addr=xx.xx.xx.xx

Any suggestions to improve load times?

**Update 3: Cache configurations in settings.php** When I enable and run test for cache and APC cache using Drupal's Testing module. I get fatal errors with "Class 'Database' not found"

I am using APC cache module, below are my settings. Is something wrong with this config. APC has 192MB and used about 110MB

```
/****
 * APC Caching.
 ****/
$conf['cache_backends'][] = 'sites/XYZ/modules/apc/drupal_apc_cache.inc';

// cache - is used for all common cache purposes. is a default cache bin for Drupal.
$conf['cache_class_cache'] = 'DrupalAPCCache';

$conf['cache_class_cache_admin_menu'] = 'DrupalAPCCache';

// cache_block - is used for storing block's cache
$conf['cache_class_cache_block'] = 'DrupalAPCCache';

$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';

$conf['cache_class_cache_field'] = 'DrupalAPCCache';

// cache_filter - is used for storing filtered input
$conf['cache_class_cache_filter'] = 'DrupalAPCCache';

// cache_form - is used for storing forms.
// This cache bin should not be assigned to volatile storage
//$conf['cache_class_cache_form'] = 'DrupalAPCCache'; // use Database

//$conf['cache_class_cache_image'] = 'DrupalAPCCache';

$conf['cache_class_cache_libraries'] = 'DrupalAPCCache';

// cache_menu - is used for storing assembled and processed menu
$conf['cache_class_cache_menu'] = 'DrupalAPCCache';

// cache_page - is used to store cached pages
//$conf['cache_class_cache_page'] = 'DrupalAPCCache';

$conf['cache_class_cache_path'] = 'DrupalAPCCache';

$conf['cache_class_cache_path_breadcrumbs'] = 'DrupalAPCCache';

// cache_update - if module Update status' is enabled this
// bin stores Drupal, modules and themes update information.
$conf['cache_class_cache_update'] = 'DrupalAPCCache';

//$conf['apc_show_debug'] = TRUE;  // Remove the slashes to use debug mode.

/*****
 * Contributed module cache
 ****/

// Browscap module
$conf['cache_class_cache_browscap'] = 'DrupalAPCCache';

// Entity cache module
// This will cache items in Database when not pointed to another cache
// There is no way to disable this caching for particular entity, it is
// all or nothing, erasing the potential little benefit for enabling this
// module for caching entity_user to increase performance of web services
/*
//$conf['cache_class_cache_entity_comment'] = 'DrupalAPCCache';
//$conf['cache_class_cache_entity_file'] = 'DrupalAPCCache';
//$conf['cache_class_cache_entity_node'] = 'DrupalAPCCache';
//$conf['cache_class_cache_entity_taxonomy_term'] = 'DrupalAPCCache';
//$conf['cache_class_cache_entity_taxonomy_vocabulary'] = 'DrupalAPCCache';
$conf['cache_class_cache_entity_user'] = 'DrupalAPCCache';
*/

//Panels module
$conf['cache_class_cache_panels'] = 'DrupalAPCCache';

// Registration module
//$conf['cache_class_cache_entity_registration'] = 'DrupalAPCCache';
//$conf['cache_class_cache_entity_state'] = 'DrupalAPCCache';
//$conf['cache_class_cache_entity_type'] = 'DrupalAPCCache';

// Rules module
$conf['cache_class_rules'] = 'DrupalAPCCache';

// Token module
$conf['cache_class_cache_token'] = 'DrupalAPCCache';

// View module
$conf['cache_class_cache_views'] = 'DrupalAPCCache';
//$conf['cache_class_cache_views_data'] = 'DrupalAPCCache';

// Default DB for the ones that change too frequently and are small
$conf['cache_default_class']    = 'DrupalDatabaseCache';
// THIS MUST BE SERVED FROM DB FOR STABILITY
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

# Answer
> 1 votes
If using NFS I highly recommend using `apc.stat=0` and then if you want to update the apc cache run `apc_clear_cache('opcode');`.

Seeing how drupal\_parse\_info\_file() is ran on every page load I'm guessing this core patch will help you out: https://www.drupal.org/node/1081266#comment-9411015

Another thing that can help with running code from a NFS drive is this issue: https://www.drupal.org/node/1443308

Also related to potential NFS issues these 2 modules usually help in that situation
https://www.drupal.org/project/imageinfo\_cache
https://www.drupal.org/project/advagg

# Answer
> 0 votes
It seems your top time consuming function is `ob_flush()` which is called only once, but for 200-500ms.

This call is invoked in `drupal_page_footer()` as follow:

```
function drupal_page_footer() {
  // ...

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

```

So in both of your cases cache doesn't work, either by the 1st load or for the reason that the page was loaded by authenticated user (`drupal_page_is_cacheable()`). So probably nothing that we can do here.

Function `ob_flush()` send the contents of the output buffer to the client, and the latency of this transport to the client is probably higher than the actually PHP buffer flushing. See: Why does calling ob\_flush() slow down my latency so much?.

Here are few ideas how to improve the load times:

* enable/disable `zlib.output_compression` (and see which option is quicker),
* test for network bottlenecks, if the problem is not with NFS server by checking the load times of simple PHP files (such as `update.php` or plain php files),
* if your buffer is flushed too slow, something holds the buffer until the page has finished loading, this can be caused by some Apache modules or client it-self,
    + if it's server fault, review your Apache modules and APC settings (you can use `strace` to investigate the problem by debugging your Apache process when it handles the request),
    + if it's client fault, test your page by disabling plugins or use different web browser, as well as disable any antivirus softwares (which can hold the buffer until it's checked for web viruses)
* install XCache instead of APC, set `xcache.count` to your cpu count something between 4-8 (check sample xcache.ini).

---
Tags: 7, performance
---


# Question
Title: Set default value for Enity Reference using View and Entity Reference View Widget Checkbox
Basically i have a field (in line item(commerce custom product)) with Field type: Entity Reference and Widget:View. The view is a list of terms and has an aditional field type:Entity Reference View Widget Checkbox to provide a checkbox in so user could configure the product.

The whole chain works fine from user point of view but there is no option to set the default value (in UI) and the option to set the default value from hook\_form\_alter() is not giving the needed result.

This is hook\_form\_alter:

```
function test_form_commerce_cart_add_to_cart_form_3_alter(&$form, &$form_state, $form_id){

    $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=6;

}

```

Please provide a solution. Thx!

# Answer
Did you try casting the value to a string? I had to do that when I was setting default values for a user reference field type. It wouldn't work otherwise. Something like

```
 $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=(string)6;

```

Also, I noticed that you had a spelling error. You had `'field_pesonal_data'` It should probably be `'field_personal_data'`

Also, I was a little confused by your use of terminology. You described that the user is configuring the entity reference field on the product. Did you mean configuring the entity on the line item? I just wanted to clarify, because if you are modifying the form that governs the adding of products (or product variations in Commerce Kickstart 2.0), you need to use a different form alter call because the product variation creation form uses the inline\_entity\_form module to manage the specific product variations.

That call is:

```
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)

```

Look at the inline\_entity\_form.api in the contrib/inline\_entity\_form folder in Commerce Kickstart 2.0

for modifying a user reference on a product, I did the following:

```
function bh_vendor_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  global $user;
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['vendor_user_reference']['und']['#default_value'] = (string)$user->uid;
  }
}

```

My widget I used was a option list. You have to have the `['und']` or it won't work either.
> 0 votes

---
Tags: forms, commerce
---


# Question
Title: Can no longer access administration pages - Warning/Error
Today, I logged in as administrator to my Drupal 7 site. I was using overlay, viewing "People", and everything was working fine. Then I clicked on "Reports".

All of a sudden, I had a white screen, and can no longer access any of the administration pages of my site. When clicking back to the home screen, I get multiple instances of this error:

Warning: require\_once(C:\inetp): failed to open stream: No such file or directory in module\_load\_include() (line 330 of C:\inetpub\wwwroot\includes\module.inc).

I was using the administration pages just fine a couple days ago. I'm not sure what could of happened. The only thing recent was I updated Views - but this was quite a little while back - and again, had no problems after that up until now.

Can someone help? Thanks!

# Answer
So all of a sudden now - the problem is gone. I did nothing to fix it. I went to the recent log messages, and I saw that cron was run just before this last successful attempt.

So perhaps running cron fixed the issue. Thank you for your help.
> 0 votes

# Answer
go to your `settings.php` and add this code below

```
error_reporting(-1);  // Have PHP complain about absolutely everything
$conf['error_level'] = 2;  // Show all messages on your screen, 2 = ERROR_REPORTING_DISPLAY_ALL.
ini_set('display_errors', TRUE);  // These lines just give you content on WSOD pages.
ini_set('display_startup_errors', TRUE);

```

follow these steps Blank pages or "white screen of death" (WSOD)
> 0 votes

---
Tags: 7
---


# Question
Title: Views List tag filtering, add a tag to a view for filtering purposes
On the Views list `admin/structure/views`, I can filter my list of views by the tags on the View.

I can search for the tags, but how do I add my own tags to the views so that I can easily filter them?

# Answer
1. Open (edit) your view
2. Click on *edit view name/description*
3. Add to/change tags under *View tag* and click Apply
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to load a field from a user that is being viewed
I am looking to load a field from a user's profile that is being viewed.For example, I am looking at another users profile and it will load their associated field.

I am programmatically adding a picture to the tpl (probably should be template.php) and then I am adding it to the background-image of a div. My code loads the user but then switches the user to user being viewed. It is obviously not good to be able to switch users.

Here is my code:

```
<?php
   $user = user_load(arg(1));
   $picture = field_get_items('user', $user, 'field_picture');
   $file = $picture['filename'];
   $url = $base_url . '/files/' . $file;
<?

```

I cannot find a secure way to do this. Anyone have an idea?

Thank you for your time.

# Answer
Try creating a user-profile.tpl.php file in your theme and messing around with that.

Default contents are:

```
<div class="profile">
  <?php print $user_profile; ?>
</div>

```

And I suggest using a variable name other than $user as $user is a global variable referring to the logged in user.
> 1 votes

---
Tags: theming, users
---


title: Updated taxonomy terms do not save

text:
# Question
Title: Updated taxonomy terms do not save
I am using the taxonomy module (D7) to list Continents, Countries, and Cities. Continents is the 1st level, Countries is the second level, Cities is the third. Or, in other words, Countries and Cities are children to Continents.

That's quite a number of terms.

All has been going well for a while but it seems I have reached some kind of a limit. Indeed, I can save new terms on the root level but when I move them to be children (at the 3rd level) the update no longer saves. There is no error message and no confirmation that the new configuration was saved. Indeed, the new terms are back to the root level after that.

I have added "max\_input\_vars = 1500" to my php.ini file but it didn't help.

The server generates no error.

Any idea or suggestion on how to fix this?

Thanks. :)

**Update:** If I move a term from the root directory to become the child of another term, the (new) automatic URL is not written in the database. I have to delete some existing terms to be able to save new terms (by the same number.) This tells me there is an imposed limit somewhere.

# Answer
> 0 votes
The fix is as follows:

In your **php.ini** file, increase the `max_input_vars` to 2000. That should fix the issue with taxonomy terms and blocks too.

---
Tags: taxonomy-terms
---


# Question
Title: How to make a page visible only to users with permission to use the administration theme?
I have created a basic page which I only want to be viewable by people who have access to the administration theme.

I have given the page a path of admin/shipping-help but to my surprise the page is visible to anonymous visitors, nor does the page display in the admin theme.

What am I doing wrong?

# Answer
> 0 votes
There are some modules that can help with this: like Content Acess, or Node Access

Node Access Content Access

# Answer
> 0 votes
For **restricting particular url** or **Basic page** you can go with

this module will suite you best path\_access

if that dont work

Refer this link for **Controlling Access to Content Overview**

hope this helps

# Answer
> 0 votes
A basic page is a node. It will be on the internal `node/%` path. Giving it an alias of `admin/shipping-help` is not going to change that. You need it to be on `admin/...` internal path.

Create a new entry for hook\_menu with your admin path and display the node in question:

```
function MODULE_menu(){
  $items = array();
  $items['admin/shipping-help'] = array(
    'title' => "Shipping Help",
    'page callback' => 'MODULE_shipping_help',
    'access arguments' => array('access administration menu'),
  );

  return $items;
}

function MODULE_shipping_help() {
  $node = node_load(70);
  if ($node) {
    return node_view($node);
  }
}

```

Then set the node in question to unpublished to protect it from unauthorised access from `node/%` path. You can even intercept a request for that path and redirect to the admin path.

---
Tags: users, uri
---


# Question
Title: Display content type images using taxnomy
In a drupal block view that I have created I am currently displaying the images and title of a certain content type. On that content type I have two taxonomy term fields one is a multi-select box

My question is this, I want to filter the title and images according to the taxonomy multi box field when a node is displaying, how?

For example if I have a multi list

```
water
coffee
tea
drupal
views

```

On creating the node I select water and drupal so when the node displays it will show all the images and titles that have the same taxonomy term in the block view

**Below I have an image of a view that is trying to displaying an image and title according to the taxonomy terms save on a node that a user is currently looking at**

It is not working of course. Do I have the right idea what am I missing?

# Answer
> 1 votes
I would try removing your Content: Related Products filter criteria.

Make sure your contextual Content: Nid filter is setting the default from the content ID in the url, and under "More" this filter is set to exclude.

Add another contextual filter for Content: Has Taxonomy Term ID. Select "Provide default value" and use type PHP Code:

```
$node = menu_get_object();
$terms = array();
if (empty($node->field_related_products)) return;
foreach ($node->field_related_products[LANGUAGE_NONE] as $term) {
  $terms[] = $term['tid'];
}

return implode('+', $terms);

```

Under "More" for this filter, enable "Allow multiple values"

Under "Other \> Query Settings" select "Distinct"

# Answer
> 0 votes
I would recommend using Views. You can choose to make it a block or page.

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that, but those are some of the obvious uses of Views.

* Setup a new View, naming it whatever you want
* set it to content, of the content type you want to show
* you probably want it set to Table to determine which fields are presented

Filtering it really depends on how you want to setup the node display. You could use a contextual filter (url parameter) or Filter by the field and expose it allowing the user to change what is displayed. The rest of the answer depends too much on your vision for the page.

# Answer
> 0 votes
You should use a taxonomy contextual filter. It will filters all nodes that have the same taxonomy terms as your current node.

If I understand well your issue, i think there is no need to use any PHP here.

In "Contextual Filters" add "Content: Has taxonomy term ID". Then select "Provide default value" and select the "Taxonomy term ID from URL". It opens a few checkbox options. Select "Load default filter from node page". There is a Vocabulary selection list if you want to restrict your query to specific vocabularies.

With those settings selected, the view will list all nodes containing terms that are selected in the current node. You can then add the title and picture field as usual in the Fields.

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


# Question
Title: Want to generate csv of a view programmatically in drupal 7
I have a view in drupal 7 and I want to generate a csv of this view programmatically after click any button.

# Answer
Views data export

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS
> * Microsoft DOC
> * Basic TXT
> * XML

You should created a Views with CSV display. And then created a bottom that point to that page.
> 2 votes

---
Tags: views
---


# Question
Title: Add Additional (Term Reference) Field to repeating Date & Time Field for Locations
So I have a question that I am not quite sure how to handle in Drupal. (I come from a Wordpress background).

So I have an Event Content Type. In this event CT I have a repeating Date/time field and I need each date/time field to be connected to its own Location. (All locations are stored in a Taxonomy called "Venues")

For Example, I could have 3 events on June 6th. Each at separate times but all three at different locations. So rather than create 3 Event nodes. I just want to set the three times and dates in one node.

Any idea's how to go about this? I was thinking I could do some type of field attach but I am not quite sure if that would be the way to go about it or to even start.

# Answer
If i understand your question correctly, you could fix this quite easily by creating a field collection

The field collection would contain the repeating date field and the term reference field.

When you add the field collection to your event content type, you can select to allow an unlimited amount of values.

I hop this can get you started?

If you should have any problem, just let me know. I will add some screenshots then. Im posting from mobile phone now...

Good luck!
> 0 votes

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


title: Face detection like seen on facebook

text:
# Question
Title: Face detection like seen on facebook
As we see in facebook, that it can detect & tag persons within a picture. Is there any way to achieve this from Drupal? any module exist?

The main purpose is to verify each user account- so everybody has only one account. Lots of country people don't have any National ID/passport. So, how can we trace their unique identification? Mobile number is a way, bt one person can have multiple numbers.

OR, is there any way, we can scan finger print as iphone6 has that built-in function........

I know i'm asking for too much,,bt I already need that kinda stuff in job :(

Any suggestions are welcome .....please

# Answer
> 3 votes
I didn't think there was a module, but I found one. Take a look at this module. From the project page:

> Face Detection module uses the jQuery Facedetection library to provide an image viewer jQuery plugin.
>
> It only has been tested on Chrome, Firefox 3-8, IE 9

---
Tags: media
---


# Question
Title: How can I present a screen that asks users to confirm their account details upon registration?
I have a site for which I would like to display a "confirm details" screen when users create an account. Basically, I would like something similar to the "required preview" option for adding a node-- just for user registration instead.

I was unable to find a module to do this. Any ideas?

# Answer
1. you have a function for that "**function confirm\_form**"

see this link https://api.drupal.org/api/drupal/modules!system!system.module/function/confirm\_form/7

**2. add through js**

```
<?php
    drupal_add_js('(function($){ $(function(){$("#edit-xxxxxx").click(function(){return confirm("confirm do that ?")});}); })(jQuery);', array('type' => 'inline'));
?>

```

refer the above link you will get three different ideas
> 1 votes

---
Tags: users
---


# Question
Title: Module to display a website's favicon when displaying a link to it
I'm looking for a module that will display a website's favicon when display a link to that site. Specifically, I want to enable it to one certain Link field.

For example, if a user edits a node and uses the URL `https://www.facebook.com/pages/Drupal/8427738891` in a Link field, I want to display the favicon `https://www.facebook.com/favicon.ico`.

Ideally, the module can cache the favicon locally (there are several benefits for this)

(Also: See my other question, if there is some a module that can do both it'll be great)

# Answer
> 0 votes
i believe this will work for you https://www.drupal.org/project/link\_favicon\_formatter

hope this helps:)

---
Tags: 7, entities, navigation
---


title: Webform E-mail send to selected user

text:
# Question
Title: Webform E-mail send to selected user
When the user is fill out my webform they are going be asked "who refer you to this page." The user would pick a user. I want to be able to send the results e-mail to that person programatically once they have submitted their question.

So I'm looking for a module allow me to e-mail the webform results base on "who refer you to this page."?

# Answer
I believe hook\_node\_presave() along with user\_load() is your answer

something like this:

```
function hook_node_presave($node) {
if($node->type == 'webform') {

$uid = user_load($node->FIELDOFUID);

$uid->mail;

// do your mail send here with $uid->mail;

}

}

```
> 1 votes

---
Tags: users, webforms, emails
---


# Question
Title: Views: how to override a linked "Content: Title" field's href programmatically?
I would like to override a Views-generated block's ***"Content: Title"*** field's **`href`** path (linked to nodes with *"Link this field to the original piece of content"*) to append a query string (`$_GET['page']`).

An example:

this is the generated link:

```
<a href="/my_drupal_subdir/hu/my_test_alias/blabla" class="views ...">Blabla</a>

```

I would like this one:

```
<a href="/my_drupal_subdir/hu/my_test_alias/blabla?page=0,0,2" class="views ...">Blabla</a>

```

**I would like to override the path and append a query string before it gets rendered as an HTML-link** (`<a>`).

How should I do this? I think Views uses views\_handler\_field\_node::render\_link() and views\_handler\_field::render\_as\_link() which calls function l() or sg. like that which should be overridden. Of course, overriding theme\_link() for modifying ALL the links is not a good way.

---

Here's an **export** of the simplest possible **block view for Articles** with pager id 3; the titles are linked:
http://pastebin.com/tmq0kZwT
I want to override the title links of this list to append a query string (to remember the actual pager when clicking on a node).

# Answer
Here is the solution:

Put the following code to your theme's `template.php` file, and substitute `MYTHEME` with your own theme's name (or you can even put it in your module's file, and substitute `MYTHEME` with your module's machine name):

```
<?php

/**
 * Implements template_preprocess_views_view_field()
 * @see http://api.drupal.org/api/views/theme!theme.inc/function/template_preprocess_views_view_field/7
 * Process a single field within a view.
 * This preprocess function isn't normally run, as a function is used by default, for performance. However, by creating a template, this preprocess should get picked up.
 */
// /* -- Comment out this line if you want to use this function
function MYTHEME_preprocess_views_view_field(&$vars) {
  // $vars['output'] = $vars['field']->advanced_render($vars['row']);

  // @see http://drupal.org/node/939462#comment-4476264
  if (isset($vars['view']->name)) {
    $function = 'MYTHEME_preprocess_views_view_field__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
      $function($vars);
      // we can return to only use the specific preprocess function (it matters if there are more codes below in this function)...
      return;
    }
  }
}
// */

/**
 * Implements template_views_view_field__VIEW_MACHINE_NAME__DISPLAY_MACHINE_NAME()
 * @see template_views_view_field()
 * @see MYTHEME_views_view_field()
 */
// /* -- Comment out this line if you want to use this function
function MYTHEME_preprocess_views_view_field__block_of_articles__block(&$vars) {
  // $vars['output'] = $vars['field']->advanced_render($vars['row']);

  if (isset($vars['row']->nid, $vars['row']->node_title)) {
    $path    = drupal_get_path_alias('node/' . $vars['row']->nid);
    $options = array();
    if (isset($_GET['page'])) {
      $options['query'] = array(
        'page' => $_GET['page']
      );
    }

    $vars['output'] = l($vars['row']->node_title, $path, $options);
  }
}
// */

```

**Don't forget to clear your cache!**
This should only be done in cases when it's really needed: for example when an Article listing block (like this really simple one which you can import: http://pastebin.com/tmq0kZwT) is also displayed next to the article nodes, and we want the current pager position to be "remembered".
> 6 votes

# Answer
Normally you should change it in the View configuration.

But there is a tricky alternative by using `hook_views_post_render` and PHP DOM as follow:

```
/**
 * Implements hook_views_post_render().
 */
function MYMODULE_views_post_render(&$view, &$output, &$cache) {
  if ($view->name == 'my_view') {
    $doc = new DOMDocument();
    $doc->loadHTML($output);
    // ... do some HTML modifications here ...
    $output = $doc->saveHTML();
  }
}

```
> 1 votes

# Answer
Try using http://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7

Altering the content can be achieved by editing the items of $view-\>result

```
function YOURMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
    foreach($view->result as $k => $result) {
      if ($some_condition) {
        // do something to the result row
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, views
---


title: Map of projects

text:
# Question
Title: Map of projects
My company is doing IT and solar/wind power projects And i would like to show it on a map When people click they should go to page with full project information

What is the best way to do it?

# Answer
Try installing GMap module

The GMap package consists of the following modules:

**GMap:** provides the GMap API, integration with Views and Location, and GMap macros.

**GMap Location:** Provides a map of all a site's nodes and a map of all of the site users.

**GMap Taxonomy:** Allows you to display different map markers based on taxonomy of a specific node.

**GMap Macro Builder:** Provides a GUI for building "macros" (a text-based way of describing arbitrary GMaps).

Find addresses on GMAP #1921872: Find address on map button - 7.x only
> 0 votes

---
Tags: google-maps
---


title: how to send a file to a specific user?

text:
# Question
Title: how to send a file to a specific user?
I have a content type which has an **entity reference** pointing to users. I need to have a permission policy that says: **only users who are defined in the content** (as entity reference) can **view** it or **download** the file attached to it. anybody else should be faced with a message which saying: It's not your business!!

help please

# Answer
> 0 votes
You can try this module: https://www.drupal.org/project/nodeaccess\_userreference. I use it too and it works very well.

As the module's page says, it "Gives content access permissions to users for content that references the users with User reference or Entity reference."

With this module you can define permissions just for the entire entity, you can't define them to the single fields.

---
Tags: uri, users
---


# Question
Title: Should you use check_plain() prior to inserting into database?
I am currently using check\_plain() etc on displaying user entered data in HTML, and I am also using check\_plain() etc prior to inserting the user data into my custom tables.

When inserting or updating the DB, I am always using db\_insert or db\_merge. Do I need to validate like I am, or are those functions doing it for me already?

If they are doing that already, do I need to use check\_plain() on output still?

# Answer
I downvoted Devaraj Johnson's answer because it suggests to `check_plain()` data before saving it to the database, which is wrong.

The idea behind `check_plain`, `filter_xss` and `filter_xss_admin` is to prevent XSS attacks, which are related to the front end.

When you handle database queries, use parameters and the DB API to prevent SQL injection attacks. Whenever you output data to the browsers, use check\_plain, and other security methods.

Note that `check_plain()`, `filter_xss()` and such functions do change the data. When you save data into the database, you are only escaping specific characters, but you do not alter the original text. If you use `check_plain()` in database insert/updates, saving data a few times can mess up your data with a lot of `&`, `<`, etc character replacements and some HTML tags stripped out.

Here are some good reads:
> 5 votes

---
Tags: 7, security
---


# Question
Title: User listing not showing up with user reference when create programmatically
I am using the References module to create a User Reference programmatically. However, when I use the field that is created, there is no listing of the users to choose from. The User Reference works when I create a field from the UI.

I first create the field as follows in my hook\_install function:

```
    $field = array(
        'field_name' => 'vendor_user_reference',
        'type' => 'user_reference',
        'cardinality' => 1,
        'entity_types' => array('commerce_product'),
        'translatable' => FALSE,
        'locked' => TRUE,
    );
    field_create_field($field);

```

I then call when the product type is created the following code

```
$instance = field_info_instance('commerce_product', 'vendor_user_reference', $product_type['type']);

if (empty($instance)) {
    $new_instance = array(
            'field_name' => 'vendor_user_reference',
            'entity_type' => 'commerce_product',
            'bundle' => $product_type['type'],

            'label' => t('Vendor User Reference'),
            'required' => TRUE,
            'settings' => array(),
            'widget' => array(
                'type' => 'user_reference_autocomplete',
                'weight' => -10,
                'settings' => array(
                        'autocomplete_match' => 'contains',
                        'size' => 20,
                        'autocomplete_path' => 'user_reference/autocomplete',
                ), //end setting array
            ), //end widget array
            'display' => array(),
    );
    field_create_instance($new_instance);
}

```

This creates the field on the entity/bundle, but when I try to use it from the UI, there are no user listings. This is the case if I use select list or autocomplete.

What am I doing wrong?

# Answer
> 0 votes
Programmatically create user reference field

I have found the solution to having the user reference field populate the user option list programmatically. You need to initialize the referenceable\_status settings when defining the user reference field. See my answer in the Question above.

---
Tags: entities, users
---


# Question
Title: Change role of users after deleting referred content via rules
I added an entity reference field to user referring to a type book.

I also created a rule that each time e user update that field, selecting one book, his role changes from authenticated to reader. So let's suppose there's a book and five users pointing to that book. These five users are readers. What i would like to do is that when that book is deleted, those 5 users role change into authenticated, being no more readers.

What i need is a way to reach the referencing users when deleting a book. I think adding multiple reference field from book to users could be kinda dirty, because there's already a connection between book and reader.

I've already created a rule that when a user change his book field, selecting no book, his role reader is revoked. I hoped that in this way, considering that when i delete a book all the users referencing to that book change automatically their referencies, their role can change too, but unfortunately it seems that this is not considered a "After updating an existing user account" condition.

How could i do that possibly using rules? If it is possible, but not via rules, can you explain me in details how can i do?

# Answer
I think i resolved it by using "fetch entity by property" and looking for the entity reference field that is equal to the current removed book. Doing that create a list that you can iterate with the loop and inside this use actions to revoke roles.
> 0 votes

---
Tags: rules, entities, users
---


# Question
Title: How to synchronize my Drupal site with content pulled from a Wordpress site?
I need a solution which asks to another site (running WordPress) for updates (i.e., I want to pull new content posted on a WordPress site into Drupal.

Please note that I need a regular (daily) sync of the contents, not a single import.

How can I implement this?
Can I read the site RSS? Or can I ask in some other way this data?
And how?

# Answer
> 2 votes
Wordpress exports its content using RSS. The standard way of pulling this content on a regular basis is to configure the core RSS **Aggregator** module (disabled by default) to pull the content from the WordPress RSS. It is highly configurable, you can pull daily or by the hour.

Here is a link to an introduction to the Drupal Aggregator - quoting:

> Aggregator is a key part of Drupal that is often ignored.
>
> I blame it on the confusing name. No, Aggregator is not an animal in Florida that eats people. Aggregator is a module that imports content from RSS feeds into Drupal.
>
> Because it has a name starting with "A", Aggregator is the first module that people ever see on the Modules page. In this tutorial, we're going to show you what Aggregator does and how to use it.

---
Tags: 7
---


# Question
Title: How to embed Responsive Youtube video in Drupal Bootstrap subtheme?
I am trying to embed a Youtube video to a block using Bootstraps .embed-responsive-item class. The Text Format is set to Full HTML.

```
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="//www.youtube.com/embed/zpOULjyy-n8?rel=0" allowfullscreen=""></iframe>
</div>

```

It’s working just fine on my static html version. However within Drupal the video canvas doesn’t use the full block dimension? What’s the correct way to embed full-size Youtube videos in a Drupal Bootstrap subtheme?

# Answer
Here’s my solution: I was using an outdated CDN version for Bootstrap before 3.2.x. Make sure that you're using at least Bootstrap 3.2.0 or higher (http://blog.getbootstrap.com/2014/06/26/bootstrap-3-2-0-released

Thus I wasn’t able to use .embed-responsive-item class in my template files. Anyway, Thank you for support and quick workaround!
> 0 votes

# Answer
This might help:

responsive-youtube-embed

The essential bit:

> You will need to wrap the responsive youtube embed code with a and specify a 50% to 60% padding bottom. Then specify the child elements (iframe, object embed) 100% width, 100% height, with absolute position. This will force the embed elements to expand fullwidth automatically.
> 0 votes

---
Tags: theming
---


title: How to remove non existing page?

text:
# Question
Title: How to remove non existing page?
I have this page where I've put block views on it but I can't seem to remove it. It's not in the menu items.

I don't know what to show you here, so please if you need screenshots ask me.

Examples:

Ex 1

Ex 2

# Answer
Example 1 is node 5 (http://erlinevanhijfte.be/node/5). go to it and delete it.
Example 2 is node 102 (http://erlinevanhijfte.be/node/102). go to it and delete it.

To find the node I just looked at the page source which has a shortlink meta tag which shows the node id and also the body tag has a class which shows the node id
> 1 votes

# Answer
Try delete Ex 1 and delete Ex 2 when you are logged on.
> 1 votes

---
Tags: views
---


# Question
Title: How to render Entityform submission (entity) without DOCTYPE and HEAD tags?
I need to render entity as a part of page instead of individual page. By this I mean I want to able to render it without DOCTYPE declaration and HEAD tags.

Typically this could be done within html.tpl.php but I haven't found the correct naming convention or other solutions.

How to render entity programmatically in a bare div container using Entity view modes? This shouldn't be a huge problem since e.g. Views can list entities using a certain display/view mode. I'm trying to render it in a Rules config to send it out as email.

# Answer
> 0 votes
So in the end it was the Emogrifier class that kept adding the DOCTYPE and everything else.

It would have been good to know that it adds CSS inline but it also fixes/creates a whole new document. So it can't be used for e.g. fragments or in this case entities.

---
Tags: forms, entities, theming
---


# Question
Title: View of taxonomy terms - add preprocess class
I have a view showing taxonomy terms with an images field. I'd like to add a class .has-images if the images field is not empty.

I've done this before with nodes using preprocess, have tried something similar and have looked around for an answer though I can't seem to get it to work. Also where would the code go? would it go in a view.preprocess.inc file?

This is an example of node.preprocess.inc

```
function THEMENAME_preprocess_node(&$vars) {
 if(!empty($vars['field_images'])) {
    $vars['classes_array'][] = 'has-images';
 }
}

```

Any help would be much appreciated.

# Answer
> 0 votes
You should try hook\_views\_pre\_render(&$view); http://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7

Also you can write a template file to write extra css class with condtion. For this go to advance section and go for theming section and choose a template name.

---
Tags: views, taxonomy-terms, theming
---


title: Create a menu with a list of all groups

text:
# Question
Title: Create a menu with a list of all groups
I have installed the Organic Group module and I created some groups. How can I make a menu which contains a list with all the groups? Thanks!

# Answer
I am not clear what is your requirement. If you want to create a single menu page and want to show list of group name , you can do this using views. Create a view page and list your content and select menu type as normal nemu item.

OR

If you want to create list of menu items according to group name, in that case you should try to create custom menu using hook\_menu. check here https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7
> 0 votes

---
Tags: organic-groups
---


# Question
Title: jquery slide toggle - affects all on the page
I have a view with a list of a content type and using drupal behaviors and jquery toggle, I trying to toggle some content when the user clicks a div. The only problem is that it's affecting all the divs and they're all toggling open, I'd just like the one they clicked to open.

Here is my code:

```
(function ($) {
 Drupal.behaviors.myToggle = {
  attach: function(context, settings) {
  $('.views-row').find('.views-field-field-mp3').hide();

    $('.mp3-toggle', context).click(function() {
     $('.views-field-field-mp3').slideToggle();
    });
  }
 };
})(jQuery);

```

I've tried return false and a couple of other things, though none seem to work.

Any help would be much appreciated.

# Answer
> 1 votes
You'll need to make use of the `this` keyword inside your click function:

```
 Drupal.behaviors.myToggle = {
   attach: function(context, settings) {
     $('.views-row').find('.views-field-field-mp3').hide();

     $('.mp3-toggle', context).click(function() {
       $(this).parents('.views-row').find('.views-field-field-mp3').slideToggle();
     });
   }
 };

```

---
Tags: views, javascript
---


# Question
Title: How do I add a Confirm Order button in Commerce Checkout?
Using Commerce Kickstart 2

With the default checkout, the payment is taken on the Review page. Then the next page (Payment) processes with the merchant (in our case Authorize.Net).

Then there is a Confirmation Page... and the only pane on that page is Express Checkout Review and confirm' (does that refer to Paypal?).

I guess I'm expecting to a see a 'Confirm Your Order' button of some kind, but it never appears. Basically, the order is processed and goes immediately to 'Completed'.

How do I get that Confirmation page to appear?

Customers will expect to see a Confirm Order page -after- they have entered their payment... rather than going -immediately- to 'Completed'.

# Answer
> 0 votes
I recommend starting at the website.com/admin/commerce/config/checkout/rules address, which will bring you to settings page where you are seeing "Express Checkout" options, which to my knowledge is not a PayPal feature and unfortunately is just shares the same name as their Express Payment Processor.

Next you want want to create a checkout rule, which will give you more control over the order process, which can be found at website.com/admin/commerce/config/checkout/rules

This process might start to get difficult, but essentially you want to create a Rule that will trigger a more detailed confirmation page, which can probably handled numerous ways and probably out of the scope of this question.

---
Tags: commerce
---


# Question
Title: Profile 2 display field on my account page
Use this module - Profile2 Registration Path and Profile2 - when registering, so that would be made at check-in person was filling certain fields, in this regard, I have a question - how do I display the fields that person fills during registration, on the profile page?

# Answer
> 1 votes
Un-check "Provide a separate page for editing profiles." on the edit profile page. The help text states:

> If enabled, a separate menu item for editing the profile is generated and the **profile is hidden from the user account page**.

# Answer
> 1 votes
you can enable profile2 pages, that comes with the core of profile 2

That module will add different pages per profile types in the user account. so your users can select their profile and check for the fields they filled during registration

---
Tags: users
---


# Question
Title: Importing nodes from custom XML feed: how do I convert some XML fields into entity references?
Here's the problem:

I'm migrating a Wordpress website to Drupal. It's a gaming portal with a highly customized Wordpress with custom fields, so we decided to generate some XML dumps from Wordpress, then use Feeds module to import that. There are two different "content types", games and articles about those games (strategy guides, tricks, so on). We have two content types, so we generate two XML files. All good so far.

The problem is that those two content types are related. To be precise, the "article" content type is always referred to a game. In Drupal terms, "article" contains an entity reference fields that points to a node of type "game".

Where's the problem? Example: we have an article entitled: "8 tricks for Clash of Clans". This article refers to game "Clash of Clans". The problem is: in our XML we have "Clash of Clans", written in words. I want Feeds module to those words to Node IDs, then save those Node IDs as node references.

I want to do the same with some Taxonomy Terms.

Makes sense?

# Answer
> 1 votes
Maybe a bit late...

Do you know the feeds\_tamper module?

But - I think you won't get around writing your own feeds\_tamper plugin. You have to parse your input field and search for node IDs, then replace it with the ID, as you wrote. This can not be done with feeds\_tamper standard plugins, because even with REGEX-replace you don't have access the node IDs.

---
Tags: entities, feeds
---


# Question
Title: How can I use the Review Order Pane twice in Commerce Checkout?
I'd like to be able to use the Review Order pane twice in the Commerce Checkout... first before the customer enters payment and then again when they Confirm the order.

Or do I need to create a new Pane?

Is this possible? How?

# Answer
> 1 votes
I haven't completely tried this out, but you can duplicate the pane by implementing hook\_commerce\_checkout\_pane\_info\_alter. Something like:

```
function mymodule_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['my_checkout_review'] = $checkout_panes['checkout_review'];
  $checkout_panes['my_checkout_review']['title'] = '[Duped] Review'; // to differentiate
}

```

I don't know what the consequences are of having two review panes, but I think this would be a good starting point.

---
Tags: commerce
---


# Question
Title: How can a field definiton be imported, either via the admin or in code?
In my admin one of the modules I have installed (I am not sure which) has the ability to export a field definition in code, but I can't see any place where I can import the field. I thought that the field creation dialog has abilty to import a field definition from the export code just as the bundle creation tool give the ability to import a bundle.

There is no such thing in the menu and I wonder if I am missing something in the interface or I have to resort to code.

Is there something missing in the admin interface, or do I have to import it in code?

# Answer
I had the solution installed, but I was using it the wrong way or overlooked something about the way it worked.

The necessary module is the Field Tools module. It has an Export Field and an Import Field option. What you need to do is to export the field definition into code, edit the field name in the code and import it.

Field Tools is worth investigating if you need something like that, and it is has a lot of other features I haven't had the chance to try out yet.
> 0 votes

# Answer
There is nothing in the interface but what you *can* do is make a temporary content type which uses the field(s) you wish to import, then export/import that content type to the target site.

Your new field(s) will then be available at the target site, make sure you attach them to other content types before you delete the temporary one or the field(s) will disappear.
> 1 votes

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


# Question
Title: Check for IE8 in theme_preprocess_page function
I'm trying to use inline svgs for a number of logos and icons, and I was considering adding the inline svg code in a preprocess function. This seems like a good place to check for svg support (namely, whether or not it's IE8) and provide a png if needed.

Are there any native Drupal functions available to check for this in a preprocess function? Or should I instead rely on a regex match using `$_SERVER['HTTP_USER_AGENT']`?

I tried to search here - https://api.drupal.org/api/drupal/functions \- but didn't have any luck, so any suggestions or links to other resources would be much appreciated!

Edit: To clarify on what I mean by 'inline svg code' - I want to use actual `<svg>` and `<path>` tags, not `<img src="example.svg" />` to allow for greater styling control with CSS.

@AyeshK - I agree that there are many pitfalls in user-agent and feature detection, mainly related to keeping an up-to-date library of user-agents and features. In this specific case, SVG seems to have broad support moving forward, and I'd like to only serve the png version of images to those few browsers (within our support matrix) who don't support it, avoiding additional HTTP requests for the many browsers that do. The idea of putting this on the server side comes from Adaptive Web Design / Responsive Design on Server Side (RESS).

# Answer
**No** there is no reliable way to detect browsers. Furthermore, you should not check browser compatibility from the server-side.

You have a few alternatives:

* In your module or theme, add IE-specific styles (hide the SVG, show an image instead, likewise). This is well covered in the handbook page. If you do not need to add the stylesheet to every page, then you can add the stylesheet in your `preprocess` hook (`#attached` is recommended. See this and this.)
* Javascript workaround. Again, checking the user agent is not that easy and fool-proof. You can check SVG compatibility either by using a library available, or just by trying to create an SVG element and see if it work. This and this covers it well.
> 1 votes

---
Tags: 7, media, theming
---


# Question
Title: Restore hacked website from database without source
I have a database backup from a hacked drupal site. The source code of the hacked website has been lost. When I try to make another installation of the site working using the old database, I have the following error:

```
Fatal error: require_once(): Failed opening required 'C:\ampps\www\drupal.fox\drupal/sites/all/modules/date/date_api/date_api.module' (include_path='.;C:\php\pear') in C:\ampps\www\drupal.fox\drupal\includes\bootstrap.inc on line 3168

```

How could I avoid such errors? is there any way to make drupal runs temporarly without missing modules or even is there a tool that able to download and install missing modules?

# Answer
Not sure about a tool to download all the modules, but you can do this pretty easily by checking the `system` table.

Run this:

```
SELECT *  FROM 'system' WHERE 'filename' LIKE '%module' AND 'status' = 1

```

You will get a list of module names, and the filename shows where the file was stored. Now, you can download the modules from drupal.org (check the schema version if you have doubts about `1.x`, `2.x`, etc minor version).

If the status of the module is shown as `1`, that means the module is enabled, and there can be tables or any other database changes done by this module. You should not uninstall those modules, because you are going to lose all that data when you uninstall it (!= disabling a module).

Also, use registry rebuild module, which adds a handy `drush rr` to rebuild the registry. You will also need to clear caches a lot (`drush cc all`) to fix any theme registry mismatches. If you have a custom theme and/or have custom `tpl.php` files custom modules or custom themes, you will not be able to restore the 100% functionality unless you have those files.
> 1 votes

# Answer
You can set status to '0' in table 'system' for missing modules P. S. 'drush cc all' is a must-run command after the manipulation like this or manually empty cache tables
> 1 votes

---
Tags: 7, backups, database
---