title: Edit a node into a custom form

text:
# Question
Title: Edit a node into a custom form
I need to edit a node into a custom module. In order to access to the form, I have a custom text link in a view, in that view I have different articles, each row is an article and when I click to the custom text link, I can edit it.

My custom module is "evento". I have the next function to take the node id.

```
   function evento_load($example_id) {

       return $example_id;
  }

```

Then, this one to call to the fuction that creates the form.

```
function edicion_wizard($form, &$form_state, $example_id) {

    $form_state['step_information'] = evento_form($form, $form_state, $example_id);

    //$form = $form_state['step_information'];
    $form['finish'] = array(
      '#type' => 'submit',
      '#value' => t('Terminar'),
      '#submit' => array('form_evento_wizard_submit'),
    );

   $form['next']['#validate'] = array();

    return $form;
}

```

And this is the function to create the form.

```
function evento_form($form, &$form_state, $node) {
  //fill your form with data from exemple_id item

     $type = node_type_get_type($node);
     //$node = node_load($example_id);
     $form['idioma'] = array(
        '#type' => 'select',
        '#title' => t('Idioma del evento'),
        '#options' => array('es' => t('Castellano'), 'eu' => t('Euskera'), 'am'=> t('Ambos'),),
        '#default_value' => $node->language,
        '#states' => array (
            'visible' => array(
                ':input[name="Idioma"]'=>array("value"=>"Ambos"),
            ),
        ),

   );

  $query = "SELECT name, tid FROM taxonomy_term_data WHERE vid=2 AND language = '$language_url';";
  $result = db_query($query);
  foreach ($result as $row2) {
     $options2[$row2->tid] = t($row2->name);
  }
  $form['municipios'] = array(
     '#type' => 'select',
     '#title' => t('Municipio'),
     '#options' => $options2,
     '#default_value' => $node->field_municipio_simple[LANGUAGE_NONE][0]['tid'],
     '#required' => TRUE,
  );

 /*  $form['Lugar'] = array(
    '#type' => 'textfield',
    '#title' => t('Lugar'),
    '#default_value' => $node->field_municipio_simple,
    '#required' => TRUE,

  );*/

  $form['inicio'] = array(
    '#type' => 'date_popup',
    '#title' => t('Inicio evento'),
    '#date_format' => 'd/m/Y H:i',
    '#required' => TRUE,
    '#prefix' => '<table border= \'0\'><tr><td>',
    '#suffix' => '</td>',
    '#default_value' => $node->field_inicio[LANGUAGE_NONE][0]['value'],
  );

  $form['fin'] = array(
    '#type' => 'date_popup',
    '#title' => t('Fin evento'),
    '#date_format' => 'd/m/Y H:i',
    '#required' => TRUE,
    '#prefix' => '<td>',
    '#suffix' => '</td></tr></table>',
    '#default_value' => $node->field_fin[LANGUAGE_NONE][0]['value'],
  );

  $form['titulo'] = array(
    '#type' => 'textfield',
    '#title' => t('Título'),
    '#required' => TRUE,
    '#default_value' => $node->title,
  );

  $form['texto1'] = array(
    '#type' => 'text_format',
    '#title' => t('Texto '),
    '#required' => TRUE,
    '#default_value' => $node->field_descripci_n[LANGUAGE_NONE][0],

    );

   $form['titulo_eu'] = array(
    '#type' => 'textfield',
    '#title' => t('Título en Euskera'),
    '#states' => array (
            'visible' => array(
                ':input[name="idioma"]'=>array("value"=>"am"),
            ),
        ),

  );

  $form['texto2'] = array(
        '#type' => 'text_format',
        '#title' => t('Texto en Euskera'),
        '#states' => array (
            'visible' => array(
                ':input[name="idioma"]'=>array("value"=>"am"),
            ),
        ),
  );

  return $form;

}

```

Obviusly, I have an other one to save the new node values.

