# Question
Title: How to migrate core profile fields into the new profile fields in D7?
**Premises:**

I´m trying to upgrade a big D6 site to D7.

I have the content profile module installed.

I have a few core profile fields that I need to keep.

The "profile" node that was created by the content profile module, has no fields in it. I just used in order to manage in a better way the theming and presentation of profiles.

I´ve installed Profile2 module. I´ve installed the profile page submodule that comes bundled with it.

**My 2 problems:**

**1.** I would like to export or convert all those core profile fields into the new entity fields in D7. **How may I do that?**

**2.** In the meanwhile (in case number 1 is just not possible at all), I´ve tried theming the ***profile2.tpl.php*** file, trying to print into it my old core profile fields.

I´ve followed the instructions to print those core profile fields, so I´ve harcoded this `print check_plain($account->profile_nombre);` into the template, but it doesn´t print the name of the user that´s inserted into the *nombre* field (core profile field). So, how may I theme the profile page?

I´ve watched this video tutorial also, about the profile2 module, but I´m still absolutely clueless on how to manage profiles in D7 when you already have a couple thousand users with core profile fields in it.

***Please note that I´ve tried using the "migrate" module, and the "drupal 2 drupal" migration module, with no luck.***

Thanks for your help and insight!

# Answer
> A good solution might be to use Feeds module (to import to fields) and Views Data Export Module (to export fields to the spreadsheet). The procedure would be:
>
> Setup a view that lists all of your users and displays all of the fields you want to migrate. Then add news display (data export) and choose CSV format.
>
> Use feeds to import the data to D7. Just map each exported field to a new field.
>
> This might seem complicated at first, but it's really simple and should work.

Thanks for your reply, take2. Thought it would be good to post it here.
> 1 votes

# Answer
you can use this module (more of a drush extension) to convert the content profile fields to core profile fields or profile 2 fields (recommended) once your site is a D7 site: CP2P2
> 0 votes

---
Tags: 7, migrations, users
---


# Question
Title: drupal_add_js - working with inline but not file
I am using the following code, which works.

```
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'job_node_form') {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  }
}

```

The following code doesn't work.

```
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'job_node_form') {
    drupal_add_js(drupal_get_path('module','conflict') . '/js/test.js');
  }
}

```

The code in sites/all/modules/mymodulename/js/test.js is the following.

```
if (Drupal.jsEnabled) {
  $(document).ready(function() {
    alert("Hello!");
  });
}

```

When I look at the page source, I can see the JavaScript file is loaded.

Is the inline code timed differently to the code in a JavaScript file?

# Answer
With Drupal, instead of using `$(document).ready`, you should use Drupal behaviors. The equivalent of the JavaScript code in the test.js file shown in the question would be the following one.

```
(function($, Drupal) {

  Drupal.behaviors.moduleName = {
    attach:function() {
      alert("Hello!");
    }
  };
}(jQuery, Drupal));

```

I would rather not use `drupal_add_js()`. Instead, the code can attach JavaScript to the form array, as the following code does.

```
if ($form_id == 'job_node_form') {
  $form['#attached']['js'][] = array(
    'type' => 'file',
    'data' => drupal_get_path('module','conflict') . '/js/test.js',
  );
}

```

This attaches the file directly to the form, allowing it to be removed/replaced by another module that implements `hook_form_alter()`, `hook_form_FORM_ID_alter()`, `hook_form_BASE_FORM_ID_alter()`.

Using `#attached` is also the method that Managing JavaScript says it's preferred over `drupal_add_js()` because the reference to the file is cached, whereas `drupal_add_js()` requires a function call to add the script to the page. In some case, for example `hook_block_view()`, `drupal_add_js()` won't be called when the block is cached, while the `#attached` array would be added from `hook_block_view()` before the block is cached.
> 5 votes

---
Tags: 7, javascript
---


# Question
Title: Same secondary menu bar on different pages and lead to different content
not sure if I can describe the situation clearly, here is the thing:

I am using D7. I have this site: there are three menu items in the main menu will lead to three product pages, their layout will be identical: start with a product image, then a secondary menu bar and the according content according to the secondary selected menu item. I intend to use a same custom node template for the three pages, and put different content into the fields I determined.

the secondary menu bar should be identical on all three pages, which may contains these menu items: Features, Technical Specs, Sales, Support.

When someone clicks on the main menu items, they will go to the product with the right image on the top and the url like mysite.com/PRODUCT\_A. When someone then clicks the secondary menu items, the product image and the layout on the page remain the same, but the according content will show up in the content area. And the url will be mysite.com/PRODUCT\_A#feature

A layout like this:

---

PRODUCT A | **PRODUCT B** | PRODUCT C

\[PRODUCT B IMAGE\]

**features**|technical specs|sales|support

\[these are the features about PRODUCT B...\]

---

Any I probably will use View for the content blocks, but I cannot get my head around how exactly I can make the whole thing dynamic enough for the administrator to add content comfortable. Also to get the right url dynamically. Any thoughts please? Thanks a lot!

# Answer
> 0 votes
If you are just using hashes to flip between hidden divs on the page, then the submenu needs to just be relative to the current location like `| <a href='#sales'>sales</a> |` and your main menu would just have the paths to the nodes like `| <a href='product-a'>PRODUCT A</a> |`

This might seem like a pointless answer, but if my assumption about you using the hashes to switch the tabs, then the solution is super simple. You just need to create the submenu in code in the template since the admin-based custom menu system won't let you do relative hashes (I don't think so anyway)

---
Tags: views, 7, nodes, routes
---


# Question
Title: I already have a complete HTML/CSS mockup should I use a base theme or start from scratch?
Will it be less painful to just build my theme from scratch using the HTML/CSS mockup that I have or should I still go through the process of using a base theme like Zen?

# Answer
It's a mix of personal preference, familiarity with the theme system and, arguably most importantly, the experience of the end-user admin and how much they'll need to modify layout.

Unless the site layout will need to be extensively modified (by a non-developer, beyond just toggling/placing blocks) I would always choose to start from scratch.
> 2 votes

---
Tags: theming
---


# Question
Title: Export Content Type to a Form Like Structure?
So, I'm just getting really lazy. I have to make new custom forms for users to input data. The form matches the Content Type exactly(except for somethings being generated server-side). Is there a way to just export a Content Type form into an form function?

If not it seems like something I might have fun developing.

Thanks, Nate

# Answer
I would recommend looking into Webform Template. All you have to do is make the Webform the one time, then you can copy the configurations for new forms.
> 0 votes

---
Tags: forms, nodes
---


# Question
Title: Why am i getting a blank UI in filedepot module in drupal 7?
I want to have proper file management for my site powered by drupal. I have downloaded the filedepot module, and have performed all the steps to configure it properly...but still i am not getting the user interface after i click the filedepot link on the navigation menu, its totally blank. i figured out there are many, who are getting the same problem; have tried different solutions, but no luck anywhere.

please suggest me some solution for the same, m using drupal 7, filedepot 7.x-1.1 and libraries 7.x.-1.0.

please please need help badly

# Answer
> 1 votes
I found this solution at "https://drupal.org/node/1268336"

Renaming it solved the issue for me.

"rename /sites/all/libraries/jquery.blockUI.js to /sites/all/libraries/jquery.blockui.js. It is case-sensitive, and the JS file is not being loaded after following the instructions provided."

# Answer
> 0 votes
Try Diagnostic Tools as shown in this article \- it describes most of common White Screen of Death causes and how to identify them. Server's error.log would be handy too.

---
Tags: files
---


title: OnSelect datepicker not working

text:
# Question
Title: OnSelect datepicker not working
I am having a problem with this function, it simply is now working. I have a module with just a basic form and im using the date module to get the datepicker to pop up and that works fine, but when I select a date from the datepicker the alert is not firing.

this is what i have in my theme js file.

```
//id for nay_date input field
$('#edit-nay-date-datepicker-popup-0').datepicker(function() {
              onSelect: function(selectedDate) {
              alert(selectedDate);
            }
        });

```

and this is the field i have in my module

```
$form[['nay_date'] = array(
    '#title' => 'Date',
    '#type' => 'date_popup',
    '#description' => '',
    '#required' => TRUE,
);

```

# Answer
> 1 votes
I use it without a function as the argument like: jsfiddle

```
//id for nay_date input field
$('#edit-nay-date-datepicker-popup-0').datepicker({
          onSelect: function(selectedDate) {
          alert(selectedDate);
        }
    });

```

---
Tags: 7, datetime
---


# Question
Title: How can I add a progress bar to Managed File upload?
How can I add a progress bar to my Managed File form field? Here's my field code:

```
    $form['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo image'),
  '#description' => t('Replace/upload a new logo for this sponsor.'),
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
  ),
);

```

I have searched for a while now, and the closest info I could find was this post but I can't quite figure out how I can add the AJAX to make this happen. Any pointers would be appreciated!

# Answer
managed\_file fapi elements are already progress bar capable by default.

**managed\_file**

> **Description**: Provides a complete ajax/progress aware widget for uploading a file and saving it to the {file\_managed} table.
>
> By default a simple upload button is provided for choosing the file to upload. Once a file has been chosen it can be explicitly uploaded via the "Upload" button. The upload is via AJAX and a progress meter is displayed. ....
>
> **Non-standard form element properties**:
>
> `#progress_indicator`: options are 'none', 'bar', and 'throbber', default is 'throbber'. `#progress_message`: (string) Progress message to display along with progress meter while a file is being uploaded. Defaults to NULL.

It may be possible that your server doesn't support file progress, in which case you should check and verify if the server settings are correct.

More info:
> 6 votes

---
Tags: 7, ajax, files
---


# Question
Title: How to create field instance with display none programmatically
I tried to create some fields and field instance programmatically in .install file.

And I need to set a specail field instance with display none.

I have google, but got nothing.

Does anyone have a solution ?

# Answer
your question is not very clear.

What do you mean "display none"?

* Make your field in the .install file.
* Add a CSS file to your module info file`files[]=mymodule.css`
* in the CSS file of your module `.field-myfield {display:none;}`.
* clear your drupal cache

**EDIT**

I think you probably want to look at Field Permissions module.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 0 votes

---
Tags: entities
---


# Question
Title: How include oun TPL in /admin/structure/types/manage/
I need to show this form by my oun .tpl. But i didnt undestand how i can do this. Can anybody help me?

