# Question
Title: hook_mail_alter() - how to access the "contact admin" form fields?
In Drupal 7.10 I have the /contact form open to anyone and would liketo add the **Reply-To** header to the mail message.

How do I get the value of the e-mail address field in the /contact form - both for guests and registered users?

Here is what I'm trying:

```
function your_module_mail_alter(&$message) {
  if ( $message['id'] == 'contact_page_mail' ) {
     $message['headers']['Reply-to'] = YYY;
  }
}

```

# Answer
Try doing this in hook\_form\_alter() instead of hook\_mail\_alter(). You can likely then run your own parameters into drupal\_mail().

I would recommend not using this contact form, though, since it's terribly limited in terms of functionality. Why not use a Webform at /contact where you can specify all of these settings and do potentially cooler things too, like pre-filling fields for logged in users?
> 1 votes

---
Tags: 7, hooks, emails
---


title: Gallery related to the article

text:
# Question
Title: Gallery related to the article
I managed to create a gallery and show it under a page (creating a view of type page).

What I really need is having one different gallery associated for each article, so I created a view of type "block", but the showed gallery is always the same, while it should related to the current article.

# Answer
> 1 votes
You need to add to your view the Contextual Filter: Content: NiD

Click Provide Default Value and select Content ID from URL

---
Tags: 7, media
---


# Question
Title: In D7 how can I append an element to the DOM via ajax on an arbitrary event (not forms and not links)?
There are many Form and Link related examples for D7's new Ajax features. I'm looking for something a little less involved but haven't got it working yet.

Using ajax-reload-of-block-on-an-event

I've modeled the following contrived example:

I'm tring to request and receive a tag and then nest it within an existing one:

```
function MY_MOD_menu(){
    $items['ajax/insert'] = array(
            'page callback' => 'ajax_return_tag',
            'type' => MENU_CALLBACK,
            'access callback' => TRUE,
    );
    return $items;
}

function ajax_return_tag(){
    $tag = "<h1>";
    $tag .= "HERE";
    $tag .= "</h1>\n";
    return $tag;
}

```

Here is the js:

```
(attach:function ($) {Drupal.behaviors.MY_MOD = {function (context){
    var insert = function(response){
            $('.field-name-field-').html(response);
    };
    $.post('/q=ajax/insert',
            {},
            insert,
            'html',
    );

}};})(jQuery);

```

It does not appear that my event is firing. Do I need to do something in addition to get the js to load on document ready? Have I made a mistake with the way I've attached the behavior?

Thanks in advance.

EDIT: Thank's for the responses. The typos are a result of me creating this example on the spot. I'm not so interested in getting this specific example to run but I am interested in a example that will update/Insert a DOM element that is not a Form or Link.

FYI I don't believe the event is firing. I assume that means that it is not registered with D7's included jQuery?

# Answer
> 3 votes
First visit example.com/ajax/insert to verify your content is being printed out.

Your overall JS structure looks odd, plus you have a lot of typos. This `.field-name-field-` is probably not a real class since it ends in a trailing dash. `/q=` is not a HTTP query, you probably want `/?q=`.

Try this:

```
(function ($) {

  Drupal.behaviors.my_mod = {
    attach: function (context, settings) {

      $.ajax({
        type: 'GET',
        url: Drupal.settings.basePath + '?q=ajax/insert',
        dataType: 'html',
        success: function(response) {
          $('.field-my-field-class').html(response.data);
        }
      });

    }
  };

})(jQuery);

```

# Answer
> 2 votes
It's not clear to me whether the event is firing or not. If it isn't, that's another problem in addition to the points Charlie S pointed out.

Consider adding some other reliable instruction like an alert, to be executed on the event. This will help you narrow down, when your expected Drupal behavior fails, whether it's because of the event failing ot fire or another reason.

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


# Question
Title: Why does Drupal url alias field allow apostrophes and passes validation?
In the node creation form, when a user unchecks the "Automatic alias" checkbox, the user can put apostrophe and other punctuation marks, which is not good in a URL.

How can I prevent this from happening?

# Answer
Use hook\_form\_FORM\_ID\_alter() to add your own validation function to node edit forms. In this validation function you'd check for characters that you want to allow/deny, and throw a form\_set\_error() on that field if there's a problem.
> 1 votes

# Answer
As mention you can set them as unavailable characters for the URL. I always install the transliteration module as well. It will help keep your URLs in check
> 1 votes

---
Tags: path-aliases
---


# Question
Title: How to assign permissions based on user points?
I am building a site where users are given permissions similar to SO. I am working with two models.

The first model assigns roles to users based on points. I can probably use Rules or a build a module for that. The nice things with this is that I get to use Drupal's build permission system. The downside is that I probably have to setup +10 roles and add even more if I want to give new permissions.

The second model is based on a custom build module (not build) that checks if a user is permitted to do whatever he/she intends to do. In this way all the roles can be avoided, but it doesn't use Drupal's permission system, which makes me a bit uncomfortable. On the other hand, there is no need for many roles.

So, is there a performance hit on having many roles? Other problems?

Any thought on this? Other approaches to give users permissions based on user points?

# Answer
Use roles.

The only problem with 10+ roles is that your permission table is going to get huge but you can solve this by limiting it per role (see link on roles list) or use a module like faster permissions.

The loading of roles is most likely much faster than doing custom checks. Also, when doing something like this, you'll certainly run into issues, for example when trying to work around existing permission checks in modules and so on. The permission system is one of the core elements of Drupal. Use it and don't try to fight it. That's not going to work.

There is a Userpoints Role module in http://drupal.org/project/userpoints\_contrib, which allows you to configure how many points users require for a given role and it should just work. There are even a few tests there now. Note that it currently gives you all permissions the user has enough points for. This might not be what you'd expect but it has the advantage that it would be enough to only specify the additional permissions each role has.
> 5 votes

---
Tags: users, userpoints
---


# Question
Title: Fatal error: Call to undefined function db_transaction()
I am new to drupal. In an attempt to achieve transaction, I get this fatal error. I am using drupal 6.22 and MySQL. `db_query()` and all the other database related functions are working fine, but `db_transaction()` alone fails. What am I doing wrong here? Any help is appreciated.

```
$transaction = db_transaction();

try {
       $result = db_query($query);
}
catch (Exception $e) {
       $transaction->rollback();

}

```

# Answer
There is no fuction `db_transaction()` for Drupal 6 (see Drupal 6 API search).

It **is** available for Drupal 7 though: db\_transaction()
> 3 votes

# Answer
The DB API in Drupal 6 does not have support for transactions.

You can however use the Backport of the Drupal 7 DB API: http://drupal.org/project/dbtng
> 2 votes

---
Tags: 6, database
---


# Question
Title: How to hide the right and left regions from a customized login page?
I'm working on Drupal 7, and trying to create one customized login page. I don't want to display the right and left regions in this page; I want a login page with only header, footer and content, where the content would be the "Username" and "Password" fields.

How can I do it?

# Answer
> 2 votes
Go to the Blocks admin page, `admin/structure/block`.

Find the regions you don't want to show. E.G., 'Sidebar A,' 'Sidebar B.'

'Configure' the blocks which appear in those regions. They will all have a 'Pages' tab at the bottom, and this is where you can configure which pages contain or exclude those blocks. You'd check 'All pages except those listed' and then put the path to your custom page.

HTH.

# Answer
> 1 votes
A good theme will have block-regions collapse (disappear) when there are no blocks in those regions.

So, every block which appears in those regions should be configured to not appear on the login page. This is a basic task with regard to configuring blocks, so, if you're not already familiar with how to define paths for block-display, you will easily find a handbook on drupal.org or many other guides or tutorials on the subject.

---
Tags: views, 7, theming
---


# Question
Title: Why does retrieving a form via drupal_get_form from another module not include AJAX settings?
I have a module in my Drupal 7 application called Feedback. It includes a form for submitting simple feedback. This form is submitted via AJAX, and I've already tested and verified the submission handling. In my feedback module, I had originally, via `hook_menu`, hard-coded the location of this form. I then decided that I wanted it to be more flexible - on a different content-type I have called Landing Page, a user may check a box to include the feedback form. When they do, I simply do a `<?= render(drupal_get_form('feedback_form')); ?>`, which pulls it in. The feedback form definition lives in a file called `feedback.admin.inc`, so I had to also put a `<?php module_load_include('inc', 'feedback', 'feedback.admin'); ?>` to get it to appear.

The form appears, but its AJAX handler is no longer working. Checking outgoing network traffic via Chrome, it appears that the AJAX request is being sent to the generic Drupal AJAX handler. So, when my function `feedback_form` is called within the feedback module, the form works correctly. When it's called outside that module, it does not. All of the functions related to this form are in the file `feedback.admin.inc`, which is being included, so I'm not sure what I'm missing.

For completeness, I've included the contents of `feedback.admin.inc` below, along with how it's being used in my Landing Page module. Any thoughts? Thanks.

`feedback.admin.inc`

```
<?php

function feedback_form($form, &$form_state) {

    $form = NULL;

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

    $form['last_name'] = array(
        '#type' => 'textfield',
        '#title' => 'Last Name',
        '#required' => TRUE
    );

    $form['organization'] = array(
        '#type' => 'textfield',
        '#title' => 'Organization'
    );

    $form['email'] = array(
        '#type' => 'textfield',
        '#title' => 'Email',
        '#required' => TRUE
    );

    $form['telephone'] = array(
        '#type' => 'textfield',
        '#title' => 'Telephone',
        '#required' => TRUE
    );

    $form['comments'] = array(
        '#type' => 'textarea',
        '#title' => 'Comments',
        '#required' => TRUE
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit Feedback',
        '#ajax' => array(
            'callback' => 'ajax_feedback_form_submit'
        )
    );

    return $form;
}

function ajax_feedback_form_submit($form, &$form_state) {

    if (count(form_get_errors())) {
        $response_text = '<ul>';

        ##
        ## Add each validation error to response text
        foreach(form_get_errors() as $element => $error) {
            $response_text .= "<li>$error</li>";
        }

        $response_text .= '</ul>';
        $header_text = 'There are errors with your feedback.';
        $error_state = TRUE;

        ##
        ## Remove message data from session so user is not reminded a second time
        unset($_SESSION['messages']['error']);
        if (!count($_SESSION['messages'])) {
            unset($_SESSION['messages']);
        }

    } else {
        ##
        ## Prepare feedback data for insertion
        $data = array(
            'first_name' => $form_state['values']['first_name'],
            'last_name' => $form_state['values']['last_name'],
            'organization' => $form_state['values']['organization'],
            'email' => $form_state['values']['email'],
            'telephone' => $form_state['values']['telephone'],
            'comments' => $form_state['values']['comments'],
            'created' => time()
        );

        ##
        ## Insert feedback record
        drupal_write_record('feedback', $data);

        $response_text = "Your feedback has been received.";
        $header_text = 'Feedback Received';
        $error_state = FALSE;
    }

    ##
    ## Return AJAX response for interpretation by Drupal.ajax JavaScript object
    return array(
        '#type' => 'ajax',
        '#commands' => array(
            array(
                'command' => 'modal',
                'text' => $response_text,
                'headerText' => $header_text,
                'errorState' => $error_state
            )
        )
    );
}

```

