# Question
Title: drupal_set_title not changing the navigation bar title
I have changed the title of a path with the drupal\_set\_title() function from hook\_page\_alter from a custom module. It works but the title in the navigation bar is still the previous one.

How can I change it too?

# Answer
Sounds like you're setting the title too late in the theme building process for this to work, possibly using at the node layer which only affects the node title not the page title. What you want to make sure to do is use a preprocess\_page function to set the title so this is in the header as well:

```
function mytheme_preprocess_page(&$vars){
    if (isset($vars['node'])) {
        drupal_set_title('YOUR TITLE');
    }
}

```

Alternatively, you can install the Page Title which gives you granular control over all of your page titles and is often recommended for SEO.
> 1 votes

---
Tags: 7
---


# Question
Title: Add custom tag in RSS XML header Drupal 7
I'm using Views to generate a custom RSS feed. I need to add an extra tag in the header. I tried different setting in Header section of the Feed Display, but nothing gets displayed in the feed.

Could anyone explain what's the best way to do it

# Answer
> 0 votes
Maybe it's because I don't know the views module well enough but I could not get views to do this at all. Instead I created a simple module that outputs an RSS feed. Use:

```
header("Content-type: text/xml");
print '<rss version="2.0">';

```

to have PHP output the correct headers.

---

EDIT: not sure it makes sense to just post the code but I can describe it:

1) The code below creates the page where your XML feed will live (should be in \*.module file):

```
function xml_sender_menu() {
   $items['feed'] = array(
     'title' => 'RSS Feed',
     'page callback' => 'rss_feed',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );

     return $items;
}

```

2) Then in the same file create a function called "rss\_feed()" (this name should be the same as the `'page callback' => 'rss_feed',` in the above array) which will contain the code that produces the actual website. The function doesn't need to return anything.

3) http://cyber.law.harvard.edu/rss/rss.html contains a good readable description of the RSS specification, use Drupal API/PHP to output the data you want into the correct fields. For example I used the node's title to fill in the `<title>` field in RSS by doing this:

```
$sourcetitle = htmlspecialchars($node->title);
    print '<title>'.$sourcetitle.'</title>';

```

4) At the end output all the closing tags `</channel> & </rss>`

I don't know what data you are trying to fill your RSS feed with, so can't really be any more specific. Finally, copy/paste the output into an RSS validator to make sure you are not missing anything.

\** Something I just realized: if you are adding other fields that aren't in the RSS specification, it's no longer an RSS feed. Instead you are just getting a plain old custom XML feed, don't know if that makes a difference to you.

HTH

---
Tags: views, feeds
---


# Question
Title: How to get node's title and send list of it to mail
I am about to send an email to website admin.

First of all, there will be a function to get list of node's title that city field equal to 'barcelona'.

After that, the list will be send to website admin once every day using e-mail.

Any idea on how to do this with Rules or custom module?

# Answer
> 0 votes
You need to create custom module and implement hook\_cron().

See:

https://drupal.org/developing/modules

Also check this post: How to create a task which run at cron time and send emails to users?

```
function get_node_titles() {
    $result = db_query('SELECT n.title FROM {node} n');

    $titles = array();
    foreach($result as $item) {
        $titles[]  = $item->title;
    }

    return $titles;
}

```

---
Tags: 7, rules, emails
---


title: Sorting by taxonomy sub-term weight

text:
# Question
Title: Sorting by taxonomy sub-term weight
I've got troubles with a views sorting. I'm attempting to order the views output by a term's weight. The problem is that each taxonomy sub-term starts with weight 0, no matter what. Is there a way to get around that, so that the sub-terms are displayed correctly?

# Answer
You can use `hook_views_query_alter(&$view, &$query)` here you can pass extra sorting more sorting fields

http://www.chrisfree.me/2010/12/use-hookviewsqueryalter-handle-special-sort-cases
please check this link
> 0 votes

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


# Question
Title: Workbench sections - notify users in a section on state change
I want to, for example, use rules to notify all users in a particular section that an item of content in their section is 'awaiting moderation'. Is there a way in Rules to get access to a node's Workbench section?

I can get access to the workbench access term id/menu id, depending on the scheme I'm using, but how can you find the users in that section from there...

# Answer
> 1 votes
If you use workbench access with a taxonomy scheme you could try this

In rules, add an event After moderation transition. Add the conditions (previous state moderation, current state moderation) according to yours states in workbench moderation Add the condition Entity has field and then select the field of your workbench access section (field\_section for example : should be the field of your taxonomy vocabulary)

Add an action : send an email.

Then in the field TO of the email , you could use this snippet php wich return the user's email wich have access to the section (specified in Editorial assignments by editor in Workbench Access) and have a specific role id. This snippet return too all the users who have been assigned by their role to the section by their role (Editorial assignments by role in Workbench Access)

```
<?php

$sections = $node->workbench_access;

$terms=taxonomy_term_load_multiple($sections);

foreach ($terms as $term) {

$parents=taxonomy_get_parents_all($term->tid);

  if (!empty($parents)) {

    foreach ($parents as $parent) {

    $tid=$parent->tid;

    $voc_name=$parent->vocabulary_machine_name;
      if (!in_array($tid, $sections)) {
        $sections[$tid]=$tid;
      }
    }

  $sections[$voc_name]="'".$voc_name."'";
  }
};

// Only the users who have the role id [ROLE_ID]
$role_id=[ROLE_ID];
$emails = array();

foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_user workbench, users_roles roles WHERE roles.rid=$role_id AND user.uid=roles.uid AND user.uid=workbench.uid AND access_id=$section");

  foreach($result as $record) {
    $mail=$record->mail;
    if (!in_array($mail,$emails)) { $emails[] = $mail; }
  }
}

foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_role workbench, users_roles roles WHERE user.uid=roles.uid AND roles.rid=workbench.rid AND access_id=$section");

  foreach($result as $record) {
    $mail=$record->mail;
    if (!in_array($mail,$emails)) { $emails[] = $mail; }
  }
}

print implode($emails, ",");

?>

```

And you complete the others email's field with the token available.

This sandbox project Workbench Notify implement this snippet

# Answer
> 0 votes
The query would be improved with joins. My version:

```
SELECT u.mail AS mail
FROM users u
INNER JOIN workbench_access_user w
ON w.uid  = u.uid
INNER JOIN users_roles ur
ON ur.uid = u.uid
WHERE ur.rid = $role_id
AND access_id = $section;

```

---
Tags: rules, workflows, workbench
---


# Question
Title: is there any option in drupal to create a node for a particular user?
I am going to create a medical lab examination system.In which i would have to display lab results to users individually.i will implement it by creating individual node for different different users, is there any option in drupal to create a node for a particular user ?

# Answer
> 1 votes
The easiest way I see to do this is by following these steps:

1. Install References module.
2. Enable User reference module under admin \> modules
3. Create a content type (say "lab result"), and add a field of type user reference.
4. Now, every time you create a "lab result" you could associate it with an user.
5. For listing the "lab result" of a particular user you could use the Views module.

---
Tags: 7
---


# Question
Title: Show node body fields for entity reference checkboxes widget?
I need to show the body field of the nodes next to their checkboxes in an entity reference field widget (default is just their node titles). Is there a way to do that without writing a new widget?

# Answer
You may want to try Entity Reference View Widget.

> This module provides an advanced Entity Reference widget that uses a view for selecting items. The view can be paginated and have exposed filters. It degrades, so it can be used even if Javascript is disabled
> 0 votes

---
Tags: 7, entities
---


title: drupal webform Confirmation Message

text:
# Question
Title: drupal webform Confirmation Message
I have got a webform in a iframe and its quite long when a customer fills the details and clicks submit they just see a white screen because the page has been scrolled down due to the form been very long and they have to scroll back up to see the confirmation message.is there anyway when they click submit the scroll resets?

# Answer
> 1 votes
> you can use this js code

```
 $('.page-node-webform #edit-actions #edit-save').click(function() {

                return confirm('Are you sure?');

            });

```

---
Tags: webforms
---


# Question
Title: How to add the Interest field in profile page which links the user with similar interest?
I have seen this type of field in drupal.org where some fields appeared as links which lists the users with similar interests or country. Don't know how to do that in Drupal7.

# Answer
This is done using taxonomy and the term reference field. Each term assigned to an entity has the option in the display mode to be a link to the term page, which in turn shows all entities tagged with that term.

Edit-

Since default term pages only look for content entities you will have to create a view to override those term pages to show user entities instead. You can use the taxonomy views integrator module to selectively choose which terms use which view. https://drupal.org/project/tvi
> 0 votes

---
Tags: users
---


# Question
Title: Is this normal to have Drupal Commerce stuck in PENDING status after a completed paypal payment?
I'm testing out drupal commance and setup a paypal sandbox seller/buyer account. When I complete a payment with the test accounts, the status of the order says "PENDING" is this what its suppose to do after a successful payment?

I would imagine it would say PAID. I see there are other order status options such as checkout complete. Shouldn't it say that instead of Pending?

# Answer
I believe these are exports of the rules that Ryan proposed. The weight is 1 to evaluate after existing rules.

Rule #1

```
{ "rules_update_the_order_status_on_checkout_completion_if_payment_" : {
    "LABEL" : "Update the order status on checkout completion (if payment complete)",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "1",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "commerce_payment", "commerce_order", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "IF" : [
      { "commerce_payment_order_balance_comparison" : { "commerce_order" : [ "commerce_order" ], "value" : "0" } }
    ],
    "DO" : [
      { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "processing" } }
    ]
  }
}

```

Rule #2

```
{ "rules_order_paid_in_full_order_state_to_processing" : {
    "LABEL" : "Order paid in full: Order state to processing",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "1",
    "REQUIRES" : [ "commerce_cart", "commerce_order", "commerce_payment" ],
    "ON" : [ "commerce_payment_order_paid_in_full" ],
    "IF" : [
      { "NOT commerce_order_is_cart" : { "commerce_order" : [ "commerce_order" ] } }
    ],
    "DO" : [
      { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "processing" } }
    ]
  }
}

```
> 5 votes