The problem that I have is that I can see the values. The form is not show. I don't know if I'm using the right functions or the correct path in the custom text link. (Is the first time I'm doing something like this).

Can anybody help me? Thanks in advance.

**ANSWERD:**

What I've done is in the hook\_menu use the wildcard

```
$items['evento/editar/node/%'] = array(
        'title' => t('Editar evento de agenda'),
        'description' => t('Editar evento de agenda - Contribuyente'),
        'parent'=> array('evento'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('edicion_wizard',3),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
        'customized' => 1, // Must be 1 in order to not dispaly the link in any language
            'language'  => 'es', // language is required in order to make the item translatable
  );

```

So in 'page arguments' I take the 3rd value that is the wildcard. That way I take the node\_id. Now, I don't need evento\_load function.

In edicion\_wizard function there was a mistake. I need to insert the values into a form, that was the reason of not beeing show.

```
function edicion_wizard($form, &$form_state, $example_id) {

    $node = node_load($example_id);
    $form_state['step_information'] = edicion_form($form, $form_state, $node);
    **$form = $form_state['step_information'];**
    //$form = $form_state['step_information'];
    $form['finish'] = array(
      '#type' => 'submit',
      '#value' => t('Terminar'),
      '#submit' => array('form_evento_wizard_submit'),
    );

   $form['next']['#validate'] = array();

    return $form;
}

```

# Answer
First you need to define your custom path to process incoming requests to '*evento/editar/node/%node*'. This can be done by implementing hook\_menu().

```
function evento_menu() {
  $items['evento/editar/node/%node'] = array(
      'page callback' => 'drupal_get_form',
      'page arguments' => array('evento_form', 3),
      'access arguments' => array('access content')
  );
  return $items;
}

```

Note where the path contains %node. This is a wildcard loader and it will automatically run 'node\_load()' for you on the node id that you display in the 3rd argument in the path. (Remember, paths start at 0)

drupal\_get\_form() has a required input of $form id (the function name that builds your form array) but also accepts any number of additional parameters.

What `'page arguments' => array('evento_form', 3)` does, is pass the $form\_id evento\_form to drupal\_get\_form and then passes the 3rd element from the URL (the automatically loaded node object %node) as an additional argument to drupal\_get\_form. To access this the additional variables you've passed to your form function you will need to use `$form_state['build_info']['args']`

You can now do your form manipulations with your additional variables passed using hook\_menu.

If I misunderstood your question, please clarify. I'll try to update my answer accordingly.
> 3 votes

# Answer
That's what Devel is for. Install it, enable it, maybe configure permissions. And then let Devel print out the values you need. Like that:

```
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id, 'FORM ID');
}

```

Let's say the `dpm($form_id)` returned `'evento_node_form'` then you'ld go on like that (and always let Devel print out the values you want):

```
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'evento_node_form') {
    dpm($form, 'FORM');
    dpm($form_state, 'FORM STATE');

    // do your custom stuff here
    dpm($node->field_municipio_simple, 'MY FIELD');
  }
}

```

And don't forget to constantly clear cache when developing.
> 0 votes

---
Tags: forms, nodes
---


# Question
Title: How to remove marker from openlayers map
I have Drupal 7 installation with Openlayers and Geofield (I am using Openlayers as the widget for Geofield). I am able to add new points and show them on the map, however I am not able to remove points from the map once they are edited. I guess that the answer might be pretty simple and I might be doing something wrong, however I can't figure it out!

# Answer
Finally I managed to deal with it. In case someone else needs the answer:

1. you choose the selection tool (the one with the cross)
2. click on a point and press DEL
> 4 votes

# Answer
Hold down "Delete" and single click the icon you want to remove.
> 1 votes

# Answer
And on Mac, I just found out that you need to: 1. select the marker 2. press fn + backspace.
> 1 votes

# Answer
You have to select the "selection" tool and then click on a marker while clicking on "Ctrl" (or Shift, I don't remember now).
> 0 votes

# Answer
click the marker you want to delete on the map and then press delete key on the key board repeat the process for each marker you want to delete
> 0 votes

---
Tags: javascript
---


# Question
Title: Do I have to use Views to use all the behaviors of OpenLayers maps module?
I just started using the http://drupal.org/project/openlayers module. There are plenty of tutorials to learn about it, but all of them make use of **views** to show the maps.

I need to show a simple map to show a single the location. I need this map to show a marker and a tooltip with some information (address, phone,...)

I tried showing a map in a node by adding the **geofield field** to a content type and then setting the **OpenLayers Map Widget** in manage display.

The map is shown up fine but as far as I see there no way to add a **popup** to the map.

Then my question is: Do I need to show the maps through a view to get all the **behaviors** provided by the module?

# Answer
> 1 votes
The learning curve is a little steep when first working with openlayers if you really want to use it you can create your map and add a geoJSON layer to it and just write the geoJSON code in the textarea provided to create the point and popup info. Checkout openlayers plus module for more behavior options.

# Answer
> 0 votes
**Yes**, you have to create a **Views** for that (using a Nid argument to show only the specific node location point) and show that map as block after/before node content. I had the same problem last week and this is the most easy way to get a map with popups.

# Answer
> 0 votes
you have create a view for that content type to create an open layer overlay & then you can easily enable that layer in behaviour section you just need to enable your created openlayer overley layer pop up layer .

---
Tags: javascript
---


# Question
Title: How to limit number of points that user can add through Geofield widget to Openlayers maps?
Im using the modules stuck very similar to one described here ( Need a simple Google Maps solution; lost in the labyrinth of modules).

```
Geofield, Openlayers, Drupal 7

```

The difference is that I dont use Address field for auto detecting the lat/lang from address. The Geofield field widget type is set to "Openlayers map" so the points can be manually added by user to the map when the node is being edited.

Is there any way to limit the maximum number of points that user can mark on map? (to 1)

# Answer
1. In the settings of the GeoField you'd like to limit the entry for, set **Storage Options** to 'Store each simple feature as a separate field.'
2. Then in **Location field settings**, you can set the limit to one.

Number 1 is important, as it will make sure that clicking on the map a second time, moves the point around, instead of creating new points.
> 1 votes

# Answer
Try the 7.x-2.x-dev version of geofield. It fix this bug.
> 1 votes

# Answer
If you go to your content type \> manage fields and click edit next to your Geofield, then scroll to the bottom of the page you should have options for `Multi-value input handling` and `Number of values` either/both if these should give you the control you want.
> 0 votes

# Answer
If you go to your content type \> manage fields and click edit next to your Geofield, then scroll to the bottom of the page you should have options for set Storage Options to 'Store each simple feature as a separate field. check thisn as it is a radio button
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to display an "Out of Page" (PopUp) ad from Google DFP on a Drupal 6 site?
Been beating my head on this for a while now. We've recently set up Google DFP for small publishers to use with a Drupal 6 site. We use the google admanager module to display the ads properly throughout the site using blocks.

I'm trying to create an out-of-page (ie. popup) for the front page.

In the past with OpenX I accomplished this by putting popup code in a block on the page. But this hasn't seemed to work yet with DFP.

Admittedly I'm still learning the in's and out's of the system, but have tried a few different ways now to no effect.

I've tried this: https://support.google.com/dfp\_sb/answer/3370474?hl=en but haven't gotten it working yet, and not sure it will even be suitable for general use by staff who submit ads.

Would love to hear how others are making this work.

# Answer
> 1 votes
Looks like I solved it. Below is how ...

Finally got the process of creating a pop up on DFP figured out, now onto the Drupal part of it. https://productforums.google.com/forum/#!category-topic/dfp/inventory-management/dfp-small-business/e4vUwjgd4lk

**UPDATE**:

Got it working this way...

OK. Looks I mostly have it.

Just bypassed the Google Admanager module and generated a tag from the ad unit page. Then I put it in my theme `page.tpl.php` header enclosed in this (to make sure it is only front page):

```
<?php if ($is_front) { ?>
<script>......</script>
<?php } ?>

```

And then put the rest in the block with php enabled. I also made sure to remove the adslot generated other than the popup.

Hackish but it does the trick.

But if anyone knows how to make it work with Google Admanager, would love to look at it.

---
Tags: 6, javascript, blocks, advertising
---


# Question
Title: How should I read values from multi-field's subfield?
I'd like to access values stored in a Multifield programmatically. I use a Computed Field to do some calculations based on these values.

My current solution utilizes `field_get_items(... ,'my_multifield')` which returns a data structure containing an array of (sub)fields. Of course, I could extract values from that data, but I wonder if there is a better solution.

I took a look at the multifield source code, especially the tests, but I could not figure it out. What is the intended method for reading values from multi-fields?

# Answer
`field_get_items()` is the only function provided by core to help with this.

The Entity module provides the `EntityMetadataWrapper` class, though, which makes these things a bit more palatable. E.g.

```
$node_wrapper = entity_metadata_wrapper('node', $node);
try {
  foreach ($node->field_my_field as $item) {
    $val = $item->value->value();
  }
}
catch (\EntityMetadataWrapperException $e) {
  // Recover...
}

```

That's about the simplest example there is, it would be worth reading the docs to find out how else you can use it.
> 2 votes

---
Tags: entities
---


# Question
Title: Creating a user reference field based on a similar field on a referenced node
I have 2 content types (project and issue), you can think of this as an OG style set up, the child nodes reference the parent node via a node reference field called "project" on the issue node type.

The "project" node type has a user reference field called "members".

I'm trying to build a view to create a user reference field on "issue" called "assignee", I would like to limit the users that may be referenced to the users who are in the "members" field of the project node.

So I've created a user view with a reference type and am playing with adding contextual relationships and references, but I am getting no results. I know this is a pretty complex way to use these modules, and typically I would just write a module to achieve this, but I would really like to do this without writing a new module.

Has anyone ever dealt with anything like this?

# Answer
> 1 votes
1. Create a view with all users.
2. Create a relationship of type reverse join to project via the members field.
3. Create a relationship of type reverse join to issue via the project field.
4. Add a contextual filter on nid using the second join we created (issue).
5. Set the view type to "references".
6. Done :)

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


# Question
Title: Add custom user image field on private messages list instead of default user picture
ok, this is what I have done so far but it is still not working.

First I wanted to add senders profile picture to the private message list on each user profile page. To accomplish that, I used the following code from drupal.org forum:

https://drupal.org/node/1549540#comment-5956560

It does work on my site, but it is using the default user picture. I would like to use a different image for users profile page. So I created an image field named `profile_image`. I am not pretty sure what is the best approach. On this page, they are trying to change the default user profile picture by the image field but for some reason it is not working for me:

How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php?

I took the `user-picture-tpl.php` which had the following code:

```
<?php if ($user_picture): ?>
  <div class="user-picture">
    <?php print $user_picture; ?>
  </div>
<?php endif; ?>

```

I removed it and add this code:

```
<?php if (!empty($user->profile_image[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->profile_image[LANGUAGE_NONE][0]['fid']);

  $account = user_load($account->uid);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'people_profile_image', 'path' => $file->uri));
}

```

Nothing is working yet. what I am doing wrong? could you please help me?

Thanks

# Answer
> 0 votes
You have made mistake in your field name, Drupal creates an machine name of any field prefixed as "field\_" if you create it using Field UI. Using thumbnail as the style and also ensure that the style you have added -- people\_profile\_image is created in the Image Styles

so your code should be

```
if (!empty($user->field_profile_image[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_image[LANGUAGE_NONE][0]['fid']);
  $account = user_load($user->uid);

  // Note the style name is "thumbnail" and that your field name is
  // field_profile_image not profile_image which you have put in second line
  // which loads the file
  echo theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri));
}

```

---
Tags: users, media
---


# Question
Title: Relationship between node and taxonomy term using migrate_d2d_ui
I used Migrate 7.x-2.6-rc1+30-dev and Migrate\_d2d\_ui 7.x-2.1-beta1 module to upgrade my "Drupal 6" website to D7, everything went fine but the node-to-taxonomy relation seems to have got lost. How to relink the relation in the imported data ?

Below is the snapshot from setting form:

This didn't work for me: https://drupal.org/node/2063203

# Answer
If you're getting values from the d6 db, but it is not mapping properly you can likely use `public function prepare($node, $row) {...}` on your migrate object to map the taxonomy terms from the d6 site to the d7 version. Off the top of my head I don't know how that looks, but that is where I would start. prepare !
> 0 votes

---
Tags: 7, migrations, upgrading
---


# Question
Title: Drupal 7 - Multi Step Registration with save on end
I have been looking through some tutorials, but couldn't find what i wanted to accomplish.

The thing i can't find in any tutorial/resource is the ability to save users registration data on the last step.

What i want to accomplish is to display a registration page for users, and the user goes through 3 steps.

* Step 1 - Registration info
* Step 2 - Payment Info
* Step 3 - Save and show custom message

Can some one post some good resource, where it shows how to do this.. Preferably with explanation so i can learn from it.

The tutorials i followed so far were saving after the first submit.

Thanks in advance

# Answer
As a clue, build a module and insert your form inside it, then set your form `['rebuilt']` attribute to TRUE in this way your form is saved in `['storage']` attribute in every step and you can get them via `$Form_state` variable.
> 0 votes

---
Tags: users, forms
---


# Question
Title: Is there a Self-Imposed Bulk Operations Limit?
My database has millions of nodes. We've been approved to delete a very large amount of them given certain criteria so I set up a view with VBO to handle the batch deletions. I've exposed the pager limit setting in Views so I can run batches of different sizes. When I try to run anything higher than 1000 nodes per batch (10 per run to prevent timeouts), the batch sets its max value to some number around 1000, depending on the server. This is limiting me to run either 1000 at a time or attempt to run the entire result set.

I'm looking for any ideas as to why there is this seemingly self imposed limit on the bulk operations. My sandbox server sets the batch max at 1001 while my production server sets it to 995.

* Drupal 7.27
* Views 3.7
* VBO 3.1

# Answer
> 0 votes
No. there is no such limit.

In Views, make sure you have enabled the option to select all items across all pages. With that configuration, all items will be selected regardless of the pager configuration.

---
Tags: views
---


title: Views display labels with empty fields

text:
# Question
Title: Views display labels with empty fields
I've created this view that displays content an author creates in a table. Trouble is, this view only appears once the author creates at least one piece of content, is there a way to show the labels by default? ie. even when there is no content in the fields?

I tried playing about with no result behaviour, but that just overrides the whole thing. I know there is a lot of info out there on how to hide fields if there is no result but i'm looking for the opposite.

Here's the table:

Here's the view:

Cheers, Rumman

# Answer
Yes, under Advacned Options for the View there is a `No Results` option. You can set a `global text result` as an example and say "sorry no values found." Then under the `Table` format `Settings` there is a checkbox to `show No Results text in Table`. That will replace the empty row with your message -- while still showing the table headers.
> 1 votes

---
Tags: views
---


# Question
Title: How to display the total number of article/page on a term views?
In Drupal 7. We created a Views to list all pages assigned to this particular TermA. But some of these pages can only be view by registered user. We would like to show the total number of pages in this TermA, so un-registered user know how many articles/pages they are missing without register. So how can I display the total number of pages in this TermA in View(not the term menu link)? It will be nice to show that number next to(or under) the Views title(see screenshots).

***Current setting on views and display***

***wanna have total number of articles in this TermA like this***

# Answer
You could achieve this by creating view attachment or block which will calculate the total number of nodes per term. Do not add access rule for this case. This can be then called in the header of the Taxonomy Term View using Global:View where you can select the newly created view and its display.
> 1 votes

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


title: Integrate simplenews and rules

text:
# Question
Title: Integrate simplenews and rules
I have a website developed in Drupal 6. I am using Simplenews for my newsletter. When a user subscribe to the newsletter I would like to redirect him to a new thank page. In order to do this, I need integrate simplenews module with rules.

In this link https://drupal.org/node/620498 there are several patchs, #40 it works. The point is that I´m not a developer and I don´t know how I do not know how to implement it. I understand I have to create multiple files with these lines of code. I do not know in which folder I have to save the files. Could anyone help me?

Thank you very much!

# Answer
> 1 votes
It seems like you don't really understand what a patch is and how you can use them. You can read about the basics at https://drupal.org/node/620014. Basically, this is a general definition of a patch:

> A "patch file" is a specific kind of file that contains code that is used to modify one or more existing files for a Drupal module.

You can use a special program to apply a patch, but I prefer applying them manually. You can find some more detailed information at https://drupal.org/node/534548.

In the patch you refer to, you find for example

```
+++ simplenews_rules/simplenews_rules.info
@@ -0,0 +1,7 @@
+; $Id$
+name = Simplenews rules
+description = Provides integration with Rules module for Simplenews.
+dependencies[] = simplenews
+dependencies[] = rules
+package = Mail
+core = 6.x

```

That means you should add the code (without the "+" signs) after `@@ -0,0 +1,7 @@` at the top (after the "0th" line) of the `simplenews_rules/simplenews_rules.info` file. If the file doesn't exist yet, simply create it with your favourite code editor at the mentioned directory. I'm using Notepad++, for example.

---
Tags: 6, rules, emails
---


# Question
Title: Relationships block other content type from showing
I have this views\_slideshow and its supposed to show two content types, but shows only one. One is simple content type with image field (the one that is not getting showed) and other is commerce product type with relationships and contextual filters. So could this be something blocking this other non commerce content type from showing up? If I remove relationships for product, then it shows the Slideshow content type, but hides Products content type.

# Answer
> 0 votes
Solved by adding `:title` filters and setting both to `not empty`. Also set second filter (default, not referenced) for a separate group under `OR` setting.

---
Tags: 7, views
---


# Question
Title: Getting Drush to play with MAMP and Acquia
I have a Mac workstation which is shared between two users, User°1 who first installed the machine, and User°2 who came along after, both administrators. User°2 has installed Drush using `brew` and Acquia Drupal and all this works very nicely. However, when User°1 tries to start Acquia Drupal he just gets an alert box saying that the Apache server failed to start - nothing shows up in the Apache error logs (the MySQL server starts ok though). I can't help thinking this is something to do with permissions, but no idea where to look.

So user n°2 has installed MAMP and that all works ok except for one thing: running Drush. Here is an example:

```
imac:~ martinknapp$ drush @eco pm-info views_bulk_operations
Extension        :  views_bulk_operations
Project          :  views_bulk_operations
Type             :  module
Title            :  Views Bulk Operations
Description      :  Provides a way of selecting multiple rows and applying operations to them.
Version          :  7.x-3.1
Date             :  2012-12-03
Package          :  Views
Core             :  7.x
PHP              :  5.2.4
Status           :  enabled
Path             :  sites/all/modules/views_bulk_operations
Schema version   :  6002
Files            :  plugins/operation_types/base.class.php, views/views_bulk_operations_handler_field_operations.inc
Requires         :  entity, views
Required by      :  admin_views
Permissions      :  none
Configure        :  Aucun(e)

```

It appears to be running PHP5.2.4 (which I believe is almost certainly the reason I am constantly getting errors on db objects). I've done everything I can to get this working, in particular by using the alias command like so:
`alias drush='/Applications/MAMP/bin/php/php5.3.27/bin/php /usr/local/Cellar/drush/6.2.0/libexec/drush.php'`
but all to no avail.

Any ideas?

# Answer
> when User°1 tries to start Acquia Drupal he just gets an alert box saying that the Apache server failed to start - nothing shows up in the Apache error logs (the MySQL server starts ok though).

Have you ensured you are only running a single apache process as OSX ships with it's own version and MAMP also has it's own. You can confirm it by running `ps aux | grep apache` in your shell.

Additionally, you can check which version has priority on the system (based on `$PATH`) by running `which apachectl` in a shell (example output).

```
$ which apachectl
/usr/sbin/apachectl

```

Which will help you determine that *if* there are conflicting version trying to run, who will be serving the requests.

> I've done everything I can to get this working, in particular by using the alias command like so: alias drush='/Applications/MAMP/bin/php/php5.3.27/bin/php /usr/local/Cellar/drush/6.2.0/libexec/drush.php' but all to no avail.

I am not sure whether you should be executing that `drush.php` file directly as all of the installations I have ever completed all point to an executable that I usually move the `/usr/bin` or `/usr/local/bin` for system wide availability - But then again, I haven't tried installing drush 6 yet so that could have changed.

If you do a bit of development and don't like dealing with issues like this, I recommend you look at virtualising your environments using a tool such as Vagrant. Doing this will allow you to build an isolated development environment where you can configure the environment then package it for reuse should you ever need to reset it.
> 0 votes

---
Tags: drush, acquia-dev-desktop
---


# Question
Title: basic question: fast mobile site with omega
I would like to propose our company to make our site responsive. I thought to use the Omega theme as a basis. But one question before I dig deeper:

I would like to have a fast mobile version of the site that does not load all blocks and that just loads a few images and these ones in a small resolution.

Can I do this with Omega? Which other modules do I need?

# Answer
Adaptive Image is great for loading a smaller version of the images on smaller devices. It determines breakpoints, or you can set them, and saves an image into different sizes. Then automatically loads smaller images on smaller screen sizes.

For hiding content, you need to decide if you want the website to be adaptive or responsive. If you are hiding block regions on a tablet view (\<768px), and someone who had their window size reduced makes their browser window full screen on a desktop, are they suddenly going to be missing blocks and regions?

I tend to just use CSS media queries, and re-arrange the content on smaller devices, and If I really have to, then hide content with display:none when the browser window, or device screen size gets reduced to a certain width.
> 1 votes

---
Tags: media, theming
---


# Question
Title: Problem in sending mail with attachement
I'm coding a small module allowing to send mail to new users with an attachement file as pdf. This pdf include all subscription details of the user.

I generated the pdf file using FPDF and I put it (temporary) in DRUPAL\_ROOT and I used two ways to send the mail:

1) Using the `hook_mail_alter`:

```
function aos_user_pdf_mail_alter(&$message) {
  if($message['id']=='user_register_pending_approval') {
    $attachment = array(
     'filecontent' => file_get_contents(DRUPAL_ROOT . '/' . 'yourfilename.pdf'),
     'filename' => 'yourfilename.pdf',
     'filemime' => 'application/pdf'
    );
    $message['params']['attachments'][] = $attachment;
  }
}

```

2) Or creating a custom function:

```
function aos_user_pdf_send_mail ($mail, $uid) {
  $user = user_load($uid);
  $to = $mail;//gets the current user's mail address
  $from = variable_get('site_mail', ''); //admin's mail address
  $body = 'This is a test mail';
  $subject = 'Your pdf';
  $attachment = array(
    'filecontent' => file_get_contents(DRUPAL_ROOT . '/' . 'yourfilename.pdf'),
    'filename' => 'FILE',
    'filemime' => 'application/pdf',
  );
  $message = drupal_mail('aos_user_pdf', 'message_key', $to,
    user_preferred_language($user),
    array(
      'body' => $body,
      'subject' => $subject,
      'attachment' => $attachment),
      $from,
      TRUE
    );
}

```

Unfortunately the mail is sent, but without the attachement, Please can you show me where's my mistake or an alternative way to do the job.

# Answer
> 3 votes
For sending mail with attachment you should use Mail System and Mime Mail module Attachment functionality is built into the Mime Mail module.

After that you must set up drupal\_mail() to use mime mail as the mail system interface. This is where the mail system module comes into play. The module is pretty straightforward, and lets you set a different mail system per module. There is a straightforward configuration at admin/config/system/mailsystem where you create a new setting for your module, and select mime mail as the mail system.

Assing anttatcment in variable

```
$message['params']['attachments']

```

After that you will be able to send mail with attachment.

For more information visit here

---
Tags: 7, emails, files
---


title: jQuery problem click function

text:
# Question
Title: jQuery problem click function
I'm having trouble doing simple stuff in jQuery. What I wanted was to call a function when something was typed in an input field.

Now I'm just trying this: when you click anywhere on the page to call an alert box like this:

```
(function ($) {
    $('body').click(function() {
        alert('test');
    });
})(jQuery);

```

This doesn't work ... . But when I do this:

```
(function ($) {
    alert('test');
})(jQuery);

```

I get an alert box when I load the page. My js file is loaded like this:

```
function xmed_preprocess_page(&$vars) {
    $path = current_path();
    if ($path == 'node/add/product') {
        drupal_add_js(drupal_get_path('theme', 'subtheme') . "/js/add.js", array('weight' => 1000));
    }
}

```

The file is loaded correctly. I'm working with `jQuery v1.10.2`. What could be the problem?

# Answer
Try this as per drupal standard

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('body', context).click(function () {
        alert("test");
      });
    }
  };
})(jQuery);

```

Go through with Managing JavaScript in Drupal 7 for more information
> 2 votes

# Answer
maybe the problem is by your css, open the firebug and see what is the dimension of the body. change the target of body to some thing else like a button. you can also set

```
body,html{
width:100%;
height:100%;
}

```

you can also test

```
(function($) {
$(document).ready(function() {
    $("body").click(function(){
         alert("test");
    });
});
})(jQuery);

```
> 0 votes

---
Tags: javascript, theming, 7
---


title: What file generated output

text:
# Question
Title: What file generated output
I was debugging by adding a `print_r()` to my code to check array values along the way. The problem is I forgot where (which module and which file) I had added the `print_r()` statement since it has been some time I had worked on it. Now some of my pages are outputting an unwanted array print out. Is there a way to find out which module and which file specifically generated the array print out?

# Answer
If you are running on Gnu/Linux or Unix, you should be able to position yourself above the directory holding your code and use the following shell command:

```
grep -r print_r .