`landing page`

```
<?php module_load_include('inc', 'feedback', 'feedback.admin'); ?>

<div class="column">
    <?= render(drupal_get_form('feedback_form')) ?>
</div>

```

# Answer
> 4 votes
Your landing page module doesn't look like a module, it looks like a .tpl file. If that's the case, you want to include the form before the theming layer. If this is being passed through a theme() function in your landing page module, perform drupal\_get\_form ***before*** calling theme(). So inside `landingpage.module`:

```
function landingpage_feedback_page() {
  module_load_include('inc', 'feedback', 'feedback.admin');
  $vars['feedback_form'] = drupal_render(drupal_get_form('feedback_form'));
  return theme('landingpage_feedback_page', $vars);
}

// Implements hook_theme() to define your custom theme function and template file.
function landingpage_theme($existing, $type, $theme, $path) {
  $items['landingpage_feedback_page'] = array(
    'variables' => array('vars' => null),
    'template' => 'theme/feedback_page',
    'path' => drupal_get_path('module', 'landingpage'),
  );

  return $items;
}

```

And inside `theme/feedback_page.tpl.php`:

```
<div class="column">
    <?php print $feedback_form; ?>
</div>

```

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


# Question
Title: How to display data in tables using Forms API?
I want to organize my data in table rows. How can I user Forms API to do it?

EDIT:

I want to show the data in the following way in multiple rows:

row1 checkbox info1 textfield1 info2 textfield2 ....

....

rowN ....

row 1 \[add a new row fields here\]

...

row 5

One should be able to cancel existing records and in the bottom fill in fields to add new records.

And I finding the solutions in this link or in this really difficult to understand.

# Answer
> 2 votes
The *simplest* way to do this (on small forms) that I have found is by taking advantage of the #prefix and #suffix elements in the render array. Here's an example:

```
$form['foo_fieldset'] = array(
  '#type' => 'fieldset',
  '#prefix' => '<table>',
  '#suffix' => '</table>',
  '#tree' => TRUE,
);
$form['foo_fieldset']['header'] = array(
  '#markup' => '<thead>
    <tr>
      <th>A checkbox</th>
      <th>A text input</th>
      <th>A text input</th>
    </tr>
  </thead>',
);

for ($i=0;$i<10;$i++) {
  $form['foo_fieldset']['row_' . $i] = array(
    '#prefix' => '<tr>',
    '#suffix' => '</tr>',
  );
  $form['foo_fieldset']['row_' . $i]['checkbox'] = array(
    '#type' => 'checkbox',
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );
  $form['foo_fieldset']['row_' . $i]['text_1'] = array(
    '#type' => 'textfield',
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );
  $form['foo_fieldset']['row_' . $i]['text_2'] = array(
    '#type' => 'textfield',
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );
}

```

The other way to do it (maybe known as the "right" way) involves building a theming function to render your form in a table. Take a look at this page (ignoring the tablesort options as you don't care about that) to see how it's done: http://coffeeshopped.com/2010/09/drupal-drag-and-drop-tables-in-custom-modules

---
Tags: 6, forms
---


# Question
Title: Best way to build pages, or page equivalent
I manage a Drupal 6 site that has various content types and is set up to display them in various methods, all of which work just fine.

However, marketing likes to generate specific campaign based landing pages. These are primarily static pages, and historically have had no usability extras at all.

Using drupal, the design team has started to request a higher level of interaction, different blocks depending on role, use of the customers name if we have it... little things for the most part.

The solution I'm seeking:

...ideally lets the designers to be able to do this themselves. Dropping in the html and images, css, video, whatever.

...is potentially free of the site theme... this is trickier. I'd like them to be able to not include the header and footer if they didn't want it... or use a different body background.

...doesn't require a large number of modules. I stated this in a way that confused people before... we use a lot of modules. I don't mind modules. But I'd to find a solution that isn't a kludge of 8 modules mashed together in a way that isn't exactly what they were designed for and doesn't deliver exactly what you want.

Or as mtro put it as concise and eloquent as possible: designers regularly give me html/img/css packs that need to live on a single page within the site, and you want to streamline creating those pages without recurring template work?

My question is what do other What do other Drupalers do when you have non-standardized content that is regularly added and has partial or no theming?

# Answer
> 1 votes
If it were me, I would build a Custom Page Template. This is ideal for landing pages and it essentially creates almost like a subtheme in your existing theme with just one file. It also allows you to do a plain vanilla layout however you want without headers, sidebars, footers or whatever but still leveraging the power of Drupal 6 and CCK (hopefully you are using that module).

I wrote a blog post on how to do this: http://highrockmedia.com/blog/creating-custom-content-type-page-templates-drupal-php

# Answer
> 2 votes
I would suggest checking out Panels and CSS Injector.

Panels does most of what you are looking for; it presents a user interface for laying out varied content on a page without having to dig into HTML. It's not quite a pure WYSIWYG interface (theme styling might not apply to the Panels UI depending on your set-up), but it is as close as you can get with an out-of-the-box solution in Drupal.

CSS Injector will allow your designers to write CSS specifically for one Panels configuration through the UI, without having to touch the theme files.

# Answer
> 0 votes
I see Drupal as a CMS (content management system) and not a super themers product. If the marketing pages have a short lifetime, and the content is not reused elsewhere, then I see nothing wrong with doing a static page called by a redirect. That way, marketing does all there design work (woo) and all you have to do is point the redirect in the right direction, add some images to the directory and maybe put a wrapper around everything to insure their css is applied correctly. It is probable that doing complex things could take multiple modules, but the effort is worth it if you need the flexibility. In this case you may not.

# Answer
> 0 votes
sheena\_d has the right idea here. If you want each individual node to be a completely different layout for these sorts of situations, you should check out panelizer. It allows you to, per content type, specify if the nodes therein can be panelized. If they can be, you can setup default panel output for them and override it after the node's been created to provide completely different layouts and blocks etc. It's a really great module that Merlinofchaos also built, it builds upon the knowledge you gain using page\_manager and panels already, and provides a lot more flexibility than you've had up until this point.

I can't suggest it enough and I think it will solve your problem perfectly.

---
Tags: theming, 6
---


# Question
Title: File upload hook - how to integrate existing file manipulation code into Drupal
I want to create a waveform image for every mp3 file I upload in a **Drupal 7** website (as admin), and store it as a png for display in the frontend. I can use this script in order to do that.

I want to know what is the Drupal way of integrating that script, specifically:

* I guess that functionality will go into a module; where should I hook? file upload (there will be more than one file types to upload, and I would just want to work on the mp3)?
* how should I save the resulting waveform picture (where in the filesystem and how would I attach it as a field to my custom node type)?

As I'm new to Drupal (but experienced with PHP), I would appreciate a detailed response, but if you know of a module that already does that - I couldn't find it - that would be the shortest answer possible. :)

Thank you!

# Answer
BetaRide gave you some good links and generic suggestions already, here's some code to help you get a quicker start:

```
function mymodule_node_presave($node) {
  //drupal_set_message('<pre>'.var_export($node, TRUE).'</pre>');
  if (!isset($node->field_pic['und'][0]) && isset($node->field_file['und'][0]['fid'])) {
    $result = db_query("SELECT filename, uri, filemime FROM {file_managed} WHERE fid = :fid",
    array(':fid' => $node->field_file['und'][0]['fid']));
    $record = $result->fetchObject();
    if ($record->filemime == 'audio/mpeg' && pathinfo($record->filename, PATHINFO_EXTENSION) == 'mp3') {
      // TODO - create the picture, save in the temporary files folder and return the filename.
      $filename = 'created_image.png';
      $image = file_get_contents('sites/default/files/tmp/'.$filename);
      // public://pics/ -> sites/default/files/pics
      $file = file_save_data($image, 'public://pics/'.$filename, FILE_EXISTS_RENAME);
      drupal_unlink('sites/default/files/tmp/'.$filename);
      $node->field_pic['und'][0] = (array) $file;
    }
  }
}

```

This script should work when you have created a content type with 'field\_file' and 'field\_pic' that both allow 1 entry. First one should accept at least mp3 files and the second png images your linked script will create. The function/hook gets called before saving a node. If there is no image present in the image field and a mp3 file is present in the other you should use the script to create the image and return it's filename. After that a copy of the file from 'sites/default/files/tmp/' gets created into 'sites/default/files/pics' (possible name conflicts are taken care of). Then the temporary file gets deleted and the image info attached to the node. As you might have guessed 'sites/default/files' and it's subfolders should be used to store public files on Drupal sites. You should also make sure 'field\_pic' file directory (set up via the GUI) matches with the one used in the code.
> 3 votes

# Answer
1. Create a content type with a file field to upload the mp3 file.
2. Create a custom module and implement hook\_node\_presave. There you can do whatever you want with your node before it gets saved.
3. For the file handling have a look at File interface.
> 3 votes

---
Tags: hooks, files
---


# Question
Title: hook_menu implementation page not found error drupal 7.10
I am trying to figure out why hook\_menu implementation is not working anymore after upgrade from 7.4 to 7.10 for a custom module Menu links were working properly until update to latest version. after update all custom module links are deleted from table menu\_links and menu\_router.

ex. of one of the menu link:

```
$items = array();

$items['a/main'] = array(
'page callback' => 'main',
'description' => 'Main front page',
'access callback' => TRUE,
);

return $items;

```