# Answer
Orders aren't being "stuck" here so much as placed here for you to determine what to do with them. When you build a Drupal Commerce site, you should consider what needs to happen to an order after the checkout process has been completed / payment has been received and either implement a manual process or some form of Rules or code based automation to do it. Drupal Commerce leaves it here because we don't make any assumptions about the type of product a Commerce site sells or the business processes involved in taking an order from checkout completion to final fulfillment.

PayPal WPS and related payment gateways are a bit of a special case, too, in that you actually cannot use the "When an order is first paid in full" event to manipulate the order status. Because these orders may not have completed the checkout process when their payment notifications arrive at the site, the checkout router still depends on these orders being in a checkout order status to complete the checkout process after the payment has been processed.

Instead, if you need to update the order status based on payment receipt for PayPal WPS, you should use the "Order balance comparison" condition in conjunction with the "Completing the checkout process" event to update the order status on that event instead if payment has been received. Additionally you can use a "Data comparison" condition to check the order status on the "When an order is first paid in full" event and update the order status if the order is not still in a checkout order status.
> 8 votes

# Answer
Actually this is normal for Drupal Commerce out of the box. When an order is fully paid, say with Paypal. The user get's redirected back to the /checkout/#/complete *(# is for order #)*
> 1 votes

---
Tags: 7, commerce, payment-gateways
---


title: OpenLayers default zoom level

text:
# Question
Title: OpenLayers default zoom level
I have a map setup with Openlayers and mapbox. I need to set the default zoom level to be in-between 1 and 2. So something like 1.5, as 2 is too zoomed in and 1 is too zoomed out.

I have entered different values under 'zoom level' within 'center & bounds', but only whole numbers seems to have an effect on the map.

Does anyone know of a way to set a default zoom level that is not a whole number? So something like 1.5 ?

I am using Drupal 7.

Thanks you help is much appreciated.

# Answer
I'm not sure you can do that, I think the Zoom level has to be an INT. Basically there is as many tiles'size as the number of zoom available. That means there is no tiles available for a float value, otherwise it will require too many tiles to have a map not fuzzy.
> 0 votes

---
Tags: javascript
---


# Question
Title: Why can't I comment on a module' project page on drupal.org?
I can't comment on the project page https://drupal.org/project/awssdk

Why is it so?

The module seems to work with long out-dated AWS SDK for PHP 1.6.2 so I just want to make a comment there to suggest the contributors to update the module and the documentation.

# Answer
> 2 votes
On Drupal.org, you cannot comment on any project page, as the comments are disabled for every node of the *project* content type.

These are the comment settings for that project page. (I am a Drupal.org webmaster; what I see when editing a node edit page is not what normal users see.)

If you see any project page with the comments enabled, please report it on the Drupal.org webmasters queue, and it will be fixed.

# Answer
> 3 votes
The project page of the module you've mentioned or any other module/theme/distribution is meant only have a brief description, and releases of that particular project.

If you need to contact any of the maintainer of the project, you should use the *issue queue* of the project which could be found at : `https://drupal.org/project/issues/{project_name}` just replace `{project_name}` with the project name, in your case *awssdk*.

Detailed reading here : Use the issue queue.

And if you feel that the project is not being updated / supported for quite some time and the bugs aren't being fixed, and you intend to fix them you have an option to take over the maintainership of the project.

More reading here : Dealing with unsupported (abandoned) projects.

---
Tags: community-official-site
---


# Question
Title: How to upload video to Drupal using Video module?
I've successfully installed the Video module and now there is no errors.

It's not clear to on Drupal website how I can start uploading videos though.

Can anyone please shed some light on this?

# Answer
To start uploading a video you have to create a new content type, and add a new field and use a field type of video. You can also choose a widget type of video upload.

Upon adding the field, on the next step you can add the extensions of the kind of video files you will like to upload
> 1 votes

---
Tags: files
---


# Question
Title: Is the video processing of the ffmpeg transcoder done locally on my server?
When configuring the Video module, I'm posed to choose either *ffmpeg* or *Zencoder* transcoder.

While it's clear that *Zencoder* leverages video transcoding cloud services by Zencoder.com, I wonder if the *ffmpeg* option here means video processing is done locally on my server?

In other words, does *ffmpeg* option use the computing power of my own server and therefore it's completely free?

# Answer
FFmpeg is licensed under GNU Lesser General Public License (LGPL) version 2.1 or GNU General Public License (GPL) version 2, depending on compiling options. Both are free and open source.

As far as I see in the code (just glanced over it, mind), both Video Presets and FFmpeg Converter uses locally installed converter. Will it be free? Probably not. Looking on FFmpeg Converter page:

> **Note:** This module is not for beginners, since FFmpeg requires rather complicated server configuration.

Sysadmin's time usually isn't free, CPU power also is not. But you should be free from licence fees all right.
> 2 votes

---
Tags: files
---


# Question
Title: Modifying the Account settings Fields/ Registration form in Drupal 7
I would like to add some markup so to explain a question section before going into the questions... How can I do this?

One of the questions is a Dropdown list, and one of the options is "Other, please specify). How would I go about adding the Other field so that it is a part of the same question? I was thinking a fieldset, but there doesn't seem to be that option?

I would like to add a label that is 200 characters long (including spaces), but at the moment it is being cut off.

# Answer
Though I have never done this but I am pretty sure you can do it by form\_alter(). You will have to add field as per your requirement and add description to the field by this hook.

Description can be based on selected value of the option list also. A simple example for this hook for user register is here --

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){ //Replace your module name by MYMODULE.
  if($form['#id'] == 'user-register-form'){
    $form['account']['mail']['#description'] = t(''); //Removing description from email field.
    $form['account']['pass']['#description'] = t(''); //Removing description from password field.
  }
}