the function work by url (/admin/structure/types/manage/*type*) but it give me default form generator.

```
function admt_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['#theme'] = 'admt_form_theme_function';
  $form['admt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Graffic User Interface'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    //'#theme' => 'admt_form_theme_function',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

    if (isset($type) && $type->has_title) {
    $title = $type->title_label;
    }
    $fields = array();
    $arrFieldsType=array(
    "number"=>"textfield",
    "text_textfield"=>"textfield",
    "options_select"=>"select",
    "taxonomy_autocomplete"=>"textfield",
    "text_textarea_with_summary"=>"textare",
    "image_image"=>"file",
    "checkboxes",
    "radios"
    );
  $instances = field_info_instances('node', $type->type);
  $extra_fields = field_info_extra_fields('node', $type->type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $form['admt'][$name] = array(
    '#type' => $arrFieldsType[$instance["widget"]["type"]],
    '#title' => t($instance["label"]),
    '#default_value' => array('value' => '...'),
    //'#options' => $type2,
     );
        if($arrFieldsType[$instance["widget"]["type"]]!="select") $form['admt'][$name]['#size']= '20';
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    if(!empty($extra_field["type"]))
    $typ=$arrFieldsType[$extra_field["type"]];
    else
    $typ="textfield";
    $form['admt'][$name] = array(
    '#type' => $typ,
    '#size' => '20',
    '#title' => t($extra_field["label"]),
    '#default_value' => array('value' => '...'),
    '#description' =>  t($extra_field["description"]),
    //'#options' => $type2,

     );
  }
 // drupal_add_js('(function ($) { Drupal.menu_update_parent_list(); })(jQuery);', array('scope' => 'footer', 'type' => 'inline'));

}
function admt_theme($existing, $type, $theme, $path)
{
  return array(
    'mymodule_userinfo_form_theme_function' => array(
      'render element' => 'form',
      'arguments' => array('form' => NULL),
    ),
  );
}

```

# Answer
First of all change this line in your alter function -
`$form['#theme'] = 'admt_form_theme_function';`
change it to
`$form['#theme'] = 'mymodule_userinfo_form_theme_function';`

Add below line of code in your admt\_theme function for `mymodule_userinfo_form_theme_function`.
`'template' => 'your-tpl-name'`

```
function admt_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_userinfo_form_theme_function' => array(
      'render element' => 'form',
      'template' => 'your-tpl-name',
    ),
  );
}

```

Then create `your-tpl-name.tpl.php` file inside your module folder.

Now you can use this new template for your form.
> 0 votes

---
Tags: theming
---


title: Multisite with search functionality

text:
# Question
Title: Multisite with search functionality
I was facing an decision about a project. We have a website in drupal 7 that talks about cars. Now we want to talk about motorcycle. The basic layout will be different, i mean the header and footer.

We want to be able for example a user in motorcycle if search for a car can show (if exist) the result from the cars sites and the link will get him to the main site.

Can we achieve this kind of behavior ?

How i want to look So we have Option A : moto.mysite.com Option B will be mysite.com/moto/

# Answer
I would not use a multisite for this. Instead, I would do Option B (mysite.com/moto).

Then I would use the Themekey module to set up different themes. If you want the two parts of the site to basically look the same, you can make the motorcycle part a subtheme of the theme you are using for the car part.

If you do this, then you don't have to worry about integrating the data; you will have two parts of the website that look different, but on the backend all the data will be kept together.
> 2 votes

---
Tags: search, multi-sites
---


# Question
Title: How to use Drupal.ajax() to update #content div on <a> click?
I'm trying to update the `#content` with AJAX. I've found the Drupal.ajax function and tried to use it with this code, copied from Views module but modified:

```
var base_element_settings = {
  'event': 'click',
  'progress': { 'type': 'throbber' }
};
jQuery('a').once('custom-ajax-processed').each(function () {
    var element_settings = base_element_settings;

    if (jQuery(this).attr('href')) {
      element_settings.url = jQuery(this).attr('href');
    }
    var base = "content";// $(this).attr('id');
    Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
});

```

But instead of replacing the `#content` it alerts the response contents with the title *An AJAX HTTP error occurred. HTTP Result Code: 200* What am I doing wrong? Is it possible to achieve with Drupal.ajax() ?

# Answer
> 1 votes
dont know it can be achievable using drupal.ajax , but created a module for drupal 6 using jquery load and Drupal.attachBehaviors with which you can load any page to any div. Now ported to 7 also :) this is the module (currently under review process)

# Answer
> 1 votes
I believe this presentation might give the answer http://www.slideshare.net/merlinofchaos/drupal-7-advanced-ajax

# Answer
> 0 votes
You could probably just do something like this:

```
$(document).ready(function(){
  $('a#load-content').click(function (e) {
    $('#content').load('/menu/callback/ajax/loader');
    e.preventDefault();
  });
});

```

Then clicking a link like `<a href="/nojs/path" id="load-content">Load</a>` should fetch and populate `div#content` with the html result of the menu callback from `/menu/callback/ajax/loader`

---
Tags: 7, ajax, javascript
---


title: Using hide($submitted); in a tpl?

text:
# Question
Title: Using hide($submitted); in a tpl?
Right now I'm working in a tpl file and in a specific place I have `<?php print render($submitted); ?>` and this works just fine. However, later when I do `<?php print render($content); ?>` it will render the submitted by link there as well. Normally I just:

```
<?php
  hide($content["comments"]);
  hide($submitted); //this does not work like it does with hiding comments and links
  print render($content);
?>

```

However, the copying the way to do it for comments and links does not work with submitted and it continues to render the submitted by in the content.

# Answer
> 1 votes
There must be 2 variables holding the "submitted" string, `$submitted` and also `$content['submitted']`. You should either forget the `$submitted` variable and if you `render($content['submitted'])` then it should put that as `#printed => true`. Then later if you `render($content)` it shouldn't print the submitted text as it's already printed.

The second option would be to `render($submitted)` and then do `hide($content['submitted'])` before `render($content)`.

---
Tags: entities, nodes, theming
---


title: How To Deal With Datebase Size?

text:
# Question
Title: How To Deal With Datebase Size?
I'm using the *Domain Access* module to share the same database with six different sub-domains. My concern is the database limit which is set to 1000 MB.

Is there a way to create new a database once the previous one reached 700 MB?

# Answer
> 2 votes
If the above fails, just change your hosting company or hosting plan, to get bigger limit. Database space is cheap, nowadays.

---
Tags: 7, database
---


# Question
Title: Showing only one feed from different URLs
I am using the Drupal 7 core module feed aggregator to list rss feeds from different websites. I am able to show 5 feeds in a block provided by the module itself as well as using views too(aggregator term type). I want to show only one recent feed from different URLs which are provided by me in the aggregator module config. Right now it is showing 5 feeds from only two URLs. It should come as:

\*Most recent Feed from 1st URL

\*Most recent Feed from 2nd URL

\*Most recent Feed from 3rd URL

\*Most recent Feed from 4th URL

\*Most recent Feed from 5th URL

Can anyone please tell me how do I do that?

# Answer
Your best option is to create an attachment display for each feed which selects just the most recent feed and combine them into a block display.
> 0 votes

---
Tags: views, feeds
---


# Question
Title: Display images of a specific content type in a lightbox when vocabulary is clicked
**Background** I am using Drupal 7 and I have a taxonomy "Kitchen Type" and content type "Kitchen Picture" having default field\_image for images. There are three Kitchen Types Traditional, Contemporary and Transitional. I have more than 10 Kitchen Pictures assigned to each Kitchen Type.

**Problem** I have a view at /kitchens (Page 1) that lists three kitchen types and when clicked, lists the Kitchen pictures (another dynamic view) (Page 2). When a picture is clicked a lightbox open up. But, I would like to have a lightbox open up with kitchen Pictures (including next-back navigation) when any of the kitchen type (traditional etc) is clicked. So, I want to skip Page 2 actually. I have no idea how to go about it. Any help would be appreciated.

**Edited** I am afraid I also have a link in the header "Kitchen Portfolio" that supposed to open a lightbox and allows visitor to navigate through all the kitchen pictures. I want to avoid loading all the images on all pages. I need a way out such as when link is clicked it loads the html and start lightbox navigation. I do not know how I can achieve it in Drupal.

I already have lightbox2 installed.

Thanks

# Answer
> 0 votes
If I were you I would create a "Kitchen Type" content type and then edit the image field to allow unlimited amount of images. Then add a taxonomy field to "Kitchen Type" assigning a taxonomy term to each.

Create a new view which pulls all "Kitchen Type" content types and add the Taxonomy Field and Image field to the display. Views allows you to style individual fields by its tpl naming convention. If you go to the "theme" option in that view you will see a set of file names to place in your theme to style individual fields. You will need to style the image field by looping through the image array and output html which conforms to the lightbox2 convention like this:

```
<div class="image-set">
    <a class="example-image-link" href="img/demopage/image-3.jpg" data-lightbox="example-set" title="Click on the right side of the image to move forward.">
        <img class="example-image" src="img/demopage/thumb-3.jpg" alt="Plants: image 1 0f 4 thumb" width="150" height="150">
    </a>
    <a class="example-image-link" href="img/demopage/image-4.jpg" data-lightbox="example-set" title="Alternately you can press the right arrow key.">
        <img class="example-image" src="img/demopage/thumb-4.jpg" alt="Plants: image 2 0f 4 thumb" width="150" height="150">
    </a>
    <a class="example-image-link" href="img/demopage/image-5.jpg" data-lightbox="example-set" title="The script preloads the next image in the set as you're viewing.">
        <img class="example-image" src="img/demopage/thumb-5.jpg" alt="Plants: image 3 0f 4 thumb" width="150" height="150">
    </a>
    <a class="example-image-link" href="img/demopage/image-6.jpg" data-lightbox="example-set" title="Click the X or anywhere outside the image to close">
        <img class="example-image" src="img/demopage/thumb-6.jpg" alt="Plants: image 4 0f 4 thumb" width="150" height="150">
    </a>
</div>

```

This should display each set of images for each kitchen type right under it. Once one image is clicked it should open up a lightbox with arrows to go to next image.

Hope this helps or at least points you in the right direction!

# Answer
> 0 votes
Here is how I implemented it

1. Created a block view to display empty links of all "Kitchen Pictures" images

* Added Content:Body, Content: Kitchen Type and Field:Image
    * Field Image Settings

    + Uncheck create a label, Set Formatter as "Image URL"
        + Set "Link image url" to "Nothing"
        + "Rewrite Result" =\> Check "Rewrite the output of this field" and paste following code.

    `<a href="[field_image]" rel="lightshow[[field_kitchen_type]]" title="[body]" class="[field_kitchen_type] portfolio_kitchen_pic"></a>`
    * Content:Body and Content:Kitchen Type Settings

    + Uncheck Create a label
        + Check Exclude from Display
        + Set Formatter to "Plain text"
2. Place the above created block in footer and use CSS to make it hidden (i.e. display:none)
3. To start lightbox of all images, I then used following JS function and applied to "onclick" of the "Portfolio" link.

```
function start_portfolio_slidshow()
{
   jQuery('a.portfolio_kpic').each(function(){
      title = jQuery(this).attr('title');

      rel = 'lightshow[portfolio]['+title+']';
      jQuery(this).attr('rel',rel);

      Lightbox.initList();
      Lightbox.triggerLightbox('lightshow', 'portfolio');

   });
   return false;
}

```
4. To start lightbox of each kitchen-type (category). I implemented following functions

```
function start_kitchen_slidshow(event)
{
    type = event.data.type.toUpperCase();

    jQuery('a.portfolio_kpic.'+type).each(function(){
        title = jQuery(this).attr('title');

        rel = 'lightshow['+type+']['+title+']';
        jQuery(this).attr('rel',rel);

        Lightbox.initList();
        Lightbox.triggerLightbox('lightshow', type);

    });
    return false;
}

```

Which is implemented to links like following (in jQuery(document).ready)

```
    $('a.lightbox_portfolio_kitchen').each(function(){
       $(this).bind('click', {type: $(this).attr('rel')}, start_kitchen_slidshow);
    });

```

Note: Links should have "lightbox\_portfolio\_kitchen" with category name in its "rel" attribute.

There may be some other solutions but this one worked for me.

---
Tags: taxonomy-terms, javascript
---


# Question
Title: How to get escaped file description from node?
I enabled file description for node and I want to display descriptions close to the download links. I would like the description be secure. I tried

```
$items = field_get_items('node', $node, 'field_files');
foreach ($items as $item) {
  echo $item['description'];
}

```

but there is html code parsed.

I can use just `check_plain()` function on the description, but is there any way to do it better?

# Answer
> 1 votes
As stated in the comments to official documentation:

> It is worth noting that field\_get\_items() returns raw values the use of which can be a security risk. Passing the raw values through field\_view\_value() handles the sanitizing of the values.

Links added by me.

---
Tags: entities, theming
---


# Question
Title: Associate an 'event' content type with a 'project' content type
I have a project content type that can be created by users with certain permissions. I want these users to also be able to create 'events' that are associated with these project content types. So for example, A user who creates a project can create events for that project. I was thinking about putting a entityreference autocomplete field on the event content type that looked up projects created by that user (or could be people who have edit permissions on that content type). Does this sound like a good way to do this or is there a more standard way to achieve this?

# Answer
First of all i totally agree with Molot's comment.

Just to help i will provide my opinion on how to do this:

Use the Node reference url widget module in combination with the Field Permissions module. With the 1st you can create an "Add an Event" link for every Project node and set the fallback behaviour of the field as autocomplete and with the 2nd you can set the permissions for that node reference field.
> 0 votes

---
Tags: entities
---


# Question
Title: How to write webform settings and conditions programmatically
I'm trying to create a webform on my node programmatically so that I can set it up to be used as for a specific scenario. What I wanted to do is have all of the components my client want to appear automatically, but also default to specific settings for user entry, email specific users and validation rules etc, because they are going to have the same setup for each one, and they aren't going to want to write their setup out every single time.

I was using the Webform Default Fields module, but I know that this only works with the components, and not the setup. So I got rid of it and started writing my own version, with big help from this answer to get me as far as I am right now. But I'm struggling to find the correct format of how to write in a conditional statement, or how you would set the settings for the webform.

My current code is as follows:

```
function mymodule_node_insert($node) {
  if ($node->type == 'event') {
    _abstract_webform_components($node);
  }
}

function _abstract_webform_components($node) {
  $components = array(
      0 => array(
        'name' => 'First name',
        'form_key' => 'first_name',
        'type' => 'textfield',
        'mandatory' => 1,
        'weight' => 1,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
      1 => array(
        'name' => 'Last name',
        'form_key' => 'name',
        'type' => 'textfield',
        'mandatory' => 1,
        'weight' => 2,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
    );
      // etc etc

  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $component['extra']['locked'] = 1;
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }

  // Retrieves information about the author
  $author = user_load($node->uid);
  // Adds the author of the node as the default email recipient
  $email = array(
    'nid' => $node->nid,
    'email' => $author->mail,
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);

  $validation = array(
   'validator' => 'max_words',
   'action' => 'add',
   'nid' => $node->nid,
   'rulename' => 'Maximum Abstract Length',
   'rule_components' => array(
     1 => '1',
   ),
   'data' => 300,
  );
  webform_validation_rule_save($validation);

  }

```

Basically I'm missing the correct notation for how you add a condition to the webform but I have the right command to insert it. Also, I have the notation for how I want to setup my webform settings, but I don't know how to apply it

Many Thanks

**EDIT**

I've got one half of it, I've managed to add the conditional statement into the code, I was actually using the wrong code, but I managed to find a proper example of how the array needs to be written, edited the code above

# Answer
I actually managed to get there in the end by re-tracing how it is written in the first place looking through the Drupal Contrib API documentation

I thought I would answer this question as a decent guide for anyone wanting to do the same again, even if I can only give them answer in my specific example

My code is as follows

```
/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {
  // Examines the node type of that being created
  if ($node->type == 'event') {

    // The declaration for how setting up the webform defaults
    // is done at this stage rather than after invoking the
    // function below
    $node->webform = abstract_webform_node_defaults();

    // Adds the default settings for the abstract submission
    _abstract_webform_components($node);
  }
}

// Custom function to overwrite the normal defaults for webform
// This notation was taken from link 1 - provided under answer
function abstract_webform_node_defaults() {
  $defaults = array(
    'confirmation' => '',
    'confirmation_format' => NULL,
    'redirect_url' => '<none>',
    'teaser' => '0',
    'block' => '0',
    'allow_draft' => '1',
    'auto_save' => '0',
    'submit_notice' => '1',
    'submit_text' => '',
    'submit_limit' => '1',
    'submit_interval' => '-1',
    'total_submit_limit' => '-1',
    'total_submit_interval' => '-1',
    'status' => '1',
    'record_exists' => FALSE,
    'roles' => array_keys(user_roles(TRUE)), // Roles are normally written as array keys for users, I wanted everyone except anonymous users to be able to enter mine
    'emails' => array(),
    'components' => array(),
    'conditionals' => array(),
  );
  return $defaults;
}

/* Custom function to setup webform as specific default */
function _abstract_webform_components($node) {
  $components = array(
      0 => array(
        'name' => 'First name',
        'form_key' => 'first_name',
        'type' => 'textfield',
        'mandatory' => 1,
        'weight' => 1,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
      1 => array(
        'name' => 'Body',
        'form_key' => 'name',
        'type' => 'textfield',
        'mandatory' => 1,
        'weight' => 2,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
      2 => array(
        'name' => 'Email address',
        'form_key' => 'email_address',
        'type' => 'email',
        'mandatory' => 1,
        'weight' => 3,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
      3 => array(
        'name' => 'Message',
        'form_key' => 'message',
        'type' => 'textarea',
        'mandatory' => 1,
        'weight' => 4,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
    );

  // Iterate through each $component record and pass into node
  // Information on how to do this taken from link 2
  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $component['extra']['locked'] = 1;
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }

  // Retrieves information about the author
  $author = user_load($node->uid);
  // Adds the author of the node as a 'reviewer'
  $email = array(
    'nid' => $node->nid,
    'email' => $author->mail,
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);

  // This function returns the value of which component is called 'Body' so
  // that I can use its key for my validation rule, just so that if I re-arranged
  // my order at a later date, it would still keep the right key value
  for ($i = 0; $i < count($components); $i++) {
    if ($components[$i]['name'] == 'Body') {
      $body_component = $i+1;
      break;
    }
  }

  // If there is a 'Body' component
  if ($body_component) {
    // Validation formatting was taken from link 3
    $validation = array(
      'validator' => 'max_words',
      'action' => 'add',
      'nid' => $node->nid,
      'rulename' => 'Maximum Abstract Length',
      'rule_components' => array(
        $body_component => 'Body',
      ),
      'data' => 300,
    );
    webform_validation_rule_save($validation);
  }

  drupal_set_message(t('Abstract Submission created, Author set to reviewer by default.'));
}

```

Credit goes to all the authors of commenters from the original questions and links provided

Link 1

Link 2

Link 3

Also I would like to credit @Nebel54, for the suggestion about using the Webform Share to get a print out of exactly how your webform is written.
> 1 votes

# Answer
I had a similar requirement :

The site will have some landing page contents and the site owner can add those contents at different times, and once a content of type landing\_pages will be created some blocks (already created) will get enabled on that node details page and a new webform node with some predefined fields will get created and get enabled as a block on that page in particular places.

I did it in D6.

My approach for the dynamic webform block :

1. I created a webform node with all the default & predefined fields, say with nid = 100
2. Enabled 'Available as block' option by visiting 'Form settings' tab in the path 'node/100/webform/configure'
3. Created a custom module 'landing\_pages'
4. I cloned the nid = 100, each time a new landing\_pages content is created
5. In hook\_init() used this code :

```

/**
 *Implementation of hook_init().
 */
function landing_pages_init() {
// Update the 'blocks' DB table with the blocks currently exported by modules.
_block_rehash( $theme = NULL );
}

```
6. In hook\_node\_api() used this code :

```

/**
 *Implementation of hook_node_api().
 */
function landing_pages_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
 switch ($op) {
   case 'insert' :
     if ($node->type == 'landing_pages') {
       $node_id = 100;
       // function to create & save the clone node
       $new_nid = clone_node_save_custom( $node_id, $node->title );
     }
   break;
   case 'load' :
     if ($node->type == 'landing_pages') {
       /*updating webform block*/
       $result2 = db_fetch_object( db_query( "SELECT n.nid , n.title FROM {node} n WHERE n.type = 'webform' ORDER BY n.nid DESC LIMIT 1" ) );
       $var_result2 = 'client-block-' . $result2->nid;
       $result3 = db_result( db_query( "SELECT b.bid FROM {blocks} b WHERE b.module = 'webform' ORDER BY b.bid DESC LIMIT 1" ) );
       $nid = $node->nid; // Can avoide this step & directly use $node->nid
       $var_result1 = 'node/' . $nid;
       $check1 = db_query( "SELECT bl.bid FROM {blocks} bl WHERE bl.pages LIKE '$nid' AND bl.module = 'webform'" );
       /*if blocks table doesn't have any entry for 'pages' like this 'nid'*/
       if (db_affected_rows() == 0) {
         $check2 = db_fetch_object( db_query( "SELECT b.bid, b.region, b.status, b.visibility, b.pages FROM {blocks} b WHERE b.delta LIKE '$var_result2'" ) );
         /*if blocks table doesn'thave any entry for 'delta' like '$var_result2'*/
         if (db_affected_rows() != 0) {
           /*if blocks table doesn't have any entry for 'region' & pages,0 as entry for 'status' & visibility*/
           if ($check2->region == '' && $check2->status == 0 && $check2->visibility == 0 && $check2->pages == '') {
             $exp = explode( '-#-', $result2->title );
             if ($exp[0] != '')
               $title = $exp[1];
               db_query( "UPDATE {blocks} b SET b.module = 'webform', b.delta = '%s', b.theme = 'YOUR_THEME_NAME', b.status = 1, b.region = 'sidebar_second', b.visibility = 1, b.pages = '%s', b.title = '%s' WHERE b.bid = %d", $var_result2, $var_result1, $title, $result3 );
             }
           }
         }
       }
    break;
    case 'delete' :
      if ($node->type == 'landing_pages') {
        $res = db_query( "SELECT b.bid, b.delta FROM {blocks} b WHERE b.module IN ('webform' , 'block') AND b.theme = 'YOUR_THEME_NAME' AND b.pages LIKE 'node/$node->nid'" );
        while ( $row = db_fetch_object( $res ) ) {
          if (! is_numeric( $row->delta )) {
            $exp = explode( 'client-block-', $row->delta );
            if ($exp[0] == '' && is_numeric( $exp[1] )) {
            //This validation can be skipped
              $type = db_result( db_query( "SELECT n.type FROM {node} n WHERE n.nid = %d", $exp[1] ) );
              if ($type == 'webform') {
                node_delete( $exp[1] );
            }
          }
        }
        else {
          db_query( "DELETE FROM {blocks} WHERE bid = %d", $row->bid );
          db_query( "DELETE FROM {boxes} WHERE bid = %d", $row->delta );
        }
      }
    }
    break;
 }
}

```
7. Supporting functions :

/**
 *Definition of clone_node_save_custom().
 */
function clone_node_save_custom($nid, $nodetitle) {
 if (is_numeric( $nid )) {
   global $user;
   $node = node_load( $nid );
   if (isset( $node->nid ) && clone_is_permitted( $node->type )) {
     $original_node = drupal_clone( $node );
     $node->nid = NULL;
     $node->vid = NULL;
     $node->tnid = NULL;
     $node->name = $user->name;
     $node->uid = $user->uid;
     $node->created = NULL;
     $node->menu = clone_node_clone_menu_link( $original_node );
     $node->book['mlid'] = NULL;
     $node->path = NULL;
     $node->files = array();
     $node->title = t( '!tit -#- !title', array('!tit' => $nodetitle, '!title' => $node->title ) );
     $node->clone_from_original_nid = $original_node->nid;

```
 if (variable_get( 'clone_reset_' . $node->type, FALSE )) {
   $node_options = variable_get( 'node_options_' . $node->type, array('status', 'promote' ) );
   foreach ( array('status', 'moderate', 'promote', 'sticky', 'revision' ) as $key ) {
     $node->$key = in_array( $key, $node_options );
   }
 }
 drupal_alter( "clone_node", $node, $original_node, "save-edit" );
 node_save( $node );
 return $node->nid;

```

  }
}
}

```

/**
*Defines clone_node_clone_menu_link()
*@param $node
*/
function clone_node_clone_menu_link($node) {
if (variable_get( 'clone_menu_links', FALSE )) {
  // This will fetch the existing menu link if the node had one.
  node_invoke_nodeapi( $node, 'prepare' );
  if (! empty( $node->menu['mlid'] )) {
    $old_link = $node->menu;
    $link['link_title'] = t( 'Clone of !title', array('!title' => $old_link['link_title'] ) );
    $link['plid'] = $old_link['plid'];
    $link['menu_name'] = $old_link['menu_name'];
    $link['weight'] = $old_link['weight'];
    return $link;
  }
}
return NULL;
}

```
8. Theme used is ZEN
9. Region I needed the webform be enabled is 'sidebar\_second'
10. We shall have control over the settings of each webform for each Landing Page

Hope it helps.
> 1 votes

# Answer
I suggest you to create the Webform normally via the GUI and use the webform share module to export your settings to code. This module produces an configuration array with all your settings, which you can use in your module then.

An example (hide field2, when field value of field1 equals the value "male") for conditions exported via webform share is:

```
$conditions = array (
  0 =>
  array (
    'nid' => '3',
    'rgid' => '0',
    'andor' => NULL,
    'action' => 'hide',
    'target_type' => 'component',
    'target' => '2',
    'weight' => '-1',
    'rules' =>
    array (
      0 =>
      array (
        'nid' => '3',
        'rgid' => '0',
        'rid' => '0',
        'source_type' => 'component',
        'source' => '1',
        'operator' => 'equal',
        'value' => 'male',
      ),
    ),
  ),

```
> 1 votes

---
Tags: 7, webforms, database
---


# Question
Title: display a taxonomy terms as autocomplete using form API
I am writing my own module. I want to display a taxonomy terms as a autocomplete field in my form using form API. How can I do that?

I am using Drupal7.

# Answer
Hope this will help you,

In Drupal 7, it can be done in 2 ways

* By using existing taxonomy field(like TAG field), for this example I'm using field\_tag ````
$node=node_load($nid);
$tags = array();
foreach ($node->field_tags['und'] as $item) {
  $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
}
$form['tags'] = array(
  '#type' => 'textfield',
  '#default_value' => taxonomy_implode_tags($tags),
  '#title' => 'Add Tags',
  '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
  '#maxlength' => 1024,
  '#element_validate' => array('taxonomy_autocomplete_validate'),page
);

````
* If you dont want to use any field then it can also be using custom autocomplete ````
//custom field
$form['taxonomy_term_field'] = array(
  '#type' => 'textfield',
  '#autocomplete_path' => 'get_TAXONOMY_NAME/autocomplete',
);
//menu callback for autocomplete
function HOOK_menu() {
  $items = array();
  ....
  $items['get_TAXONOMY_NAME/autocomplete/%'] = array(
    'page callback' => 'TAXONOMY_NAME_autocomplete_callback',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
  );
  return $items;
}
//autocomplete callback function
function TAXONOMY_NAME_autocomplete_callback($str = 0) {
  $matches = array();
  //vocabulary id
  $vid = 2;
  $result = db_select('taxonomy_term_data', 't')
    -> fields('t', array('tid', 'name'))
    -> condition('vid', $vid, '=')
    -> condition('name', $str.'%%', 'LIKE')
    -> range(0, 10)
    -> execute();
  foreach ($result as $term) {
    $matches[$term -> tid] = check_plain($term -> name);
  }
  drupal_json_output($matches);
}

```` References : Existing taxonomy field and Custom autocomplete field
> 8 votes

# Answer
```
$form['nameField'] = array(
    '#type' => 'textfield',
    '#autocomplete_path'=>'example/autocomplete'
);

//HOOK_MENU
 function MODULENAME_menu() {
    $items['example/autocomplete'] = array(
    'title' => '',
    'description' => '',
    'page callback' => 'example_autocomplete',
    'access callback' => TRUE,
);

 function example_autocomplete() {
    $termes = taxonomy_vocabulary_get_names();
    $vocabulary = taxonomy_get_tree($termes['MACHINENAME']->vid);
    $list = array();
    foreach ($vocabulary as $taxonomy){
           $list[$taxonomy->tid] = $taxonomy->name;
    }
    print drupal_json_encode($list);
    exit();
}

```
> 2 votes

# Answer
1) Custom Module name : common\_operations

2)

```

/**
 *Implements hook_menu()
 */
function common_operations_menu() {
  $items['autocomplete/taxonomy'] = array(
    'title' => 'Menu Title',
    'description' => 'Menu description',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('common_operations_autocomplete_taxonomy_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['path/autocomplete'] = array(
    'title' => 'Custom Autocomplete',
    'page callback' => 'common_operations_custom_autocomplete',
    'access arguments' => array('access taxonomy autocomplete'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
  *Defines autocomplete_taxonomy_form()
  *@param $form
  *@param &$form_state
  *@return $form
  */
function common_operations_autocomplete_taxonomy_form($form, &$form_state) {
  $form['taxonomy'] = array(
    '#type' => 'textfield',
    '#title' => t('Campus'),
    '#autocomplete_path' => 'path/autocomplete',
    '#maxlength' => 60,
    '#size' => 15,
    '#required' => 0,
  );

  //--------------------Others------------------

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Lets Go!'),
  );

  return $form;
}

/**
 *Page callback for menu 'path/autocomplete'
 */
function common_operations_custom_autocomplete($string) {
  $matches = array();
  $result = db_select('taxonomy_term_data', 'ttd');
  $result->fields('ttd', array('tid', 'name'));
  $result->condition('vid', array(VID1, VID2,...), 'IN');
  $result->condition(db_or()->condition('ttd.name', '%' . db_like($string) . '%', 'LIKE'));
  $query = $result->execute();

  foreach ($query as $row) {
    $matches[$row->tid] = $row->name;
  }

  // Return the result to the form in json
  drupal_json_output($matches);
}

/**
 * Implements hook_permission().
 */
function common_operations_permission() {
  return array(
    'access taxonomy autocomplete' => array(
      'title' => t('Access Custom Taxonomy Autocomplete'),
        'description' => t('Access permission of Custom Taxonomy Autocomplete.'),
    ),
  );
}

```

3) Replace VID1, VID2, ... with the Vocabulary ID's

4) Clear drupal cache

5) Set Permission

6) Access path 'autocomplete/taxonomy' & try

Hope it helps
> 1 votes

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


title: Drupal 7 Fields CSS

text:
# Question
Title: Drupal 7 Fields CSS
I'm having trouble customizing the CSS for a content type I'm developing. Here's an example of what I'm trying to accomplish:

* Field Name = Appetizers
* Value 1 = Appetizer1 Name `<div class="field-item even">`
* Value 2 = Appetizer1 Price `<div class="field-item odd">`
* Value 3 = Appetizer1 Description `<div class="field-item even">`
* Value 4 = Appetizer2 Name `<div class="field-item odd">`
* Value 5 = Appetizer2 Price `<div class="field-item even">`
* Value 6 = Appetizer2 Description `<div class="field-item odd">` etc...

In this case, if I want to style all Prices, I'd look to style `field-item odd` but I'd end up styling Name & Description as well.

Ideally, I'd want to have a class for Name, Price and Description. So I changed the field input format to Full HTML and started wrapping the value contents in those classes - but the markup looked pretty sloppy.

Essentially: `<div class="field-item even">` `<div class="appetizer-price">`

In that case I wouldn't have any styling applied to field-item even, so it seems like a waste to even have it in the first place. Why not just have my custom class only?

Is there a best practice for assigning a class on the value level? Preferably where I can override the field-item odd / field-item even assignment.

# Answer
I've stumbled across this module, which appears like it could do the job.

http://drupal.org/project/fences

Details from its project page:

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
>
> Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!
>
> This kind of tool is needed in order to create semantic HTML5 output from Drupal. Without such a tool, you have to create custom field templates in your theme for every field.
> 1 votes

# Answer
You can implement a field theme function in the template.php file of your theme, like this:

```
// Assuming that the field name is "field_foo".
THEMENAME_field__field_foo() {
  // Implementation...
}

```

See the default theme\_field implementation as a starting point. In your case, you probably want to give different values to the `$classes` variable depending on the `$delta`.

As an alternative, you could implement a custom field template by copying the file modules/field/field.tpl.php to your theme's folder and renaming it to field--field\_foo.tpl.php. Again, see the description of theme\_field and comments for examples.

Another option: if you hate coding or are in a hurry, use the Field Templates extra functionality bundled with the Display Suite module (even though I don't think it covers your specific need).
> 1 votes

# Answer
Would using Views to output your content suit your situation?

If so, I suggest using the built-in facilities in Views that can add CSS classes to your fields based on variable-data - i.e. tokens, from the fields.

Follow the usual procedure to create a view to show your content type. Once you have created the view, for my solution to you, you would start from here:

```
admin/structure/views/view/<insert your view name here>/edit

```

Under fields, right-click on the field that you want to customise the CSS for. In the pop up you can control the markup output of both the wrapper and/or the content itself and construct CSS class names based on the field name or the content in the field itself.

See my example below:

Here you can see I am adding a CSS class generated from variable data using the tokens that are available - for a full list, expand the 'rewrite results' section, check the box 'rewrite the output of this field' and then click to expand the 'replacement patterns' subsection to see the available tokens. (NOTE: Don't forget to uncheck 'rewrite the output of this field' as you wouldn't be using it for this particular case - it was just to see the available tokens.)

Then in your theme, you can style the content, e.g. in my example, in stylesheet.css for my theme, the fragment of code added to it would be:

```
.label.label-actualfieldvalue {
    background-color: darkcyan;
}

```

(where actualfieldvalue is a value that can occur in that field.)

Also, someone else has provided an answer for a similar problem here: Customizing a View with Taxonomy, color coding and icons
> 1 votes

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


title: Problem with Jquery in Durpal 7

text:
# Question
Title: Problem with Jquery in Durpal 7
I am using Drupal 7 and bootstrap theme, I also have installed jquery update module,

Now I have created a js (jquery) file and saved it under js folder in bootstrap theme, I tried to call my js file in the info file using script\[\] = '...', the console then suggested that '$ is not a function', which means my js file was called before jquery was called.

Then I decided to call the my js file from template.php:

```
function bootstrap_preprocess_html(&$variables) {
  $options = array(
    'group' => JS_THEME,
  );
  drupal_add_js(drupal_get_path('theme', 'bootstrap'). 'js/product_pages.js', $options);
}

```

then the following line showed up in the console:

```
GET http://localhost/Brompton/sites/all/themes/bootstrapjs/product_pages.js?mpprnf 404 (Not Found)

```

I am confused, how exactly can I get jquery work properly here?

# Answer
> 1 votes
Technically you've got two Problems. The first one is namespacing, like Molot pointet out. To use $ for jQuery you need at least to wrap your code into this construct:

```
(function ($) {
  $('body').fancystuff();
})(jQuery);

```

That's enough for getting your code executed, for the drupal way you need to attach a behaviour to the Drupal object like the tutorial in Molot's link shows.

The second problem is a missing slash in your drupal\_add\_js:

```
drupal_get_path('theme', 'bootstrap') . '/' .'js/product_pages.js'

```

---
Tags: javascript, theming, .info
---


title: Services module update date field

text:
# Question
Title: Services module update date field
Hi i am using drupal services 3 module. Every thing is perfect except updating date field. I tried many ways to update that field but didn't get any solution. Is any core issue related to date field?

# Answer
> 7 votes
it depends on the field widget how you submit your values for the service. For instance when you have a date field (datetime) with a select/dropdown widget, the form of the value should be the following:

```
"field_date":{"und":[{"value":{"month":"3","year":"2013","day":"6","hour":"0","minute":"0","second":"0"}}]},

```

---
Tags: 7, services
---


# Question
Title: Drupal updating form fields on file upload
I am trying to update form fields based on an uploaded file. Specifically, the text that is displayed on the webpage. If the user then presses a `submit` button, these values are then passed to `hook_node_submit()` and saved in the database. I'm using `hook_form_alter()` to perform these updates, and I have found that I can change the `default_value` of a field when the webpage is first loaded. However, when the `upload` button is pressed by a user, and `hook_form_alter()` is called again, the same operation does not work. For instance,

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'mymodule_node_form'){

       // I can change the default value here
       $form['field_myfield']['und'][0]['value']['#default_value'] = "Some Value";

       // Check to see if the upload button has been pressed
       if (array_key_exists('clicked_button', $form_state))){
           $trigger = $form_state['clicked_button']['#value'];

           if($trigger == 'Upload'){

               // Try to change the default value here.  The value is changed in $form,
               // but the field is not updated on the website.
               $form['field_myfield']['und'][0]['value']['#default_value'] = "New Value";

               // try changing the value after_build
               $form['#after_build'][] = 'mymodule_after_build';
           }
       }
    }
}

function mymodule_after_build($form, &$form_state){
    $form['field_type']['und'][0]['value']['#value'] = 'New Value';
    $form_state['values']['field_type']['und'][0]['value'] = 'New Value';
    return $form;
}

```

Do I need to perform some sort of refresh on the form? I briefly looked at AHAH, is this something that I need to use?

I am new to Drupal so I apologize in advance if there is something fundamentally wrong with this approach. Any help is greatly appreciated.

**Edit:**

I added some code trying to use an `after_build` function to change the cck values. This still doesn't change the value that is rendered on the website.

# Answer
After many hours, I've found a solution! Thanks goes to Matthew Davidson, who posted this workaround on drupal.org, full post The working code looks like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'mymodule_node_form'){

       // create a button to populate the form
       $form['mymodule_pop_btn'] = array(
           '#type' => 'submit'.
           '#value'=>t('Populate Fields'),
           '#submit'=>array('mymodule_populate_fields'),
       );
    }
}

//function to populate the form fields
function mymodule_populate_fields($form, &$form_fields){
    $form_state['input']['my_field']['und'][0]['value'] = 'Some New Value';
    $form_state['rebuild'] = TRUE;
    $form_state['no-cache'] = TRUE;
}

```
> 1 votes

# Answer
1. Make sure you are altering the desired form by checking $form\_id value. hook\_form\_alter alters all the forms.
2. You can use the submit handler of the form - function the\_form\_id\_submit() - to add your custom functionality.
> 0 votes

---
Tags: entities
---


title: Ajax Link In A FAPI tableselect Row

text:
# Question
Title: Ajax Link In A FAPI tableselect Row
I'm trying to add an ajax link to my tableselect rows and replace part of this form with ajax.

```
$options = array();
foreach ($result as $camp) {
    $options[$camp->uuid] = array(
        'select_link' => array('data' => array(
            '#type' => 'link',
            '#name' => 'select_link',
            '#title' => t('use'),
            '#href' => 'ajax_use_data_callback/nojs/',
            '#attributes' => array(
                'class'=>array(0=>'use-ajax')
            ),
            '#ajax' => array(
                'wrapper' => 'selected-data-div',
                'method' => 'replace',
            ),
        )),

        ...

    );
}

```

This triggers an alert with a 404 error and the site's default html. How do I tell this ajax link to be handled like a regular ajax form element?

# Answer
> 0 votes
This can be solved by building a `'select'` element with an option for each row id in the tableselect that gets an ajax link. Then we can add links to the tableselect row with `'#markup'` and use Drupal.behaviors to attach a function that sets the value of the select element and triggers its `'change'` event. In the form building function, if `$form_state['triggering_element']['#name']` is the new select element, `$form_state['triggering_element']['#value']` is the one we want to process.

The select element could then be hidden and the in-row ajax links are still fairly clean. Of course this won't work if javascript is off.

# Answer
> -2 votes
you must declare hook\_menu() for ajax\_use\_data\_callback/nojs/ path

---
Tags: forms, ajax
---


# Question
Title: Adding target _blank to ajax form based on response
I have been pulling my hair out on this for a few days now, and I cannot seem to actually execute something as simple as this successfully on submission of my form.

What I am trying to do is this... If I fill out my form and it passes validation and the ajax response is sold on click, I would like the form to go to /success and open a new tab/window that goes to google.com else just go to the failed page

It's simple I know. The problem is this, that when I do click it and have a new window/tab come up, the pop up window blocks it. This tells me that this method isnt really a valid method of clicking the button.

This is what I have as my form .module

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

        $form['first_name'] = array(
            '#type'  => 'textfield',
            '#title' => t('First Name'),
            '#required' => TRUE,
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#ajax' => array(
                'callback' => 'storage_form_ajax_callback',
            ),
            '#attached' => array(
                'js' => array(
                drupal_get_path('module', 'storage_form') . '/storage_redirect.js' => array(
                'scope' => 'footer',
            ),
         ),
      ),
    );

        if(isset($form_state['values'])){
            $form['page_output'] = array(
            '#markup' => storagedb_submit($form, $form_state)
            );
        }
        return $form;
    }

    /**
     ** Form Ajax
     **/
function storage_form_ajax_callback($form, $form_state) {

      $receipt_info = 'sold';

$commands = array();
      $commands[] = ajax_command_remove('div.messages');
      $commands[] = ajax_command_before('#main', theme('status_messages'));

    if(!form_get_errors()){
      $commands[] = array(
        // The command will be used in JavaScript file
        'command' => 'storage_redirect',
        // JavaScript function:
        'itemstatus' => $receipt_info,
    );

    }
    return array('#type' => 'ajax', '#commands' => $commands);
}

    function storage_form_ajax_callback_validate($form, $form_state){

        if($form_state['values']['first_name'] == ''){
            form_set_error('first_name', t('First name required.'));
        }
    }

```

storage\_redirect.js

```
    (function($){
    Drupal.ajax.prototype.commands.payday_redirect = function(ajax, response, status){
                if(response.leadstatus == 'sold'){
document.location.replace("http://localhost/storageform/thanks");
window.open('http://www.google.com','_blank');
                    }else{
document.location.replace("http://localhost/storageform/failed");
                }
        }
    }(jQuery, Drupal));

```

Please someone help me with this small nightmare of a problem I am having. Thank you.

# Answer
> 1 votes
I believe the answer is, you can't. Pop-up blocking is intended to prevent the browser from opening a new window or tab when the action was not initiated by the user (they click on a link). There are several ways to open a new window or tab; however, unless you can truly trick the browser into thinking the user actually clicked it (no, `$(a).click()` will not fool it) or the user has pop-up blocking turned off, you will always have the pop-up blocker doing it's intended duty.

I'm sure you're advising the user that you intend to open another window for them, why not just provide the link upon successful form submission? Alternatively, you can do a delayed redirect such as is often seen on, I believe, phpBB login screens (the ones that say, "Thank you for logging in. You will be redirected to XXX in 5 seconds").

# Answer
> 0 votes
A way to circumvent popup blocker would be to open new window directly on user click, with content like "Waiting for form validation". Direct user action can usually create new windows all right. Then, on ajax complete, either update that window with proper location, or simply close it.

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


# Question
Title: Is it possible to only update one panel (or block) as a result of a the URL clicked elsewhere?
Is it possible to only update the content in a particular panel as a result of a URL clicked elsewhere? (i.e no other pages get refreshed.)

I have created Views with context filters and would be using them in Panels and would prefer for the whole page not to have to be refreshed.

I'm particularly interested in how to retain the zoomed position of a OpenLayers map, but general advice welcome. (I would consider my OpenLayers use as being a 'side' case of my general question. I think the permalink co-ords option may help me here.)

# Answer
If you want your links to stay unaffected, you need to:

1. Attach `onclick` javascript event to all links. In it, send AJAX query to server.
2. On server side detect when links are clicked on page supporting dynamic loading (`referer` is a good start). Send HTTP 204 status code to prevent full page reload. Do **not** avoid it by returning false from event mentioned in point 1 - if you will, address bar will not match content.
3. In response to ajax query, server should return what IDs are supposed to get replaced, and with what.
4. Javascript on page needs to accept and process data from point 3.

Little explanation: `HTTP 204` from server tells the browser that http request is legit, but no data from the server is needed. Normally when you want to alter url in browser window, at least part before `#`, browser reloads page. This is to prevent theft page from impersonating bank page and so on. So you need server-side solution to actually allow address change without reload - target server will not impersonate itself. Or if it will, it's his right to do so.
> 1 votes

---
Tags: 7, panels
---


title: Privatemsg rule problem

text:
# Question
Title: Privatemsg rule problem
With Privatemsg and Rules modules, I want to create a rule :

Anyone create a node, a special role user recept accepted a privatemsg.

But when I create the rule, in the actions, meet a problem:

The "Data selector" in RECIPIENT, I can't find the role.

Does anyone have a solution ?

# Answer
The *Recipient* in the Privatemsg rules integration does not provide a user object, because the recipient could be a user or a role. (There is a Privatemsg function for sending messages to roles, not just individual users.)

So, this is a limitation of the Privatemsg rules integration. If you want to do this, you will have to add that functionality to the module yourself.
> 1 votes

---
Tags: rules, privatemsg
---


title: #ajax['path'] vs #ajax['callback']?

text:
# Question
Title: #ajax['path'] vs #ajax['callback']?
> # ajax\['path'\]
>
> Description: This is the Drupal menu path for a callback function which will generate HTML and return the string of HTML to Drupal. The result will replace the div specified in #ajax\['wrapper'\]. This property is infrequently used in Drupal 7 and higher, because it is set automatically if using the #ajax\['callback'\] property.

However, I can't still why `#ajax['path']` function offers more than `#ajax['callback']`.

When should I use which one?

# Answer
> 4 votes
It depends on your need.

From Form API Reference,

> #ajax\['callback'\] and #ajax\['path'\] are mutually exclusive. 'callback' is easier to use and requires less code setup, but may not provide the capabilities required for some functions. When you can, use 'callback'.

In simple words the function specified in `#ajax['callback']` generates the content and `#ajax['path']` controls the execution of that callback.

`#ajax['path']` is defaults to `system/ajax` which fetches the respective form from the cache and process it then calls the specified callback for fetching the new content.

However if you want alter this flow, instead of `system/ajax` give your custom callback(But you will end-up with writing another AJAX system).

For example Views module uses its own path(`views/ajax`) instead of system/ajax. The reason is that Views doesn't want the cached form so its re-builds it again(However there is a issue going on with regards to this approach).

So just set the `#ajax['callback']` alone to have AJAX Form.

---
Tags: forms, ajax
---


# Question
Title: writing form action path programmatically
Here is a custom user login form by Overriding the template. But can't understand how to print the destination/action path on the form. here is my code:

> **block--user--login.tpl.php**

```
<form accept-charset="UTF-8" id="user-login-form" method="post" action="/node?destination=node">
  <div class="custom-form">
    <div class="form-item form-type-textfield form-item-name">
  <label for="edit-name">Username <span title="This field is required." class="form-    required">*</span></label>
  <input type="text" class="form-text required" maxlength="60" size="15" value=""     name="name" id="edit-name">
</div>

    <div class="form-item form-type-password form-item-pass">
  <label for="edit-pass">Password <span title="This field is required." class="form-required">*</span></label>
  <input type="password" class="form-text required" maxlength="60" size="15" name="pass" id="edit-pass">
</div>

<div id="edit-actions" class="form-actions form-wrapper">
  <input type="submit" class="form-submit" value="Log in" name="op" id="edit-submit">
</div>

<div class="item-list">
  <ul>
    <li class="first"><a title="Create a new user account." href="/user/register">Create new account</a></li>
        <li class="last"><a title="Request new password via e-mail."     href="/user/password">Request new password</a></li>
  </ul>
</div>

<input type="hidden" value="<?php print $elements['form_build_id']['#value']; ?> "     name="form_build_id">
    <input type="hidden" value="user_login_block" name="form_id">
  </div>
</form>

```

Here we are using a default path like `action="/node?destination=node"` its really a bad idea..
So i want to print the action path programmatically.. Any idea?
This maybe an idea: `<?php print $elements['actions']['#the_path']; ?>`

# Answer
The action is stored in the form's `#action` property, so assuming your form is represented by the `$elements` variable in the template, something like this should do it:

```
<form accept-charset="UTF-8" id="user-login-form" method="post" action="<?php echo $elements['#action']; ?>">

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Error messages appear in background page, not in dialog
I have a form being displayed in a jQuery modal dialog. When the form is filled out incorrectly (ie a required field left blank) the error messages appear in the background page, not in the dialog overlay. This is not the beaviour I want and is confusing for users. How do I get drupal status messages to appear in the dialog box?

I am using Drupal 7 with jQuery 1.5.

Thanks.

# Answer
To help those implement @Clive's suggestion you can do the following:

```
(function ($) {
  $(document).ready(function () {
    $("#dialog").dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        open: function() {
            $('.messages').prependTo('#dialog');
        }
    });
  });
})(jQuery);

```

Substitute #dialog with the name of the div containing your dialog's components.
> 0 votes

---
Tags: 7, javascript
---


title: Export fields properly with Features

text:
# Question
Title: Export fields properly with Features
I want to improve the way I put my Drupal sites in production. For that I began to use 'Features' to export every single content type I created. (I'm doing it on the Drupal 6 websites).

But when I import those features on the production version of the website the only field I get is the title and other parameters. My field's from CCK are not exported.

I have the same module's (and version) on the local, staging and production website. All required modules are installed. During the generation of the 'Features' I added the custom fields I have created.

Has anyone experienced this behavior? Is there any solution? Did I forget something during the process?

# Answer
> 1 votes
Just because this comes up high on google when searching for the answer (and I just figured this out):

1. Run cron
2. Run update.php

Your fields will then appear. This is a Drupal 6 Features issue only. With Drupal 7 the fields should show instantly.

# Answer
> 0 votes
I experience the same problem. I have a module which I have written called order\_form. The feature export contains CCK fields, views, permissions and many other things. I have carefully made sure from the selection the right things are checked.

1. I download my feature put it in the directories then I commit my code
2. I disable the module on staging
3. Update my code from SVN on staging
4. Re-enable the module to see the new version.
5. Mark components that need review.
6. Check to see the content type (module in this case) and see if the features have carried through. This is a CCK form by the way which includes conditional fields. I have permissions not automatically set, ordering is fine however the conditional fields rules are missing.
7. Try revert on all components. Get no new behavior or visibility.

I am unsure what I am doing wrong. I am using Drupal 6.

---
Tags: 6, features
---


title: Separate Exposed Filter Widgets

text:
# Question
Title: Separate Exposed Filter Widgets
Howzit! I have a sandbox site set up, and one of my views overrides the default taxonomy term page for one of my vocabularies. The image below shows how it currently is (unstyled) - and this works just fine. The description of the manufacturer is embedded using Views Field View module, and I'm also using the Better Exposed Filters module.

Click for larger image

What I'm trying to do is separate the **Sort By/Order form** from the **Category filter widget** form as depicted in the Photoshop'd image below.

Click for larger image

My only experience with overriding `tpl` files has been minor theming/positioning stuff. So I overrode `views-view.tpl.php` and `views-exposed-form.tpl.php`, but the latter obviously just renders one form for exposed filters. Will sincerely appreciate your help with this.

FWIW, I'm using Devel and Theme Developer modules for the first time, and am completely lost with figuring out where the variables I'm looking for are, but I'll create another post for that if I'm still lost.

# Answer
> 0 votes
Ok, so I realise that due to the fact that the exposed filters are on one form, it will be difficult to separate the rendered elements. However, I ran some tests using jQuery to reposition the sort elements, and so far it seems to work using the following:

```
jQuery(document).ready(function() {
  jQuery('div#edit-sort-by-created').appendTo('#custom-sort-block');
  jQuery('div#edit-sort-by-title').appendTo('#custom-sort-block');
});

```

NOTE: This breaks if Ajax is enabled in the view, but that can be circumvented using the jQuery `live()` function I'm sure.

It certainly isn't pretty and definitely is a hack, but it will have to do for now. I won't be marking this as the answer in the hopes that someone can suggest a more elegant and *Drupaly* way of accomplishing this.

---
Tags: 7, views
---


# Question
Title: (custom )Autocomplete won't work when the user is not logged
I'm kind of new to drupal (been working with it for 2 months) and i seem to hit a wall with this issue . I've written a little module to allow my users to find phone numbers quickly . It uses autocomplete and works perfectly fine when the user is logged in , but fail when it ain't the case (no icon in the field no http requests fired).

Digging a little further , i can see that neither the autocomplete.js is loading nor the targeted field is properly formatted for autocomplete .

```
<form action="/" method="post" id="annuchum-form" accept-charset="UTF-8"><div><div class="form-item form-type-textfield form-item-search">

<label for="edit-search">Nom de l'agent </label>
 <input type="text" id="edit-search" name="search" value="" size="30" maxlength="128" class="form-text" />
<div class="description">Tapez une recherche et cliquez votre choix pour obtenir le numéro</div>
</div>

```

Anybody got any idea ? Maybe I missed something as I'm a seasoned php Dev but a total Drupal Newbie .I've searched the whole net looking for a clue

here my .module

```
<?php

/**
 * @file
 * Un module pour la récupération de données d'annuaire , et leur présentation sous UI Web 2.0
 */

/**
 * Immplements hook_block_help().
 * @param $path
 * @param $arg
 * @return string
 */
function annuchum_help($path,$arg)
{
    switch($path)
    {
        case "admin/help#annuchum":
            return '<p>' . t("Annuaire du Centre Hospitalier Universitaire") . '</p>';
        break;
    }
}

/**
 * Implements hook_block_info()
 */

function annuchum_block_info()
{
    $blocks['annuchum'] = array(
        'info' => t('Annuaire CHUM'),
        'cache'=> DRUPAL_CACHE_PER_ROLE,
    );

    return $blocks;
}

function annuchum_block_view($delta='')
{
    switch($delta)
    {
        case 'annuchum':
            $block['subject'] = t('Annuaire CHU ');
            $block['content'] = drupal_get_form('annuchum_form');
            break;
    }

    return $block;
}

function annuchum_form()
{
    $form =array();

    $form['search'] = array(
        '#title' => t('Nom de l\'agent'),
        '#type' => 'textfield',
        '#size' => 30,
        '#autocomplete_path' => 'annuchum/autocomplete',
        '#description' => 'Tapez une recherche et cliquez votre choix pour obtenir le numéro',
    );

    $form['annulink'] =array('#markup' => "<a href='http://portail.fr:81/?q=annuaire-interne'>Annuaire détaillé</a>");

    return $form;
}

function annuchum_menu()
{
    $items['annuchum/autocomplete'] = array(
        'page callback' => '_annuchum_autocomplete',
        'title' => 'autocomplete pour annuaire',
        //'access callback' => TRUE,
        //'access' => user_access('access annuchum autocomplete'),
        'access arguments' => TRUE,
        'type' => MENU_CALLBACK,
        'delivery callback' => 'drupal_json_output',
    );
    return $items;
}

function _annuchum_autocomplete($string ='')
{
    $matches = array();

    $res = db_query("SELECT node.nid , node.title,field_prenom_value,field_tel_value
          FROM field_data_field_tel, field_data_field_prenom, node
          WHERE field_data_field_tel.entity_id = node.nid
          AND field_data_field_prenom.entity_id = node.nid
          AND node.type = 'annuaire'
          AND node.title LIKE LOWER(:ustring) ",array(':ustring' => '%' . db_like($string) . '%'));

    foreach($res as $node)
        if(strlen($node->title) + strlen($node->field_prenom_value) < 15)
            $matches[$node->field_tel_value] = check_plain($node->title . " " .$node->field_prenom_value . " " . str_replace(" ","",$node->field_tel_value));
        else
            $matches[$node->field_tel_value] = check_plain($node->title . " " .substr($node->field_prenom_value, 0 , 12 - strlen($node->title) > 0 ? 12 - strlen($node->title): 1) . ". " . str_replace(" ","",$node->field_tel_value));

    //print_r($matches);
    //echo 'alive';
    //return $matches;
    drupal_json_output($matches);
}
?>

```

Sorry for poor grammar , i'm not a native speaker . Thanks in advance :)

# Answer
> 2 votes
You're so close...

`access arguments` should be an array of arguments to pass to the function in `access callback`. If `access callback` isn't explicitly defined, `user_access()` is used by default.

`user_access()` can take a single argument (the permission string you want to check access for, against the current user), so you need to pass a permission string as the first argument of `access arguments`.

I haven't checked, but I imagine Drupal's clever enough not to add the autocomplete widget in full if access to the path is denied, which it currently will be as you're not providing enough access information for the system to make a decision (the default is pessimistic, to deny access).

Using your existing code as an example I'm pretty sure this is what you're looking for:

```
$items['annuchum/autocomplete'] = array(
    'page callback' => '_annuchum_autocomplete',
    'title' => 'autocomplete pour annuaire',
    'access arguments' => array('access annuchum autocomplete'),
    'type' => MENU_CALLBACK,
    'delivery callback' => 'drupal_json_output',
);

```

After you clear caches the changes should take effect, assuming that you've granted *access annuchum autocomplete* permissions for the anonymous role.

For a much more in-depth look at `hook_menu()`, this question/answer is basically required reading

# Answer
> 0 votes
In `hook_menu()` you should comment out 'access arguments' and uncomment 'access callback'.

```
$items['annuchum/autocomplete'] = array(
    'page callback' => '_annuchum_autocomplete',
    'title' => 'autocomplete pour annuaire',
    'access callback' => TRUE,
    //'access' => user_access('access annuchum autocomplete'),
    //'access arguments' => TRUE,
    'type' => MENU_CALLBACK,
    'delivery callback' => 'drupal_json_output',
);
return $items;

```

---
Tags: 7, ajax
---


title: Some user images switched after upgrade

text:
# Question
Title: Some user images switched after upgrade
I'm working on an upgrade process, and I've noticed something strange when I upgrade my D6 site to 7. I've noticed some behavior that's kinda odd, and was wondering if anyone one else had experienced something similar in their upgrades.

1: Some users have the their avatars in the "file\_managed" table, uri field set to: `sites/default/files/user-pictures/...`

These are the correct pictures, but they won't work with image styles unless I switch the value of uri to be the correct uri format. Any ideas why some of the images wouldn't get switched to the proper uri formate durring a 6-7 upgrade?

2: Some users have the completely wrong avatar. The avatars aren't even necessarily other user's avatars, though some of them are, but some are just images from site pages. For example, user 55 in D6 had an avatar at picture-55. After upgrading, I find no record of an image with the file name of picture-55 in file\_managed, the user table says his user image is set to a file with an fid of 20, which is in attached images.

I've got a lot of users, so making sure the avatars mach up correctly is important. I would appreciate any help in figuring what's causing this/how to fix it.

# Answer
> 0 votes
Thanks to Molot for his help with this, I was able to do a few things in order to get this to work, so I figured I would write down exactly what I did in order to get everything set (incase I need to refer back on it, or if anyone else needs it.)

1. First, I used MSQL workbench to download the D6 User table. I grabbed the whole thing, but really I only ended up using uid, name, picture and mail. It would probably be best if I had left the password field, but as this is a test on my local machine, I figured it was ok to just grab everything for now.
2. Switching back to my D7 instance, I downloaded Feeds, Feeds Image Grabber, and **Feeds User Picture Mapper** (note, feeds does not handle user images, and you need this module that's only a few lines long. I had to patch it to get it to work, the patch is covered here :https://drupal.org/node/1734398 )
3. This part's kina kludgy, but forever reason I found myself having to download the images from somewhere other than the local environment, so I had to go and make sure all the relative paths in my CSV were pointing to my prod box. Not sure if this was absolutely necessary, but it's what worked for me.
4. I then created my importer for the users. It is important to make sure the User processor setting is set to UPDATE existing users users. Also, make sure the CSV mapping is all set.
5. Run the processor.
6. Viola! Users now have their correct user images.

# Answer
> 1 votes
Drupal 6 did not have `{file_managed}` at all. Also, user profiles wasn't really fieldable. And both styles and fields changed between 6 and 7. 3 big changes affecting one value - that's bound to create problems.

To get around it, you can use Views Data Export to expose users from old site, and then import your users back using for example Feeds

> Import or aggregate data as nodes, **users**, taxonomy terms or simple database records.

with Feeds Image Grabber

> an addon for Feeds module, which grabs image for each feed-item from their respective webpages and maps it to an image field

---
Tags: 7, database, users, migrations, upgrading
---


title: convert webform date to oracle format

text:
# Question
Title: convert webform date to oracle format
I need to ask some help in converting the date format of a webform.

I'm writing a custom module that send the submissions of my webforms to a third party, however I have to convert my date format from "m/d/Y - H:i a" to the oracle format "DD-MON-YYYY"

I've read up on articles saying that webform uses the site's "short form" but Ideally I'd like to make the conversion in my mod, to keep it contained and because I don't know if changing the "short form" will break anything currently on the site.

This is the line capturing the date field of my form:

```
 $dob = $submission->data[11]['value'][0];

```

I'm using Drupal 6.19 and webforms 6.x-3.4 if anyone can give me some suggestions I'd appreciate it. Please let me know if I need to provide more detail.

Thanks! Steph

# Answer
> 0 votes
This is more of a PHP question, I believe, as you use PHP functions to accomplish this.

```
<?php
  $dob = $submission->data[11]['value'][0];
  $time = strtotime($dob);
  $oracle_format = date('d-m-Y', $time);
  // OR
  // $oracle_format = date('d-m-Y', strtotime($dob));
?>

```

This uses the functions `date()` and `strtotime()`

# Answer
> 0 votes
There's an issue with your time string of "07/10/2013 14:50pm" You are mixing 24hr format with AM/PM, which confuses the parser.

Either use date('H:i') \[14:50\] or date('g:ia') \[2:50pm\]

---
Tags: 6, webforms, datetime
---


# Question
Title: How do I display the user login in a popup?
When menu item "Login" is clicked, I want to display the login form as a popup. How can I achieve this?

I have looked into the following but with little luck. (Let me know if the answer is below and I am missing it.)

* modules: Overlay paths, Popup, Ajax login/register
* Code: `hook_admin_paths_alter()`

Any help will be great. I am looking for a clean pop up option that I can theme too.

# Answer
> 4 votes
There is a module for that: Modal Forms. Enable and configure it, you're just a checkbox away from modal login :)

# Answer
> 3 votes
Are you looking for the Fancy Login module?

> Fancy Login adds javascript based, lightbox-style login functionality to your site. When the user clicks on any link that links to /user/login, they screen dims and a login box is created in the center of the screen.

# Answer
> 2 votes
You can use the following code, which requires the Chaos Tool Suite (ctools) module.

```
function mymodule_user_login_block_ajax_callback($form, $form_state) {
  return _mymodule_form_ajax_callback($form, 'mymodule-user-login-block');
}

function _mymodule_form_ajax_callback($form, $wrapper_id) {
  $commands = array();
  $commands[] = ajax_command_replace('#' . $wrapper_id, theme('status_messages') . drupal_render($form));

  $form_errors = form_get_errors();
  if (empty($form_errors)) {
    ctools_include('ajax');
    $commands[] = ctools_ajax_command_redirect('checkout');
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 1 votes
Check the TinyBox (Simple Splash) module.

> TinyBox module uses TinyBox, a lightweight and standalone modal window script. The main purpose of this module is to provide Splash Screen/Window as simple as possible.

---
Tags: theming, javascript
---


title: When does Drupal 5 run cron?

text:
# Question
Title: When does Drupal 5 run cron?
What causes Drupal 5 to run a cron job?

I know about cron.php. Are there any other ways in which cron is likely to be called? For instance are there any core or commonly used modules that call it?

# Answer
Poormanscron is the most common module used for calling cron within Drupal (integrated into core in D7).
> 1 votes

---
Tags: cron, 5
---


# Question
Title: Why isn't my managed file getting saved?
Please save me from ripping out the rest of my hair...

I've got a "managed\_file" field in a form; nothing special. When the form is submitted, I run something like the following code to, presumably, catch and save it:

```
$destination = "public://video_posters";
$file_return = file_save_upload('field_poster_frame', array('file_validate_extensions' => array('jpg jpeg png gif')), $destination, FILE_EXISTS_RENAME);
if ($file_return) {
     $file_return->status = FILE_STATUS_PERMANENT;
     file_save($file_return);
     file_usage_add($file_return, 'my_module', 'node', $some_nid);
}

```

(There is more testing of $file\_return to catch the other cases, and a few other things, but you get the idea.)

What's happening is:

* An entry shows up in the `file_managed` table that is correct except that its uri is `temporary://the_file_name.jpg` instead of, presumably, `public://video_posters/the_file_name.jpg`.
* The file was indeed uploaded and is in the indicated place in temp storage -- just not where I want it to be.

Am I missing something obvious? Any things to check on? This is really driving me over the edge. Thanks!

# Answer
> 9 votes
The `managed_file` element handles moving the file into place and adding a file record, you don't need to save it yourself. The file module does all this in a validation function which makes the fid available in the submit handler.

So, for example, if your file element is defined with `$form['file_id'] = ...`, you can change your code to something like the following

```
$fid = $form_state['values']['file_id'];
$file = file_load($fid);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'my_module', 'node', $some_nid);

```

---
Tags: 7, files
---


title: Why do I get a 403 error?

text:
# Question
Title: Why do I get a 403 error?
I'm trying to setup a REST server to allow login from external apps.
I managed to get the sequence working using the Poster plugin in Firefox but can't seem to replicate using a small Perl script.
I manage to get the X-CSRF-Token but fail to connect, getting a 403 response.

This is the sample Perl code.

```
my $ua = LWP::UserAgent->new(env_proxy => 0,
keep_alive => 0,
timeout => 60);
$ua->agent('Mozilla/5.0');

my $req = new HTTP::Request('GET', 'example.com/services/session/token');
my $response = $ua->request($req);
unless ($response->is_success) {
    die $response->status_line;
}
my $token = $response->content;

my $header= HTTP::Headers->new;
$header->header('Content-Type' => 'application/x-www-form-urlencoded', 'X-CSRF-Token' => $token);

$req = new HTTP::Request('POST', 'example.com/smartphone_service/system/connect.xml', $header);
$response = $ua->request($req);

```

I installed the Services module and REST server locally, and that test worked. Service config is the same as the prod. What could be wrong?

# Answer
> 1 votes
Finally got it. It was mod\_security indeed. I could not see errors in my (cpanel) log because I am on a shared host but went ssh and saw it:

UNSUPPORTED DELAYED Rules: POST request must have a Content-Length header

```
$header->header('Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => 0, 'X-CSRF-Token' => $token);

```

That did the trick

Thank you Molot and David for taking the time to respond

---
Tags: 7
---


# Question
Title: commerce feeds product import not showing up
I imported a file with 5 fields *UPC-\> SKU(Unique), Product Description -\> Title, Unit Price -\> Price Amount* and 2 custom fields for wood type and knife number the import process says it created 21 products and I can find these products through *phpmyadmin* in various places including *commerce\_product, commerce\_product\_revision*.

There are also a number of entries of type *commerce\_product* in the *field\_revision\_field\_product\_category* table where as the types of my already created content are node in the same table. They all have a price of 0 but are not showing up in the product listing.

I'm using commerce kickstart 2.0, commerce feeds 1.3, feeds 2.0 alpha 7 and have feeds tamper 1.0 beta 4. I have run cron and flushed all caches.

I tried this in a fresh install of Commerce Kickstart but the products are still not showing up in the *view products* screen.

I also created a *barebones Drupal 7* install with commerce and feeds/commerce feeds and other required modules and the products seem to be created just fine.

# Answer
> 0 votes
Yesterday on #drupal-commerce in IRC, someone had a similar question. It appears that the "title" module may be interfering with commerce\_feeds. Try disabling the "title" module and see if that helps your import woes.

# Answer
> -1 votes
It seems Bojan Zivanovic is right. I don't see anything about a second importer to create the nodes. You'll need two importers and need to specify what gets added to the product (variation) and what gets added to the node (content type).

---
Tags: feeds, commerce
---


# Question
Title: Optional multiselect field, hide the - None- option
I am working on a form made mostly of multi-select fields, which are optional for the user to choose.

The multi-select fields work fine in general; however I really need to hide the *-None-* option in the multi-select fields which are not required for user to select. I can override it and change the text but thats not the point, since user can still select the *-None-* value in the process of selection, even tho it wont show after node is saved.

It just looks a bit confusing, even though it works as it should; users can select both the *-None-* option along with other options available and that makes the whole form different from what I want.

Here is an image of an example field showing what I mean.

>

>

I tried searching through the CCK module, but I couldn't really find anything.

# Answer
To get rid of "- None -" from selected field of a selected form, use:

```
function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    unset($form['field_name'][LANGUAGE_NONE]['#options']['_none']);
}

```

Of course for many fields it's inconvenient, but if they all share common parent (fieldset), you can iterate using `foreach` like:

```
function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    foreach( element_children($form['fieldset_name']) as $key => $child) {
       unset($form['fieldset_name'][$key][LANGUAGE_NONE]['#options']['_none']);
    }
}

```

This is not a ready code, just a sketch. Hints to make it work:

1. Unset elements of original `$form`, not `$child` generated by `foreach`.
2. Test if what you want to unset is there at all.
3. `dpr()` or `var_dump()` to see what's the exact structure you are working with.

You will need to wrap these into a Drupal custom module. Read Module developer's guide, especially Creating Drupal 7 modules, and `hook_form_alter()` API reference if you need more backgroung.

Inspired by this answer.
> 1 votes

---
Tags: forms
---


# Question
Title: User can upload files, but can't link to them
I have an author user who is able to upload files Using the Attachment field, however when trying to link to the same file via the Link icon in the text editor, they can't see the file they've just uploaded.

It seems to be a permissions issue... But I can't exactly figure out how to fix it.

Any help would be greatly appreciated.

The upload destination for the attachment field is set to Public

As a test run, I uploaded two different files, one as user1 and another as a different user. Running the ls-l command, they both get uploaded the same, with same permissions and user...

The files get uploaded to /public\_html/sites/default/files

**I am able to browse to the file the other user creates by using user1 account. But this is not the solution, as I want the authors to be able to link to their own files they upload...**

# Answer
> 0 votes
I don't believe it's a good idea security wise as it allows your "Samplers" access to your root and that could wreak havoc on your system.

In IMCEs config page "admin/config/media/imce/profile/edit/\[Sample's uid\]" right under Profile Name, make sure you tick the "Display file browser tab in user profile pages." checkbox, and uncheck the "include subdirectories" checkbox under the directory for Sample. Then clear all your caches (including browser) and it should work hopefully :-)

---
Tags: users, files
---