This code was working properly in 7.4 but not anymore. Have tried to do all cache clearing, menu\_rebuild()... etc. nothing seems to work.

Even tried to copy sample code from hook\_menu API page like function mymodule\_menu() { $items\['abc/def'\] = array( 'page callback' =\> 'mymodule\_abc\_view', ); return $items; }

```
function mymodule_abc_view($ghi = 0, $jkl = '') {
// ...
}

```

and does not work as well.

So I am wondering if anything changed after 7.4 version or I am really missing obvious details?

Thank you for comments.

# Answer
Try adding a 'title' to your return array.

I noticed that the D7 menu documentation lists 'Title' as required:

```
"title": Required. The untranslated title of the menu item.

```

Now there is a comment on the doc page that claims it is not required.

But That comment is from March 20, 2011.

Perhaps the title is now finally required in a more recent release.

Edit: Your code from comment:

```
/** * Implementation menu(). / */
function misite_menu() {
    $items = array();
    $items['a/main'] = array(
             'title' => 'main',
             'page callback' => 'main',
             'description' => t('Main front page'),
             'access callback' => TRUE, );
    return $items;
}

/* * Implementation hook_theme(). */
function misite_theme() {
    return array( 'main' => array (
        'template' => 'main',
        'variables' => array('title' => NULL),
        ),
    );
}

function main() {
    $path = drupal_get_path('module', 'a');
    $title = t('');
    $build['mainelement'] = array( '#theme' => 'main',
                                                '#title' => $title, );
    $output = drupal_render($build);
    return $output;
}

```

Several observations.
1) I think your inclusion of hook\_theme could be causing needless grief. Try getting an example of hook\_menu working independent of hook\_theme.

2) I wouldn't use 'main' as a page callback name; it may not be conflicting with another function elsewhere but I don't think it is a good idea regardless.

Try this:

```
function misite_menu() {
    $items = array();
    $items['a/my_main'] = array(
             'title' => 'my_main',
             'page callback' => 'my_main',
             'description' => t('Main front page'),
             'access callback' => TRUE
            );
    return $items;
}

function my_main() {
    $output = 'HERE I AM';
    print($output);
}

```

Then navigate to a/my\_main and see if you can see "HERE I AM". If you can then you know your hook menu is working and that your problem is in your hook\_theme.
> 2 votes

---
Tags: routes
---


# Question
Title: html text or custom image to the user profile page?
On my user profile page, how do i add some extra html code or custom php code to the user profile page? as i would like to add a custom generated image based on userid in the profile page.

Please advice.

# Answer
you can also add a block to the "content area" to be shown below the user profile (restricted to user/\* pages). In the block you an use short PHP snippets.
> 2 votes

# Answer
You can add custom php/html code at user-profile.tpl.php.This file can be found inside the modules/user folder.
> -2 votes

---
Tags: media, users, entities
---


# Question
Title: The Field module shows an error when I call drupal_get_form()
I have a menu local task callback in `hook_menu()`:

```
$items['leg/add'] = array(
    'title' => t('Create a new leg'),
    'page callback' => 'mymodule_leg_node_form',
    'access arguments' => array('create leg content'),
    'file' => 'node.pages.inc',
    'file path'=> drupal_get_path('module', 'node'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
);

```

This is the page callback function:

```
function mymodule_leg_node_form(){
    $form = drupal_get_form('leg_node_form');
    return $form;
}

```

When I visit that page, I get the following error:

> Fatal error: Cannot access empty property in path\to\site\modules\field\field.attach.inc on line 197

I have a "Leg" content type, and I just want to show the form to create nodes of that type in a tab.

My content type has two fields: "field\_from" and "field\_to."
`drupal_get_form()` calls `_field_invoke()`, and the error is generated from that function.

I tried to change the menu definition as below, but I get the same error.

```
$items['leg/add'] = array(
    'title' => t('Create a new leg'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('leg_node_from'),
    'access arguments' => array('create leg content'),
    'file' => 'node.pages.inc',
    'file path'=> drupal_get_path('module', 'node'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
);

```

I'm implementing something similar to what reported in http://drupal.org/node/251526#comment-827860; it might work in Drupal 6 with the CCK module, but it doesn't seem to work on Drupal 7.

I found the same problem reported in Drupal bug issues, but I could not find any qualified answer.

# Answer
Solved this issue when I upgraded to drupal 7.10, but I had to create a node object in the page callback function.

```
function mymodule_leg_node_form(){
    global $user;
    global $language;

    $node = new stdClass();
    $node->uid = $user->uid;
    $node->type = 'leg';
    $node->language = $language->language;

    $form = drupal_get_form('leg_node_form', $node);
    return $form;
}

```
> 2 votes

# Answer
My first guess is that your form is not being built correctly. Some field is not valid. If it's not that in your code 'leg/add' seems risky, I don't know, but maybe 'leg\_add' would not throw the error? This is just guessing since there is a lot of code you did not post (like your form).
> 0 votes

# Answer
Do I get you right, that you have content type "let" with two (or more fields)? There's no need to code anything with forms or menu. Fields (or CCK in D6) does everything for you. Simply go to node/add/leg (after removing your hook\_menu stuff) and you will see your form.
> 0 votes

# Answer
Node is not saved when the add node form is implemented in a menu local task.
Finally, I solved this by calling `node_save()` explicitly in my extra\_submit function attached to `$form['#submit']`.

```
function mymodule_leg_node_submit($form, &$form_state){
    global $user;
    $values = $form_state['values'];
    $nid = $values['nid'];
    if(empty($nid)){
        # Create a node object, and add node properties.
        $node = new stdClass();
        $node->type = 'leg';
        $node->uid = $user->uid;
        $node->created = strtotime("now");
        $node->changed = strtotime("now");
        $node->status = 1;
        $node->comment = 0;
        $node->promote = 0;
        $node->moderate = 0;
        $node->sticky = 0;
        $node->language = LANGUAGE_NONE;
        $node->field_from[LANGUAGE_NONE][0]['value'] = $values['field_from'][LANGUAGE_NONE][0]['value'];
        $node->field_to[LANGUAGE_NONE][0]['value'] = $values['field_to'][LANGUAGE_NONE][0]['value'];

        node_object_prepare($node);
        // Save the node.
        // The node will also get published, if $node->status was set to 1.
        node_save($node);
        $nid = $node->nid;
    }
    $form_state['redirect'] = 'leg/' . $nid . '/transport';
    drupal_redirect_form($form_state);
}

```

I don't know why drupal did not save the node in this case, probably it is a bug.
> 0 votes

---
Tags: entities
---


title: Sorry, 10.0.11.38 has been banned

text:
# Question
Title: Sorry, 10.0.11.38 has been banned
For my website when using Firefox or Chrome you get the following message: Sorry, 10.0.11.38 has been banned. For Internet Explorer you 403 forbidden error.

Note: 10.0.11.38 is the internal IP of the load balancer which has the domains certificate and associated public IP address.
I went to admin/user/rules and noticed that this ip of 10.0.11.38 has been listed as a host to deny access so I deleted this rule and the drupal website displays again. We did not enter this ip as a rule originally so I suspect that drupal somehow decided to add this ip as a denied host.

How would I prevent this from happening again?

# Answer
admin/user/rules is not a path in a regular Drupal install, so you must have some module that does this for you. Since you tagged your post with domain-access I can only guess that the one. You should start looking into the settings of whatever module holds that path.
> 2 votes

---
Tags: domain-access
---


# Question
Title: Redirect anonymous users to the register page
Is it possible to redirect anonymous user to user/register page?
How can I do that?

# Answer
You should take a look at the Rules module and setup a rules that redirects anonumoys users to the user/register page.
> 4 votes

---
Tags: 6, users, redirection
---