```

This will recursively search through the current directory and all the directories below it for the string "print\_r" and print out all lines containing that string, prefixed with its file name.

For future debugging, I suggest you install the Devel module for debugging. At least one of its debug printout functions (`dpm()`) will print where the debug statement is placed by name of file and line number if the object is complex enough to produce a Krumo accordion display of the object/array.

For simpler objects, use the second argument to `dpm()` to remind yourself where you placed it. E.g.:

```
dpm($uid, 'mymodule, line 42, $uid');

```
> 1 votes

---
Tags: debugging
---


# Question
Title: How can I print e-mail messages sent by Drupal to the screen for debugging purposes?
For debugging, I'd like to print the values being used to send e-mail messages to the screen.

After enabling the devel module, I tried this code (modified as per Letharion's comment):

```
function MY_MODULE_mail_alter(&$message) {
  dpm($message, 'email_test');
}

```

I don't get any error message, but I don't see any output, either. How can I print the value of '$message' to the screen?

More details about my site:

I'm trying to debug the e-mails sent upon user registration. There should be one sent by Drupal itself via the Logintoboggan module and another sent by the Rules module.

Anonymous users have the same permissions as admin to view debug messages; I tested this by adding a `dpm()` in my `page.tpl.php`.

I tried setting `Display redirection page` to on as per Clive's comment but the workflow is unchanged from before. If I add `debug($message)` to the `MY_MODULE_mail_alter()` then `debug()` will print the message from Drupal/logintoboggan but not the message from Rules.

# Answer
> 1 votes
The way I debug email is by using the `TestingMailSystem` class:

```
// Use testing mail system.
variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

```

You can then capture and print the mail contents with the following statement:

```
$mails = $this->drupalGetMails();
debug($mails); // $mails is an array holding all mails sent.

```

Here `$this` is the current testing class (instance of `DrupalWebTestCase`).

This is very simple to use as part of automated testing (using the **Testing** framework that is part of the Drupal core).

If you don't want to be troubled by setting up the full **Testing** framework, an alternative method for debugging email is to hijack `drupal_mail`.

To do this you need to install the Devel module and edit the core `mail.inc` by replacing the standard `drupal_mail` with the following function:

```
/**
 * Function to debug mail.
 */
 function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
  dpm('Using hacked version of drupal_mail.');
  dpm($params, 'mailbody');
  // Print out more arguments if required.
  return TRUE;
}

```

And yes, this is hacking core, so: 1) Don't do this on a production site; and 2) Remember to restore `mail.inc` with a pristine version when done debugging.

**Note:** The latter method is a rather nasty hack (but I've found it useful a few times). Using the **Testing** framework to debug mail is the recommended method.

---
Tags: debugging
---


title: How to install Chosen using Drush Make?

text:
# Question
Title: How to install Chosen using Drush Make?
From Chosen module page:

> This module comes with a Drush make file, which will automatically download the jQuery plugin if you use Drush make to set up your website.

I have Drush Make, but commands like..

```
 drush dl chosen
 drush en chosen

```

..don't help.
Should I use `drush make ...` command instead? Maybe there are other commands for quick libraries download.

P.S. I'm working on already installed copy of Drupal.

# Answer
> 3 votes
I found a way:

```
# cd to Drupal root folder
drush dl chosen
drush make sites/all/modules/chosen/chosen.make.example --no-core
drush en chosen -y

```

**Update 04/29/2014**: Chosen now provides Drush command `chosenplugin`.

This answer is still useful for other projects with `*.make.example` files but without custom Drush installation commands.

# Answer
> 3 votes
for the latest version of chosen I usually do the following

drush dl chosen

drush chosenplugin

drush en chosen -y

You not only need to download the drupal module (drush dl chosen) but also the chosen jQuery library (drush chosenplugin) in order for the module to work.

---
Tags: installation, drush, theming
---


title: update panels 3.3 to 3.4 and patch

text:
# Question
Title: update panels 3.3 to 3.4 and patch
It is my first time that I want to patch a module. when I want to update the panels module with drush some message come up that says :

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table '….cache\_panels' doesn't exist: TRUNCATE {cache\_panels} ; Array \[error\]

though I could update the module with administrative UI (but after this update the site goes wrong and my pages shifted to the right of the screen)

so I thought that I should apply this patch ""cache\_panels doesn't exist" error on update"

But when I want to patch the module

\[by copying the patch file into the module directory (7.x-3.3 version) and using cygwin64 command "C:\cygwin64\bin\patch.exe -p1 \< C:\xampp\htdocs\rgpars\sites\all\modules\panels\2188277-panelscache-schema-2.patch" or I even used p0 instead of p1\]

I face with the error that says :

can't find file to patch at input line 5 perhaps you used the wrong -p or --strip option? the text leading up to this was:

---

diff --git a/panels.install b/panels.install index b913012ab645d1be40e2176f516844910822e6b6..196afd10675f46443751fd2b838df45aea04a0ec 100644 --- a/panels.install +++ b/panels.install

---

file to patch:

I would appreciate if you give me the reason behind this error?

# Answer
Issue where the patch came from: https://drupal.org/node/2188277 Look like it was committed on 2014-03-03 http://drupalcode.org/project/panels.git/shortlog/refs/heads/7.x-3.x

My recommendation is to use the latest dev version of panels. You'll also have this issue fixed as well https://drupal.org/node/2196091 `Last packaged version: 7.x-3.4+2-dev` The +2 means those 2 issues have been committed.
> 3 votes

---
Tags: panels, version-control
---


# Question
Title: How to know that the node of a specific type is being viewed for the first time?
I want to display a block on the node page if it is being viewed for the first time. After that that block will not be displaying.

It will be for all the nodes of a given content type.

I know the Drupal put the node in the cache if it is being viewed for the first time but I can't found its code.

Is it possible? Any Ideas?

# Answer
Used the core statistics module.

and then on node view used the function statistics\_get() function and then check it the total count is less than 1.
> 2 votes

# Answer
Use Views Blocks and filter it with *Content: Has new content* to know if it is being viewed for the first time.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Drupal Add Javascript type=text/javascript
I am trying to add javascript to my page and use type="text/javascript" however when I include the following it just encloses it in script tags. How can I fix this? Also, how can I add the type="text/javascript to external files (see the second example)

```
drupal_add_js("$(document).ready(function() {
    // Infinite Ajax Scroll configuration
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    });",'inline');

```

Here is the second example:

```
drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js','external');

```

UPDATE: As suggested by the comments I tried the following:

```
$js = "(function($) {
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

```

But that resulted in the following HTML:

```
<script>(function($) {
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    };
})
(jQuery)</script>

```

# Answer
you can use

```
$js = "(function($) {

    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

```

OR

```
drupal_add_js("(function($) {
$(document).ready(function(){
    $('.mobile-navigation').click(function(){

     });
    });
})
(jQuery)","inline");

```

OR

```
drupal_add_js('sites/all/themes/dawn/js/skrollr.js', array('scope'=>'footer'));
drupal_add_js(drupal_get_path('module', 'module name') . '/js/name.js');

```
> 2 votes

---
Tags: javascript
---


# Question
Title: select term from reference field but deny edit term
How can I allow users of a particular role select a term from a reference field on a node but deny them to 'edit' the terms from that reference field?

Selecting terms: great. If, under taxonomy permissions, you tick 'Administer vocabularies and terms' for a particular role, they will see my own created term reference field and they are able to select the term of their preference which is great.

Editing terms: bad. But if they view the node and see the term, they can click on that term and then they also have the 'edit' permission to edit the term. Surely not what we want because the user might potentially mess up the settings of my carefully designed term reference field.

I'm using taxonomy access control but that only takes care of the node access, not of the term edit access.

# Answer
> 0 votes
Found it. It appears to be a bug in both the rc version and the dev version of the module Taxonomy Access Control for D7. Details from project page:

> Access control for user roles based on taxonomy categories (vocabulary, terms).
>
> * Automatically controls access to nodes (based on their taxonomy terms).
> * Configuration page for each user role.
> * Three node access permission types: View, Update, Delete.
> * Two term access types: View tag, Add tag.

Once a user has access to the edit node form AND they are allowed to 'add tag' on the access-rules-for-user page for that vocabulary, that term will show up and will be able to be ticked/set on the node form regardless of whether or not the default and other vocabulary terms in that vocabulary have been set to 'allow' or 'deny' the 'add tag' on the access-rules-for-user page. Hopefully this makes sense to others as well.

---
Tags: taxonomy-terms
---


# Question
Title: search-api solr is nor performing OR search
I am trying to provide the OR feature for my solr search . when user type words, the search should be able to return result which matches with any word present in the query . I changed the default operator from AND to OR in my schema.xml , After change it looks :`<solrQueryParser defaultOperator="OR"/>` however , It still doesn't perform OR search . The result is empty when I type multiple words . I am using search\_api with solr I have aplplied the changes to my drupal solr configuration as well as solr server .what could be wrong ? any pointers is really appreciated Thanks

# Answer
> 0 votes
You can implement the hook :

```
hook_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query)