```

Play around & I hope you will find solution.
> 0 votes

---
Tags: theming
---


# Question
Title: Domain access issue w.r.t viewing a content other than admin user
I am using domain access module with sub domains and content creation.

I am able to create content but I am not able to view content which was created by the user, it says `You are not authorized to access` this page where as admin I am able to create and view content.

In my another local site I tried domain access module and for other roles I am able to crate and view and edit the content. I don't have any issues. Same settings only I have for my another site.

But still it throws me this error `You are not authorized to access this page` after creating a content and in view section it shows this error.

Is any other module causing this issue?

# Answer
My answer is based on experience with D6 version of the module but I believe the core is still relevant. As the site administrator (user id 1) you can view all site content unless you disable that option in the domain settings page (Administer \>\> Site Building \>\> Domain \>\> Domain Settings \>\> Domain module behaviors fieldset \>\> **Enforce rules on administrators:**).

With relation to content viewing for other users, it is the default behavior to return HTTP 403 (Not authorized) when a content created specific to one domain without being shared to all affiliates is viewed from a different domain. The option to publish node to one or few of the sites is available in the node creation or edit form.

If you wish to change the default behavior of specific node types, the option to either allow specific node types to be published to all affiliates can be found in Node settings under Domain. When nodes are saved that way domain access table has an entry for such nodes with affiliated domains as `domain_site`.
> 0 votes

---
Tags: 7, domain-access
---


# Question
Title: Is there a module for adding field types for latitude, longitude, compas coordinates, etc?
Either my google searching skills are low, or there is no such module for D7. I want to create a content type where a user can add his position on the sea: latitude, longitude, knots, heading (000°) and other coordinates. Do you know any module that does this?

# Answer
The Geofield module allows you to store such data:

> Latitude and Longitude Supports entering data as both Decimal Degrees (122.340932) and Degrees-Minutes-Seconds (-123° 49' 55.2" W). The Degrees-Minutes-Seconds input is very tolerant of inconsistent input.
>
> Bouding Box Four textfields where lat / lon can be entered
>
> Well Known Text (WKT) A textarea for direct WKT input
>
> Draw on an OpenLayers Map Allows drawing of Points, Lines, Polygons and Bouding Boxes
>
> HTML5 Geolocation Transparently asks the browser for the user's current location. Works great on Chrome and smartphones with GPS.

You can encode data from another field using the Geocoder module as well.
> 2 votes

# Answer
You could use the Gmap module along with location module.

For more details you could go through the README.txt of these modules.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: how to make background of Drupal blocks transparent
I just successfully added a background paper texture to my drupal site using the BackgroundImages module. https://drupal.org/project/bg\_image One remaining issue I have is that the blocks themselves on my pages still have a solid white background. Can someone direct me on how to change the background of my drupal blocks to transparent?

# Answer
To change background color use `background-color: transparent`

Also for example you can use

```
.block {
 background: none transparent;
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: 500 internal server error on a single node
This just happend randomly today. I tried to access a page, but it keeps giving me a 500 internal server error http://www.austravel.com/holiday-destinations/australia

All the other pages are working fine. Any ideas why this may be?

# Answer
Sorry for not posting this sooner.

Just to answer @AgA yes there is a **error\_log file, I checked it and found the problem.**

For anyone wondering, it was just a large image file that was breaking the page. I deleted it from the page and it worked fine.
> -1 votes

# Answer
Display PHP errors for that page or examine your Apache log file with errors enabled. Nobody can tell you what's misconfigured, or whatever typo you've made in your PHP ... log files can tell you though.

**EDIT:**

For further explanation on "errors" and specifically 500 error from Apache see: https://stackoverflow.com/questions/8564259/php-5-3-troubleshooting-500-errors-debugging-parse-errors

> PHP will respond with a "500" when it encounters a Fatal error, such as E\_PARSE, E\_ERROR and uncaught exceptions. 500 is the HTTP response code for "Internal Server Error" - something unrecoverable happened while processing the request.
>
> In your php.ini, on a development machine, you should set your error\_reporting level to (at least) E\_NOTICE - preferably E\_ALL - and make sure display\_errors is on. This will show you the error message in the browser, including for "500" errors.
>
> You can also check your Apache error logs, the errors will be listed there, as long as log\_errors is enabled in php.ini. By default, this will be at \logs\error.log.
>
> You can also control all this at run time with ini\_set() and error\_reporting()
> 0 votes

---
Tags: nodes, http-request
---


# Question
Title: How to get work Internationalization module with l function?
I am using Internationalization module to translate content. How to get work this module with l function?

for example, when I create programatically link to content:

```
l(t('About us'), 'node/22');

```

I would like to achieve, that path 'node/22' will change when I switch website to another language. With Internationalization module, each translation of node creates another node, so I need to change paths in links on website.

For this time, I can create just if-else condition:

```
<?php
if ($language->language == 'en')
$output = l(t('About us'), 'node/22');
elseif (($language->language == 'de')
$output = l(t('About us'), 'node/23');
?>

```

IS it possible to use l function in that way, that I don't need to write else-if condition?

# Answer
There's no easy way to do this, but you can do something like this:

```
$nid = 22;
$node = node_load($nid);
if ($node) {
  $translations = translation_node_get_translations($node->tnid);
  $nid = isset($translations[$language->language]) ? $translations[$language->language]->nid : $nid;
}

```

Or use the Entity translation module, which relies on the ability of fields to have values in multiple languages and then the node id doesn't change.
> 2 votes

# Answer
I would try:

```
l(t('About us'), t('node/22'));

```

and translate node/22 to node/23, but this maybe wrong it's just an idea.
> 0 votes

---
Tags: navigation, i18n-l10n
---


# Question
Title: Can't attach #ajax to altered form displayed in block
I have a module that displays an existing signup form in a block.

```
function my_contact_block_view($delta = '') {
    switch ($delta) {

        // Newsletter signup block
        case 'newsletter_signup':
            $block = my_contact_get_emma_block();
            break;
    }
    return $block;
}

```

I make some minor alterations to the form. Some markup elements are removed from the form (this works), and I am attaching an `#ajax` property to the submit element (this doesn't seem to work):

```
function my_contact_get_emma_block(){
    $form = drupal_get_form('my_contact_emma_form');

    // get wrapping markup
    $header = variable_get('my_contact_emma_block_header', '');
    $footer = variable_get('my_contact_emma_block_footer', '');

    // unset some stuff
    unset($form['heading']);
    unset($form['copy']);
    unset($form['required_blurb']);
    unset($form['privacy_blurb']);

    // alter some stuff
    $form['fname']['#attributes']['placeholder'] = t('First');
    $form['lname']['#attributes']['placeholder'] = t('Last');
    $form['email']['#attributes']['placeholder'] = t('Email');

    // config to submit via ajax
    $form['submit']['#ajax'] = array(
    'callback' => 'my_contact_emma_form_ajax_submit',
    'wrapper' => 'brd-contact-emma-form',
    'method' => 'replace',
    'effect' => 'fade',
    );

    // render the form
    $form = drupal_render($form);
    $markup = $header . $form . $footer;

    // return renderable array for block
    return array(
        'subject' => t('Event Email Sign-Up?'),
        'content' => array(
            '#type' => 'markup',
            '#markup' => $markup,
        ),
    );
}

```

Unfortunately, it never hits my ajax submit function. Instead the page submits to the normal submit routine (`my_contact_emma_form_submit`).

```
/**
 * Ajax callback function. (Never called)
 */
function my_contact_emma_form_ajax_submit($form, $form_state) {
  // Dummy/dumb validation for demo purpose.
  if (!empty($form_state['input']['email'])) {
    return 'Subscribed !';
  }
  else {
    return $form;
  }
}

```

What am I doing wrong?

# Answer
> 1 votes
The real problem here is that my whole approach was wrong. I should not have been trying to bend the same form to serve multiple purposes.

If all I needed to do was minor alterations the display of the form (which were working above), I probably could have gotten away with it. But when I tried to do things like change the submission method things got sticky. And when I realized that I wanted to show the user a different result for ajax submissions (a simple 'Ok!' instead of a whole confirmation page), things really broke down.

What prevented me from doing what I want is that there is no way to detect the difference between Form A submitted from a block and Form A submitted from a page. Because I couldn't differentiate between them, I could not use `hook_form_alter` (or similar) to create 2 different use cases.

Ultimately, the solution was to basically duplicate the first form, make all the alterations in my original post in that form, and handle the ajax there as well.

# Answer
> 1 votes
drupal\_get\_form will return a builded form/ rendered form. i.e Your form has been already prepared based on the specification done in the form callback, like its finalized.

So making changes to the return values of drupal\_get\_form wont work.

If you want to alter any of the form then you should use any of the following hook

# Answer
> 1 votes
Try using `button` instead of `submit`.

```
$form['submit']['#type'] = 'button';

```

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


# Question
Title: Export set variables from site to include in install profile
Is there a module, separate from Features, that can export currently set variables (as you can see if you run drush vget) - in the correct format so that I can copy and paste into the install profile. - e.g. as `variable_set('admin_theme', 'minimal');` for example.

# Answer
> 5 votes
Here's two functions, a menu callback with a simple function to query and export all defined variables.

No required module dependencies, just Drupal core.

```
/**
 * Implements hook_menu
 */
function MODULE_menu() {
  $items['export/variables'] = array(
    'title' => 'Export variables',
    'page callback' => 'MODULE_export_variables',
    'access arguments' => array('administer site configuration'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Menu callback to export variables
 */
function MODULE_export_variables(){

  // Fetch and export variables from the database.
  $query = db_select('variable');
  $query->fields('variable');
  $query->orderBy('name');
  $result = $query->execute();

  $output = array();
  $output[] = '<pre>';
  foreach($result as $row){
    $output[] = 'variable_set("'.$row->name.'", '.var_export(unserialize($row->value), 1).');';
  }
  $output[] = '</pre>';

  print implode(PHP_EOL, $output);

  drupal_exit();

}

```

Visit `http://yoursite.com/export/variables` to get the raw output for copy/paste into the install profile.

# Answer
> 7 votes
A year or so ago I was working on a Drush command to export a working site as an installation profile. I haven't worked on it for a while, but it was my intention to use something like the Configuration Management module, or perhaps Drush CTools Export Bonus to include site configuration information with the installation profile.

If you are hand-generating your installation profile, typically you do write variable\_set commands and put them directly into your installation profile. When generating configuration information, though, I think it is typically the case that the config information is bundled in some other module.

**Answering first question**

By convention, variables in the variables table are named after the module that defined them, so if everyone is cooperating, you know where the variables are coming from. Install a fresh copy of Drupal, and make note of the variables that it defines, and their default values. Compare these against the values in your site to find the ones you have changed. Do the same thing for contrib modules, installing each module in your scratch site, and checking the default values. Another option is to use Strongarm, which will show you the variables that changed (when they change), just like other features modules do.

The catch here, though, is that not all configuration is stored in the variables table. Some modules define their own tables. If you want to hand-code your configuration, you need to investigate the APIs for each module you use in turn, and figure out how to make settings programatically. This is a difficult thing to do, which is why most people use features, or the configuration management module, or Ctools export bonus. Even these modules are not always enough, as not everything supports exportables. It's a good thing that the CM initiative in D8 is addressing this problem.

# Answer
> 1 votes
Looks like you need Configuration Management module:

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.
>
> For the most part this module provides the same functionality as a subset of the features module.

So, if for some reasons Features are not the way for you, this one might be a good replacement.

---
Tags: 7, importing-exporting, installation
---


# Question
Title: Creating fielded entities in a module: how to ensure unique field names?
I created some entities with the Entity Construction Kit, exported them with Features and proceeded to build a module upon that.

I had been pretty much ignoring field names, then realised I'd used really generic names for my fielded entities. Oops.

What's the best way to ensure names are not going to crash into the namespace of something else \[in future\]?

Is it `module_name_entity_name_field_fieldname`?

And if so, is there any problem with really long field names (and presumably, therefore even longer column names in the tables)? Is there a limit?

**EDIT:** yes, there seems to be a 32 character limit for field names. So **how can you be sure of a unique field name**?

# Answer
> 1 votes
The only way to be sure you have a unique field name is to test on creation whether the same field already exists.

As you have realised, this is a problem when deploying your fields as a feature, as you do not know what environment your fields will be deployed in. Unfortunately Features does not provide you with a way to rename the fields when a feature is first enabled.

This is something you could implement yourself ; it should be possible to do this in a way that doesn't stop you from automatically re-creating the feature. Here is an idea about how this could be done:

(1) Name all your fields `prefix_fieldname` (I will assume you used 'mymodpref' for the prefix) and ensure they are no more than (say) 30 characters ;

(2) In your module's .install file, implement `hook_install` such that you find a safe field prefix that will make your fields unique. For instance:

```
function mymodule_install() {
  $prefix = 'mymodpref';
  $prefix_index = $prefix;
  $index = 1;
  $found_unique = FALSE:
  while (!$found_unique) {
    $c = db_query("
      SELECT COUNT(*)
        FROM {field_config}
       WHERE field_name LIKE :prefix",
    array(':prefix' => $prefix . '_%')
    )->fetchField();
    if ($c > 0) {
      $prefix_index = $prefix . $index;
      $index++;
    } else {
      $found_unique = TRUE;
    }
  }
  if (strlen($index) > 2) {
    // Our fields are up to 30 characters, so we can't have an index
    // of more than 2 characters. If this happens we're in trouble -
    // add some code here to tell the user we can't install the module.
  } else {
    variable_set('mymodule_field_prefix', $prefix_index);
  }
}

```

(3) In you feature's main module file, add an implementation of `hook_field_default_fields_alter` which allows you to change the default field definitions, and rename them with the right prefix :

```
function mymodule_field_default_fields_alter(&$fields) {
  $prefix = variable_get('mymodule_field_prefix', 'mymodpref_');
  $new_fields = array();
  foreach ($fields as $key => $field_info) {
    // Replace 'myentity' and 'mybundle' accordingly
    if (strpos($key, 'myentity-mybundle-') === 0) {
      $new_field_name = $prefix . '_' . $fied_info['field_config']['field_name'];
      $field_info['field_config']['field_name'] = $new_field_name;
      $field_info['field_instance']['field_name'] = $new_field_name;
      unset($fields[$key]);
      $new_fields['myentity-mybundle-' . $new_field_name] = $field_info;
    }
  }
  $fields = array_merge($fields, $new_fields);
}

```

---
Tags: entities
---


# Question
Title: Which hooks can I use in profile development?
Which hooks are available in profile distribution development? Which other hooks can I use except `hook_install_tasks()`?

# Answer
> 2 votes
I can't find a documented list anywhere, but a quick look at the code suggests these are the available hooks:

---
Tags: 7, hooks, distributions
---


# Question
Title: How do I let users with a certain role add nodes but use the front end theme (not the admin theme)
I have a role that allows users to create nodes themselves. What is the standard practice way to let them add nodes but not see the administration theme (I am using adminimal), and rather use a different theme on the node/add page.

# Answer
> 2 votes
Role Theme Switcher seems to be what you need:

> Useful Drupal module to assign separate themes for different roles (including anonymous) in your system.
>
> Often you want to separate Drupal administrative interface from frontend. You can do this assigning appropriate theme for you as user. What to do if you want to show different theme for non-authorized user?

# Answer
> 2 votes
For a *very* simple, module free solution, you could either:

1. Disable the `Use the administration theme when editing or creating content` option in `admin/appearance`.
2. Remove the `View the administration theme` permission for the role in `admin/people/permissions`

---
Tags: users
---


title: hook_block_view not being called

text:
# Question
Title: hook_block_view not being called
I have a custom module which has some custom blocks in. My blocks display in the block page so they are being registered with `hook_block_info`.

However my modules are not displaying anything on the screen. I have added a `dpm('hit')` at the the top of `hook_block_view` for my module but nothing is being displayed.

I have added `hook_block_view_alter` to my module and see that the blocks are being displayed there but with the `$data` parameter being null/empty.

I have run my code through the coder module and it is not seeing any errors.

What could be going wrong?

# Answer
> 2 votes
After looking around the code I ended up the `_block_load_blocks` function. Before calling `drupal_alter('block_list', $block_info);` I had 6 elements in `$block_info`. After the function had run I had 2 items.

Doing some digging in `drupal_alter` I fount out what modules were touching `$block_info`. The domain module was removing the blocks.

Looking at the settings on the block page I did not have my domain ticked. The message under the domain options did say:

> Limit block display to these affiliates. This block is visible on all domains by default using this theme.

So thought the block would appear by default. This was not the case.

---
Tags: 7, blocks, hooks
---


# Question
Title: Custom module and template.tpl.php files
I am just getting started with custom modules for my test site on my localhost. Is there a simple demonstration online where there is an example of using a mymodule.tpl.php files to render my content?

At the moment I have create a hook\_menu() function also a function for the page call, all it does is return some text.

# Answer
> 7 votes
There are a lot of examples of use of the Drupal API for module developers in the Drupal documentation. In particular, you may find the Examples for Developers module handy, especially the "theming\_example" sub-module. This is not an actually functional module, but just a container for a lot of example code that new developers can test, manipulate and learn from.

# Answer
> 4 votes
I know its too late to answer this now, but still could be helpful to many: This is the best and exact to the point: http://www.nicklewis.org/drupal-hackers-cookbook/theming/hook\_theme-and-template-files

---
Tags: 7, theming
---


# Question
Title: how to remove duplicate from views' result page
I went through all solutions found on the web.

Both *Distinct* or *Aggregation* do not work at all in my case. **Is there a way to remove the duplicates using hook\_query\_alter()** ?

My sql query run in the view is the following:

```
SELECT node.changed AS node_changed, node.nid AS nid, SUM(search_index.score * search_total.count) AS score
FROM
{node} node
LEFT JOIN {search_index} search_index ON node.nid = search_index.sid
LEFT JOIN {search_total} search_total ON search_index.word = search_total.word
INNER JOIN {search_dataset} search_dataset ON search_index.sid = search_dataset.sid AND (search_index.type = search_dataset.type)
WHERE ((( (search_index.type = 'node') AND (search_dataset.data LIKE '% saadan %' ESCAPE '\\') AND (search_dataset.data LIKE '% goer %' ESCAPE '\\') AND (search_dataset.data LIKE '% du %' ESCAPE '\\') ))AND(( (node.status = '1') AND (node.type NOT IN  ('nodetype')) )))
GROUP BY search_index.sid, score, node_changed, nid
HAVING (( (COUNT(*) >= '2') ))
ORDER BY node_changed DESC
LIMIT 10 OFFSET 0

```

Last note:

I am also aware of the solution the removes content by hooking into hook\_views\_pre\_render() but I do not really consider this a solution since it cracs up your results.

**The query works perfectly if I replace 'GROUP BY search\_index.sid, score, node\_changed, nid' with GROUP BY nid.** How do I achieve this?

# Answer
What actually worked is the following

```
function mymodule_query_alter($query) {

  if (isset($query->alterMetaData)) {
    if (isset($query->alterMetaData['view'])) {
      if($query->alterMetaData['view']->name == 'node_search') {
        $fields =& $query->getGroupBy();
        // Tried various fields to check which was the field creating the problem.
        unset($fields['score']);
        $query->groupBy('nid');
      }
    }
  }
}

```

Answer found at http://www.brenthartmann.com/blog/how-use-hookqueryalter-drupal-7

PS: In order to check the sql query that produces your view, you need to go to admin/structure/views/settings and enable "Show the SQL query".
> 5 votes

# Answer
Hope this will help you,

Using Distinct or Aggregation you can solve your problem. You can apply **GROUP BY** or **DISTINCT** to remove duplicate records.

Just check it out the steps.

Using **Distinct**

* The simple way to achieve distinct values in view is to make follow:
    + Go to your view
    + In Advanced » OTHER section click on "Query setting"
    + Check "Distinct" check-box.

Using **Aggregation**

* You can apply **GROUP BY** by enabling views aggregation settings to remove duplicate records.
    + Go and edit your view
    + In Advanced » OTHER section by enabling Use aggregation: Yes
    + In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.
> 6 votes

---
Tags: views, search, database
---


title: Create taxonomy term with code

text:
# Question
Title: Create taxonomy term with code
I want to know how i can create taxonomy term programmatically.

I have this code

```
$term = new stdClass();
$term->name = ‘Term Name’;
$term->vid = 1; // ‘1’ is a vocabulary id you wish this term to assign to
$term->field_custom_field_name[LANGUAGE_NONE][0]['value'] = ‘Some value’; // OPTIONAL. If your term has a custom field attached it can added as simple as this
taxonomy_term_save($term); // Finally, save our term

```

From Link

I don't know where to write it. I think it will be in template.php with some hook ?

Drupal 7

# Answer
If you just want to run an arbitrary PHP script through Drupal, the easiest way is probably using the Devel module

It provides a page (/devel/php) where you can copy/paste PHP code and have it run inside a fully bootstrapped instance of Drupal.
> 4 votes

---
Tags: hooks
---


# Question
Title: How do I create a link that points users to the edit profile page?
I would like to create a link that leads each user to their edit profile page.

What should I use as URL? I get access denied on the paths I tried, including http://example.com/user/\[uid\]/edit.

# Answer
> 1 votes
You might want to try using the Menu Token module, so you could add a user id token in the path.

Otherwise you'd need to create a page callback in a custom module using hook\_menu(), say to 'user/edit', and in that callback, redirect the user to 'user/\[uid\]/edit'. That way you could add a menu link to 'user/edit' and it would work. See this comment for an example.

---
Tags: navigation
---


# Question
Title: Webform, creating customized directories for uploaded files
Newbie and my first question on here. I'm still learning Drupal. So apologies if I missed anything

Here is my issue I am using Webform to create an upload page. The user enters an ID(text field) and uploads the file. The file gets uploaded to a private section on the server. Now I am trying to make sure that the file gets uploaded into this separate folder(named after the ID)( say all/private/ID/). Can I do that using a Webform ? For now, all I can use are basic tokens,not values I can grab from other fields(ex: %username) to create these directories.

If webforms are not the answer, what else would be a good method to go about it ?

# Answer
Greetings welcome to the land of Drupal stuff :)

In general here are some tips:

* creating a folder off of a textfield `ID` is going to be cumbersome. How will you know subsequent users aren't putting in the same `ID` and or overwriting eachothers files?
* Webform has an API of available hooks. For instance look at webform\_submission\_presave() which allows you to change/capture a users submitted answer and alter it; you could likely alter the destination of the file to be saved, and assure the destination directory exists with a Drupal API function file\_prepare\_directory.

If you're looking for an all-in-one no code solution. Look at this issue queue PATCH for webform that looks like it supports custom tokens for upload files.
> 0 votes

---
Tags: webforms, tokens, files
---


# Question
Title: how to make config fields stick at admin/structure/types/manage/<content_type>?
I am adding a config option to all content types. I have textfield and checkbox now.

How to SAVE what I write in the textfield and state of checkbox when I hit submit?? Do I need to alter submit function for this form?

```
function neil_misc_form_node_type_form_alter(&$form, $form_state) {
  global $user;
  if (isset($form['type'])) {
    $form['followbtn'] = array(
      '#type' => 'fieldset',
      '#title' => t('Follow Button settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
    );

$form['followbtn']['comment'] = array(
  '#type' => 'textfield',
  '#title' => t('Email address to send updates to'),
  '#default_value' => $user->mail,
);

$form['followbtn']['followbtn_default_mode'] = array(
  '#type' => 'checkbox',
  '#title' => t('Add Follow button to this Node Type?'),
  '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, ADD_FOLLOWBTN),
);
  }
}

```

# Answer
> 0 votes
You can add a custom submit handler for your custom group of options and controls. For example on the base form you add an additional `#submit` value and check your own custom fields:

```
$form['#submit'][] = array('mymodule_form_followbtn_custom_submit');

```

if needed you can validate is form element independantley:

```
$form['followbtn']['followbtn_default_mode']['#element_validate'] = 'mymodule_followbtn_element_validate_default_mode';

```

or ...

```
$form['followbtn']['comment'] = 'mymodule_followbtn)element_validate_comment';

```

Then your submit function just does your processing (after elements validate on submission:

```
function mymodule_form_followbtn_custom_submit($form, &$form_state) {
  // save your stuff ...
}

```

---
Tags: 7, forms
---


title: views: all terms as images

text:
# Question
Title: views: all terms as images
I have a node view and want to show all terms (which have one image field per term) related to that node (which might be multiple terms), explicitly showing their respective images. How can I do that?

I was assuming that I would choose 'all taxonomy terms' as a field and then would e.g. rewrite the output, showing the terms' image fields. But they don't exist, hence don't show up. I know some workarounds based on theming with overwritten .tpl.php files, but I prefer dynamical solutions... So - does anybody have any suggestions for me?

# Answer
The solution given by DrupalMonster is a straightforward, but barely scalable. I've been through a similar scenario and I eventually gave up on it when it got to real life.

I haven't been at Drupal for some time but I hope my suggestion will get you going.

1. Make a view that lists the terms. You will want to use contextual filter with node ID to tell Views which node you are viewing, and then test it (using normal environment) to make sure that it retrieves appropriate terms.
2. Once your view is working well, install Viewfield module. The module will provide a new field "Viewfield". Attach an instance of it to your node content type and configure it to display the View you have tested.
3. Theme the view using Views' tpl naming convention, accessible from `Theme information` in the Views editor.

HTH
> 1 votes

# Answer
You can, with some limitations, get terms to display as images rather than words or links using Display Suite. In brief, you customise a view mode and then use that view mode in your view. This approach can be done entirely in configuration.

See answer to the DA question How to display multiple taxonomy fields in a view for detailed steps.

For greater flexibility, you can use Views PHP to do your rewriting.
> 0 votes

# Answer
How about creating views with terms related to node? If you want you can create use that view inside another view by displaying that view in header or footer or views view field so that it inherits filters from it's parent.

If you dsm() the node within for example HOOK\_node\_view() it should show values for selected taxonomies for that node. You could use that information to output list of terms as images via alter function.
> 0 votes

# Answer
Sorry, I'm a bit confused on this here, but can you get the terms to list out in the view? If you can get the terms to list out in a view just add a CSS class to the term link (it should print out as a link by default): edit field--\>Style Settings--\> Customize field HTML --\> Add a CSS class--\> Use a token substitution for this class (tokens are found under "Rewrite Results"). It should let you use \[tid\] as a token. So just make the css something like 'imageTerm\[tid\]'. That should output your link like

```
"<a class="imageTerm18"

```

Then in your CSS just style that link to be an image:

```
.imageTerm18 {
display:block;
width:100px;
height:100px;
text-indent:-9999px;
background-image:url('term18image.jpg');
}

```

This should work in theory, but I haven't tested it. If you get weird CSS output you may have to include the term field twice. Once rewritten as plain text with no spaces first, which will be used for your class name. The other you use the rewritten plain text tid field in the "Customize Field HTML".
> 0 votes

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


# Question
Title: How to set a specific timeout for each video played with Views Slideshow on Drupal 7?
I have come accross with an issue with the view Slideshow.

I have images and videos to play on my slideshow.

However when the video plays , the slideshow just rotates before the end of the video.

As I am aware it is impossible for the slideshow to know when a video ends, I have done many researches to be able to set a dynamic timeout for each video played.

I came accross this post: https://drupal.org/node/1541254 This post describes exactly what I need to do.

However being quite new to Drupal, I have no idea where to copy and paste the given patch.

If someone could please guide me on which file in the View slideshow module I have to copy and paste that would be great.

Or even if anyone had a better solution, please share. Many thanks

# Answer
welcome to this community.

I recommend you look at the Drupal Patch Documentation (this is how to Apply a Patch, other docs go into how to create one). What you're asking about is the Linux/Unix patch command when using a patchfile.

If you look at the file (from the 1st patch in the issue queue, you'll likely grab a later one). You'll see the following beginning lines:

```
diff --git a/contrib/views_slideshow_cycle/js/views_slideshow_cycle.js b/contrib/views_slideshow_cycle/js/views_slideshow_cycle.js
index 3e72ed5..c865b6d 100644
--- a/contrib/views_slideshow_cycle/js/views_slideshow_cycle.js
+++ b/contrib/views_slideshow_cycle/js/views_slideshow_cycle.js

```

This should tell you exactly what module `views_slideshow_cycle` and exactly what file `views_slideshow_cycle.js` the patchfile is a Patch for.
> 0 votes

---
Tags: 7, javascript, views
---


# Question
Title: New User Registration Sequence for Services 3.4?
This comment outlines a working way to login with the new CSRF token:

1. POST to /rest/user/login (nothing in headers). Construct the $cookie from session name + id
2. GET to /services/session/token (include $cookie in the headers). Save the $token returned.
3. Include $cookie and $token in the headers of subsequent requests of a logged in user.

That sequence works even though the first POST happens without sending the token. (The documentation suggests that the token should be used for any POST requests, which does not work in this case.)

What is a working sequence of **HTTP requests** to **register** a new user account? I'm looking for what requests to make in what order - not implementation code.

UPDATE: To be clear, I'm not looking for the `login` sequence. I need a sequence of requests (similar to login example above) that allow a new user to `*register*` their account.

Failed Attempt with system/connect:

```
1. GET:services/session/token

2. POST:system/connect
      Content-Type: application/json
      Accepts: application/json

3. POST:user/register
      Content-Type: application/json
      Accepts: application/json
      X-CSRF-Token: [token]
      Cookie: [session_name]=[sessid]
      Body: {
               "name":"drupalspec0rVzsWAU",
               "pass":"PYKSItFK",
               "mail":"drupalspec0rVzsWAU@drupalspec.com"
      }

```

The Drupal user is created correctly, but the request in step 3. times out.

# Answer
> 5 votes
Edit: to address the change in the question

> I'm looking for what requests to make in what order - not implementation code

You can safely ignore the actual code implementation below - the order of the requests remains the same. In fact, exactly the same as in your original question.

If you're already making requests in the order that you've outlined, you needn't do anything more except provide an actual implementation. I'll leave the code in as an example, and so you can see exactly what order the requests need to be made in. I've stuck some numbering in to make it more obvious; the requests are denoted by 1, 2 & 3.

---

This is a basic PHP (i.e. non-Drupal) example...

First off make a generic function for sending your requests:

```
function send_request($url, array $post_array = array(), $cookie = NULL, $token = NULL) {
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, 'googlebot');
  //curl_setopt($ch, CURLOPT_VERBOSE, $post_array);

  if (!empty($post_array)) {
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
  }

  if ($cookie) {
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  }

  if ($token) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-CSRF-Token: ' . $token));
  }

  $result = curl_exec($ch);
  curl_close($ch);

  return $result;
}

```

**1**. Then make your first call to log the user in:

```
// Login.
$data = array(
  'username' => 'user',
  'password' => 'password',
);

$result = send_request("http://server/endpoint/user/login.json", $data);

try {
  $result = json_decode($result);
}
catch (Exception $e) {
  die('Login failed: ' . $e->getMessage());
}

```

Next get the session name and ID, creating your cookie string to send with subsequent requests:

```
$session_id = $result->sessid;
$session_name = $result->session_name;
$cookie = $session_name . '=' . $session_id;

```

**2**. Then get a CSRF token, making sure to pass the cookie along:

```
$token = send_request("http://server/services/session/token", array(), $cookie);

```

**3**. Finally you can perform your request to the endpoint you're actually interested in. The cookie and token are injected by the send\_request() function.

```
$user = array(
  'mail' => 'test@test.com',
  'name' => 'name',
  // Other relevant properties/fields.
);

$result = send_request('http://server/endpoint/user', $user, $cookie, $token);

```

I haven't tested the user creation endpoint so that might not be the exact structure it needs, but checking the responses for errors should let you know exactly what it's after quite quickly. I get the impression from your question that you're mainly interested in the steps leading up to that last request anyway.

The above is adapted from a basic test script I use, for a production environment you'll want to add more error/sanity checking in there. And the functionality is crying out to be wrapped in a class, and be extended to support PUT/DELETE, but I'll leave that to you :)

---
Tags: 7, users, services
---


# Question
Title: In Drupal 7, Where is field settings data stored? (Not the field data)
I'm trying to update my field's data tables structure manually via phpmyadmin as I cannot modify it via the fields settings page since i have data in them. The thing is, where do I update the "fields settings" to encompass these table structure changes?

# Answer
> 16 votes
Base field data is in `field_config`, and instance data is in `field_config_instance`. Rather than modifying them manually, though, you can always use the API:

```
$field = field_info_field('field_name');
$field['key'] = $new_value;
field_update_field($field);

```

Or for an instance

```
$instance = field_info_instance('node', 'field_name', 'article');
$instance['key'] = $new_value;
field_update_instance($instance);

```

Using the API will clear the appropriate caches, and it's just a better idea than editing the data manually.

Either way, make sure to backup the database first in case something goes horribly wrong :)

---
Tags: 7, entities
---


# Question
Title: How exactly do I package latest dev snapshot of Commons locally?
I am trying to build up-to-date instance of Drupal Commons 7.x-3.x-dev. Release notes say to use command: "drush make build-commons-dev.make". I am totally new to drush and am trying to follow that instruction.

Can anyone provide more detailed instructions? That is my basic question.

Thanks, and more details below:

I thought I had figured it out. I can now go to root folder of site and run "drush profiles/commons/build-commons-dev.make" and I get what appears to be current Drupal Commons 7.x.-3.x-dev. However, as I test my instance, I am reporting bugs that Drupal coders say are already fixed and committed to github. So it seems that I am not properly synched.

Maybe I have wrong makefile? I got it from http://drupalcode.org/project/commons.git/tree/1228f4b

When I run "drush update" it says I am using all sorts of dev modules and that my site is 100% current. But I am clearly not current, because I am finding bugs that have already been fixed. Thanks for your help so I can test and contribute to Drupal Commons.

# Answer
> 1 votes
I eventually got the answer straight from ezra-g at Acquia. From a unix-like console you can execute these commands (make sure you have drush and git installed locally):

1. cd ~
2. git clone --branch 7.x-3.x http://git.drupal.org/project/commons.git ./commons-profile
3. cd public\_html
4. drush make ../commons-profile/build-commons-dev.make --prepare-install my\_Drupal\_Commons\_site

---
Tags: 7, version-control, drush
---


title: Votable node content type in D7

text:
# Question
Title: Votable node content type in D7
I'm trying to figure out the best way of creating a content type that allows for creating nodes that can be assigned to a group and can be voted for in competition with the other nodes in that group. I started writing a module for it by using the Fields API, Node API and Voting API but I want to check to see if I can use an existing module to do this before I get too far into the project.

For example, I want to create a content type called "contestant" and give the content type 3 different brackets it can be assigned to. Then when I create the contestent content and select one of those brackets, the content becomes votable and is ranked against other pieces of content within that bracket.

Any references to existing modules or suggestions would be awesome.

# Answer
I'm not sure I totally follow what you're trying to achieve, but Fivestar is a very flexible module

https://drupal.org/project/fivestar

I use it to vote for a few different content "dimensions" (2-3 votable fields) and then with views you can output it as a table with click sorting by any one of the ratings fields.
> 0 votes

---
Tags: 7, nodes, rating
---


# Question
Title: Re-creating Blocks Page for Content Authoring?
I'm using Drupal 7.14, and the biggest complaint I get from people new to Drupal is visualizing where the content goes once its created.

It got me thinking of some clever/native ways to do this with the base installation. I looked into the Overlay module that the administrators have access to, then Blocks page, then Context page, and none seem to provide an easy to use interface for doing what I want. I remember the Themer module in Drupal 6 highlighted the regions in the Blocks page when you're moving components around, and my question begs whether or not this can easily be re-created somehow?

Now I'm familiar that Drupal 8 + Sparks helps with content authoring a bit, I've seen the demo's where users can edit content on the page/layout, but it still doesn't allow for adding new ccks, nodes to a specific region on a page.

I'm not sure this is an appropriate D.SE question, but has anyone heard of a module, or can think of a way to provide a GUI for users to attach their newly created content to the specific region in a theme, most preferably when they are creating the content?

# Answer
The nodeblock and node-level-blocks modules may be a good starting point.
> 1 votes

# Answer
If you want to do this on a node-by-node basis, the Panels In-Place Editor (IPE - part of the **Panels** project) will do exactly that.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to show nodes of a content type using contextual filters as filters?
I have a profile page for each user where it will show all nodes he has created for each content type.

For instance, Autos content type will only list all autos he has authored. I'd like to be able for the user to access it using this path : `http://localhost/mysite/myreports/autos` and will show his autos, .../myreports/jobs will show his job postings, .../myreports/events for events etc...

I have tried doing it in views using page views with path ..../myreports/% (where argument is the name of the content type) and added a views contextual filter for 'content type' but i cannot get it to work.

I had read this : Drupal 7 Views Contextual Filter to show only nodes of the same type but it's not working.

I can set up each unique view to a content type without using contextual filters so I can specifiy a permanent url for say ...myreports/autos but then that would be inefficient.

Any suggestions?

# Answer
After hours of tinkering here is my solution to the above. If anyone has the same requirement this will help:

Drupal 7.16, views-7.x-3.5

The View Setup :

The result (sample 1):

Sample 2:

No other settings required. Even in the section "WHEN THE FILTER VALUE IS NOT IN THE URL" does not matter, what seems to be important is you set the validation to always return TRUE regardless.

The path of this view is set to /myreports/%

Perhaps, the filter value in the URL that was found will be validated to always true. Then resolves to using this as a normal filter, as is the case with the normal filter setting. Hence, Filter content type = events (or jobs).
> 3 votes

# Answer
Add contextual filter as content type and set value from url path. See screenshots.
> 1 votes

# Answer
The problem with the previous solution is that it will not work for Content Types that have more than one name such as "Press Releases". This worked for me

1. For Context Filter, select Content Type.
2. Select "Provide Default Value" and select "PHP Code".
3. Enter the following snippet of code:

$node = node\_load(arg(1)); echo $node-\>type;
> 0 votes

---
Tags: 7, views
---


title: Bypass permissions in custom module

text:
# Question
Title: Bypass permissions in custom module
I have written a custom module which generates a PDF when a Webform is submitted and mails it to the admin. I am using the Print module to generate the PDF. The problem is, it seems to use the user's permissions when generating the PDF, and not the admin's. This is generally ok for authenticated users, but for guests, it just fails completely.

I have enabled "Access the PDF version" and "Access own webform submissions" permissions for all users (anonymous and authenticated), but I guess "own" still checks for a user ID and fails for guests.

The Print module uses this code to get the content of the $node from the URL.

```
$node = new stdClass();
$node->body = menu_execute_active_handler($path, FALSE);

```

This is how I am using the Print module to generate the PDF content.

```
module_load_include('inc', 'print_pdf', 'print_pdf.pages');
$pdf_url = 'node/' . $nid . '/submission/' . $sid;
$file_content = module_invoke('print_pdf', 'generate_path', $pdf_url);

```

When the logged-in user has the permission, this works fine; it generates and mails the PDF successfully. The content of `$node->body` is fully populated.

However, when with anonymous users, the content of `$node->body` is just an integer. Is there any way for me to tell it to bypass the permissions when generating the PDF? Or is there a better, secure way around this?

# Answer
Looking at `webform_submission_access`, prior to getting the PDF url, try:

```
// Where $sid is the webform submission id
$_SESSION['webform_submission'][$sid] = TRUE;

```

If that works for the anonymous user, it may grant access to view that submission.
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Specific permissions for rules components
I created two rules components but i can't find any module to set specific permissions for roles.

I want to let some role's users to allow run the first component but not the second one.
thanks.

# Answer
Rules provides a UI to configure access to components based on a permission.

1. Edit the component
2. Click to expand "*Settings*"
3. Check "*Configure access for using this component with a permission*"
> 3 votes

# Answer
Add a condition to your component for *User has Roles*, change the data selector to *site:current-user:roles:* and set the roles you require for the component to run.
> 1 votes

---
Tags: 7, rules, users
---


# Question
Title: The Zencoder API library is not installed ... zencoder in a library path such as sites/all/libraries
I have installed Zencoder 2.1.1 for my Drupal 7.22 but it's not working as I see the following error:

```
The Zencoder API library is not installed. Download the library and install it to a directory called zencoder in a library path such as sites/all/libraries.

```

I have already done what it required:

```
[root@ip-10-128-146-179 libraries]# pwd
/var/www/html/drupal/sites/all/libraries
[root@ip-10-128-146-179 libraries]# ls -lrt zencoder/Services/
total 12
-rw-r--r-- 1 root root 7867 Jul 21 16:32 Zencoder.php
drwxr-xr-x 2 root root 4096 Jul 21 16:32 Zencoder
[root@ip-10-128-146-179 libraries]# ls -lrt
total 4
drwxr-xr-x 5 root root 4096 Jul 21 16:32 zencoder

```

What do I need to now?

Screehshot

# Answer
I cleared all caches and ran cron and that solved the problem.

Thanks to this.
> 0 votes

---
Tags: files
---


title: Country based city list selection

text:
# Question
Title: Country based city list selection
I can use hierarchical select module but it contains lot of manual work in entering data. I want for all countries their city list. How to do it ?

Is there any module which helps to show city list based on a country selection? Is there a custom way to do it? thanks in advance

# Answer
You can use the Address Field module. To do just the country and city, you will have to define a plugin. Look in the `addressfield/plugins/format` directory for examples.

To add the cities, you will have to define a list of cities for each country in the plugin. You can then format the list and add it to your plugin and you should be good to go.

One advantage of using the Address Field module is that if you do not define a list of cities for a country, users will still be able to input the city themselves.
> 4 votes

# Answer
Taxonomy CSV import/export allows you to **import or export** taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.

> It helps you to quick import a non-standardized vocabulary, for example an old thesaurus, a hierarchical taxonomy or a simple list of children, synonyms, descriptions, weights or related terms to terms.

• import common field types.

• import repeatable fields.

• import a hierarchical (tree) or a polyhierarchical vocabulary.

• import translations.

• import your hierarchical tree structure and your fields simultaneously (7.x-5.11-dev).

• export names, fields, tree, translations... to a csv file.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Hiding 3rd level menu from sidebar, but displaying elsewhere. Possible? - D7
I have a 3 level menu structure in the sidebar. I would like to add a set of submenus for one of the Second level menu items, but would this time like to hide it's children from the sidebar. Instead, I would like this menu to be displayed in the main content area. Is this possible? How would I go about doing this?

So just to clarify, some 3rd level menus I would like to display in the sidebar, but other 3rd level menus I would like to hide from the sidebar, but instead display in the main content area.

# Answer
The level of control you need can be achieved using Menu Block module:

> So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
>
> So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
>
> Pretty simple, eh?
> 0 votes

---
Tags: routes
---


# Question
Title: mark single form field as cause of error on form validation
I've a custom field, and I'm trying to write the validation for the field values. however when a particular field causes the failure, the whole fielset is marked in red. I only want the specific field element to be highlighted, and in the case of Unlimited I only want the specific entry highlighted.

here is the code I have so far. but the whole fieldset is marked in red when ever a validation fails.

```
   function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langtype, $items, $delta, $element) {
      $base = $element;

      if ($instance['widget']['type'] == 'prodlist_text') {
        $element['#element_validate'] = array('_prodlist_text_validate');

        $element['prod_type'] = array(
          '#type' => 'select',
          '#title' => t('Product Type'),
          '#default_value' => isset($items[$delta]['prod_type']) ? $items[$delta]['prod_type'] : NULL,
          '#options' => type_options(),
          ) + $base;

        $element['prod_description'] = array(
          '#type' => 'select',
          '#title' => t('Description'),
          '#default_value' => isset($items[$delta]['prod_description']) ? $items[$delta]['prod_description'] : NULL,
          '#options' => description_options(),
          ) + $base;

        $element['order_amount'] = array(
          '#type' => 'textfield',
          '#title' => t('Amount'),
          '#default_value' => isset($items[$delta]['order_amount']) ? $items[$delta]['order_amount'] : NULL) + $base;
      }
      return $element;

    }

function _prodlist_text_validate($element, &$form_state) {

  if ($form_state['complete form']['#form_id'] == 'field_ui_field_edit_form') {
    return ;
  }

  $values = $form_state['values'];
  $language = $values['language'];
  $field_name = $element['#field_name'];
  $field_name_error_box = $field_name;

  foreach ($values[$field_name][$language] as $delta => $item) {

    if (isset($item['order_amount'])) {

      if (is_numeric($item['order_amount'])) {
        if($item['prod_description'] != 'no order' && $item['order_amount'] <= 0 ){
          form_set_error($field_name_error_box, t('Order amount has to be more then 0'));
        } else if ($item['prod_description'] == 'no order' && $item['order_amount'] > 0) {
          form_set_error($field_name_error_box, t('You have created an order amount without selecting a product.'));
        }

      } else {
        form_set_error($field_name_error_box, t('Order amount has to be numeric'));
      }
   }

  }

}

```

I'm trying to set the variable `$field_name_error_box = $field_name;` to the correct value but it either lights up the whole form section or nothing at all.

I've tried the following, and lots of other variants without luck.

```
$field_name_error_box = $field_name . 'order_amount';

```

# Answer
You must use a field name like this: 'parent\]\[element'

In your case,

```
$field_name_error_box = $field_name . '][order_amount';

```

should work.
> 1 votes

---
Tags: entities
---


title: What can cause Drupal to crash Apache?

text:
# Question
Title: What can cause Drupal to crash Apache?
In my local development environment, Drupal keeps crashing Apache when I try to load admin pages. The user pages all load fine, but any admin page causes apache to reset itself.
In the apache error log I get:

```
Parent: child process exited with status 255 -- Restarting.

```

The files were all copied from our test server, although I removed all the cached data inserts from the database while transferring it over.

We're running a separate admin theme (Garland for admin, custom theme for all other pages). The custom themed pages work fine. I haven't found a way to determine if its the theme or the admin pages that are causing the problem.

I'm using Drupal 6 with WAMP, on Windows 7.

I'm looking for suggestions about what's causing the resets.

# Answer
> 2 votes
In your settings.php add this line `ini_set('memory_limit', '128M');` and disable update module.

# Answer
> 2 votes
I had the same issue "Parent: child process exited with status 255 -- Restarting." on my setup with below configuration

* Windows 7
* Apache Server 2.2.25
* PHP 5.2.17 / 5.3.27
* MySQL Server 5.6

*\*Note that this is not a XAMPP or WAMPP setup. All components were individually installed.*

This error occurs due to multiple reasons, the answer for some of which you can find directly via google but unfortunately mine was not one of them. After spending a lot of head scratching, I finally got it working. The issue was due to stack size allocated to Apache threads. This can be resolved by setting 'ThreadStackSize' to a higher value. Add the below line to your httpd.conf or better enable loading of httpd-mpm.conf and add it there.

```
<IfModule mpm_winnt_module>
    ThreadStackSize  8388608
</IfModule>

```

# Answer
> 1 votes
I had a similar problem. Everything was resolved with the installation of latest version of xampp.

# Answer
> 1 votes
The Update Manager is a module that can increase the required resources to run Drupal, as it gathers update information about the installed modules (whatever they are enabled, or not).

It runs for pages for which `arg(0)` returns `'admin'`, but it doesn't run for specific pages, as visible in update\_init().

```
  if (arg(0) == 'admin' && user_access('administer site configuration')) {
    switch ($_GET['q']) {
      // These pages don't need additional nagging.
      case 'admin/appearance/update':
      case 'admin/appearance/install':
      case 'admin/modules/update':
      case 'admin/modules/install':
      case 'admin/reports/updates':
      case 'admin/reports/updates/update':
      case 'admin/reports/updates/install':
      case 'admin/reports/updates/settings':
      case 'admin/reports/status':
      case 'admin/update/ready':
        return;

        // If we are on the appearance or modules list, display a detailed report
        // of the update status.
      case 'admin/appearance':
      case 'admin/modules':
        $verbose = TRUE;
        break;

    }
  }

```

If you see the same issue for any admin page, then Update Manager is not the cause. If the issue appears for all the admin pages, except the ones listed after "// These pages don't need additional nagging." then chances are the Update Manager module is causing the issue.

---
Tags: 6
---


# Question
Title: How to turn multi-value image field into a UL
I have a multi-value image field. I want to output the images in a UL/LI. Should I add a prefix and suffix in preprocess\_field?

# Answer
> 3 votes
You could certainly do it with a preprocess function...or you could install the Fences module and do it through the UI:

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

---
Tags: 7, theming
---


# Question
Title: Separate permissions for form access and form submit
I have a module on a website, called members, and 2 roles: "low admin" and "manager". They have permissions: 'low admin tasks' and 'manager tasks'. Every low admin has access to both permissions.

There is an edit member form. Manager must be able to view the data, but not be able to update. Low admin can do both operation. Here is the code:

```
function members_menu()
{
       $items = array();

       //members_edit calls members_edit_form
       $items['members/edit'] = array(
           'page callback'    => 'members_edit',
           'access arguments' => array('manager task'),
           'type' => MENU_CALLBACK,
           );

       return $items;
}

function members_edit_form($form, &$form_state, $data_array = NULL)
{
    //here I prepare the fields
    ...

    //submit button is shown only for the low admin
    if (user_access('low admin tasks'))
    {
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            );
    }

}

function members_edit_form_submit($form, &$form_state)
{
    if (user_access('low admin tasks'))
    {
        //save to the database
    }
}

```

Is it possible to remove the condition from `members_edit_form_submit` and set somewhere (maybe in members\_menu), that only users with 'low admin tasks' privilege can call `members_edit_form_submit`?

# Answer
> 3 votes
It's an odd use-case where certain roles can view the form itself, but not submit it. Perhaps better to allow non-privileged users to view the rendered form output instead of the input form.

That way, you can put the access check on the menu callback for the form itself.

Anyway, have you considered putting the access check into the form validate function?

e.g

```
function members_edit_form_validate($form, &$form_state)
{
  if (!user_access('low admin tasks'))
  {
    form_set_error('submit', t('Sorry, you do not have access to update this form'));
  }
}

```

---
Tags: users, forms
---


# Question
Title: Services Module - 500 Internal Server Error When Accessing REST URL
I created a services endpoint but any time I access the REST URL, e.g. `http://www.mysite.com/endpoint` I get a WSOD and the following in the firebug console:

```
"NetworkError: 500 Internal Server Error"

```

No errors in the dblog. No errors in the apache error log.

The site is hosted on `aegir`. So as a troubleshooting step I moved the entire drupal files and database to my local machine, hoping that I could step through with a debugger. Guess what, everything works fine!

I've tried uninstalling modules one by one - no luck

I've tried with a clean drupal install on `aegir` \- same 500 error

I'm wondering if anyone can suggest any further troubleshooting steps?

It seems that it could be something to do with the server or aegir configuration.

# Answer
The problem turned out to be the PHP version on the server. The Rest Server had a line of code that requires PHP 5.3.

There is an issue at https://drupal.org/node/2003396 and a patch at https://drupal.org/files/ServicesRESTServerFactory.inc\_.patch

Installing the patch solved the problem without the need to upgrade the php version on the server
> 2 votes

---
Tags: 7, services, aegir
---


title: Download image without watermark

text:
# Question
Title: Download image without watermark
I have a content type that includes an image field. After the image is uploaded, I add a watermark to this field using the Imagecache Actions module.

I would like to allow users to download the image without watermark. Is it possible?

# Answer
> 5 votes
Before watermarking the image, store the original copy in another, private file mode image field.

Then you can control access to the original image with hook\_file\_download().

---
Tags: media
---


# Question
Title: can needs-data be an array in drupal hook_token_info?
Can the function `hook_token_info()` have an array for needs-data ?

```
hook_token_info()  {
 $type = array(
                'name' => t('ABC Settings'),
                'description' => t('Tokens related to ABC admin settings.'),
                'needs-data' => array('abc_user','abc_trans' ,'abc_trans_sub' ,'abc_gist_email_for_report_download','abc_gist_email',
                                      'abc_st_email' ,'abc_send_fax'),
                );}

```

# Answer
> 2 votes
There is no type limit on needs-data. It all depends on how do you want to call token\_replace(). On the other hand, it might be wise to use 'node' approach - when you provide node, you provide also user object of node's author, even if it is never provided or mentioned in `needs-data` explicitly.

---
Tags: 7
---


title: Adding JavaScript before drupal.js

text:
# Question
Title: Adding JavaScript before drupal.js
I am trying to add jQuery to my page (it is not being added by default). The file is adding to the page but after drupal.js causing the error:

```
SCRIPT5009: 'jQuery' is undefined
drupal.js, line 5 character 1

```

The code that adds drupal.js to the page in common.inc

```
...
'misc/drupal.js' => array(
          'data' => 'misc/drupal.js',
          'type' => 'file',
          'scope' => 'header',
          'group' => JS_LIBRARY,
          'every_page' => TRUE,
          'weight' => -1,
          'preprocess' => TRUE,
          'cache' => TRUE,
          'defer' => FALSE,
        ),
...

```

In my module `hook_init` I have:

```
  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'cache' => TRUE,
  ));

```

I would think with a lower weight it would load before drupal.js?

The header of the page contains the following scripts:

```
<script type="text/javascript" src="http://mysite.com/misc/drupal.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/misc/jquery.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/misc/jquery.once.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/default/files/languages/nl_c9aC92_wtuULa79-hTFcGPM53oqk1yKwciOa_Q3yO28.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/all/modules/lang_dropdown/msdropdown/jquery.dd.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/all/modules/lang_dropdown/lang_dropdown.js?mqdxrf"></script>
<script type="text/javascript" src="http://mysite.com/sites/all/modules/devel/devel_krumo_path.js?mqdxrf"></script>

```

# Answer
> 3 votes
In the end I got it working by changing the code to:

```
  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));
  drupal_add_js('misc/jquery.once.js', array(
    'group' => JS_LIBRARY,
    'weight' => -19,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));

```

This then meet the rules on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7

* First by scope, with 'header' first, 'footer' last, and any other scopes provided by a cust om theme coming in between, as determined by the theme.
* Then by group.
* Then by the 'every\_page' flag, with TRUE coming before FALSE.
* Then by weight.
* Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal\_add\_js() that happened later in the page request gets added to the page after one for which drupal\_add\_js() happened earlier in the page request.

# Answer
> 2 votes
You should not add jQuery manually. It is added by Drupal itself. Adding existing libraries is known to cause problems.

If you need newer jQuery version than one included within Drupal, use jQuery update module.

---
Tags: javascript
---


# Question
Title: How can I get the current widgets name of a node?
I'd like to know if it is possible to get the current widgets of a node ?

field\_info\_widget\_types() shows all the widget

But I'd like to get the widgets the current page is using and not all of them :(

Is there a way to to it ?

Thanks

# Answer
I found the solution and I also find a way to display all the field used in the current node !

```
function mymodule_form_alter(&$form, $form_state, $form_id){
    $entity=$form['#entity_type'];
    $bundle=$form['#bundle'];

    $instance = field_info_instances($entity, $bundle);
        foreach ($instance as $key => $value) {
          if(!empty($value['widget'])){
            $widgetlist[$key] = $value['widget']['type'];
          }
        }
        foreach ($instance as $key => $value) {
            $fieldlist[$key] = $value['field_name'];
        }
    var_dump($widgetlist);
    var_dump($fieldlist);
}

```
> 0 votes

# Answer
From the docs of `field_info_widget_types()` :

> Returns information about field widgets from `hook_field_widget_info()`.
>
> Parameters:
>
> `$widget_type`: (optional) A widget type name. If omitted, all widget types will be returned.

You might be leaving the parameter empty. Hence, it is returning all field widgets. Pass the name of the widget from the current node, to get the right information. You can use `menu_get_object()` to get the node object of the current page, and find the appropriate widget to pass to `field_info_widget_types()`.
> 1 votes

---
Tags: entities
---


# Question
Title: How can I label content in views as "new"?
I use a panel with views on the home page of my drupal site (workaround.org). But I would like to put a "new" label in front of any article that was created or edited in the past 2 weeks. The view field "Node: has new content" did not help me because it will flag any content as "new" for anonymous users. Instead I just want to show anonymous users what content has been added recently.

# Answer
I have some suggestions, ranked below sort of from simple to complex.

1. You can simply add a static text field to the view, write "New" in the text field, and then filter the view to contain only content from the period you want to have the "New" label on them.
2. If you want the same list to also display more content, create an `attachment` display in the same view, override the text field and the date filter, and set the display to *attach after the first one*.
3. Use the `Theme information` in the view to directly override the views output. Find the content id in the template, load the node, and check the creation date.
4. Render the content through a *view mode* instead of on a field by field basis. In the the node-template, you can now check the creation date of the node and output the label. This solution would possibly benefit from an added 'per-view-mode' theme suggestion.
> 4 votes

# Answer
You can make use of the Views PHP module to write a small custom code that will check if node creation date is within the last two weeks, and then print a label.

Something like this (I'm using \[pseudo field names\], you need to check which is correct ones)

```
$show_date = time() - (60*60*24*7*2); //time minus 2 weeks
if ($data->[node_updated_date] <= $show_date) {
  print '<span class="new-label">New</span>';
}

```

To see which field names to use, you can get the content of the $data object by using the devel modules' dpm($data);

It is adviced not to use the Views PHP module too much, but I never ran into problems using it for small snippets like this.
> 0 votes

# Answer
Views by default provide this functionality for the new content

You just need to select the **field(Content: Has new content)** in views, it will add a div with unique class and with text "new"

it works with individual user, means if user is watching it first time then only for that user new tag will appear

I hope this will help you. Thanks
> 0 votes

---
Tags: views, entities, nodes
---


# Question
Title: Drupal places a <br> after text automatically?
I have the below code, however when I place it within Drupal 6, Drupal places a
after the text 'Coordinator', see second code insert for the firebug info. I am not sure where this
is coming from? but it would be useful to remove as it means I have a text description, and the selection boxis on the line below. While all my other input box are inline with their descriptions.

```
Coordinator:<?php
 //Drop Down Select
 $sql = "SELECT user_id, concat (user_firstname,' ', user_surname) as username  FROM   user_tbl WHERE coordinator='True'";
    $result = pg_query($sql);
         echo "<select name='user_id'>";
       while ($row = pg_fetch_array($result)) {
          echo  "<option value='" . $row['user_id'] . " '>" . $row['username'] ."</option>";
 }
         echo "</select>";
?>

```

Second Code

```
<p>
Coordinator:
<br>
<select name="user_id">
</p>

```

# Answer
> 0 votes
PHP filter / HTML filter was to blame with the auto break text

# Answer
> 0 votes
I didn't see this problem before but maybe try to rewrite code above as follows:

```
<?php
//Drop Down Select
$sql = "SELECT user_id, concat (user_firstname,' ', user_surname) as username                       FROM   user_tbl WHERE coordinator='True'";
    $result = pg_query($sql);
         echo "Coordinator:<select name='user_id'>";
       while ($row = pg_fetch_array($result)) {
          echo  "<option value='" . $row['user_id'] . " '>" . $row['username']     ."</option>";
 }
         echo "</select>";
?>

```

---
Tags: input-formats
---


# Question
Title: Link to send private message to current user in the node (author of the content)?
Is it possible to create a link to send private message to CURRENT USER in the node (to the author of the node content to be more precise). I'm using the Privatemsg module. I was trying to do this with the Display suite dynamic fields, but I am not able.

I found that the Privatemsg module comes with an option to "Display link on the selected content types. So, I have the "contact current member link" right in the content type, but it shows only for logged in users.

Is there any configuration or hook that I can implement to show the same link to anonymous user?

This is the code that shows the link.

```
function privatemsg_node_view($node, $view_mode) {
  $types = array_filter(variable_get('privatemsg_link_node_types', array()));
  $url = privatemsg_get_link(user_load($node->uid));
  if (in_array($node->type, $types) && !empty($url) && ($view_mode == 'full' || (variable_get('privatemsg_display_on_teaser', 1) && $view_mode == 'teaser'))) {
    $node->content['links']['#links']['privatemsg_link'] = array(
      'title' => t('Contact member'),
      'href' => $url . '/' . t('Message regarding @node', array('@node' => $node->title)),
      'query' => drupal_get_destination(),
      'attributes' => array('class' => 'button radius privatemsg-send-link privatemsg-send-link-node'),
    );
  }
}

```

To make it clearer, I don't want anonymous user to send messages. What I want is just a link to log in for anonymous users. Expressing it with pseudo-code...

```
global $user;

if (isset($user->roles[1])) {
  // Do not show button to Anonymous user and show something else or a button to log in (THE CODE FOR LOG IN)
  echo "something else";
}
else {
  // Show button to logged in user (the code of "Send author a message" button)
}

```

# Answer
I did it with a Display suite custom code field. With it I am able to use some PHP code.

```
global $user;
// If the user is anonymous (role=1) show this; otherwise show nothing.
if (isset($user->roles[1])) {
  print l(t('Contact member'), 'user/login', array('attributes' => array('class' => array('radius', 'button'))));
}

```

So, when the user is logged-in, this code above will be replaced with the contact member link (*Send author a message*).
> 1 votes

---
Tags: privatemsg
---


title: Having two types of view for one path

text:
# Question
Title: Having two types of view for one path
I need a view for taxonomy terms that shows both any child terms as links and a table of product nodes tagged with the term, but I can only work out how to apply one or the other.

Any help appreciated!

edit for clarity: For the path taxonomy/term/%, I need to show the child terms of parent terms, or for a child term a table of all products (nodes) that are associated with that term. I have assumed it would be easiest to combine these two into one view somehow.

# Answer
> 0 votes
By the sounds of it are you trying to display two different views on one page? if so have a look at panels, or you can do it manually by loading the views pragmatically in the template. if not, please clarify.

---
Tags: 7, views
---


title: Panel page title with date field

text:
# Question
Title: Panel page title with date field
I have a panel page with title set to %node:field\_pub\_year from substitution list. field\_pub\_year is a date field which is to select publication year. My problem is this is displaying whole date like '2012-01-01 00:00:00' as title. Is it possible to show only '2012' as title.

Thank you.

# Answer
> 1 votes
In theme\_preprocess\_page hook

```
    // CIsSharp, 07/23/2013: For 'projects' page, only display year as title
    if (isset($variables['node'])) {
        if (isset($variables['node']->type) && $variables['node']->type == 'projects' &&
            isset($variables['node']->field_pub_year)) {
          $date = strtotime($variables['node']->field_pub_year[LANGUAGE_NONE][0]['value']);
          $year = date('Y', $date);
          $title = $year . ' Project';
          drupal_set_title($title);

          // Because breadcrumb creation executes before preprocess
          // Fix breadcrumbs title also
          $crumbs = drupal_get_breadcrumb();
          if (count($crumbs) > 0) {
             $crumbs[count($crumbs) - 1] = $title;
             drupal_set_breadcrumb($crumbs);
          }
      }
   }

```

# Answer
> 0 votes
You can try to define title like %node:field\_pub\_year:value:custom:Y

---
Tags: 7, panels
---


# Question
Title: 'drush field-create' with type INTEGER from command line? drupal (ver 7.22) | drush (ver 6)
tried to manage fields of tpye 'int' with drush (batch), without success!

working: drush field-create user streetname,text,text\_textfield --entity\_type=user

not working: drush field-create user streetnumber,integer,text\_textfield --entity\_type=user

workaround: drush field-create streetnumber --entity\_type=user -\> offers interactive dialog only Field name: ... Choose a field type ... Choose a widget ... --\> '\_http://default//fields/streetnumber'

Maybe there's another way to provide data, like

* drush field-create user streetnumber \< inputfile ??
* drush field-create user streetnumber \< 'fieldname\_XYZ','6','1' ??

any ideas?

# Answer
> 1 votes
for an integer field type, try this :

```
drush field-create user streetnumber, number_integer, number_textfield

```

Or :

```
drush field-create user streetnumber, number_integer

```

(because you can ommit the widget type and the default one will be used).

If you are looking for the name of another field type, create the field in the admin panel, then look in your database, in table field\_config, you will find it in the type column.

---
Tags: drush
---