# Question
Title: How do I make the custom module "Configure" option appear on the module list?
I have written a simple module that implements `hook_menu()` (the added path is admin/settings/mymodule").

On the admin/modules page which lists all the present modules, there is no "Configure" link for my module. How do I implement it so that the link to "admin/settings/mymodule" is visible on the modules page?

# Answer
> 12 votes
It's done in the module's ".info" file, using the "configure" key.

```
name = Example module
description = Gives an example of a module.
core = 7.x
package = Views
dependencies[] = views
dependencies[] = panels
files[] = example.test
configure = admin/config/content/example

```

---
Tags: 7, routes, hooks
---


# Question
Title: User roles and keeping their IDs when using features
I have defined some user roles and I'm assigning them to users through the rules module. I have created a feature with the rules and the roles and moved them to another site. My problem is that the user roles get new IDs and that the IDs are hardcodet in the exportet rules. Therefore the rules assigns wrong roles and I don't want to fix that each time I install the feature.

Can I somehow hardcode the user roles programatically and let the rules module work on them? Is there a better solution for the problem?

It is more or less the same problem for taxonomies that also get assigned new IDs.

# Answer
The Role Export module causes Role IDs to be hashes of Role Names — so the same Role Name will have the same Role ID on all sites. Great in conjunction with Features.

For Taxonomies, the UUID Features module may be helpful.
> 3 votes

# Answer
In short, this is a limitation in Core. Not everything has a machine name, and thus cannot be reliably exportable. Perhaps by D8's release everything will have UUID or a similar solution, allowing us to solve this. Then again, it's not a "magic bullet", as it comes with it's own set of issues, which is why we still have this problem around.

I have a question over here that revolves around how to handle this problem. There are no perfect solutions, but you have some good input over there.
> 1 votes

# Answer
This is a limitation of the features module. The makers of the features module have decided to use a so called *machine name* to identify exportables. Roles don't have a machine name. You can, however write your own module that exports roles based on the rid of the role. See the file *API.txt* in the feature module directory for an explanation about which hooks to implement.
> 1 votes

---
Tags: taxonomy-terms, users, features
---


# Question
Title: How can I get a list of all active enabled contexts on drupal site with drush?
I can list all enabled modules by calling `drush pml`.

I can also used flags to only return certain kinds of modules, based on where they are enabled or not and so on:

```
Show a list of available extensions (modules and themes).

Options:
 --type                                    Filter by extension type. Choices: module, theme.
 --status                                  Filter by extension status. Choices: enabled, disable and/or 'not installed'. You can use multiple comma
                                           separated values. (i.e. --status="disabled,not installed").
 --package                                 Filter by project packages. You can use multiple comma separated values. (i.e. --package="Core -
                                           required,Other").
 --core                                    Filter out extensions that are not in drupal core.
 --no-core                                 Filter out extensions that are provided by drupal core.
 --pipe                                    Returns a space delimited list of the names of the resulting extensions.

```

How can I list all the contexts enabled on a site in a similar fashion, so I can rype something like `drush context-list`

# Answer
> 2 votes
i would say something like this:

```
drush php-eval "print_r(context_active_contexts());"

```

---
Tags: drush
---


# Question
Title: Multiple instances of a field, differently formatted - how?
And if I wanted a particular field displayed on a node twice, but each instance built with a different formatter - what should I do? Example: a term reference field - formatted as plain text at the top, and as a link - at the bottom of a page.

# Answer
> 3 votes
To a render a field with a named formatter you can use `field_view_field()` with an array of display settings:

```
$display_settings = array(
  'label' => 'inline', // Position of label; 'inline', 'above' or 'hidden'
  'type' => 'link', // Name of the formatter,
  'settings' => array(/* Array of settings for the formatter based on your requirements */)
);

print render(field_view_field('node', $node, 'field_name', $display_settings));

```

# Answer
> 5 votes
I would use Panels. You can add each field as many times as you want and pick a different formatter every time.

1. Install the Chaos tool suite (ctools) module, and Panels.
2. Enable the Page Manager and Panels.
3. Enable the node template
4. Create a variant of type "Panel".
5. Pick a suitable layout.
6. Go to the "Selection rules" settings and add a "Node:type" setting so this is used for a single node type.
7. Add your fields and select your formatters.
8. Save

Using Panels requires a bit of understanding of the tools it provides. There are a few videos here.

---
Tags: 7, entities
---


title: drupal_add_js to Search module

text:
# Question
Title: drupal_add_js to Search module
I'm trying to add some custom JS to the search module in Drupal 6. I've added all of my custom JS through template.php via `THEME_preprocess_node()`

How can I add JS to the search module (without hacking the search module) via template.php in my theme?

# Answer
> 2 votes
Use `THEME_preprocess_search_block_form` to add `drupal_add_js` calls for the required javascript.

---
Tags: 6
---


# Question
Title: drupal_add_js cannot find my javascript file
I am trying to add a simple footer.js to my page. I created a new block and put it in the footer. I then use PHP snippet in the body of the block with the PHP code:

```
<?php
drupal_add_js('footer.js');
?>

```

When viewing the source code, footer.js is there but when I click on it, it is a 404 error (not found). The footer.js is located under: /var/www/drupal/sites/www.example.com/footer.js. Then I tried:

```
<?php
drupal_add_js('footer.js', array('type' => 'file', 'scope' => 'footer'));
?>

```

I don't think that is working, either. I think the issue is with the path. Any ideas, or do I have to write a custom module?

# Answer
> 1 votes
It is most likely a path issue, you should be able to use the `DRUPAL_ROOT` constant to get the correct one:

```
$path = DRUPAL_ROOT . '/sites/www.example.com/footer.js';
drupal_add_js($path);

```

---
Tags: 7, javascript
---


# Question
Title: Author of question flags only nodes that are answer to his question (node reference)
I have 2 node types - questions as parents and answers as referencing nodes. I would like to display flags only for nodes created as an answer to a given question. This should be only selectable by the author, not everyone.(same as stackoverflow best answer) So far I found out that I can manually place in node-answer.tpl.php the link using:

```
<?php print flag_create_link('select_answer', $node->nid); ?>

```

This will print the flag on every answer node, but I would like it to be selectable only by the author of this particular question. (basically it is the same functionality as stackoverflow - author can select best answer) There is an API function `flag_create_link($flag_name, $content_id)`, so I need to set `$content_id` to point to all referenced answers for a given question.

ANy idea how can I do it? Any advice appreciated.

# Answer
> 3 votes
Are they 2 nodes or 2 node *types*? If types, just create 2 separate .tpl files for them (node--type1.tpl.php and node--type2.tpl.php).

If they are the same content type, you can check that the node reference exists inside node.tpl.php like so:

**Edit: code below now only prints the link if the current user is also the author of the node.**

```
global $user;
if ($user->uid == $node->uid && isset($node->field_my_reference_field_name[LANGUAGE_NONE)) {
  print flag_create_link('select_answer', $node->nid);
}

```

# Answer
> 2 votes
The module Answers may provide the functionality you are looking for. Also check out the related modules, Best answer and Related answers (listed on the Answers module page). Do not load Answers Userpoints. It is missing dependencies that have no releases at this time.

---
Tags: 6, nodes, flags
---


# Question
Title: How do I provide multiple menu tabs for a view?
I have a view to select many articles with a specific taxonomy term with a path of Example.com/materials/% where the % uses a contextual filter to pick the correct material. The filter works.

Each article can be further subcategorized to discuss various subjects regarding the material and is given a path such as Example.com/materials/%/general or Example.com/materials/%/standards

I thought I would be able to display a default view for materials/% and have menu tabs defined by variations of the view to display /general or /scope parts.

I cannot get any menu tabs to display with the view.

Please respond with any questions, suggestions or alternative approaches that have worked for you.

Thanks

# Answer
I have solved this problem using the Quicktabs module.

I use a panel to set a page where I can put a quicktabs block, then I call different views with each tabs, also you can even set arguments.
> 2 votes

---
Tags: views, routes
---


# Question
Title: How do I get Drupal to use table prefixes so I can install multiple drupal installations in the same database schema?
My webhost is pretty limited, and I only have one database user & schema. I would like to install multiple drupal installations on this database schema.

How do I tell each installation to prefix its tablenames with a given string?

# Answer
> 2 votes
In the settings.php file, a normal setup might look like

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

```

The only difference is that you add a 'prefix', like this:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => 'site1_',
  'collation' => 'utf8_general_ci',
);

```

Make the prefix different in each settings.php site, and you can have as many sites as you want within the same database.

---
Tags: database
---


title: no field settings in block views?

text:
# Question
Title: no field settings in block views?
coming from D6, Im confused about why I can't seem to choose which fields from a content type I want to be displayed when I want to use the view as block? I searched for drupal 7 views fields settings but the results weren't about this particular issue.

# Answer
> 1 votes
If you select the content link on the 'show' line in the format section of the block definition (first column), you can switch the format to fields and then the available fields can be added. You may want to view the video learning series at nodeone.se called "Taming the Beast' for more on how to use Views.

---
Tags: 7, views
---


# Question
Title: Pressflow online users stats does not show correctly
I can not say enough of performance gain that my site gained through migrating to Pressflow + Varnish. However I have a rather annoying problem with Pressflow. After migrating to Pressflow 6, the statistics of online users does not show correctly. For example the forum shows 70 online users while there are actually over 1000 users online.

I am wondering whether it can be fixed or it is just a "collateral damage" that one should afflict to gain the performance. If it can be fixed, appreciate your hints to do so, and if not, how else can I show the correct stats.

Thanks

# Answer
> 2 votes
I believe this is because of how Pressflow handles anonymous sessions. It implements what are called "lazy sessions", which only creates sessions when actually needed.

This behavior can be changed by putting a `drupal_start_session()` in a custom hook\_init. If you do this, though, you will likely take a performance hit.

I have had to do this with a few projects to fix session problems when moving from Drupal 6 to Pressflow 6.

EDIT TO ADDRESS COMMENT:

You can simply put the hook in a custom module, such as

```
function mymodule_init ()
{
  drupal_start_session();
}

```

Note that you should really profile before and after to see what the performance impact is.

---
Tags: 6, nodes
---


title: Drupal 7: Collection of nodes field

text:
# Question
Title: Drupal 7: Collection of nodes field
Which is the best way to attach a collection of nodes to another node?

I'm creating a meal and ingredients nodes. I want to assign multiple ingredients to a meal and I'd like to do it programatically via modules ( content types )

Which is the best way to achieve this? Can you point me to the right direction ( links, etc...)

Thanks

# Answer
> 1 votes
* What about a taxonomy vocabulary for the ingredients list, and then just reference those taxonomy terms in your meal node?
* You could try the Insert View module, create a view with whatever other nodes you want, and then display it at the right place in your node
* If you want something a bit more complex, you could relate the meal node with the ingredient nodes, and collect them with a view, and *then* use Insert Views.

As a general note though, Views sounds like what you want to use -- it's perfect for that collecting of different information from other nodes and displaying it.

---
Tags: 7, nodes
---


# Question
Title: How to add a book page: material types empty
I run a Drupal 7 website since a year and have been always upgrading it - up to the version 7.10.

I have 2 Books and users' Blog at my web site. One of the Books is holding "Site Help" and "Imprint" stuff.

Now there have been a need to add to add 2 new pages "Terms of Service" and "Privacy Policy" to that book.

I go to **/node/add** but there is a message that no "material types" have been defined.

But I don't remember deleting them. And when I go to **/admin/structure/types** I see both "Machine name: blog" and "book" defined there:

Thank you

# Answer
> 1 votes
`Node/add` works for me, but try `admin/content/add`. Also check that you are logged on as the administrator.

---
Tags: 7, nodes
---


title: Redirect to a new domain?

text:
# Question
Title: Redirect to a new domain?
I'm currently running my drupal site on a subdomain (a.example.com). I would like to temporarily redirect any requests to example.com and www. example.com to a.example.com.

Mark Trapp already offered a great solution using .htaccess files. In this case I would prefer to add a little module code. I was thing about checking $GLOBALS\['base\_url'\] and then redirecting with drupal\_goto(). Are those the right functions and which hook would I use?

# Answer
> 2 votes
Maybe you're looking for the Domain 301 Redirect module. Here is a quote about it (from the module's project page):

> ... allows sites to 301 redirect to a domain that is marked as the main domain. This means you can have all subdomains and other domains pointing to the site 301 redirect to a domain that you choose as the main domain. This provides great SEO benefit.

# Answer
> 1 votes
The most easy way to do this is by using the drupal\_goto function in your `page.tpl` file.
It's bad practice because this file is almost the last one to be called, but it will do the trick.

---
Tags: 7, redirection
---


# Question
Title: Trouble with implementing contextual links
I have a block with dynamic content and two contextual links.

I have at the moment two problems:

1. The second element is not visible.
2. The first link does not allow to pass a date. I have to set a prefix e.g. "\_"