```

Have a look to your query & params and see if the solr query is what you were expected, if it's not you can alter it.

---
Tags: search
---


# Question
Title: Disable all form elements when doing AJAX
I have a form where every user input field is AJAX enabled, and I'd like to disable all of the form elements when one of them is changed - is it possible?

# Answer
> 12 votes
Yes, it's possible. For example, you can attach a .js file to your form and extend the Drupal.ajax object.
Every element which can initiate AJAX submission from a form has its own instance of Drupal.ajax. You can find it in the global object `Drupal.ajax`. And every Drupal.ajax object has the methods `success`, `error`, `beforeSend` etc.
Here is a simple example to demonstrate the idea:

```
;(function($) {

  Drupal.testAjax = {
    // Our form
    form_id: 'node-type-form'  //Yes, I tested on my extended node creation form
  };

  Drupal.behaviors.testAjax = {
    attach: function(context, settings) {
      // We extend Drupal.ajax objects for all AJAX elements in our form
      for (ajax_el in settings.ajax) {
        if (Drupal.ajax[ajax_el].element.form) {
          if (Drupal.ajax[ajax_el].element.form.id === Drupal.testAjax.form_id) {
            Drupal.ajax[ajax_el].beforeSubmit = Drupal.testAjax.beforeSubmit;
            Drupal.ajax[ajax_el].success = Drupal.testAjax.success;
            Drupal.ajax[ajax_el].error = Drupal.testAjax.error;
          }
        }
      }
    }
  };

  // Disable form
  Drupal.testAjax.beforeSubmit = function (form_values, form, options) {
    $(form[0].elements).not(':disabled')
                       .addClass('test-ajax-disabled')
                       .attr('disabled', true);
  }

  // Enable form
  Drupal.testAjax.enableForm = function(form) {
    $(form).find('.test-ajax-disabled')
            .removeClass('test-ajax-disabled')
            .attr('disabled', false);

  }

  Drupal.testAjax.success = function (response, status) {
    Drupal.testAjax.enableForm(this.element.form);
    // Call original method with main functionality
    Drupal.ajax.prototype.success.call(this, response, status);
  }
  Drupal.testAjax.error = function (response, uri) {
    Drupal.testAjax.enableForm(this.element.form);
    // Call original method with main functionality
    Drupal.ajax.prototype.error.call(this, response, uri);
  }

})(jQuery);

```

This approach may seem a little difficult, but it gives you full control over AJAX in your forms.
Another way is to use jQuery methods like `.ajaxStart()`, because Drupal uses jQuery AJAX Framework.

# Answer
> 3 votes
I created a widget that can completely disable or present a read-only view of the content on your page. It disables all buttons, anchors, removes all click events, etc., and can re-enable them all back again. It even supports all jQuery UI widgets as well. I created it for an application I wrote at work. You're free to use it.

Check it out at ( http://www.dougestep.com/dme/jquery-disabler-widget ).

# Answer
> 1 votes
You can disable/enable some elements during ajax using this jQuery script:

```
  // Disable elements on ajax call.
  $(document)
    .ajaxStart(function() {
      if ($('.ajax-disabling').length) {
        // Disable elements.
        $(".ajax-disabling input").attr("disabled", "disabled");
      }
    })
    .ajaxComplete(function() {
      if ($('.ajax-disabling').length) {
        // Enable elements.
        $(".ajax-disabling input").removeAttr("disabled");
      }
    });

```

If you will add class `ajax-disabling` to the `<form>` or `<div>` (or any other wrapper) all inputs will be disabled inside during ajax.

You can play around with selectors and disable also selects and textareas.

See also https://drupal.stackexchange.com/a/76838/6309

**Update**

If you have already disabled elements on form and you want to keep them disabled after ajax use next code:

```
  // Disable form elements on ajax call.
  $(document)
    .ajaxStart(function() {
      if ($('.ajax-disabling').length) {
        // Disable elements.
        $('.ajax-disabling input, .ajax-disabling select').each(function(){
          if($(this).attr('disabled') !== 'disabled') {
            $(this).addClass('ajax-form-disabled');
            $(this).attr('disabled', 'disabled');
          }
        });
      }
    })
    .ajaxComplete(function() {
      if ($('.ajax-disabling').length) {
        // Enable elements.
        $('.ajax-disabling input, .ajax-disabling select').each(function(){
          if($(this).hasClass('ajax-form-disabled')) {
            $(this).removeClass('ajax-form-disabled');
            $(this).removeAttr('disabled');
          }
        });
      }
    });

```

---
Tags: 7, forms, ajax
---


# Question
Title: Remove all styling from views field view?
I am using the views-field-view module to output the number of teachers I have in each school, so it's just a plain number. The parent view that this child view is embedded in is a table with some other information (see screenshot).

Is there a way for me to remove any and all formatting from the child view so that the final output looks like it's all coming from one view? As you can see in the screenshot, there is some misalignment with the numbers, and there is also a weird line above the numbers coming from the embedded view.

http://screencast.com/t/cFi0ctcZS

Thanks in advance!

Lukas

# Answer
Yes, you have to override the templates of the child view to remove the markup you don't want.

You will might need to override (in order of how likely it is you need to override them in some way):

**views-view.tpl.php**
**views-view-unformatted.tpl.php** (if you are using the unformatted style. Otherwise whichever style template is relevant to your view)
**views-view-fields.tpl.php**

You need to find where the unwanted line is coming from in the markup/css and then find the template that markup is printed in, then override that template and remove the offending markup.

Alternatively you can likely style it out with css but I would favour the template override option.
> 2 votes

# Answer
If you do not need ANY CSS rule at all from the view module, you will find more effective to just disable the CSS file by adding this function to your theme template.php file:

```
function MYTHEME_css_alter(&$css) {
 //Define an array with the path to the CSS file and a boolean flag
 $exclude = array(
  /*
   * It is possible to define more exclusions by adding more definitions
   * in this zone following the template:
   * 'path/to/css/file.css' => FALSE,
   */
  'sites/all/modules/views/css/views.css' => FALSE,
 );

 //Then array_diff will clean up the unneeded files
 $css = array_diff_key($css, $exclude);
}

```

You can add any CSS file from the system by just specifying the path from the root folder, for instance this will remove the default system CSS file for the module user:

```
'modules/user/user.css' => FALSE,

```

This will reduce the bandwidth consumption and generate smaller files if you use the compress CSS files option.
> 1 votes

---
Tags: theming, views
---


# Question
Title: What is the order of return value for field_info_instances?
I've used `field_info_instances` function to retrieve all fields info under a content type.

`field_info_instances('$entity_type','$bundle_name')`.

As from API page,

1. If `$entity_type` is not set, return all instances keyed by entity type and bundle name.
2. If `$entity_type` is set, return all instances for that entity type, keyed by bundle name.
3. If `$entity_type` and `$bundle_name` are set, return all instances for that bundle.

I didn't get the third point here. what is the default order for return output by `file_info_instances` when `$entity_type` and `$bundle_name` given.

Any idea?

# Answer
This is the query run by `field_read_instances()`:

```
$query = db_select('field_config_instance', 'fci', array('fetch' => PDO::FETCH_ASSOC));

$query->join('field_config', 'fc', 'fc.id = fci.field_id');
$query->fields('fci');

// Turn the conditions into a query.
foreach ($params as $key => $value) {
  $query->condition('fci.' . $key, $value);
}
if (!$include_inactive) {
  $query->condition('fc.active', 1)->condition('fc.storage_active', 1);
}
if (!$include_deleted) {
  $query->condition('fc.deleted', 0);
  $query->condition('fci.deleted', 0);
}

$instances = array();
$results = $query->execute();

```

So it's safe to say there's no default order for field instances; they'll be in whatever order they went into the database, or perhaps different depending on your DBMS and settings.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How I can delete all node/field revisions?
I have a drupal 7 sites, where it keeps node and field revisions. I keep revisions for the case where by mistake a new faulty version is saved and I want to revert back.

But, now I want to clean and optimize the database so to take less space in hard disk.

What are some methods of deleting all the revisions except the current one, for all nodes/fields of the site?

# Answer
> 13 votes
Use the Node Revision Delete module to delete and manage your revisions. (I am the maintainer of the module.)

> The Node Revision Delete module allows you to manage the revisions of the Node according to your choice. It helps you to keep the specific number of revisions for the node. This module provides you the flexibility for applying the revision delete for the specific content type and run it on the specific time. You can manage your settings from the Node Revision Delete Administration Page.

# Answer
> 16 votes
There's not yet a stable release for Revision deletion but a D7 port is on its way (not sure if its functional at all).

In this thread someone suggested using VBO to isolate revisions and delete them.

If you feel comfortable with the API, make a loop through all your nodes, retrieves the revisions using `node_revision_list()` and delete them using `node_revision_delete()`.

As a last resort and if you like messing with the DB (like I do) you can delete revisions' rows in `field_revision_*` and `node_revision` tables. Try this:

**WARNING: not tested at all !**

```
DELETE FROM field_revision_body
WHERE NOT EXISTS (
  SELECT NULL
  FROM node
  WHERE vid = revision_id
);

DELETE FROM node_revision
WHERE NOT EXISTS (
  SELECT NULL
  FROM node
  WHERE node.vid = node_revision.vid
);

```

You can find the complete list of your revisions' tables in the `information_schema` database:

```
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'field_revision%'
AND TABLE_SCHEMA = 'your_database';

```

# Answer
> 2 votes
In same situation I used code below:

```
foreach (node_load_multiple($nids) as $node) {
  // Delete sub revisions.
  foreach (node_revision_list($node) as $vid => $revision) {
    node_revision_delete($vid);
  }
  // Delete archived revisions.
  revisioning_delete_archived_revisions($node);
}

```

# Answer
> 1 votes
I made this for the VBO folks (execute arbitrary PHP), it will delete all revisions (except current). This relies on the sort order built into `node_revision_list()`, **so back up your DB & test for desired results before using on live data**.

```
  krumo($entity);

  $revision_array = node_revision_list($entity);
  $revision_array_ASC = array_reverse($revision_array, TRUE);
  krumo($revision_array_ASC);
  krumo(count($revision_array_ASC));

  foreach ($revision_array_ASC as $vid => $node) {
    $count = count($revision_array_ASC);
    if ($count > 1) {
          node_revision_delete($vid);
    }
  }

  $revision_array = node_revision_list($entity);
  krumo($revision_array);