How can I fix this problems?

Here is the main part of my module:

```
define('MY_DIR', 'somedir');

function mymodule_menu() {
    $items[MY_DIR] = array(
        'page callback' => 'status_page',
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );
$items[MY_DIR.'/%'] = array(
    'page callback' => 'status_page',
    'access callback' => TRUE,
);
    $items[MY_DIR.'/edit'] = array(
        'title' => 'Edit item',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_object_edit_form', 2),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    );
    $items[MY_DIR.'/%date/update'] = array(
        'title' => 'Edit date',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_object_edit_form', 2),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    );

    return $items;
}

```

And here is my status page:

```
function status_page($date=null) {
    $object=new stdClass();
    $build=array();

    if(empty($date)) {
        $day=get_next_match();
    } else {
        // parse data
    }

    // set title
    $title="Title for ".$day->format("j.m.Y");
    drupal_set_title($title);

    $object->title = $title;
    $object->content = "Some dynamic content";

    $build[0] = array(
        '#theme' => 'filteredusers_object',
        '#object' => $object,
        '#contextual_links' => array(
            // contextual link 1
            'update-option' => array(
                MY_DIR,
                array("_$date"),
            ),
            // contextual link 2
            'edit.option' => array(
                MY_DIR.'/edit',
                array(),
            ),
        ),
    );
    return $build;
}

```

If something is unclear feel free to ask.

# Answer
After one day of research I got a solution:

```
$build[1] = array(
    '#theme' => 'filteredusers_object',
    '#object' => $object,
    '#contextual_links' => array(array('', array())), // replaced by dummy data
    '#marker' => 'marker',
);

```

And adding this new hook:

```
function filteredusers_contextual_links_view_alter(&$element, &$items) {
    if(isset($element['#element']['#marker']) &&
             $element['#element']['#marker'] == "marker") {
        $element['#links']['custom-link'] = array(
            'title' => 'Some title',
            'href' => url('node/42', array('absolute' => TRUE)),
        );
    }
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Are there two identical .htaccess files in a Drupal installation?
I run a Drupal Commons site and I'd like to set it up on a new server. When I set this particular site up, I need to replace Drupal's base `.htaccess` file so that it runs in my server environment.

However, this answer states that the `.htaccess` is present in two places:

> The .htaccess files (which are present in at least two places) should have the permission 644.

Is this true? If so, where is the second one? Is it the one in `sites/default`?

# Answer
> 5 votes
There are actually 1+n `.htaccess` files in any given Drupal directory, where `n` is the number of working sites:

1. In the Drupal root
2. One for each site's `files` directory

The contents of the `files` directory `.htaccess` file is the following:

```
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

```

This was done as part of a security update to Drupal 4.6.x and 4.7.x, and has been there ever since. The relevant security advisory, SA-2006-006, explains why:

> Certain -- alas, typical -- configurations of Apache allows execution of carefully named arbitrary scripts in the files directory. Drupal now will attempt to automatically create a .htaccess file in your "files" directory to protect you. This line references SA\_2006\_006 to lead Apache administrators to this announcement.

Thus it's not advised that you replace or remove that file.

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


title: Need a price quote engine

text:
# Question
Title: Need a price quote engine
Folks, I need a module that will give me the ability to collect service requests from anonymous users and will return to them an estimated price, so a quoting engine basically. I need the information they submit to also be summarized and sent in an email to a sales rep.

I know about Ubercart, but it seems to be overkill for what we need. Does anyone have experience with it and can vouch for it as far as this problem goes?

EDIT: Further elaboration on collecting service requests. The requestee selects a few services that they require, and in what quantity, and this request is forwarded to a sales rep who then prices out the request and contacts the requestee via email with a price quote. Really I see this as a one way mechanism where requests are just submitted, and then the rest of the conversation is carried out either over the phone or via email.

# Answer
I've used ubercart in this way before and it does give you some nice free functionality, for example you can mix non quotable items in your database and have Conditional Actions (Rules) that look to see if you need to make this a quote only type request. Once it's in there, the order can have it's status changed so that the customer can see how it's progressing and you can define new/different order states to correspond further to your workflow.

Having said all that, a D7 install I would probably start on commerce rather than Ubercart :)
> 1 votes

# Answer
*Receiving requests*

With webform, you can create forms that allow you, or your site-admins, to create and maintain the form that site-visitors will fill out. When the form gets submitted, you can use Rules to send this information on as an e-mail. The module Webform Rules, provides the bridge between the two modules, allowing Rules to react to webform events.

*Answering requests*

Just turn the whole process around. Again, use webform to create a form for the request reciever to fill out. When this form gets submitted, send a mail to the requestee with the reply.

*Custom work*

You will most likely need to do some amount of custom coding to make this whole thing work. For example, in the mail to the sales rep, a link must be autogenerated to a form that gets prefilled with the requestee's e-mail. Auto-filling the form is likely best done as a hook\_form\_alter. There is a lenghty Rules video series that you can view to learn more about how to work with Rules and how to extend it to do what you need.
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: How to store HTML data in a database field?
I'm trying to write some code for the Image marker module to allow an HTML description to be stored in the database. Currently all text is escaped and stored as plain text.

The module stores x/y coordinates and descriptions as name/value pairs in a database field, for example:

```
x=208&y=251&id=208-251&description=wheel;x=77&y=142&id=77-142&description=light

```

Can I store HTML descriptions this way? Is there a better way to store this kind of data?

# Answer
**Assumption:** You can't just point Image marker to this table of yours and it will figure out the rest itself. You will need some amount of *php code*, to make the module do what you want. For example you will pass your data on to a theme function.

**Proposition:** It seems to me like it would be better to serialize an array like this:

```
array(
  0 => array('x' => 208, 'y' => 251, 'id' => '208-251', 'description' => 'wheel'),
  1 => array('x' => 77, 'y' => 142, 'id' => '77-142', 'description' => 'light'),
);

```

and store the serialized data? That, or create a 4 table column, one column for each type of value. That should make it easier to pass the information on to Image marker, as opposed to using explode(), which I assume you will need to do if you store a long string of HTML.

On a more general note, I would generally avoid storing already escaped data in the DB. There may come a time when you do want to use the data in an un-escaped fashion, which could become a huge mess of regexp to reverse the escape. One example is if you load, edit, and re-save the data, you will have & escaped into & when you load, which in turn will become & when you escape the data *again* for saving.

Escaping data is, in my opinion, for display of data, not storage. That said, if you are absolutely certain you will *never* need the un-escaped data again, then you could avoid one potential security hole.
> 2 votes

# Answer
Basic info about user input sanitization in Drupal.
> 4 votes

# Answer
Not sure you want to be escaping all the text, especially if the description gets to be long.

You might be better served by creating a new table, keyed on the marker's id, using a longtext field to store the html.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Set amount of fields on an existing content type
One of our website requirements is to have a content type that lets you decide on the total amount of form fields on the fly.

For example, if I specify a number 10, then it ought to generate the form fields consecutively; the text area and the checkbox form fields are created 10 times.

Essentially, to break it programmatically, it will create:

```
for(i = 0; i < 10; i++) {
  echo "<input type = 'textarea'></input>";
  echo "<select><option>1</option><option>2</option></select>";
}

```

This is pretty straightforward if I was dabbling with simple PHP files, but with Drupal 7's fields it is posing a bigger challenge than what it ought to be. I have tried exploring modules that let you create content types on the fly and considered creating a custom content type programmatically which seems like another challenge altogether.

I am curious if anybody has an alternative for this, and has dabbled with this challenge before.

# Answer
If I understand you correctly, you're trying to change the *cardinality* of a field based on user input. You can do this by using `field_update_field()`:

```
$field_name = 'field_bar';
$field = field_info_field($field_name);

$field['cardinality'] = 10;  // Change to number you want

// field_update_field() throws an exception on failure
try {
  field_update_field($field);
}
catch (Exception $e) {
  drupal_set_message(t('Could not update field.'), 'error');
}

```

As you can see, cardinality is actually a per-*field* setting: if you wanted to do this on a per-instance basis (so, separate cardinality for the field for each content type/bundle), you actually need to create an entirely new field for each bundle.

This would likely cause a number of issues, particularly if you wanted to do things like display the values in a view (each field would be handled separately, even though the only thing different is the name and the cardinality).

Instead, what I'd do is just set the cardinality of the field you want to be dynamic to "unlimited" (`FIELD_CARDINALITY_UNLIMITED` in code): out of the box you get a fancy widget that lets users add as many values as they'd like.
> 3 votes

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


# Question
Title: How to check if drupal_get_messages() returns an empty array
I am running drupal 6.22 with MySQL. I am trying to check if there is any error message set by using the following `If` statement, but with no luck.

```
if(count(drupal_get_messages('error',FALSE)) > 0){
...
}

```

When I try this condition, I get a parse error saying...

```
Parse error: syntax error, unexpected T_IF

```

What am I doing wrong here? And how do I check if there is any error message in the message queue?

# Answer
What you get is a syntax error not a parse error, meaning that the code never executed, but PHP couldn't parse it. My hunch is that the problem is in the code before the if statement. One way of getting this error would be to do:

```
$var = 'foo' // Missing ;
if (TRUE) {
  $var = 'bar';
}

```

This would result in the error message you got.

A lot of things could be wrong, but when it is a syntax error, the gist of it, is that you made code PHP couldn't understand.
> 3 votes

---
Tags: 6
---


# Question
Title: Can i port theme settings also in a feature
I tried to port a theme settings like default theme, other theme settings in a feature. But when i enable this feature along with the theme on a new website. It does not take effect.

# Answer
Theme settings are usually stored as a variable, which is exportable with strongarm. Note that some things in the theming system is cached.
> 1 votes

---
Tags: 7
---


# Question
Title: Adjust topic title length on topic listing page (Advanced Forum)
I'm trying to find the right way of adjusting the topic title length displayed on the topic listing page generated by Advanced Forum (mysite.com/forum/\[myforum\]).

I tried to manipulate the title variable offered by the `template-advanced-forum.naked.topic-list-view.tpl.php` and the corresponding theme function but it gives me formatted HTML like this:

```
<a href="/debatindlaeg/lorem-ipsum-lorem-ipsum-lorem-ipsum-lorem-ipsum-lorem-ipsum-lorem-ipsum-lorem-ipsum" title=" lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum  lorem ipsum lorem ipsum lorem ipsum lorem ipsum   "><span class="forum-topic-title">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum </span> </a> <br /> by <span class="username" xml:lang="" typeof="sioc:UserAccount" property="foaf:name">Anonym</span> » ons, 18/01/2012 - 17:05

```

My guess is that I need to go "further back" in the theming process somehow to get a hold of the title variable, but I must admit this is beyond my Drupal skills. Any suggestions?

I am using D7 and Advanced Forum (version 7.x-2.0-beta1).

# Answer
> 1 votes
Not sure if this is exactly what you're looking for, but Advanced Forum integrates itself with Views.

So (assuming you have the Views module), you can trim the length of the title field in the `advanced_forum_topic_list` view. This c done by clicking the `Content: Title (Topic / Topic starter)` field, going to *'Rewrite results'* and checking *'Trim this field to a maximum length'*.

Because the field contains HTML to insert a span tag, you'll have to add 32 to the trim count (e.g. if you want to trim to 20 chars, enter 52), and ensure *'Field can contain HTML'* is checked.

---
Tags: 7, theming, nodes
---


title: Count the number of users in roles

text:
# Question
Title: Count the number of users in roles
In my D7 installation I'd like to have a view where all roles are listed followed by the number of users that have that particular role.

i.e. of my expected result:

1. role 1: 2
2. role 2: 5
3. role 3: 1
4. role 4: 8

In addition to this, when I can exclude a role (the admin role) from this view, it would make my day...

Thanks for your support!

# Answer
Create a User View. Then add a "Contextual Filter" for the field "User: Roles". Set the "When the filter value is NOT available" option to "Display Summary" and leave all the other settings. Now you should get the list you want ...

Check the other settings for any customization of the list.
> 6 votes

---
Tags: views, users
---


# Question
Title: How to load module include files in .test file?
I'm trying to update the Drupal 7 version of the password\_policy.test file that is included with the Password Policy module. When I run the tests, I'm getting "Fatal error: Call to undefined function password\_policy\_constraint\_uppercase\_validate()".

The function in question is in an include file in the constraints subdirectory, located inside the module's directory. I've tried adding to the test's setUp() function, along the lines of:

```
drupal_load('module', 'password_policy');
module_load_include('inc', 'password_policy', 'constraint_uppercase');

```

I've also tried adding the module\_load\_include line inside the individual test method generating the error. However, none of my attempts so far appear to be working and the error still persists.

How should I go about loading the ./constraints/constraint\_uppercase.inc and other include files, so that the necessary functions are loaded prior to the tests being run?

# Answer
You have a flaw in your code, `module_load_include` works by including files relative to the module base dir, so you should do

```
module_load_include('inc', 'password_policy', 'constraints /constraint_uppercase');

```

to include `password_policy/constraints/constraint_uppercase.inc`

When you do

```
module_load_include('inc', 'password_policy', 'constraint_uppercase');

```

You instead try to include `password_policy/constraint_uppercase.inc` which doesn't exist.
> 7 votes

# Answer
I believe you can add in the modules .info file:

```
files[] = constraints/includeme.inc
files[] = constraints/includeme2.inc
files[] = tests/included.test

```
> -1 votes

---
Tags: 7, testing
---


# Question
Title: do i need to check expiration cache in drupal from cache_get?
I'm using drupal 6 and I've build table that is similar to cache (hook\_schema) for using it with function cache\_get/cache\_set. I just want to be sure how things should work in drupal.

1. To clean the table I'll need to use hook hook\_flush\_caches() where I'll decide if i want to clear expire data or whole cache? hook\_flush\_caches is called on cron?
2. In case I'll need to check data expiration by second, I'll need to do manually after cache\_get function ?

This is kinda confusing...

# Answer
It is actually pretty simple.

For your implementation of `hook_flush_caches`, all you need to do is return an array containing the names of your cache tables, eg

```
function mymodule_flush_caches ()
{
  return array("cache_mymodule");
}