```

# Answer
> 0 votes
Node Revision Delete module now has a stable release.

> The Node Revision Delete module lets you to track and prune old revisions of content types. Features:
>
> * Define the max amount of revisions to keep per content type.
> * Run on Drush, cron run or on a different period (daily, weekly, etc).

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


# Question
Title: how can i store an image in my postgresql database?
I want to save some data in my module's form like an image.

In fact i want to store an image in my Postgresql database.

# Answer
> 2 votes
You need the Storage API module.

This allows you to set a field's upload destination to a custom storage class, one of which is database.

I've used this module for this exact purpose and worked well.

---
Tags: forms
---


# Question
Title: Using migrate, how can you set the default format to Full HTML?
Using the migrate module to import content from a database. One of the fields contains full HTML but on import the text field defaults to plain text. The admin default is set to Full HTML, but even though the imports are being created by admin, it defaults to plain text.

How do you set the default to full HTML for imports? There's obviously a way around this in code but wondering if there's a patch or anyone has advice on the right approach.

# Answer
> 0 votes
In Drupal 6, when you import with the Migrate and Table Wizard modules there is a text field when mapping each field that is empty. Just type in full\_html and each node when imported with have full\_html entered into that row in the database.

# Answer
> 0 votes
```
$this->addFieldMapping('body', 'body')
     ->arguments(array('format' => 'full_html'));

```

This works for me.

---
Tags: importing-exporting, theming
---


# Question
Title: Rename/hide "Save" and "Save as draft" buttons for non-admin roles
I have four content types on my site that registered users can create, but they are set to be approved by admins before publishing. Since the site also sends out notifications to subscribers when a new node is created, the following problem occurred - the regular users could save new nodes which are not published until approval, but the notifications go out immediately after they save it anyway.

The registered users creating new nodes must not have the ability to *create* i.e. save the node and that's why we added the "Save as draft" option (via Save Draft module). What I need is to only show the "Save as draft" button, possibly under another label and completely hide the "Save" button. Understandingly, I would need to do this only if the user is not an admin or an editor, otherwise I might create a big confusion on the site.

This is the rule which sends notifications to users who subscribed for notifications:

```
{ "rules_new_content_notifications" : {
    "LABEL" : "New content notifications",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--slucaj_plan" : { "bundle" : "slucaj_plan" },
      "node_insert--inicijativa" : { "bundle" : "inicijativa" },
      "node_insert--izgradnja" : { "bundle" : "izgradnja" },
      "node_insert--projekat" : { "bundle" : "projekat" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "8" : "8" } },
          "subject" : "New content created",
          "message" : "..."
        }
      }
    ]
  }
}

```

The content approval module only sets the node to "unpublished" after a non-admin saves it and the way the administrators approve it later is to edit it and set as "published".

# Answer
Focusing just on the save draft module (whatever rules you are using are unrelated).

You can implement a custom module will the following form alteration:

```
/**
 * Implements hook_form_BASE_FORM_alter().
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Get the current user object.
  global $user;
  // Role ids of the current user.
  $user_roles = array_keys($user->roles);
  // Role ids of your admin roles.
  // Change these to suite your role ids.
  $admin_roles = array(8, 9);

  // For users that don't have the appropriate roles.
  if (!array_intersect_key($user_roles, $admin_roles)) {
    // Restrict access to the save button.
    $form['actions']['submit']['#access'] = FALSE;
    // Change label of save draft button if it is present on this
    // content type.
    if (isset($form['actions']['draft'])) {
      $form['actions']['draft']['#value'] = t('Save as draft button label');
    }
  }
}

```

For this to work your module's form alter function needs to run after the save draft module.
To achieve this you need to either add an install function that changes the weight of your module in the system database table so that it is 1 (save draft is 0 so you need a higher number), or you can implement hook\_module\_implements\_alter() to make your form alter hook run after.

For more information on making your form alter run after the save draft form alter see the two answers at How can I modify the advanced search form when my hook runs too early? \- these explain how to do both the solutions I mentioned above.
> 1 votes

---
Tags: forms, rules, users
---


# Question
Title: How to change the delete Message "Are you sure you want to delete" in Drupal 7
I want to change the message "Are you sure you want to delete" to simple "delete". Can someone explain how I can do that?

# Answer
> 3 votes
One option (that requires no coding) is to use the String Overrides module.

It allows you to replace any string with another string that is passed though the `t()` function, though a nice easy to use GUI.

The other option is to use `hook_form_alter()`. For more details on that see the question that Rupesh linked to.

# Answer
> 2 votes
The term "Are you sure you want to delete" does not appear on its own in any of the strings embedded in the function `t()`, so you *can't* use String Overrides to change this in a single replacement rule.

Instead it appears in constructs such as:

```
Are you sure you want to delete the forum %name?
Are you sure you want to delete %title?
Are you sure you want to delete %category?
Are you sure you want to delete the block %name?
Are you sure you want to delete the term %title?
Are you sure you want to delete the vocabulary %title?

```

(and about 20 more on my site - exact number depends on what modules you've installed).

The String Overrides module will only replace the *complete* string that is passed through `t()`.

In other words, you cant feed "Are you sure you want to delete" to String Overrides and expect a result, you need to feed "Are you sure you want to delete the forum %name?" and repleace it with "Delete the forum %name?" to have the effect you've after.

You then need to repeat the procedure with *every* string containing the words to have see this universally applied.

If you find it cumbersome to repeat all these strings, you can implement `hook_menu_alter()` to alter the menu callback associated with the "node/%node/delete" menu item.

---
Tags: nodes
---


# Question
Title: Redirect user to language other than default
So... i have set a drupal website with 2 languages, english (default) and portuguese. At some point during development the client asked me to change the default language to portuguese but as i've read all over the web that turning the default language to other than engish is not advisable. Is there a way to redirect the user to the portuguese version of the site?

Thank you all guys. niebes

# Answer
This might be the answer you're looking for: Install profile with variable default language messes up translations

If the strings were originally written in english and not translated since you'll need to set the `i18n_string_source_language` variable to `en` rather than the site default (which is no longer `en`)
> 0 votes

---
Tags: i18n-l10n, redirection
---


# Question
Title: menu item <front> does not get class expanded nor active-trail when at homepage
I have a menu which has a link to the homepage in it.

This link to the homepage has subItems. I was hoping for the menu item to expand and show the links of the lower lvl when i was at the homepage.

This does not happen. It does expand when i'm on one of the pages of the links of the lower lvl.

Is there any way i can expand this menu item when on the frontpage?

version: \- drupal 7.14 \- Menu 7.14

# Answer
Go to `admin/structure/menu/manage/[your-menu-name]` and Enable the *show as expanded* checkbox in your parent menu item settings.
> 1 votes

# Answer
You can bypass this "issue" by creating a blank page with for example url index.html, then change front page address to index.html , then create your menu with top level pointing to index.html and it will show children elements after being clicked without any jquery manipulation.
> 0 votes

---
Tags: navigation
---


# Question
Title: Restrict webform component use to certain roles
I want to restrict the usage of a custom component only to a specific role. What's the drupal way of doing that? I tried https://drupal.org/project/webform\_component\_roles but this just defines usage permission for all the components not each specific one.

# Answer
> 2 votes
Try Webform Webform Locked Fields module, you can set permission for specific role

> Users who have the "administer webform locked fields" permission will see a checkbox titled "Webform creator can modify" when they edit a webform component. If that box is unchecked, the component can only be modified or deleted by users who have the the "administer webform locked fields" permission. Other users who have webform creation permission will be taken to a page that says "Not allowed" if they attempt to edit or delete that component.

---
Tags: entities, webforms
---


# Question
Title: 404 errors for pages other than homepage when uploaded to web-server
I and new to php and I got started with drupal and this is my demo site http://sugandha.net63.net/ Yea and it works but when I try to click on any link it throws 404error message. What might be the problem? It works fine in localhost.

My setting is as follows :

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'a2256974_drupal',
      'username' => 'username',
      'password' => 'pwd',
      'host' => 'mysql1.000webhost.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

This is my database setting and

```
 # $base_url = 'http://www.example.com';  // NO trailing slash!

```

# Answer
> 2 votes
* Do you have an `.htaccess` file in your root of your installation?

Its one of the most common problems because its a hidden file and people keep missing uploading it to their web server

if you have the .htaccess file then its got to be your base url..change it like Jorge Córdoba said...

* Uncomment *(remove #)* and change example.com...Like this:

`# $base_url = 'http://www.example.com'; // NO trailing slash!`

to

`$base_url = 'http://sugandha.net63.net'; // NO trailing slash!`

if it still doesn't work:

* try using `?q=` before the relative url..eg:

`http://sugandha.net63.net/admin` to `http://sugandha.net63.net/?q=admin`

if that works then you have to disable clean urls on the online installation

# Answer
> 1 votes
Check the settings for your site, most probably your host string is defined to "localhost" and therefore any links in the site are directed to "localhost/whatever" instead of the actual location.

You need to edit the "$base\_url" variable in your settings.php file which can be found in sites/default for single site drupal instalations.

# Answer
> 1 votes
Another possibility: If it's a new server, make sure that Apache has `mod_rewrite` installed. Happened to me.

---
Tags: 7
---


# Question
Title: Can I display video from youtube and file system in the same field?
I am using Media (7.x-1.4), Media: YouTube (7.x-2.0-rc4) and MediaElement (7.x-1.2) modules for drupal 7.

I have a video field where you can upload videos or enter a youtube url, thanks to the media module.

The problem is, I cannot display videos from the two sources. If I choose "rendered file" in the "Manage display" settings, the youtube video displays, but the local file is given as a link. If I choose "media element video", then the local video is displayed, but the youtube one will not.

Is there a way that I can display videos from both sources?

# Answer
> 0 votes
**Video Embed Field Module:**

You need to use Video Embed Field module. This is enabled in filed type in MANAGE FILEDS.If you select a filed to Video Embed and select a widget to Video. as WELL as MANAGE DISPLAY that select format to Video Player. and you add a youtube url to content type that display video format.

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


# Question
Title: Print the secondary links as expanded in a template file
I'm trying to print the secondary links for the main menu as expanded in my template node--products.tpl.php. In my menu I have three levels.

-Products

--Product category

---Product

-Another menu link

The result should be a menu with all product categories with the child items. I don't want to print the root level in the menu; I only want the secondary level, and its children to appear.

I have tried to print the secondary menu like this, but the child items doesn't appear. Any help appreciated.

```
$secondary_menu = theme_get_setting('toggle_secondary_menu') ? menu_secondary_menu() : array();
print theme('links__system_main_menu', array(
    'links' => $secondary_menu,
    'attributes' => array(
    'id' => 'main-menu-links',
    'class' => array('links', 'clearfix'),
  ),
    'heading' => array(
    'text' => t('Main menu'),
    'level' => 'h2',
    'class' => array('element-invisible'),
  ),
));

```

# Answer
> 1 votes
In your themes template.php add the following:

```
function THEMENAME_preprocess_page(&$variables) {

  // Get the entire menu tree (you can replace this string with any menu you want)
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Generate structure for rendering the menu.
  $menu = menu_tree_output($tree);

  // Replace the $menu array with the #below array beloning to the first top
  // level menu item.
  $menu = $menu[key($menu)]['#below'];

  // Add $main_menu_no_top as a variable to use in our theme
  $variables['main_menu_no_top'] = $menu;
}

```

Then, in page.tpl.php, you can just use:

```
<?php print render($main_menu_no_top); ?>

```

---
Tags: routes, theming, navigation
---


# Question
Title: Add a prefix to all path with hook_url_outbound_alter and/or hook_url_inbound_alter
I'm trying to add a **prefix** to all path aliases, without changing the URL's destinations (*internal path*) of my website.

I'm setting a `$_SESSION` var with `hook_init()` when a visitor arrive on the website. This `$_SESSION` var is determined by the incoming URL of the visitor.

The website is should be accessible by different URL like:

So if the `$_SESSION` var is "**thisevent**", I'd like to change all default path like this:

I think this could be done with `hook_url_outbound_alter()` and/or `hook_url_inbound_alter()` but I can find any clear examples to implement my goal. I found this post but the author didn't post his solution.

Any help appreciate. Thanks

# Answer
I finally made it but not without the help of a sympathetic module: PURL.

And here's my final solution:

1. Create a custom module
2. In the `mymodule.module` file create 3 functions:

```
/**
 * Implements hook_purl_provider
 */
function mymodule_purl_provider() {
  return array(
    'mymodule_provider' => array(
      'name' => t('My module provider'),
      'description' => t('Sets a prefix for URL.'),
      'callback' => '_mymodule_prefix',//I didn't really use this callback and I don't really know how to :-)
      'example' => 'my-prefix',//anything you want. only for UI I think
    ),
  );
}

function mymodule_purl_modifiers() {

  $mymodule_events = _get_all_events();//custom function to get some data

  foreach ($mymodule_events as $kid => $e) {
    $modtab['mymodule_provider'][] = array('value' => $e['alias'], 'id' => $e['nid']);//this array must be structured like this!
  }
  return $modtab;
}

function _mymodule_prefix(){
  $event = _get_one_event();//custom function

  if ($event) return true;
}

```

then you can go in `/admin/config/search/purl` to configure PURL with your data you've just created with mymodule.

1. In `/admin/config/search/purl/types` you select the type you need (I checked only "Path")
2. In `/admin/config/search/purl/list` you should see your modifiers you've created with mymodule.
3. And in `/admin/config/search/purl` you can select witch type you use for your provider

I am a bit sad because I didn't manage to use the 2 hooks (like purl does :-) but the good news is that "it works"

Cheers.
> 2 votes

---
Tags: hooks, path-aliases
---


# Question
Title: Migrating a Drupal 7 domain to another domain while keeping dynamically generated URLs intact?
I currently have a website that does repairs and web development.

I want to separate the repair section of the website into its own domain name while also keeping the old domain's URLS intact. Since I have many pages generated by views I'm not sure how to go about doing this.

What I was thinking was clone the current site and remove what is unnecessary on the new site.. then the old site would redirect all those links to the new domain.

What is a good solution to such a migration problem?

# Answer
> 1 votes
If the two websites should be identical but available at separate domains and you use relative URLs throughout your site this is actually quite simple. This is assuming you want all links available at both domains.

Direct the new domain name to point your Drupal install.

Depending on your system configuration there are several ways you may need to do this. If you have a dedicated IP you can simply point your domain to the appropriate IP and ff you use virtual hosts you may need to setup a symbolic link.

```
ln -s /var/www/example.com /var/www/newdomain.com

```

All relative URLs should inherit the currently loaded domain name.

I believe for this to work though you will need to leave $base\_url commented out in settings.php.

```
/**
 * Base URL (optional).
 *
 * If you are experiencing issues with different site domains,
 * uncomment the Base URL statement below (remove the leading hash sign)
 * and fill in the URL to your Drupal installation.
 *
 * You might also want to force users to use a given domain.
 * See the .htaccess file for more information.
 *
 * Examples:
 *   $base_url = 'http://www.example.com';
 *   $base_url = 'http://www.example.com:8888';
 *   $base_url = 'http://www.example.com/drupal';
 *   $base_url = 'https://www.example.com:8888/drupal';
 *
 * It is not allowed to have a trailing slash; Drupal will add it
 * for you.
 */
 # $base_url = 'http://www.example.com';  // NO trailing slash!

```

Using this method I rarely have to make custom edits. This includes views output. Just make sure you always use relative URLs.

If you want the content split up between the sites or want to make change the theme or layout you may need to do something a bit more complex.

There are other more robust and complicated ways to separate out your content. A few modules and concepts that come to mind include...

* Domain Access
* Multi-Site (Added for reference, does not meet your requirements.)
* Virtual Sites (Disclosure: I haven't used this.)
* Duplicate your sites (As you mentioned in your question)

I will try to update my answer to be more appropriate with your feedback. Feel free to add details about your hosting environment and how and if the content will be split.

# Answer
> 1 votes
**Virtual Hosts:**

Edit hosts file -\> /etc/hosts and add 127.1.0.1 sitename

```
<VirtualHost *:80>
ServerAdmin webmaster@localhost
     ServerName sitename
     ServerAlias  sitename-alises
DocumentRoot /var/www/sitename/
<Directory /var/www/sitename/>
    Options FollowSymLinks
    AllowOverride ALL
</Directory>
<Directory /var/www/sitename>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

```

**.htaccess:**

Create a .htaccess file with the below code, it will ensure that all your directories and pages of your old domain will get correctly redirected to your new domain. The .htaccess file needs to be placed in the root directory of your old website (i.e the same directory where your index file is placed)

```
 Options +FollowSymLinks
 RewriteEngine on
 RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