```

drupal\_flush\_all\_caches and cache\_clear\_all take care of the rest. `drupal_flush_all_caches` is called anytime you manually clear the cache (the perforamnce page, admin menu, drush, etc). system\_cron does get called by cron, and also clears the cache tables, but does not do some of the other things that `drupal_flush_all_caches` does.

When you get something out of the cache with `cache_get`, expired items will have already been removed from the cache; you don't need to manually check expirations. They will be handled automatically according to how you put them in the cache with `cache_set`.

That's it.
> 3 votes

---
Tags: 6, caching
---


title: add fields to comments programmatically

text:
# Question
Title: add fields to comments programmatically
I know how add fields to entity, now what is XXX in below code when I want add this field to comment of articles?

```
$instance = array(
    'field_name' => 'field_image',
    'entity_type' => 'xxx',
    'bundle' => 'xxx',
    'label' => t('Images'),
    ....

```

if any other setting is required, then what is that?

# Answer
> 4 votes
I found my answer, see:

```
dsm(entity_get_info());
dsm(field_info_bundles());

```

so my code should be:

```
$instance = array(
    'field_name' => 'field_image',
    'entity_type' => 'comment',
    'bundle' => 'comment_node_article',
    'label' => t('Images'),
    ....

```

---
Tags: 7, entities, comments
---


title: Help with themeing the Admin Theme

text:
# Question
Title: Help with themeing the Admin Theme
I'm working on a D7 site at the moment and need a bit of help with the admin themes.

I've got 2 levels of admin for the site. Super user and a lower level admin that can only edit content they created. The lower level does not have access to the administration theme so their pages and admin forms are showing up in the site's content.

My question is: Is there a way of theming these pages through a template? Does it just use the basic node.tpl.php file? I can style the page in the CSS but I don't think this is going to be enough.

Thanks

# Answer
> 10 votes
Admin pages are not nodes, so you would need to use the page template rather than the node template. You can copy your theme's page.tpl.php file and rename it to page--admin.tpl.php to create a template just for all admin pages. If you need these changes to extend for node edit pages, then you would need to also create a page--node--edit.tpl.php file.

Another option is the ThemeKey module; it allows you to specify which theme to display based on path (i.e. you could change it for all admin/\* paths) and/or based on user role (change theme for super users and low-level admins). You could choose a contributed admin theme to display on these conditions, or create a sub-theme of your front-end theme to display.

# Answer
> 2 votes
i had a similar thing and the thing i did was that

You can let them access the Overlay (Access the administrative overlay View administrative pages in the overlay.)

and then let them use the Use the administration toolbar

and then everything that you like to use let say "Access the content overview page" we will be placed in the toolbar and will be displayed in the overlay.

So the pages will not load right in the template but in the overlay so will be more clarify (but still uses the default template) but it's better

That solution came up to me..!

---
Tags: 7, theming
---


# Question
Title: What mapping solution do people use that has a proximity filter?
For D6 I used gmap, which allowed me to easily create map-based views and include proximity filters and sorts. With D7 I've been tempted to move to OpenLayers - I like the idea of learning one powerful mapping tool that can be used to solve more problems than presumably gmap could. *However* I can't for the life of me find anything that looks close to stable for proximity filters and sorts. I find this a bit surprising - does anyone know of anything I've missed? The best lead I've found so far is this sandbox project, but I haven't given it a go yet.

So can anyone recommend a way, with or without OpenLayers, to have Views-based mapping and proximity filters on D7?

# Answer
> 3 votes
As of writing this, jpstrikesback's sandbox: Proximity is really solid. I have it running on a few production sites without issues. Once he feels it's 100% it is either going to be released as the D7 version of OpenLayers Proximity or use the new namespace "Proximity" (as it really does not require OpenLayers to function).

I recently wrote up a walkthrough of how to get this up and running for another question on stack exchange. See Need a simple Google Maps solution; lost in the labyrinth of modules.

As you mentioned GMap was ok in D6, but using OpenLayers is much more robust and flexible. It's worth spending the extra time to get it set up. Good luck

---
Tags: 7, google-maps
---


title: Drupal permission table

text:
# Question
Title: Drupal permission table
If u have seen drupal permission table, that is like

structure 1

```
pid rid    perm                   tid
1    1   view f1, edit f2          0
2    2   view f1                   0

```

what is good with structure1?

why drupal doesn't use this structure?

```
table1

    fid      name
    1      view f1
    2      edit f2

table2

pid  rid  fid
1     1    1
2     1    2
3     2    1

```

# Answer
Table 1 matches how it is in Drupal 6, table matches more or less how it is in Drupal 7.

So to answer your Question, the newest Drupal does indeed use a schema close to what you proposed.
> 5 votes

---
Tags: 6, database
---


title: Drupal 7 AJAX disables my callback

text:
# Question
Title: Drupal 7 AJAX disables my callback
I have JavaScript attached to an element in a form that sends it's new value to a PHP callback function. The callback function queries the database and then returns a value that JavaScript then puts in a text box as its value.

I have experimented, and found that callbacks do not work on node edit forms. I assume it has something to do with the new AJAX functionality built into forms.

How to get around this problem?

# Answer
According to the code example that you posted, you are using a *relative path* in your AJAX request. Maybe you should try anchoring your request to the *base path* by using `/objnum_callback` instead of just `objnum_callback`. This will ensure that your request is pointing to the same place regardless of the current page.
> 1 votes

# Answer
have you tried looking in to the form API #ajax attribute, more importantly `#ajax['callback']`? Personally I would go this route as it would allow your callback to be called when the form is being rendered rather than after render.

What I would look in to is altering the node form you're trying to change with hook\_form\_alter or a more specific form id for the kind of like hook\_form\_BASE\_FORM\_ID\_alter(). Once that is done you can modify the form field you were looking to have populated and add the `#ajax['callback']` and have it be the function you're trying to call via the `$.ajax.`

If you go this route you would be using Drupals native ajax framework rather than adding on over top of it.
> 0 votes

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


title: Dynamic colors for node bodies

text:
# Question
Title: Dynamic colors for node bodies
In Drupal 6, I have a CCK colorpicker field, and I would like to use the color for links, b/em tags, and headers in the body of the node. In D7 i could use `drupal_add_css` to create inline CSS that is not aggregated, but that is not available in D6. Is there a way of doing this that doesn't involve preprocessing the body and adding inline styles to the individual elements?

# Answer
> 1 votes
I haven't done it to make inline CSS, but you could try creating a new region in your `.info`, and using drupal\_set\_content to add structured content. You can then parse / format it in a template\_preprocess\_page, and then print it in your `page.tpl.php`. I've had to resort to similar tricks in the past to work around this.

I suspect your best place to call `drupal_set_content` from is a hook\_nodeapi(&$node, "view")

---
Tags: 6, entities, theming
---


# Question
Title: Does using Views Aggregation break title field as node link?
I have a working View that uses aggregate to count members of Organic Groups that I modeled off of the View described here.

The title of the Groups is also included in the View; however, even though "Link this field to the original piece of content" is selected the View does not configure the Groups title as a link.

Does anyone know if this is because Aggregate is interfering with the link? Should the Aggregate settings on the title field be something specific? Or does it have something to do with the way the Organic Groups Views relationships are defined?

# Answer
I can confirm this was fixed in a recent dev release of the Views module.
> 0 votes

---
Tags: 7, views, organic-groups
---


# Question
Title: I got a notice every time I upload an image
Suddenly, I got this error every time I want to upload an image. It does not matter if it is an file field, or an IMCE import to CKeditor. I got the message, and the image does not upload. Do you have any idea?

> Notice:getimagesize() \[function.getimagesize\]: Read error! in image\_gd\_get\_info() (line 349 of /www/mysite.com/modules/system/image.gd.inc

My "tmp" and "sites/files" directories have the permission 777, php5-gd is already installed.
I have also problems uploading attachments files, after upload them the size of the file is 0 bytes.

In this conversation, they suggest two solutions: one is changing the path of the "tmp" directory, but it doesn't work for me; the other is related to favicon set.
I remember that I uploaded a favicon in theme settings as I always do, and I think after that I began to have the issue. I am not really sure if it is related because this bug happened in older versions of Drupal.

Some images of my problems.

# Answer
> 1 votes
The issue is already fix. The hosting provider had changed some permissions of my shared account.

# Answer
> 0 votes
We had a similar issue in Drupal before and the issue was with the installed GD library on the server. Our server admin fixed it with instructions that he found here - http://drupal.org/node/134331

---
Tags: 7, media
---


# Question
Title: Can i populate the empty sites/default/files/ with files from a local installation?
There are no JavaScript and CSS files in the following folders:

```
/home/vhost/WWW/mysite.com/sites/default/files/js
/home/vhost/WWW/mysite.com/sites/default/files/css

```

All the folders are empty. Can i populate the folders with aggregated css and js files from another drupal installation that is the same?

**Update:** thx to googletorps and sheenas ideas and hints regarding the special constitution of the aggregated css and js-files i just have had a closer look at them - which are based on my local (!!!) installation of the exacly same installation - a drupal commons: for the sake of a better understanding the aggregation of the hashed files i add the output of the shell here:

we see the **files how the should (!!!) look like:**

here we see the **css-files**

```
linux-vi17:/srv/www/htdocs/com624/sites/default/files/css # ls -l
insgesamt 872
-rw-rw-r-- 1 wwwrun www 158526 22. Jan 12:10 css_2c40e29bada7df2a0872e3284d5906c0.css
-rw-rw-r-- 1 wwwrun www 164051 22. Jan 12:04 css_509f375f4dd1349c65961ef65612b39f.css
-rwxrwxrwx 1 root   www  62359 20. Jan 23:35 css_715c2ea6e483943b9fb7a7870eb8d3af.css
-rwxrwxrwx 1 root   www 163905 20. Jan 23:35 css_7d8ae0563cfe8042f1ae8c8b997decaf.css
-rw-rw-r-- 1 wwwrun www 158378 22. Jan 12:08 css_ad58026023b58c62611ee2690b7767ed.css
-rwxrwxrwx 1 root   www 164051 20. Jan 23:52 css_dc93777fb44b0e70ce92cdbc3fb098e9.css
-rwxrwxrwx 1 root   www    869 20. Jan 23:35 css_dfe74e375bbbe435aaa2c17f83c4843a.css
linux-vi17:/srv/www/htdocs/com624/sites/default/files/css #

```

and here the **javascript-files**

```
linux-vi17:/srv/www/htdocs/com624/sites/default/files/js # ls -l
insgesamt 2004
-rw-rw-r-- 1 wwwrun www 252042 22. Jan 12:09 js_49eafedecb47a7ddbcbaca1afe9934bd.js
-rwxrwxrwx 1 root   www 116020 20. Jan 23:35 js_5b2fd4858d6549bf716717a2aeff7ec8.js
-rwxrwxrwx 1 root   www   2619 20. Jan 23:35 js_5e4cf1f9d580681533f28941e5369206.js
-rw-rw-r-- 1 wwwrun www 291843 22. Jan 12:04 js_7308bd15ff335fb80932a983f43a674e.js
-rw-rw-r-- 1 wwwrun www 244292 22. Jan 12:08 js_7fccee0ff92c41edc64dbe9af3cc42d5.js
-rwxrwxrwx 1 root   www 291843 20. Jan 23:52 js_b03baa42e9679d7c9bfa96bf43b644de.js
-rwxrwxrwx 1 root   www 291460 20. Jan 23:35 js_b6a467b980c752283820195189e6e5e0.js
-rw-rw-r-- 1 wwwrun www 289758 22. Jan 12:10 js_c97e31b30c535ae5779711f7966b6096.js
-rw-rw-r-- 1 wwwrun www 252637 22. Jan 13:49 js_e4cc5b6ab05a295dab73ce5aac20ac1d.js
linux-vi17:/srv/www/htdocs/com624/sites/default/files/js #

```

**Note:** and what we can see here in a good way - the **files are generated at different** times. (note this is not!!! the mentioned site with the broken style - this is a site that is runned locally on the local lampp)

Well what makes me wondering is the **following fact** we have very differnet owners of the files - see that we have sometimes have

```
root   www
wwwrun www

```

**question:** why is this so!? i do not understand this! OR wait - the owernship corresponds with the permission (chomod..) what do you think? in othe words: is there a **relationship** between the permission which is in one case pretty much/ high \]

```
-rwxrwxrwx 1 root   www   2619 20. Jan 23:35 js_5e4cf1f9d580681533f28941e5369206.js

```

and in the other case pretty low / weak and this correspondents/results in the wwwrun-user:

```
-rw-rw-r-- 1 wwwrun www 291843 22. Jan 12:04 js_7308bd15ff335fb80932a983f43a674e.js

```

**latest Update**: after adding the files i have the following results: http://campus-24.com/?q=home

# Answer
If your two Drupal installs are exactly the same, it is possible. Your biggest problem will be figuring out the name of the files, since they will have some hash value generated by Drupal. I don't know exactly how this is generated, but yes it is possible.

Now while this is possible, it's not a long term solution. If you had a live site, and something was failing to generate the aggregated css and js files, it could be a quick short term solution until the real problem was found and fixed.

I believe that you have asked about this already and received answers about file permissions etc, some of this which doesn't belong here, since it's about setting up a server and not Drupal itself. I would advise against pursuing this path, and instead try to resolve the real issue. If you want to upload files, use image cache and a lot of other modules and features you need to resolve this anyways. Making a hacky unstable solution will do you no good.
> 1 votes

---
Tags: javascript, theming, files
---


# Question
Title: How can i add a block below the content of a node?
I created many blocks and used them in my nodes regarding to contet types.

But i need another thing. I created new block. In the "/admin/structure/block" page i dragged this block to "Content" region. The block appeared in content region. But it appeared above the node body.

In content part of "/admin/structure/block" there is 2 blocks: "Main page content" and "My own block". My own block is below the other block. But still it appears above the content body. Should i pay attention any other thing? Thank you.

# Answer
Sometimes it helps to drag the block around in the `admin/structure/block` page. For instance drag it above the content block, and then back down to below. Then be sure and click 'Save.' :-)
> 3 votes

# Answer
In the Block UI at admin/structure/block toggle "Show Row Heights"

Set the weights manually to ensure they are correct.
> 5 votes

---
Tags: blocks
---


# Question
Title: Access description field for file in a view
Gents, I have two fields that accept multiple file uploads. One of those fields has file descriptions enabled. I need to access those field descriptions in my view, but I don't see the file description field popping up in the list of available file fields.

I've added the relationship fid for the field that has multiple files associated with it.

So, I'm confused as to how I'm supposed to get the file description view exposed. How do I do so?

Let me know if I need to clarify further.

# Answer
You can get the file description to display by adding your file field (just as Content: fieldname), then choosing to 'Rewrite Results'. For the Replacement Text, there is an option to use \[field\_fieldname-description\].

Reference: http://drupal.org/node/1128270#comment-5253600
> 6 votes

# Answer
It does not show up when you are choosing the field in your view but it will once you choose the file field itself and see your preview. (see my screen capture.). This is all assiming you enabled "descriptions" in the content type field itself but you implied you have already done that.

Does this help?
> 0 votes

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


# Question
Title: How to Pass argument from URL to field in Views
I need some help about the follow case:

I have a json file from webservice that i extract all informacion and shows into a view. (I have a module that do it) The json file is specify in a field into a views: Json\_file: "http://\[path\]/event/4.json"

However, only show all informacion about the EVENT 4 ("event/4"). My question is: Is there any solution to pass an argument and change the url that is defined in the field of the route? (Only change the number after "event/")

For example: Json\_file: "http://\[path\]/event/4.json" Json\_file: "http://\[path\]/event/5.json" Json\_file: "http://\[path\]/event/3.json"

Note: The structure of the URL is static, always have the same structure.

# Answer
> 3 votes
This is done using contextual filters. The easiest way to do it is to set up a "page" display by clicking Add+ on the views page. Give the page the URL of http://\[path\]/event/% (you may also have to try %.json depending on the exact call you are trying to make, the json files are known to drupal right?). The % gives you the argument you are looking for. Then you need to set up a Contextual Filter found under the advanced section of the view. Here you pick the field you are passing the number 4 or 4.json to and choose the correct settings. You may find that you need to pick Provide Default Value for this exact case and then use raw value from url or even php code and do some magic on the $argument (depending on exactly what it is you are doing).

---
Tags: views
---


# Question
Title: Infinite Redirect Loop with PURL and spaces_og
I created a calendar feature for organic groups, and tried to enable it in a group with spaces\_og. The page refreshes saying changes have been saved but the feature is still disabled. In the logs, there is a message that purl prevented a redirect loop.

I realize spaces is still in dev with d7. Is this a known issue? Did I do something wrong when creating my feature, or is there a better way to create features for use in organic groups?

# Answer
> 0 votes
This issue occurred because I didn't have a path prefix set for purl. I created the group prior to enabling purl and spaces. After adding the path in the group node edit form, the redirect loop was no longer present.

---
Tags: organic-groups, features, 7
---


title: entity_get_controller Fatal error

text:
# Question
Title: entity_get_controller Fatal error
`entity_get_controller()` is giving me an error when I try to use a class. This class is defined in another file called ingredient.controller.inc

> Fatal error: Class name must be a valid object or a string

The following code doesn't work:

```
 function ingredient_add() {
   $ingredient = entity_get_controller('ingredient')->create();
   return drupal_get_form('ingredient_add_form',$ingredient);
 }

```

The following one works;

```
function ingredient_add() {
  $ingredient = (object) array('iid' => '','name' => '',);
  return drupal_get_form('ingredient_add_form',$ingredient);
}

```

The class code is the following one:

```
class IngredientController extends DrupalDefaultEntityController {

    public function create() {
      return (object) array(
        'iid' => '',
        'name' => '',
      );
    }
}

function nutrition_entity_info() {
  $return['ingredient'] = array (
    'label' => t('Ingredient'),
    'controller class' => 'IngredientController',
    'base table' => 'ingredient',
    'uri callback' => 'ingredient_uri',
    'fieldable' => TRUE,
    'entity keys' => array (
      'id' => 'iid',
      'label' => 'name',
    ),
    'static cache' => TRUE,
    'view modes' => array (
      'full' => array (
        'label' => t('Full content'),
        'custom settings' => FALSE,
      ),
      'teaser' => array(
        'label' => t('Teaser'),
        'custom settings' => FALSE,
      ),
    ),
  );

  return $return;
}

```

Do you have any idea?

Should the implementation of `hook_entity_info()` be `nutrition_entity_info()` or `ingredient_entity_info()`?

Nutrition is the module name, ingredient the entity I am creating.

---

There was some kind of typo on the code, as it seems to work now.

# Answer
I suspect that you haven't implemented `hook_entity_info()`, which is why `entity_get_controller()` returns nothing, and you can't call a method of nothing.

The Examples project has an issue in the queue for an entity example. Give it a read. :-)

Hooks have the module name, so if the module is called nutrition, you'd declare nutrition\_entity\_info().
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Hide or show fields based on whether the node is published
I'm looking to show and hide form fields based on the current progress of a node using contributed modules like Workflow, Maestro or rules.

For example, I would like to show certain fields if a post is published and hide those same fields if it is in draft. I would like to avoid writing a custom module if possible.

Is there a simple way to interact with the Drupal 7 FormAPI to show and hide fields based on the status of a node using Rules, Workflow, Maestro or other contributed modules?

Also, is there an easy way to modify 'select lists' produced with the FormAPI using any of the noted plugins?

# Answer
> 2 votes
You might be able to piece something together using Conditional Fields, but a custom module (using hook\_form\_alter()) would definitely be the recommended path here, because it sounds relatively custom.

Conditional fields are simply hidden using JS, while it sounds like you might need to make it so people can't access the fields (so, #access property = FALSE) on the edit form in certain situations.

Rules doesn't have much integration with content editing forms; but you could probably set some field to a different value if the status of a node is changed from draft to published, or something like that, which could trigger something with Conditional Fields... but I think doing it in a custom module would be better in this case, and would definitely be more robust.

# Answer
> 2 votes
+1 for a new module, but `hook_node_view_alter()` makes more sense.

In fact I thought I'd try it out. This will hide a field called `field_hide_me` if the node is published:

```
/**
 * Implements hook_node_view_alter().
 *
 * If the node is published then we hide a field
 * called 'field_hide_me'.
 */
function if_published_node_view_alter(&$build) {
  // only for full view mode
  if ($build['#view_mode'] == 'full') {
    // check whether our field exists
    if (isset($build['field_hide_me'])) {
      // grab the node
      $node = $build['#node'];
      // status is 1 for published, 0 unpublished
      if ($node->status) {
        unset($build['field_hide_me']);
      }
    }
  }
}

```

Sandbox here: http://drupal.org/sandbox/Mile23/1415030

# Answer
> 0 votes
I don't know about aGUI only solution. You can of course implement hook\_field\_access. It allows to implement fine grained access control for fields.

---
Tags: forms, rules, workflows
---


title: Drupal Commerce Line Items

text:
# Question
Title: Drupal Commerce Line Items
I want use drupal commerce's line items in the following case.

1. I have 3 Products. (Product A, Product B, Product C).
2. I want to add line items to these 3 different products. So Product A will have the following structure. Product A -\> Line Item A-1, Line Item A-2 Product B will have the structure as , Product B -\> Line Item B-1, Line Item B-2

Now, This is okay with me. But if I want to add line items to the first level of line items. How can it be possible ?

The case is, If I want to add 2 Line items to Line Item A-1. So the Product A will have a final structure as,

```
                              Product A
                      ___________|____________
                     |                       |
                Line Item A-1           Line Item A-2
          ___________|____________
         |                       |
     Child Line Item A-1(i)   Child Line Item A-1(ii)

```

I hope I am able to tell you my problem. Please help me on this.

# Answer
Judging from your question you seem very confused about line items and what they are used for.

Line items are used to link products to an order. The whole idea is that some data you want to fetch from the product directly, like it's title, media etc, while some data you need to copy, like the price and sometimes you need to add data, like the address for a subscription and quantity.

The reason you need to copy the price, is that if you ever change the price of the product you want to preserve the old orders which is why you need to store the price for each purchase.

There is nothing technical that will hinder you to create a relationship from products to line items or from line items to line items, but it won't make much sense to do so, and will most likely result in some strange bugs, as line items are used for orders to store info about products, and commerce expects this.
> 4 votes

---
Tags: commerce
---


title: Add tabs to a view-page

text:
# Question
Title: Add tabs to a view-page
What I want to achieve is rather simple but either I haven't drank enough coffee yet or Google is boycotting the wanted results :)

I have a view ("the view"), of type "page" , formatted and styled exactly the way I want it; all is good.

Using the Weight module I have created another view ("the sorter"), also a page, with which to sort "the view".

What I'd like to do is to add 2 tabs, above both views, one leading the "the view's" url and one leading to "the sorter's" url, for easy back and forth transitions from the sorting mechanism to the front-end.

Thanks in advance!

EDIT: Of course I want only the administrators to see those tabs.

# Answer
1. For "the view" you should add a menu style default menu tab with View URL: `example.com/view/the-view` and a parent menu item with URL: `example.com/view`.
2. For "the sorter" you should add a menu tab menu item and have the View URL be `example.com/view/the-sorter`.

This is easier to do than to explain. You might need to fiddling around to get it, but this is the gist of it.
> 3 votes

---
Tags: views
---


title: Running check_plain after t

text:
# Question
Title: Running check_plain after t
Will this be correct :

```
drupal_set_title(check_plain(t("Donation Details for Project: $project->title")))

```

I want all of the string to be translated when needed. Should call check\_plain first then t or vice versa?

# Answer
> 0 votes
Call t() first. t() should be applied to literal strings, not to variables and not to results of function calls. From the manual of t():

> Because () is designed for handling code-based strings, in almost all cases, the actual string and not a variable must be passed through ().
>
> Extraction of translations is done based on the strings contained in () calls. If a variable is passed through (), the content of the variable cannot be extracted from the file for translation.

# Answer
> 4 votes
This would be better:

> drupal\_set\_title(t("Donation Details for Project: @title"), array('@title' =\> $project-\>title));

Taken from here

> Special variables called "placeholders" are used to signal dynamic information in a string which should not be translated. Placeholders can also be used for text that may change from time to time (such as link paths) to be changed without requiring updates to translations.
>
> @variable, which indicates that the text should be run through check\_plain, to escape HTML characters. Use this for any output that's displayed within a Drupal page.

# Answer
> 0 votes
Better call check\_plain first it will escape the html tags.Then you convert them into whatever the language you want.

---
Tags: 6, forms
---


# Question
Title: How to define multiple file downloads for a single library in drush make
I am trying to create a make file for the closedquestion module following the instructions in the readme file.

I know the below configuration snippet doesn't work - due to the fact that I am overwriten the first declared download with the second.

```
; Closedquestion libraries

; * Put jquery.json in sites/all/libraries/jquery-json
;   get it from: http://code.google.com/p/jquery-json/
;   This should result in one of the files (you might have to rename it):
;   - sites/all/libraries/jquery-json/jquery.json.js
;   - sites/all/libraries/jquery-json/jquery.json.min.js

libraries[jquery-json][download][type] = "file"
libraries[jquery-json][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.js"
libraries[jquery-json][download][sha1] = "2bf6472f96791d6f8a5a405fe6eabe87babf8931"

libraries[jquery-json][download][type] = "file"
libraries[jquery-json][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"

```

I also tried renaming the second to jquery-json-min & defining a directory\_name, but that just throws an error that the folder already exists as would be expected.

```
libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][directory_name] = "jquery-json"

```

Any input on how this could be solved would be much appreciated.

# Answer
> 1 votes
You are close, you should use destination instead:

```
libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][destination] = "libraries/jquery-json"

```

---
Tags: drush
---


# Question
Title: user_authenticate() function not working
I'm working with Drupal 7, the function `**user_authenticate()**` working fine with the default User module, but I have implemented a custom "user login" module, and I use this same function in that module, but somehow it is not working at all in this new module.

When we are using this function in default module, it's retrieving all the records based on the user parameters, but in my case it's retrieving nothing.

This is the code that I have put in my custom module file.

```
if (module_exists('user')) {
     $username = $form_state['values']['name'];
     $pass = trim($form_state['values']['pass']);
     $userRecord = user_authenticate($username, $pass);

     print_r($userRecord); // its resulting me BLANK!!
     exit;

   }

```

Can anybody help me out please? What would the problem be?

# Answer
`user_authenticate($name, $pass)` (Drupal 7) will return the user ID on successful authentication, or `FALSE` on failure. In Drupal 6, it will return the user info array.
> 2 votes

---
Tags: 7, users
---