```

**Symbolic link:**

Execute below command line

ln -s /var/www/from/directroyname /var/www/to/directoryname

Replace example.sites.php file to sites.php

Edit as your need.

\# $sites\['devexample.com'\] = 'example.com';

\# $sites\['localhost.example'\] = 'example.com';

---
Tags: 7, migrations, redirection
---


# Question
Title: want to make the selected radios as default value when form submit is called
my form

```
$form['area']['check'] = array(
    '#type' => 'radios',
    '#options' => array(
        'search' => t('search'),
        'search_user' => t('search_user'),
        'search_tags' => t('search_tweets'),
        'search_name' => t('search_name'),
    ),
    '#default_value' => 'search_tweets',

```

## and form\_submit is below

```
$_SESSION['check'] = $form_state['values']['check'];
if(isset($_SESSION['check'])){
  form_set_value($form['area']['check'], $radio_value, $form_state);
  form_set_value($form['area']['check'], 'search_user', $form_state);
  $string_replace = str_replace(" ", "-", $results->name);

  $form_state['rebuild'] = true;
  // drupal_goto('tweets-by-tags/' . $string_replace);
  $form_state['redirect'] = array('tweets-by-tags/' . $string_replace);
}

```

# Answer
> 1 votes
Your declaration of the default value is wrong.

You should use the option's key in the `default_value` of your radios element. So you would end up with :

```
$form['area']['check'] = array(
  '#type' => 'radios',
  '#options' => array(
    'search' => t('search'),
    'search_user' => t('search_user'),
    'search_tags' => t('search_tweets'),
    'search_name' => t('search_name'),
  ),
  '#default_value' => 'search_tags',
);

```

---
Tags: forms
---


# Question
Title: View with empty filter result visible only to admin user
So I am new to Drupal 7, just so you know.

Here is my problem:

I created a view displaying all registered users ("members"). Following a tutorial, I managed to display their user pic, name, date joined and amount of posts. The latter was done using aggregation and the relationship filter "User: content authored".

All works great in the preview and real view, but only for the Admin role. When I log out and try it as a fake member I created for testing, the members with 0 posts don't show up.

I have searched for an answer for hours now and have fiddled with filter settings until I am blue, but no luck.

ETA: I have found that some people have had luck using the Views Field View Module. I tried it, setting up a new view for the post counter and then adding it to the parent view, but now I am getting the same post count for all users. Don't know what I am doing wrong...

Please can anyone help?

# Answer
So, in the end I followed some advice I found on another somewhat similar problem which said one can go onto the Advanced Settings on your view \> Query Settings \> check "Disable Query Rewriting"

This worked, but anyone following this advice should be aware of the security implications regarding visibility.
> 1 votes

# Answer
you have to look into the permissions i gueass ... you haven't set permissions to see other users profile for anonymous & authenticated users users...
> 0 votes

---
Tags: views
---


# Question
Title: How do I do custom shapes (Complex Multipoint Geometry) using Geofield and Leaflet?
I need to create regional boundaries using Geofield 2.x and Leaflet. How gan I go about doing this?

I have tried using Leaflet Widget for Geofield but it currently doesn't support the 2.x version of Geofield and the patch in the queue to make it compatible doesn't work.

I am looking for alternative method to the Leaflet Widget for Geofield module, perhaps using just Geofield.

I am not looking for a complete walkthrough. Just point me in the right direction and I will figure the rest out. :)

# Answer
> 0 votes
It's pretty straight forward and somehow I missed it when looking to figure it out myself. I just added a Geojson field to a content type and then used http://geojson.io to build out my complex shapes then copied and pasted the geojson output into my geojson field.

# Answer
> 0 votes
I think this is already possible when using Geofield with OpenLayers. Although I'm not using complex geometries in my current case, all settings indicate that the module is capable of it. E.g. if you choose in the setting of your Geofield for the storage option for 'single collection' it indicates that the widget will allow complex geometries.

---
Tags: location, javascript
---


title: Dependent date_popup maxDate

text:
# Question
Title: Dependent date_popup maxDate
In a profile2 profile, I want to change the maxDate of a date field depending on the selected value of gender field.

I am using a custom module implementing the `hook_form_profile2_edit_PROFILE_TYPE_form_alter()` and loading JavaScript. The date field uses the datepicker widget and the gender field is set as radios.

When the gender is selected as female, the maxDate should be set to "-18y". When selected as male, the maxDate should be set to "-21y".

Using the JavaScript, when a gender is selected the first time, the maxDate is set correctly. But, when the gender is changed, the maxDate does not change. It remains set at the first value. When the gender is changed, the maxDate should change too.

Here is my JavaScript:

```
(function($){
Drupal.behaviors.meh_profile = {
    attach: function (context, settings) {
        $('input:radio[name="profile_main[field_profile_gender][und]"]', context).change(function(){
            var genderVal = $('input:radio[name="profile_main[field_profile_gender][und]"]:checked').val();

            if (genderVal == Drupal.settings.gender_options.gender_female) {
                for (var id in Drupal.settings.datePopup) {
                    Drupal.settings.datePopup[id].settings.maxDate = '-18y';
                }
            } // if female

            if (genderVal == Drupal.settings.gender_options.gender_male) {
                for (var id in Drupal.settings.datePopup) {
                    Drupal.settings.datePopup[id].settings.maxDate = '-21y';
                }
            } // if male

        }); // gender change handler
    }
};
})(jQuery);

```

What am I missing?

# Answer
> 0 votes
Solved!

Instead of trying to change the maxDate using Drupal.settings.datePopup\[id\].settings, pass it as options to datepicker using the jQuery Datepicker syntax `$( ".selector" ).datepicker( "option", { name: value } );`

Here is the solved JavaScript code:

```
(function($){
Drupal.behaviors.meh_profile = {
attach: function (context, settings) {
    $('#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0').attr('disabled', 'disabled');
    $('input:radio[name="profile_main[field_profile_gender][und]"]', context).change(function(){
        var genderVal = $('input:radio[name="profile_main[field_profile_gender][und]"]:checked').val();
        if (genderVal == Drupal.settings.gender_options.gender_female) {
            $("#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0").val('').removeAttr('disabled').removeClass('hasDatepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '-75:-18',
                maxDate: '-18y'
            });
        } // if female
        if (genderVal == Drupal.settings.gender_options.gender_male) {
            $("#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0").val('').removeAttr('disabled').removeClass('hasDatepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '-75:-21',
                maxDate: '-21y'
            });
        } // if male
    }); // gender change handler
}
};
})(jQuery);

```

---
Tags: 7, datetime
---


title: How to alter the menu overview?

text:
# Question
Title: How to alter the menu overview?
I was trying to add another additional column in the menu overview (admin/structure/menu/manage/main-menu). I used the following code:

```
function mymod_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'menu_overview_form') {
        foreach ($form as $key => $item) {
            if (is_array($item) && isset($item['#item'])) {
                $item['node_url'] = array(
                    '#markup' => 'foobar'
                );

            }
        }
    }
}

```

It actually adds the indexes but the render output is not changed. How can I add an additional column to that overview?

Thanks

# Answer
i think you should look at `hook_menu_alter()` please Visit:https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu\_alter/7
> 0 votes

---
Tags: forms, theming
---


# Question
Title: Appropriate way to include a PHP file in a theme tpl
I guess this is more of a "Drupal way" question than a technical question. I have a multi-site install with a base-theme shared by all of the sites. The base theme has two 'page' theme files (one is specifically for the homepage). As you can imagine, there are shared elements to the layout (let's say a header and footer for conciseness). I'd like to keep the 'header' and 'footer' in separate PHP files so that I have one place to edit them versus going into 2 separate files and editing four blocks of code if something changes.

What is the appropriate way to create php files for 'header' and 'footer' and include them in the page.tpl and page--homepage.tpl templates?

Should they be in a folder called includes with a .inc extension, should this not be done at all, etc..?

# Answer
I think the "Drupal Way" would be to create a variable in your template.php file, and then just call the variable in your page theme.

http://drupalize.me/videos/overview-templatephp
> -1 votes

---
Tags: 7, theming, multi-sites
---


# Question
Title: Getting the auto generated thumbnail of the video Using MediaFront and Views
Ok here what's the situation I have,

I made content-type of Products with 2 fields: Image field and Video field with unlimited inputs.

Using MediaFront module and Views I made a block for displaying all the video's on my node with the playlist which works just fine except it doesn't load the thumbnail by itself.

Reading the documentation of the module you need to set another field (i.e. image field) as the thumbnail.

I can make this 2 ways:

1. make the playlist get the thumbnail automatically from the video which I have no idea how to that.
2. make every video that I upload has it's own image as thumbnail which kinda works weird. What I mean is that it only shows the first image of the Imagefield for all the videos.

Here's the address of the page I'm working on.

The Output of the view:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'media';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'mediaplayer';
$handler->display->display_options['style_options']['mediafront_preset'] = 'video_thumbs';
/* Field: Content: videos */
$handler->display->display_options['fields']['field_product_videos']['id'] = 'field_product_videos';
$handler->display->display_options['fields']['field_product_videos']['table'] = 'field_data_field_product_videos';
$handler->display->display_options['fields']['field_product_videos']['field'] = 'field_product_videos';
$handler->display->display_options['fields']['field_product_videos']['label'] = '';
$handler->display->display_options['fields']['field_product_videos']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_product_videos']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_product_videos']['type'] = 'mediafront_player';
$handler->display->display_options['fields']['field_product_videos']['settings'] = array(
  'preset' => 'video_thumbs',
);
$handler->display->display_options['fields']['field_product_videos']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'products' => 'products',
);

/* Display: main video player block */
$handler = $view->new_display('block', 'main video player block', 'block_1');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'mediaplayer';
$handler->display->display_options['style_options']['mediafront_preset'] = 'openstandard';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['header'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: videos */
$handler->display->display_options['fields']['field_product_videos']['id'] = 'field_product_videos';
$handler->display->display_options['fields']['field_product_videos']['table'] = 'field_data_field_product_videos';
$handler->display->display_options['fields']['field_product_videos']['field'] = 'field_product_videos';
$handler->display->display_options['fields']['field_product_videos']['label'] = '';
$handler->display->display_options['fields']['field_product_videos']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_product_videos']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_product_videos']['settings'] = array(
  'preset' => 'openstandard',
);
$handler->display->display_options['fields']['field_product_videos']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_product_videos']['delta_offset'] = '0';
/* Field: Content: Images */
$handler->display->display_options['fields']['field_product_images']['id'] = 'field_product_images';
$handler->display->display_options['fields']['field_product_images']['table'] = 'field_data_field_product_images';
$handler->display->display_options['fields']['field_product_images']['field'] = 'field_product_images';
$handler->display->display_options['fields']['field_product_images']['label'] = '';
$handler->display->display_options['fields']['field_product_images']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_product_images']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_product_images']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_product_images']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_product_images']['delta_offset'] = '0';
$handler->display->display_options['block_description'] = 'main video player block';

```

I'd really appreciate any helps.

# Answer
Ok I read the whole documentation and at the moment there's no way of using two separate fields to add infinite number of videos and images and get proper thumbnailing, here's how I did it:

Created a separate content-type called Videos including these fields:

* Video
* Thumbnail
* Title

for each video, I upload the thumbnail of it as well.

Then at my Products content-type I added the `Entity Reference` field so I can reference the videos I want for my products this way.

then in Views I created a block as following image to add on my products node:

I know that it isn't what I wanted and it has some thumbnail uploading work to do but to my knowledge it was the only way I could find to make this happen without any extra coding.
> 1 votes

# Answer
In the Image field add the path to your image overlay, then re-write the display of the video. Or use youtube API wich is returning you the image and all results.

here is the link to youtube API thumbnails Youtube API v3 Hope it helps! I've done the same thing on a couple of websites.
> 0 votes

# Answer
I don't know if you are in the same situation than this guy but maybe his article could help you to generate automatically thumbnails from your videos with MediaFront module: http://blog.netflowdevelopments.com/2011/11/20/drupal-fun-auto-generating-playlist-thumbnails-from-videos/
> 0 votes

---
Tags: 7, views, media, files
---


title: List of Views add-on modules

text:
# Question
Title: List of Views add-on modules
Is there anywhere that I can find a list of add-on modules for the Views module? If I search for "Views plugins" or "Views add-on", the search just picks up on "Views" and returns a million results that contain "Views". I was hoping to find a list of things like "views\_conditional", "views\_or", etc.

# Answer
> 1 votes
You can either use google (or some other search engine if that's your thing), or drupal.org search.

On the drupal search pages you can filter by modules and by the "views" category, among other things.

For example, see https://drupal.org/search/site/views?f\[0\]=&f\[1\]=&f\[2\]=im\_vid\_3%3A89&f\[3\]=drupal\_core%3A103&f\[4\]=sm\_field\_project\_type%3Afull&f\[5\]=ss\_meta\_type%3Amodule&solrsort=iss\_project\_release\_usage+desc

Other than that there are no secret ways, just persistent searching.

---
Tags: views
---