# Question
Title: Simple newsletter send only This is a test version of the newsletter
I am using Newsletter module to send newsletter to all my registered users. I have created two lists

> 1. Blog
> 2. Project (Have created templates for them as well).

My questions are;

The test mail just sends the `[node: title]` like tokens. What should I add to mail the contents of the node?

Thanks

# Answer
First, the newsletter module isn't yet stable, so I am giving you a solution for the Simplenews module.

If you want to send Views in a newsletter, you want to use the Viewsfield module. It allows you to create a Views field for your Simplenews content type. Then create a single Simplenews node and add your required View (there's a dropdown available with all active Views).

Since the content of the Views might change and you want to send the newsletter on a regular basis, you also need the Simplenews Scheduler module. It allows you to send the newsletter for example once a week with the updated content of your selected view.

I did something like that some time ago and also added a documentation on drupal.org.
> 0 votes

---
Tags: emails
---


# Question
Title: Show whole taxonomy tree starting from current term
I'm trying to show taxonomy tree starting from current term. Like this when you are in taxonomy term1 page.

> -term1 (this is the term1 page where we are now)
> --term2
> --term3
> ---term4
> ----term5
> ----term6
> -----term7
> -----term8

And if we are for example term4 page then it will show starting from term4:

> ---term4
> ----term5
> ----term6
> -----term7
> -----term8

I have used Views Tree to but I have not found proper way to "filter" to show right terms when you are for example in term4 page.

All I can get is to show first child level like:

> --term1
> ---term2
> ---term3

It should show whole tree starting from current term - as deep as the tree goes.

# Answer
Take a look at Taxonomy Menu Block Module

> Taxonomy Menu Block allows you to make blocks containing unordered lists that represent the structure of your vocabularies, creating a menu out of your taxonomies (without using Drupal's menu system).
> 1 votes

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


# Question
Title: Is it possible to use Google to find Drupal with a specific version of Drupal?
Ideally it wouldn't be possible to use Google or another search engine to find many Drupal installations with e.g. Drupal core 7.31. But I'm not sure if it's not.

So I would like to know: is it in fact possible to find Drupal installations of a specific version?

# Answer
Using Google Search it might be a little difficult for you. This search phrase can give you a few websites.

For better results you need some website profiler like BuiltWith to give you the list. The closest I came across was http://trends.builtwith.com/websitelist/Drupal-7 You have a list of Drupal 7 websites here but not 7.31 in particular. They might give you the details in pro-version but I have never tried.
> 1 votes

---
Tags: security
---


# Question
Title: How to show main menu links based on user roles?
I am showing menu items and I want to show some links to Anonymous user only and some links to Authenticate user.

It it possible to accomplish this in Drupal 7? If so how?

# Answer
> 2 votes
Meet Menu Per Role Module

> This module allows you to restrict access to menu items1 based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual.

# Answer
> 2 votes
You can use the Menu item visibility module.

> This module exposes configurable and extendable visibility settings for menu links.

# Answer
> 2 votes
Also go for Custom Menu Permissions

It allows for the permission used to access any menu item on the system to be overridden.

It allows for custom permissions (see hook\_permission()) to be created through the admin interface. These permissions can be used the same as any permissions created in a module using hook\_permission() - ie in modules, templates, and in hook\_menu() callbacks.

# Answer
> 0 votes
If you don't want to install any contributed module. Create two menus one for anonymous and one for authenticated. Assign them to two blocks. (Menu Blocks).

Now give access permissions to those Blocks accordingly. One Block to anonymous and one for authenticated.

So the menu links added for them will be visible based on their role

---
Tags: 7, users
---


# Question
Title: Which megamenu supports i18n content translation?
Do you know which megamenu supports i18n content translation?

# Answer
At this time only tb\_megamenu seems to support i18n.
> 0 votes

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


# Question
Title: Limited permissions for users logged in with facebook and twitter
I would like to know if there's a way to allow people to log in into my Drupal site with limited permissions with their Facebook or Twitter account.

I have created a website which allows **authenticated users** to upload images. I have added a voting option which can be used by the authenticated users. I want to allow the people logged in with facebook or twitter to be only able to vote and not upload images.

I am using Social Login to allows users to login users with their facebook and twitter. Is there a way to set this limitation?

# Answer
> 0 votes
You could use Rules to automatically assign them specific roles, then limit permissions based on those roles.

A few ideas about how to work with rules and auto-assigning roles.

---
Tags: users, authentication-authorization
---


title: User name list in Select Option field

text:
# Question
Title: User name list in Select Option field
I am using webforms and I want to add a Select Option field with the list of all authenticate user names. And if any new user add in my site than it will add automatically in that list Is that possible? if yes than how?

# Answer
> 2 votes
You have to look into hook\_webform\_select\_options\_info.

It is quite straight-forward. You use the hook to define a new kind of select option list and register a callback. In the callback, you return the list of all users.

Assuming your module name is `webform_users_list`.

```
/**
 * Implementation of hook_webform_select_options_info.
 */
function webform_users_list_webform_select_options_info() {
  $items = array();

  $items['users_list'] = array(
    'title' => t('List of registered users'),
    'options callback' => 'webform_users_list_get_list',
    'options arguments' => array(),
  );

  return $items;
}

function webform_users_list_get_list($component, $flat, $filter, $arguments) {
  // Get list of users through a method such as EntityFieldQuery or db_select.
  return $users;
}

```

If the callback is in a different file, you need to define the `'file'` in the array in `hook_webform_select_options_info` as per regular Drupal conventions.

To use this in your webform, add a regular select option to your webform and while configuring, you will be able to select the option list as `List of registered users`.

# Answer
> 1 votes
You could use the References module. This module enables you to use the results from a view as the values for a field.

# Answer
> 1 votes
I just did something quite similar today, with using entity form module instead of webform which can have the same results.

using Entity refrence, you can get that working in like 2 minutes.

# Answer
> 0 votes
You can put this code as second function to get the list of users :

```
function webform_users_list_get_list($component, $flat, $arguments) {

  $all_users = entity_load('user');
  foreach($all_users as $value) {
    $user_list = (array)$value;
    if($user_list['uid'] > 1) {
      $user_names[$user_list['uid']] = $user_list['name'];
    }
  }

  return $user_names;
}

```

So the complete file webform\_users\_list.module will be :

```
/**
 * Implementation of hook_webform_select_options_info.
 */

function webform_users_list_webform_select_options_info() {
  $items = array();

  $items['users_list'] = array(
    'title' => t('List of registered users'),
    'options callback' => 'webform_users_list_get_list',
    'options arguments' => array(),
  );

  return $items;
}

/* Get user list and return it */

function webform_users_list_get_list($component, $flat, $arguments) {

  $all_users = entity_load('user');
  foreach($all_users as $value) {
    $user_list = (array)$value;
    if($user_list['uid'] > 1) {
      $user_names[$user_list['uid']] = $user_list['name'];
    }
  }

  return $user_names;
}

```

---
Tags: webforms, users
---


# Question
Title: How to set different logout times for roles?
I would like to define/set a log out time for different roles for my Drupal site.

Say for example if I set log out time for X role for 30 Minutes. The users under that role would be logged out in 30 Minutes from the time they logged in and also I would like to show notification to users for their remaining time for timeout.

How can I achieve that in Drupal?

# Answer
> 4 votes
We can achieve that using the Automated Logout module. combination of the Javascript Timer module.

Using the Automated Logout module we can set different timeouts for user roles and using Javascript Timer we can display remaining session time (countdown timer) for a logged in user.

Automated Logout

> This module provides a site administrator the ability to log users out after a specified time of inactivity.
>
> It is highly customizable and includes "site policies" by role to enforce logout.
>
> **Features**
>
> * Different timeouts based on role
> * Disabling of timeouts based on role
> * Permission for users to set their own timeout
> * Includes some JS mechanisms to keep uses logged in even if multiple tabs are open or if the user is working on a form for a long period
> of time.
> * Includes developer hooks to allow users to remain logged in depending on your own project specific requirements
> * Optional integration with Javascript Timer Timer

---
Tags: 7, sessions
---


# Question
Title: Allow users to uploading videos to vimeo
I am totally new at making websites using Drupal. I started on Monday (April 1st) and I've been using drupal.org and drupalize.me to start learning and building some basic stuff. There is one thing I want to do and I've been stuck for 2 days now.

I want to be allow the users of my site to upload videos which will get stored inside my database and, using the data from my database, upload it to Vimeo site and use vimeo player as the player.

This is my goal right now but I am stuck on the very first step TnT. I have the module "Media-7.x-1.3" installed on my site and tried using it to upload videos. I know this only allows me to upload videos from the admin end when you are creating a new content and you have to edit the "article" or "blog" post that contains the video file if you want to change something and doesn't allow the users of my site to upload the videos directly but I just wanted to get started on something.

So I followed the instructions and went to \- Structure -\> Content Types -\> Add content type -\> name the content type (video files) -\> save and add fields (everything else is left as default) -\> add new field (upload videos) -\> field type = file -\> widget = media file selector -\> save -\> upload destination = public files (there are no other options for me to choose) -\> save

this will bring me to manage fields page label = upload videos -\> allowed file extensions for uploaded files = mp3, mp4, wmv, jpg (i gave it bunch of random extensions so I can test it if it works or not) -\> maximum upload size = 50 MB -\> every other fields are left as default -\> save

inside manage display page upload videos format = rendered file -\> save

after all the configurations, I go to Add content -\> video files -\> title = videos -\> click on "Select media" at the bottom -\> Browse -\> select my video file I want to upload (mp4 file, 34 MB) -\> Submit and nothing happens. no error message, no video uploaded or anything. I'm just stuck in the upload overlay page and I would have to hit cancel to get out of the page.

but if I try to upload a image file (jpg file that I allowed earlier), I can see the preview of my image and gives me an option to "Select media" or "Remove media" (the upload overlay page is gone of course).

So I have no idea why it's not working for video files or what is going on. AND this is not even what I want to do...sigh...

Please help me TnT

Thanks!

# Answer
I don't believe uploading directly to Vimeo is a supported feature. I do see an unmaintained module that claims to do something similar, though: http://drupal.org/project/mm\_vimeo

I haven't looked at the code, but you could write a module to accomplish the following:

1. Use a regular file upload field for videos. Nothing fancy. Use the Media module to enable URL video embedding (as if we've copied/pasted a Vimeo URL directly).
2. Create a cron job to keep an eye on nodes created/updated of that type, making note of videos that should be uploaded to Vimeo.
3. Upload videos to Vimeo (see: http://developer.vimeo.com/apis/advanced/methods#vimeo-videos-upload)
4. Modify the Video nodes to include a Vimeo URL to embed in the player.
5. Remove the file upload, chances are it's huge and not worth retaining.

I've used a modified approach with this in the past with transcoding services in conjunction with Amazon S3 storage and Cloudfront CDN hosting. Very good combo.
> 1 votes

# Answer
I\`m actually working on this:

Use this module for vimeoapi oauth2 integration:

vimeoapi

media\_vimeo\_upload: it sends the media video upload by the user (file) to vimeo and change the drupal file to a vimeo url on the media file. This is a sandbox code but is useful for the moment.

media\_vimeo\_upload

Check that for the moment your filename should be or change the code (this will be configured by UI on future commits):

```
$fieldnames = array(
  'field_media_video',
);

```

As both modules work are in progress, help and patches are welcome!
> 1 votes

# Answer
You can check out this Vimeo Video Uploader module, Its has feature related as you expect.

> A Module for integrating Vimeo APIs with Drupal. Installing the module creates two fields in selected content type which will be used to upload Video to Vimeo. This module uses Video Embed Field for embedding video URL after video is uploaded.
> 1 votes

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


# Question
Title: Select query for get title and url of node
I need to query the database directly using php. I need to limit my query to nodes created in the current year. I know that the node table contains the date the node was created in the 'created' column and that this contains a date as a timestamp.

I am not sure how to get the current year and express it as a range of timestamps and return only nodes that were created between the two timestamps.

# Answer
> 1 votes
You don't need to make any tricks like that to compare a timestamp to the current year.

You can obtain the **year of the timestamp** by using the PHP date function:

```
date('Y', 1394010573)

```

will return

```
2014

```

You can obtain the **current year** by using the same function but without mentionning any timestamp (it will take the current date by default):

```
date('Y');

```

Knowing this, you can easily limit your query.

---
Tags: database
---


# Question
Title: Large file uploads stop immediately, 404 error
I am having a weird problem with uploading large files in the Drupal admin's file field. I have the size limit set to 500 MB. I also have the php.ini settings for upload size, post size, and memory all set to 500 MB.

When I upload a smaller file like 50 MB everything works perfectly. If I upload a larger file such as 250 MB then the upload fails immediately and I get a 404 error in the Network tab of the Chrome inspector.

The 404 error is on this URL: http://example.com/file/ajax/field\_video\_file/und/0/form-tpohUDjq\_v0b7OcNhtnQl2TaRc5UcFl9zwJQzI3mlwE

The server is running IIS 7.5.

Any ideas what could be causing this?

Thanks!

# Answer
> 0 votes
From: https://www.drupal.org/node/97193

> Drupal's limits on upload file size are determined by your server's PHP settings (as well as Drupal specified settings that can be set at Admin \> Site Configuration \> File Upload). The default values for PHP will restrict you to a maximum 2 MB upload file size.
>
> On the settings page for the upload module, Drupal calculates and displays the maximum file size that you can set based upon two PHP settings: 'post\_max\_size' and 'upload\_max\_filesize'. Since 'post\_max\_size' is the limit for all the content of your post, many people choose 'post\_max\_size' to be a multiple of 'upload\_max\_filesize' to allow multiple files to be uploaded, but this is not essential. The upload module limits the size of a single attachment to be less than either post\_max\_size, or upload\_max\_filesize, whichever is smaller. The default PHP values are 2 MB for upload\_max\_filesize, and 8 MB for post\_max\_size.
>
> Depending on your host, changing these two PHP variables can be done in a number of places with the most likely being php.ini or .htaccess (depending on your hosting situation).
>
> For example, to increase the limit on uploaded files to 10 MB:
>
> ```
> Add the below to the relevant php.ini file (recommended, if you have access). Note that for some hosts this is a system-wide setting.
>
> ```
>
> However, for hosts running PHP as a CGI script with suexec (for example) you may be able to put these directives in a php.ini file in your Drupal root directory. upload\_max\_filesize = 10M post\_max\_size = 10M Add the below to your .htaccess file in your Drupal root directory. php\_value upload\_max\_filesize 10M php\_value post\_max\_size 10M
>
> The PHP documentation states that the memory\_limit setting also affects file uploading. Generally speaking, memory\_limit should be larger than post\_max\_size. If this is an issue, see the page on how to Increase memory available to PHP (3 methods)
>
> Drupal also allows/enforces its own size limits, independently of what PHP allows. These are found in Drupal 6 at "Administer » Site configuration » File uploads" ( /admin/settings/uploads ). In Drupal 7 size limit is controlled on per-field basis. The Drupal settings cannot be larger than those permitted by PHP, but may be smaller if you haven't updated them, so remember to check there also, after updating the php.ini.

Also, make sure your permissions are set correctly from your public/private folders you've set Drupal for file handling. The folders are located at */admin/config/media/file-system*

---
Tags: 7, files
---


# Question
Title: Create images defined by image styles on node save
In Drupal 7 I wish to create several images defined by image styles when saving a node. There is only one image field, and it is just several styles of that image that I need to generate.

None of these images are displayed when viewing the node, they will be accessed through XML and Services.

I think mabye the `hook_preprocess_HOOK` and `theme_image_style` can be used as pointed out in this question: Multiple image styles. Is this correct? And if so, can anyone point me to some examples where this is done? In the link above, images are echo'ed out, but is this how it should be done when saving a node?

# Answer
> 1 votes
I ended up creating a separate content type and a theme template file that solved this specific problem I had. I will update this if I ever find a way to do this in a module or other.

EDIT:

I ended up creating a module that solves this.

**in hook\_menu:**

```
function mymodule_menu () {
  $items['node/%/generateimages'] = array (
    'title' => 'Generate images',
    'page callback' => 'mymodule_generate_images',
    'page arguments' => array(0, 1),
    'access callback' => TRUE,
  );
}

```

In the callback function:

```
function mymodule_generate_images ($arg1, $arg2) {
  $retval = '';
  $path   = drupal_lookup_path ("source", $arg1 . '/' . $arg2);
  $node   = menu_get_object ("node", 1, $path);

  drupal_set_title ('Generate images ' . $node->title);

  global $language;
  $lang = $language->language;
  $files = field_get_items ('node', $node, 'field_image');

  foreach ($files as $key => $media) :
    $url   = image_style_url ('related_thumbnail', $media['uri']);
    $thumb = theme ('image_style', array('style_name' => 'related_thumbnail', 'path' => $media['uri']));
    $retval .= $thumb;
  endforeach;

  return $retval;
}

```

After node creation, I manually have to go to thenodeurl/generateimages and images defined in the callback function is created.

I wish someone could tell me a better way to solve this :)

# Answer
> 0 votes
I had the same need so that a certain image style was available for an email digest.

I got the answer here https://drupal.stackexchange.com/a/54584/38200 making sure to add the image\_style\_load call as explained here https://drupal.stackexchange.com/a/82089/38200 to make sure the correct image style is appied.

---
Tags: 7
---


# Question
Title: How to retrieve node body from nid with an SQL query in Drupal 7?
From this question I learned that I have to look in `field_data_body` to retrieve the body of a node from a database.

`field_data_body` does not have an `nid` field though.

What query can I use to retrieve the body from an `nid`?

To clarify: I simply wanted to quickly fetch a text from a database dump without installing the dump on an actual site. So not looking for PHP here.

# Answer
> field\_data\_body does not have an nid field though.

Because a field can be attached to any entity, which may have a different primary key than nid.

If you **really** must use direct SQL, you can query the field like this

`SELECT body_value FROM field_data_body WHERE entity_type = 'node' AND entity_id = 1`

However, this bypasses several of Drupal's layers, so it's normally strongly discouraged to use direct queries.

Instead, it's better to

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('nid', 1)
;
$result = $query->execute();

$nodes = node_load_multiple(array_keys($result['node']));

foreach ($nodes as $node) {
  $bodies = field_get_items('node', $node, 'body');
  foreach ($bodies as $body) {
    var_dump($body['safe_value']);
  }
}

```

The EFQ version have several advantages

1. It's safe. You can't (easily) accidentally open injection attacks.
2. It outputs a safely escaped value, avoiding XSS attacks.
3. It works if a node has multiple values for the body field.
4. It works on sites with multiple languages.
> 7 votes

# Answer
I believe it's because `field_data_body` can be associated with entities that are not nodes, you need to look at the `entity_id` field as equivalent to the `nid` field.

If it's a node's body content you're trying to query, then I would run `db_query('SELECT body_value FROM `field_data_body` where entity_id = :nid, array(":nid" => $nid));`
> 0 votes

# Answer
In general, all entities are fieldable. Thus, the table `field_data_body` holds data for all `body` fields, regardless of being attached to a node or a comment. Hence, the column you are looking for is `entity_id` (with `entity_type = 'node'`).

On a side node, you shouldn't tamper with the database in such a way, just use

```
$node = node_load($nid);
$body = node->body['und'][0]['value'];

```

to get the body (exact code of course depends on your site setup in terms of language, etc.).
> -1 votes

---
Tags: 7, entities, database
---


# Question
Title: unlimited number of values gets really big
I have created a content type with a field inside which can take unlimited number of values. eg a city with the names of its inhabitants.

The problem is that this number can get really big (i.e. 100000).

Up to 5000 people I can edit this node with no problems (apart from the fact that it takes much time to load). But above this number I just get a white screen.

What should I do in order to be able to edit (e.g. the name of a certain inhabitant) with no problems?

My UI idea would be something like pagination (loading 100 records each time I change the page), but is this possible?

# Answer
Put the relationship the other way round, ie let every inhabitant be a separate entity that has an entity reference to a city.

Then you can still display them on a city content view by using an embedded view, such as EVA or Display Suite dynamic field, or using Panels. You can even embed it via a preprocess\_node function using view\_embed\_view, and have pagination on it.

And views will use the inverse relationship just fine.

Look at the wiki entry for Cardinality (data modeling) for more information on this principle.
> 3 votes

---
Tags: nodes, entities, paging
---


# Question
Title: How to define an intermediate admin user as the default install profile on fresh drupal 7?
When generating a new drupal site (multisite), I would like to define the default user profile as an admin user without acces to administration menu.

How can I create this new user as an install profile with default login infos, keeping at the same time the admin user?

# Answer
You need to create a new role

```
$admin_role = new stdClass();
$admin_role->name = 'myadminwithoutmenuaccess';
user_role_save($admin_role);

//This will give them all perms
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));

```

Then you just revoke administration menu

```
 user_role_revoke_permissions($admin_role->rid, array $permissions = array('administration menu'))

```

if you need to get the $rid at a later time you can do `user_role_load_by_name()`
> 1 votes

---
Tags: 7, users
---


# Question
Title: Easiest way to add color to a title field?
I have 2 fields, one is an image and the other is just a title. Now the title hovers above the image, but the problem here is that the image might clash with the font color. If the image is predominately white and the text is white, you wont be able to see it.

I was thinking of creating a new field just for the user to select white or black. Then i would create a tpl just for this article page to parse the "color" field and expose it for css styling. I feel like this is the long way to do this.

What other possible ways can this be accomplished?

# Answer
> 0 votes
Why not play with the styling? You can add text shadow or 50% dark transparent background to the text or add text outline as demoed here: http://css-tricks.com/adding-stroke-to-web-text/ All these options will give you a better contrast.

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


# Question
Title: feed import module: is it possible to have a feed importer without unique field
I'm using Commerce Kickstart 2.

The SKU field of my products is automatically generated in relation with a serial field that I've created (Serial field module). That was done with the appropriate token generated with the serial field attached to automatic SKU generation. So I want to import my products with Feed Import module without to have a unique field configured, because the SKU will be automatically generated.

Is it possible to setup a feed importer without unique field?

Sorry about my bad English.

# Answer
> 0 votes
Check out Feed Tamper module. It allows you to modify the imported data before it is saved. For example, you can specify a token as the default value for the field or add a placeholder which then you can replace when you generate SKU.

---
Tags: feeds, commerce, importing-exporting
---


# Question
Title: Which is the most performant way of overriding views field output
This question sureley can only be answered by people with some drupal experience. As I have quite different and complex views, which I need to control totally, I need to come to a design decision. Which way has the highest performance putting out view content?

1. Define the fields in the Views UI, don't output them and use them in custom text? Like described here: http://highrockmedia.com/blog/rewriting-drupal-views-output-custom-theming-css
2. Provide a views-view-field--field-machine-name-of-field.tpl, get the $row\['\_field\_data'\]\['nid'\]\['entity'\]-\>{'field\_machine\_name'} and iterate over its contents?
3. Another or better way of which I'm not aware off?

Example, of how a result could look like:

```
<div itemscope itemtype="http://schema.org/Product">
  <img itemprop="image" src="dell-30in-lcd.jpg" />
  <span itemprop="name">Dell UltraSharp 30" LCD Monitor</span>
  <div itemprop="aggregateRating"
    itemscope itemtype="http://schema.org/AggregateRating">
    <span itemprop="ratingValue">87</span>
    out of <span itemprop="bestRating">100</span>
    based on <span itemprop="ratingCount">24</span> user ratings
  </div>
  <div itemprop="offers" itemscope itemtype="http://schema.org/AggregateOffer">
    <span itemprop="lowPrice">$1250</span>
    to <span itemprop="highPrice">$1495</span>
    from <span itemprop="offerCount">8</span> sellers
  Sellers:
  <div itemprop="offers" itemscope itemtype="http://schema.org/Offer">
    <a itemprop="url" href="save-a-lot-monitors.com/dell-30.html">
     Save A Lot Monitors - $1250</a>
  </div>
  <div itemprop="offers" itemscope itemtype="http://schema.org/Offer">
    <a itemprop="url" href="jondoe-gadgets.com/dell-30.html">Jon Doe's Gadgets - $1350</a>
  </div>
</div>

```

# Answer
> 1 votes
I would go for Template based solution for the sake of maintainability and flexibility. For example, if you are using the same field in two different views, you can use a .tpl file that applies to all views that have that field. But if you depend on Views UI, you will have to configure each field in every view separately which may complicate things in the long run. Also, the fewer access to database to retrieve configuration the better.

---
Tags: views, theming, performance
---


title: Ordered list in Books navigation

text:
# Question
Title: Ordered list in Books navigation
By default the navigation in books is an unordered list:

* Vegetables
    + Carrots
    + Tomatoes
* Fruits
    + Apples

Is there any way to make it an ordered list?

1. Vegetables

1.1. Carrots

1.2. Tomatoes
2. Fruits

2.1. Apples

# Answer
It is possible manually. Suppose you have a book entitled **"Tutorial"**. inside it you have created 3 book pages entitled : **"Installing"**, **"Configuring"**, **"Running"**. When the book is dispalyed the 3 pages will be ordered starting with the most recent

To reorder the book, edit the book first and choose outline in the tabs

In that screen, click on the link **"reorder an entire book"**. The result wil be the following: Click on the link **"edit order and titles"** to access the interface where you can reorder the pages Use the + icons on the left of pages to reorder thje book. I hope this will help.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: How Generate Configure button ? (Module Page)
What hook or how do I generate the configure button in the module page?

I'm trying to have the operation button that user click on the module page to take them to the configuration page.

If someone can provide me good resource or an example I will appreciated.

Here is an example of what I'm trying to generated.

# Answer
test.info file

```
    name = configure test
    description = configure test.
    core = 7.x
    ; NEW LINE
    configure = admin/config/test

```

test.module file

```
<?php
/**
 * Implements hook_menu().
 */
function test_menu() {
  $items = array();
  $items['admin/config/test'] = array(
    'title' => 'Test',
    'description' => 'Configuration for test module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
?>

```
> 2 votes

---
Tags: 7
---


# Question
Title: How to hide header and footer from 404 page?
I create a 404 page on D7 site ( ie. mysite.com/404), which is a Basic Page. I am trying to hide the header and footer from this page. The header and footer are blocks, and they are placed in every page using Context. I tried tweaking the Context so that if Path = 404, hide the header and footer.

It works when I go to mysite.com/404. However I try to hit an alias that doesn't exist (ie. mysite.com/asdf), instead of redirecting to /404, Drupal pulls the node body of the 404 page and stay at /asdf. The rule in the Context therefore doesn't apply.

I don't want to use the Visibility control in the Block module because migrating the configuration between sites can be troublesome. How would you go about it?

# Answer
I do this by overriding the template used by the theme. In the template.php:

```
/**
 * Set path to page-error.tpl if http error is returned.
 */
function yourtheme_preprocess_page(&$vars) {
  // Set custom error template:
  $http_status = drupal_get_http_header("status");

  if (isset($http_status)) {

    switch ($http_status) {
      case "403 Forbidden":
      case "404 Not Found":
      case "500 Internal Server Error":
        $vars['theme_hook_suggestions'][] = 'page__error';
        $vars['http_status'] = "Error: " . $http_status;
        $vars['error_message'] = drupal_get_messages();
        break;
    }
  }
}

```

Then you can create page--error.tpl.php in your templates directory using whatever regions you want to display. This has added the benefit of automating error pages, so you don't have to set a path in the site config.
> 0 votes

---
Tags: 7, theming
---


title: Change View Mode on Taxonomy Tag Pages

text:
# Question
Title: Change View Mode on Taxonomy Tag Pages
I have a field that is linked to a taxonomy vocab called tags when creating my "Article" content. When I show these tags on the node page, it links to: /tags/

I can't seem to find where I can change the view mode for this /tags/ page. Currently its on teaser view mode.

# Answer
It is not clear what you want to achieve here but I'm making a guess that you want to display the full content. You can either change the "Teaser" display mode for the content type "article" or you can create a template file "taxonomy-term--tags.tpl.php" and customize it.
> 0 votes

---
Tags: 7, theming, taxonomy-terms
---


# Question
Title: Creating Preprocess function to add extra classes dependent on field value
I have a content type called "article" and I have a field called "text color" and I want to add this text color field's value as a class to either the body or content container and change the text color of the content.

* Which preprocess function should i go about using?
* Is it possible to just do an inline style using the text color field's value so i don't have to also edit my css file too?
* Or is there another elegant way of doing this without using a preprocess function?

# Answer
You can add the class to the body from the node field value in `hook_preprocess_html`

Something like:

```
/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$vars){
  // Check if on an article node page
  if($node = menu_get_object('node') && $node->type == 'article'){
    // Get field values
    if($text_color = field_get_items('node', $node, 'field_text_color')){
      // Add first text_color value to body class
      $vars['classes_array'][] = drupal_html_class(reset($text_color));
    }
  }

}

```
> 1 votes

---
Tags: theming
---


title: Filter for taxonomy term view

text:
# Question
Title: Filter for taxonomy term view
If I create a view for content types, then the filter allows me to display selected taxonomy terms on the view. Right now, I need to create a view for taxonomy terms and their related fields, but I only want to show some of them. When I select the filter of Taxonomy Term: Term, I do not get the option to select the terms I want displayed.

After I choose is one of, there is no option to choose is one of what. Is this a bug or am I doing this wrong?

# Answer
> 0 votes
After some fiddling, I managed to get it to work. Turns out sort criteria has to be defined before the terms will show up.

# Answer
> 0 votes
When you create filter "Taxonomy term: term" there's first step you are choosing "vocabulary" and "selection type" of the filter. It looks like vocabulary you have chosen has no terms.

# Answer
> 0 votes
can you filter that by writing `php` code?? I would use `views php` module, and add a `php field` that have been excluded from the view, and filtering logic goes there by values provided with this module. I myself haven't encountered any problems yet, but it's a *red* module in drupal. be aware!

# Answer
> 0 votes
I did it inserting the taxonomy term *field* first, with settings: *Exclude from display*. Then you can have it to set in the *filter criteria*.

# Answer
> 0 votes
fwiw, this happened to me after renaming a content type that was referenced by an existing view, then subsequently trying to filter that view by a tax term field on the content type I'd renamed. Same symptoms: I could filter by vocab but when asked whether I wanted to allow terms to be one of or all of, etc., there was never an opportunity to say what term(s) I wanted to filter by.

In my case, the solution was as simple as flushing the cache. :)

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


title: Hierarchical select hook form alter

text:
# Question
Title: Hierarchical select hook form alter
I have a problem with getting my `module_form_alter` to work for hierarchical select. I am running on *Drupal 7* and my content type is called *mytemp* and I'm pretty sure my form-id is *mytemp\_node\_form*. I have a taxonomy called *ICA* which my hierarchical select references to.

I get the following error when I run it:

> *Warning: Invalid argument supplied for foreach() in arjmod\_form\_alter() (line 8 of /var/www/hcms/sites/all/modules/arjmod/arjmod.module)*

I would like to have my hierarchical select appear with a fixed row height but I can't get it to work.

This is my code:

```
<?php
function mymodule_form_alter (&$form, &$form_state, $form_id){
  if($form_id == 'mytemp_node_form'){
    foreach ($form['taxonomy'] as &$vocab)
      if($vocab['#type'] == 'hierarchical_select')
        $vocab['#size'] = 10;
}} ?>

```

Please point me in the right direction.

# Answer
Looks like `$form['taxonomy']` is not an array.

There are some options for hierarchical selects maybe this is all you need:

`http://localhost/admin/config/content/hierarchical_select`
> 0 votes

# Answer
I think you need to assign taxonomy to a variable, and $vocab shouldn't be passed byref:

```
$taxonomy = $form['taxonomy'];
foreach ($taxonomy as $vocab) {...}

```
> 0 votes

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


title: Wide blog theme for drupal

text:
# Question
Title: Wide blog theme for drupal
I've been searching internet for paid or free drupal themes that is best for blogs and does have wide space for html context, not center of screen with a very tight space.

Tight space example: http://envato.tabvn.com/demo.php?theme=aqua responsive-blog for drupal

As you can see, they are simply wasting whole html area space and using only middle of it.

In fact, I want something like this: http://fumalwareanalysis.blogspot.com/p/malware-analysis-tutorials-reverse.html

I'm currently using free Best Responsive. Also it should work properly in mobile devices and ipad, so if browser is mobile device, resize it or fit the page etc. Any good example theme for drupal?

# Answer
You could modify Best Responsive theme enlarging the page width. More precisely changing #wrap ID width from 960px to something bigger, like 1200px or a percentual value like 90%.

You can edit the style.css file and change the width from:

```
#wrap {
  width: 960px;
  margin: 0 auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

```

to:

```
#wrap {
  width: 90%;
  margin: 0 auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

```

You'll have to update some other elements width like #content and #sidebar using a percentual value and fix the sidebar background image.

Anyway the theme can easily be customized.

In this way the template is still responsive but on desktop the size is more wide.

I hope this will help.

Regards.
> 0 votes

---
Tags: theming
---


title: How to upgrade only core with drush?

text:
# Question
Title: How to upgrade only core with drush?
There's a huge security leak in \<7.32. So I want to upgrade all my Drupal sites asap without too much worrying about breaking stuff.

But...

```
$ drush dl drupal-7.32
It's forbidden to download drupal core into an existing core.

```

This one works:

```
$ drush up

```

But that's not what I want now.

How can I only upgrade core to latest version?

`drush up drupal` is not sufficient on its own: (Sorry about the Dutch. You'll get the gist.)

```
$ drush up drupal
Controle of updategegevens beschikbaar zijn ...                                                            [ok]
Update information last refreshed: di, 10/14/2014 - 20:57

Update status information on all installed and enabled Drupal projects:
 Naam                               Geïnstalleer  Proposed     Status
                                    de versie     version
 Administration menu (admin_menu)   7.x-3.0-rc4   7.x-3.0-rc4  Actueel
 Drupal                             7.31          7.31         Actueel
 Chaos tools (ctools)               7.x-1.4       7.x-1.4      Actueel
 Service links (service_links)      7.x-2.2       7.x-2.2      Actueel
 Entity API (entity)                7.x-1.5       7.x-1.5      Actueel
 Google Analytics                   7.x-2.0       7.x-2.0      Actueel
 (google_analytics)
 Localization update (l10n_update)  7.x-1.0       7.x-1.0      Actueel
 Module filter (module_filter)      7.x-1.8       7.x-1.8      Actueel
 Pathauto (pathauto)                7.x-1.2       7.x-1.2      Actueel
 Redirect (redirect)                7.x-1.0-rc1   7.x-1.0-rc1  Actueel
 Token (token)                      7.x-1.5       7.x-1.5      Actueel
 Views (views)                      7.x-3.8       7.x-3.8      Actueel
 Webform (webform)                  7.x-3.20      7.x-3.21     Nieuwe versie beschikbaar

No code updates available.

```

# Answer
In this case, it looks like you need to do

```
drush rf    # pm-refresh

```

before you do

```
drush up drupal

```

This will refresh the list of available updates so Drush knows there is a new release for Drupal.
> 68 votes

# Answer
Worth mentioning is

```
$ drush up --security-only

```

> Only update modules that have security updates available.

That includes Drupal core.
> 39 votes

# Answer
```
drush up drupal

```

Appending the project you want to update makes drush to only update that project.
> 10 votes

---
Tags: drush, upgrading, security
---


# Question
Title: Drupal Error : The website encountered an unexpected error. Please try again later
I made a site locally and when I uploaded it to the hosting server, it worked fine except when I went to edit some content type. It showed this error:

```
The website encountered an unexpected error. Please try again later.

```

It was showing nothing except the above error. To get more error output, I added a few lines to my index.php file (these lines were added right after the first line):

```
error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE);

```

The error output was now showing this error:

> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away' in /home/a2682242/public\_html/includes/database/database.inc:2171 Stack trace: #0 /home/a2682242/public\_html/includes/database/database.inc(2171): PDOStatement-\>execute(Array) #1 /home/a2682242/public\_html/includes/database/database.inc(683): DatabaseStatementBase-\>execute(Array, Array) #2 /home/a2682242/public\_html/includes/database/database.inc(2350): DatabaseConnection-\>query('SELECT expire, ...', Array, Array) #3 /home/a2682242/public\_html/includes/lock.inc(167): db\_query('SELECT expire, ...', Array) #4 /home/a2682242/public\_html/includes/lock.inc(146): lock\_may\_be\_available('theme\_registry:...') #5 /home/a2682242/public\_html/includes/theme.inc(449): lock\_acquire('theme\_registry:...') #6 /home/a2682242/public\_html/includes/bootstrap.inc(446): ThemeRegistry-\>set(Array) #7 \[internal function\]: DrupalCacheArray-\>\__destruct() #8 {main} thrown in /home/a2682242/public\_html/includes/database/database.inc on line 2171

The site was working fine locally. I am not having much clue as to where the problem is. Is it some problem with the mysql server setting of my hosting provider? Or something else?

# Answer
Please try increasing your `max_allowed_packet` setting in MySQL.

Open **my.cnf** file & update `max_allowed_packet = 16M` or more
> 3 votes

---
Tags: 7, debugging
---


title: Dynamically add images to article body

text:
# Question
Title: Dynamically add images to article body
I want to add images to my article body field dynamically. Just like displaying advertisements in between the content.

Please help.

# Answer
> 1 votes
To accomplish this you need to edit the body field before rendering. There are 2 ways of doing this.

**1) Using the node template file** In case of an article the template file would be node--article.tpl.php. Here is some sample code to edit the body field and include an ad after 4 paragraphs. The node--article.tpl.php file can be edited to make the following change.Here is the quick reference to theme pages in drupal.

```
 <?php
       $array = explode("<p>", render($content['body']));
       $array_size = sizeof($array);
       if($array_size < 5 ){
         $array[array_size-1] = $array[array_size-1]. $ad;
       }else{
         $array[4] = $array[4]. $ad;
       }
       $content['body'] = implode("", $array);
       print render($content['body']);
    ?>

```

instead of rendering the body using `<?php print render($content['body']); ?>`

**2) Using the hook\_node\_view.**

This node gets invoked before the node gets rendered. You can include your logic to edit the body field based on your requirement in this hook. I am assuming you have some idea of implementing hooks in your custom module. Refer to this link for more details of this hook.

---
Tags: nodes, media, advertising
---


title: multiple profile type values

text:
# Question
Title: multiple profile type values
I have following requirement

I have user with multiple profile type like main profile, personal profile, and role profile

A role profile has fields like

```
role paid
role status
role start date
role subscription date

```

A single user can have multiple role profiles and above fields associated with each role profile

I heard about field collection per field which means we can have multiple values per field , But how can we have set of multiple profile values

Example :

```
Role name : Moderator
   role paid : yes
   role status : yes
   role start date : xxxxxx
   role subscription date : xxxxxx

Role name : testrole
   role paid : yes
   role status : no
   role start date : xxxxxx
   role subscription date : xxxxxx

```

and continues...

# Answer
I think usage of profile2 module works only with 1 -1 relationship with user to each profile type. Node or custom entity might work better for your use case. Field collection is one way of creating such entity. This article (Creating your own entities) might help, if you replace task -\> role\_licence and task\_type -\> role\_licence\_template.
> 0 votes

---
Tags: users
---


title: Customized search result

text:
# Question
Title: Customized search result
I have a content type let's say content type 'A', I am using view to show some of the field on some page, Now the problem is that pages generated by the content type are just a junk because I am not showing it to uses , only i am showing it using view page/block. Problem: I don't want to show those junk page in Search result , Plz let me know how to do it?

# Answer
You can achieve required customization by using Search configuration module.

additional things can be done with the modules are:

1. Alter the appearance of the core node search form.
2. Group content types for more meaningful searching
3. **Restrict search results by the content type. This is a role based restriction.**
4. Restrict search results from showing individual items.
5. Alter the pager limit (aka number search item results per page).
> 0 votes

# Answer
If you are still using the search from core, you should switch to for example search\_api.

That beeing sayed, if you wish to avoid installing another contrib module and are willing to implement the functionality as a part of custom module. You could set excluded node types (programmatically) and then use hook\_query\_alter to filter out those types from each search.
> 0 votes

---
Tags: nodes, search
---


# Question
Title: How do I change the ID of a copy of an exposed filter?
I'm using answers from Expose a view's filters both in a block, and in the actual view to duplicate an exposed filter as a block and make it appear in another region on every page.

I want to style both form copies a bit differently. When I started to look into the markup, I noticed that I'm getting two forms with identical IDs. Putting aside the styling, that's not good.
The code I am using is the following.

```
function MYMODULE_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'mysearch':
      $block['subject'] = t('My Search');
      $block['content'] = _MYMODULE_get_exposed_filter_form();
      break;
  }
  return $block;
}

/** Function to get the Exposed filter form **/
function _MYMODULE_get_exposed_filter_form(){
  $view = views_get_view('node_index_view');
  $view->set_display('page');
  $view->init_handlers();
  $exposed_form = $view->display_handler->get_plugin('exposed_form');
  return $exposed_form->render_exposed_form();
}

```

How do I alter the ID of the copied exposed filter block? If I use `hook_form_alter()` or `hook_form_views_exposed_form_alter()` it's going to apply the alteration to both instances.

# Answer
> 0 votes
This issue was discussed and answered in this thread, it includes a patch to fix the issue:

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

Another option is to use the module MEFIBS - More exposed forms in blocks

---
Tags: forms, views
---


# Question
Title: Poll with multilingual choices in Drupal 7
I've installed the poll module in Drupal 7 and I want to have a multilingual poll, so that the choices could be in differents languages and sum the votes of the choices. I've found these posts:

Multi language Poll output

Poll in two languages

The problem is that I'm not able to develop the solution because I don't know where I have to apply the patch since i18n module in drupal 7 doesn't include the i18n\_poll subfolder.

Thanks in advance

# Answer
> 1 votes
@chabea you are right in asking the question, the answers given in the links above do not explain how to apply the patch on D7. Here is what you need to do:

1. Under the `i18n` module created a `i18n_poll` folder.
2. Copy the patch to the above folder.
3. Run the command `patch < 1173130_i18n_poll_module_5.patch`. This creats two files `i18n_poll.info` and `i18n_poll.module` which are all you need to get the `poll aggregate` module in D7. **(I'm assuming you are using \*nix operating system and have already enabled the core poll module)** You can checkout how to apply a patch in Drupal.
4. Then go to the poll content type edit page `Structure > Content Types > Poll > Edit`. In the `publishing options - multilingual support` section check the `Enable, with translation` option.
5. Now go to the poll content type create page `Content > Add Content > Poll` and create a new poll.
6. On the newly create poll page there is a `Translate` link.
7. The translation page provides a list of language that the poll can be translated to so click on the language of your choice to start translation.

The translation workflow is quite consistent to other modules/content types. Hope this helps.

---
Tags: 7, i18n-l10n
---


# Question
Title: How to edit and delete drupal 8 custom block content?
I am not getting any option to edit my custom block body content and not able to delete also.

Please suggest me.

Thanks

# Answer
> 8 votes
Visit your block library, there's a tab on blocks page.

Block library can be found here: /admin/structure/block/block-content

---
Tags: blocks, 8
---


title: Weird usernames on my Drupal site

text:
# Question
Title: Weird usernames on my Drupal site
I help run quite a Drupal site (up to date) with around a few thousand registered users. More and more frequently I am finding users who have registered with usernames like the following (found 13 so far but I am going back through the history to see if there are anymore):

```
briantuffddwwjbsao
heiditsfacjsheiffg
vickikqskaiwlfnxcg

```

I am 99% certain these are not legit users and I have blocked their accounts for the time being. Oh and they have been authorised (clicking link in email).

When looking at the profile, in every case the first and last names are populated by the same text (the same as the first four or five characters of the username). The last part of the username is seemingly random characters (no numbers/special characters). I also note the address does usually exist (at least on gmaps) but I cant comment on the zip code/telephone being accurate (it doesn't seem so).

We do have a CAPTCHA implemented.

Has anyone else had experience with users registering on Drupal with this type of username? Are they legitimate or is it some sort of "bot"? Am I just being paranoid?

# Answer
Yes those are most likely bots; you can never be 100% sure but if you're seeing a pattern, and these users aren't contributing to the site in the same way regular users do, it's likely.

I think anyone who's ever administered a medium-large Drupal site has experienced this at one time or another. Standard tools for the arsenal include:

* Botcha

> BOTCHA is a highly configurable non-CAPTCHA spam protection framework.
* Spambot

> Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.

Both are very effective in my experience, though Spambot can get fairly intense on outgoing http requests if you get a lot of registration attempts. There are some others listed on the Spam control modules page too.
> 10 votes

# Answer
To contribute to Clive's accurate answer, you can also alternatively use the following modules:

> In short, Mollom handles incoming posts intelligently, in much the same way a human moderator decides what posts are acceptable. Therefore, Mollom enables you to allow anonymous users to post comments and other content on your site.

Mollom in ways is similar to the Spambot module as recommended by Clive.

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

Personally I find Honeypot a very neat solution as it is a small module and I find it has a respectable success rate with my web sites.
> 1 votes

# Answer
If your site is small then you can also limit the login name max length to be 10-12 characters max. This can be done by attaching a validator in hook\_form\_alter.

Moreover I guess these bots choose small sites only for attacks. I've never tested this but always want to add this.

The bots always choose such length with random words so as to be unique. So I don't think they will like to try with smaller login names.
> 0 votes

---
Tags: users
---


# Question
Title: Change the expiry time for welcome user notification message
Is there any way to change the expiry time for the welcome message sent after an administrator user created a new account for a user? By default, the login link included in the email is valid for a day, and I would like it to last seven days.

# Answer
> 0 votes
In Drupal 7: Set user\_password\_reset\_timeout variable (i.e. in settings.php, or strongarm): i.e. in `settings.php`:

```
$conf['user_password_reset_timeout'] = '604800';

```

source : https://www.drupal.org/node/246029

---
Tags: users
---


title: Block restriction

text:
# Question
Title: Block restriction
I have content with URLs in the following pattern:

> `http://example.com/subdirectory/working-site/major-event-2/event/4580/speakers`

There is a Views generated Block which I am trying to restrict to the display only for the following pattern:

> event/\*/speakers

It seems correct to me but whenever I try it, my block does not display.

This should be really simple but I wonder if anyone can help by telling me what I'm doing wrong which is preventing my block from displaying?

# Answer
If base url is this

> example.com/subdirectory/

this might help you

> working-site/major-event-2/event/\*/speakers
> 0 votes

# Answer
You were nearly there, based on your pattern the visibility settings assume that the URL will start with **event** so just change it to this:

```
*/event/*/speakers

```

That will allow anything before the event as well (given that you have the event name etc in after the base URL).

You can have any number of wildcards in the pattern and the wildcard is a `*` for visibility settings, `%` is used in functions like `hook_menu` for wildcards.
> 0 votes

---
Tags: 7, views, blocks, uri
---


title: view contents flagged by other users

text:
# Question
Title: view contents flagged by other users
I would like to make a view to select the contents flagged by a list of users.

I tried this: https://www.drupal.org/node/1191228

but it works only for one user at time. ***I would need that for multiple users***.

In the "uid" contextual filter I tried to set "Allow multiple values" in the "more" area, but when I use more than one user ("uid1, uid2" or "uid1 + uid2"), the view is not ran.

any idea?

thank you

# Answer
Try to uncheck the "require this relationship" checkbox in the relationships of your view
> -1 votes

---
Tags: 7, views, flags
---


# Question
Title: How to insert records in different table
```
function lawyer_register_form($form,&$form_submit)
{
$form = array();
$form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
);

$form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,
);

 $form['fname'] = array(
 '#title' => t('Full Name'),
 '#type' => 'textfield',
 '#size' => 20,
 '#maxlength' => 20,
);

 $form['phone_no'] = array(
 '#title' => t('phone_no'),
 '#type' => 'textfield',
 '#description' => t(''),
 '#size' => 20,
 '#maxlength' => 20,
);

$form['street_address'] = array(
'#title' => t('Street Address'),
'#type' => 'textfield',
'#size' => 50,
'#maxlength' => 100,
);

$form['county'] = array(
'#title' => t('County'),
'#type' => 'textfield',
'#autocomplete_path' => 'lawyer_register-autocomplete-engine',
'#size' => 20,
'#maxlength' => 20,
 );

$form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1,
 );

 $form['submit'] = array(
  '#value' => 'Submit',
 '#type' => 'submit'
 );
 return $form;
 }

 function lawyer_register_form_submit($form, &$form_submit)
 {
 $new_password = user_password();
 $edit = array(
  'name' => $form_submit['values']['name'],
  'pass' => $new_password,
  'mail' => $form_submit['values']['mail'],
  'init' => $form_submit['values']['mail'],
  'status' => 1,
  'access' => REQUEST_TIME,
  ');
   $edita=$edit->uid;
  db_insert('field_data_field_name')
  ->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_name_value' =>$form_submit['values']['fname'],
))->execute();
   db_insert('field_data_field_county')
->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_county_value' =>$form_submit['values']['county'],
))
->execute();
    db_insert('field_data_field_address')
->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_address_value' =>$form_submit['values']['street_address'],
))->execute();
    db_insert('field_data_field_phone_no')
->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_userphone_value' =>$form_submit['values']['phone_no'],
))->execute();

   user_save(drupal_anonymous_user(), $edit);

```

I have already created table in database. I want to insert value of

```
fname, street_address, phone_no & county

```

In those table. How is it possible?

I have searched lots of time in google but not getting right answer.

# Answer
> 1 votes
if you wants to simple insert the field values in a different table you can write insert query in form submit.

```
 function lawyer_register_form($form,&$form_state)
{
$form = array();
$form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
);

$form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,
);

 $form['fname'] = array(
 '#title' => t('Full Name'),
 '#type' => 'textfield',
 '#size' => 20,
 '#maxlength' => 20,
);

 $form['phone_no'] = array(
 '#title' => t('phone_no'),
 '#type' => 'textfield',
 '#description' => t(''),
 '#size' => 20,
 '#maxlength' => 20,
);

$form['street_address'] = array(
'#title' => t('Street Address'),
'#type' => 'textfield',
'#size' => 50,
'#maxlength' => 100,
);

$form['county'] = array(
'#title' => t('County'),
'#type' => 'textfield',
'#autocomplete_path' => 'lawyer_register-autocomplete-engine',
'#size' => 20,
'#maxlength' => 20,
 );

$form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1,
 );

 $form['submit'] = array(
  '#value' => 'Submit',
 '#type' => 'submit'
 );
 return $form;
 }

    function lawyer_register_form_submit($form, &$form_state)
         {
         $username = $form_state['values']['name'];
         $new_password = user_password();
         $edit = array(
          'name' =>  $form_state['values']['name'],
          'pass' => $new_password,
          'mail' => $form_state['values']['mail'],
          'init' =>  $form_state['values']['mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
          'field_first_fname' => array(LANGUAGE_NONE => array(array('value' =>     $form_state['values']['fname']))),
          'field_first_street_address' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['street_address']))),
          'field_first_phone_no' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['phone_no']))),
          'field_first_county' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['county']))),
          );

    user_save(NULL, $edit);
$user_id = db_query("SELECT uid FROM {users} WHERE name = :username", array(':username' => $username))->fetchField();

        $insert = db_insert('table_name') // in which table you want to insert
                  -> fields(array(
                        'uid' => $user_id,
                        'fname' => $form_state['values']['fname'],
                        'country' => $form_state['values']['country'],
                        'phone_no' => $form_state['values']['phone_no'],
                       //write other fields you want to save
                        ))->execute();
                }

```

# Answer
> 0 votes
```
 $user = user_load(1);
    or
 $user = user_load(array('uid' => '1'));
echo '<pre>';
print_r($user);
die();

```

check the fields then save

i think this much code in enough to save fields.

```
function lawyer_register_form_submit($form, &$form_state)
             {
             $username = $form_state['values']['name'];
             $new_password = user_password();
             $edit = array(
              'name' => $form_state['values']['name'],
              'pass' => $new_password,
              'mail' => $form_state['values']['mail'],
              'init' => $form_state['values']['mail'],
              'status' => 1,
              'access' => REQUEST_TIME,
              'field_first_fname' => array(LANGUAGE_NONE => array(array('value' =>    $form_state['values']['fname']))),
              'field_first_street_address' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['street_address']))),
              'field_first_phone_no' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['phone_no']))),
              'field_first_county' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['county']))),
              );

        user_save(NULL, $edit);
    }

```

---
Tags: users
---


# Question
Title: Linked images from the Media module in WYSIWYG having A tags stripped when rendered to template
I am using the WYSIWYG module to load TinyMCE 4.x, I am then uploading an image via the Media button in the toolbar of TinyMCE finally I am using LinkIt to link the image to a location.

All of this is fine inside the WYSIWYG editor, but once it is published and viewed on the page the wrapping `<a>` tag is stripped.

So in the editor if I view the source I see:

```
<a href="/my-exciting-page/index.html">
    [[{"fid":"7","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"","field_file_image_title_text[und][0][value]":""},"type":"media","link_text":null,"attributes":{"height":376,"width":640,"class":"media-element file-default"}}]]
</a>

```

However once this is rendered to the template I see simply:

```
<img height="376" width="640" class="media-element file-default" typeof="foaf:Image" src="http://example.org/sites/default/files/miscl.jpg" alt="" />

```

If I then edit this piece of content again and view the source of the WYSIWYG editor the `<a>` tag is definitely still wrapped around the Media module's little string of JSON.

In a bid to prevent this from happening I changed the Wysiwyg Profiles and Text Profiles so that they don't remove broken tags or attempt to clean up an HTML or introduce any of their own HTML. Unfortunately this has had no effect.

Is there some way that Media/Drupal/WYSIWYG/LinkIt can be setup so that it will allow images to be linked? I have been unable to find a relevant issue or patch floating about out there on the web either.

# Answer
> 2 votes
I posted this as an issue on the media\_wysiwyg module bug tracker over at https://www.drupal.org/node/2357993 and have been working my way through it since. Here is the best result I have managed to achieve so far copied from my responses to that issue.

---

This issue is mostly caused by the file\_entity module. To work round this I have restricted the view modes available to media\_wysiwyg in /admin/config/media/wysiwyg-view-mode. I have set images to only allow the WYSIWYG view mode like so:

I have then created an override template for the file entity called `file--image--wysiwyg.tpl.php` (see https://www.drupal.org/node/1793548) and I have the following code in it:

```
<?php

hide($content['links']);
print render($content);

```

This has now removed all the annoying links, headers and wrapping `<div>`s from the output EXCEPT for the media\_wysiwyg wrapping  mentioned in comment #4.

As this is just one wrapping `<div>` and the page is HTML this now no longer breaks the link, but it would still be preferable to be able to remove this annoying wrapping `<div>`.

---
Tags: media, wysiwyg, navigation
---


# Question
Title: How do I get a hold of the session object in my form handler?
I have build a form in D8 and on submit I want to save the form values into a session, so that I can access them 3, 4,.... page requests later. In D7 I just used

```
$_SESSION['key'] = $value

```

I have a feeling, in D8 and symfony, this is (very) bad practice. How should I solve this? At the moment I'm using the following chunk of code, but I don't know if this is the correct way:

```
$session = new Session();
$session->set('name', 'value');

$name = $session->get('name');

```

# Answer
The conversion to the Symfony session component is not yet complete, therefore you still have to access the session using the superglobal.

Follow https://www.drupal.org/node/1858196 and its sub-issues, if you like to stay up to date regarding this issue.
> 1 votes

---
Tags: 8, sessions
---


title: themeing os user edit profile page

text:
# Question
Title: themeing os user edit profile page
I am doing theming of user edit profile page

Now i have three fields here

Password, currentpassword, confirm password

What are their field items

i have tried

```
    <?php print render($user_profile['account']['pass']['pass1']); ?>
<?php print render($user_profile['account']['pass']['pass2']);

```

Which is not working

Also i am not sure about third filed

Anybody can tell me

Thanks

# Answer
> 1 votes
You should use:

```
<?php print render($user_profile['account']['pass']); ?>

```

The password field is only split into 2 in a `#process` function, and you can't access the separate fields before the element is rendered. To do that you would need to provide a `#theme` property for the element itself, and write a function/template that returns the desired markup.

---
Tags: 7, theming
---


# Question
Title: Menu block makes parent menu item active when maximum levels not cover the linked node
In Drupal 7, a menu block can specify maximum levels. If the maximum levels is not enough to cover all menu items linked node, when in the not-covered menu items linked node, could menu be active at their parent menu item?

For example, a menu has 3 levels, and specify maximum levels = 2, when at level 3 menu item linked node, could open its parent menu item in level 2?

Have a menu like this: M1 M11 M111 M112 - link node PageM112 M12 M121 M2

If maximum levels = unlimites At PageM112 node page, the menu will be like this. M1 M11 M111 M112 - linking to PageM112 M12 M2

If maximum levels = 2, going to PageM112 node page, the menu will closed, like this. M1 M2 M3

In this situation, could the menu be active at its parent menu item, M11, with the menu expanded like this? M1 M11 - active M12 M2

# Answer
> 0 votes
If I understand correctly you need the Menu Position module. Using this module you can keep Parent Menu item active at any level of it's sub items.

> This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

---
Tags: navigation
---


# Question
Title: how to make radio buttons be one under the other on drupal contact form
by default the radio buttons on my drupal contact form come out next to each other and the title is very far from the actual button.

with CSS alone it doesnt work. I seem to need to be able to edit the html which I cant do since its a drupal form. https://stackoverflow.com/questions/26432418/how-to-line-up-radio-buttons-and-text/26432623#26432623

Thanks

# Answer
add this to each of the select button wrapper `display: block;` also it's not a drupal issue, you should ask these kind of question on stackoverflow
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: How do i use a template file for my content type?
quite new to drupal here so forgive me if things seems evident for you.
i'm building onto an already existing site in drupal 7. the site is a onepager frontpage and from the frontpage there are links to various content types.
now i created a new content type named article.
when i link to such an article from the frontpage i (arrive at an article and) cannot go back to the frontpage through the menu anymore, while it does work with the other content types. I have searched and searched and made sure every setting is the same as the other content types but the links just don't work (they do nothing).
I did see in the templates folder that there are template files for each content type except the one i made. I'm wondering if that is the problem? If so, i don't know what exactly to do to keep it working though. I duplicated a template file and renamed it after node-article.tpl.php, but i guess it doesn't suffice.
can anyone assist?

Thx

# Answer
```
function THEME_preprocess_node(&$variables) {
  print_r($variables['theme_hook_suggestions']);
}

```

put this code into you template.php this will give you the suggestions to make your tpl file.

And for your answer you just can print anything in you page.tpl.php file it prints then you just have to change in your page.tpl.php file
> 0 votes

# Answer
just for the record, i found the problem. Apparently i needed to tell the main.js to check on the current page if it contained a certain string. If it didn't it could go back to the frontpage. I just needed to add that bit of code for that content type: `if(window.location.href.indexOf("customercase") == -1 && window.location.href.indexOf("jobs") == -1 && window.location.href.indexOf("article") == -1)`
> 0 votes

---
Tags: routes, nodes
---


# Question
Title: Views conditional referenced field depending on user taxonomy term
I have a Content-type that an admin can assign it's nodes to other users, and users are separated by their taxonomy term.

I'm using Entity Reference field to reference the user and overriding the output of it using views to reduce the user list to my preference.

This is how user referencing works:

* Each user has a taxonomy term (e.g. Editor, Moderator, BadAss, UberSuperEditor, etc...)
* Each term parents more than 100 of users.

I want the Admin to be able to filter the output of users based on their taxonomy before selecting and assigning the node to them.

I want to make a view and make a conditional relation based on the "Term" selected then show the related users of that term.

# Answer
I believe your explanation is describing the Reference Field Option Limit module:

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.
>
> This is best illustrated by examples:
>
> Example 1: countries and cities Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
>
> With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
>
> Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.

Give it a try and let me know how it works. The module currently supports Taxonomy terms and Entity Reference Widgets.
> 1 votes

---
Tags: views, taxonomy-terms, entities, users
---


# Question
Title: How can I remove old polls/results in Drupal 7?
How can I remove the links to old polls and results in Drupal 7? I unset view results for anonymous users, but they still can view results. I'd like to remove the link to old polls and poll results in template. Is it possible to do it? if the answer is yes, which code should I add to template.php to remove those links?

# Answer
You can remove the links by either copying the poll-results--block-tpl.php template file to you theme and removing the line that prints `$links` or with `template_preprocess_poll_results(&$vars)` in your template.php file in your theme and removing the line that sets the links variable.

**poll-results--block.tpl.php**

```
<div class="poll">
  <div class="title"><?php print $title ?></div>
  <?php print $results ?>
  <div class="total">
    <?php print t('Total votes: @votes', array('@votes' => $votes)); ?>
  </div>
</div>

```

**template\_preprocess\_poll\_results(&$vars)**

```
function template_preprocess_poll_results(&$variables) {
  if (isset($variables['vote']) && $variables['vote'] > -1 && user_access('cancel own vote')) {
    $elements = drupal_get_form('poll_cancel_form', $variables['nid']);
    $variables['cancel_form'] = drupal_render($elements);
  }
  $variables['title'] = check_plain($variables['raw_title']);

  if ($variables['block']) {
    $variables['theme_hook_suggestions'][] = 'poll_results__block';
  }
}

```
> 1 votes

# Answer
Other way to do it will be using hook\_block\_view\_MODULE\_DELTA\_alter()

```
function THEME_block_view_poll_recent_alter(&$data, $block) {
  unset($data['content']['links']);
}

```
> 0 votes

---
Tags: 7, theming, polls
---


# Question
Title: How to add css class to these form fields?
I wan to be able to add certain css class to all the text fields in my content edit forms. here is a picture of what i can see using Devel:

Those arrays under the "Und" are for the fields I want to add the class. I have tried to do this with the following:

```
function iclub_form_article_node_form_alter (&$form, &$form_state) {
dpm($form);
$form['field_body']['und']['0']['#attributes']['class'][] ='addRecactor';

foreach ($form['field_paragraph']['und'] as $i) {
    if (is_numeric($i)) {
        echo $i .'</br>';
        $form['field_paragraph']['und'][$i]['field_myparagraph']['und']['0']['#attributes']['class'][] ='addRecactor';
        foreach ($form['field_paragraph']['und'][$i]['field_myparagraph']['und'] as $y) {
            if (is_numeric($y)){
                $form['field_paragraph']['und'][$i]['field_myparagraph']['und'][$y]['#attributes']['class'][] ='addRecactor';
            }
        }
    }
}

```

but this does not work for all the fields and I think it is not the solution as it is not robust.

How may I be able to add the class to these fields?

# Answer
You should write a statement that first check the form element type then add class attrubutes to it, something like //in form\_alter

```
foreach($form as $form_elem){
if($form-elem['#type']=='textfield'){
    $form[$form_elem]['#attributes']['class'][] = 'myclass';
   }
}

```

(this is not the exact solution,I just want give you idea)

another way is using `hook_preprocess_field`

and the final and easy way is using js to add class, because drupal set default class for his textfields,you just need one line jquery code to add you

```
   $('.form-text').addClass('myclass');

```

if you don't want this js not load in all page, I suggest you add your js with `drupal_add_js` conditionally in `hook_form_alter`, it means that

```
    //in hook_form_alter
     $des_forms=array('node_add_page','node_add_prodcut');
    if(in_array($from_id,$des_forms)){
    drupal_add_js('your js'); //you also add it inline,but I suggest you put it in js and add it as file
}

```

**again I tell you because I have no time in this moment I just suggest you some solution idea, I hope could help you**
> 1 votes

# Answer
```
$form['name']['#attributes']['class'] = array('class' => 'formInput formInputB');

```

Try this
> 0 votes

---
Tags: theming, forms, nodes
---


title: Boost not caching non-latin urls

text:
# Question
Title: Boost not caching non-latin urls
I have set clean urls and Boost work great with latin urls like www.mysite.com/yes-this-works.

But when the url have non-latin words like www.mysite.com/μπου-χου this fails.

Any way to solve this?

From my Plesk i see the page name correct but from filezilla the greek characters show ÎµÏÎ¹ÎºÎ¿Î¹Î½ÏÎ½Î¯Î±\_.html like this.

Drupal 7

# Answer
I suspect your host is not using UTF-8 for their filesystem (rather rare these days, for example, in the early 2000, I've seen hosts using ISO-8857-7 or CP-1253 encodings for their files, because that's what Microsoft Windows did). Alternatively, Plesk or FileZilla is not using UTF-8, but that would only be a problem displaying the file names and Boost should work.

If it is because of the filesystem of your host, you could try to forward-port this old patch from 6.x-1.x which would convert with iconv the filename before saving it to disk: https://www.drupal.org/node/797136

To detect the encoding used on the filesystem, type the command "locale". It should display:

```
LANG=en_US.utf8

```

If it display anything else than utf8, such as iso8859-xx or cp-xxxx, that would probably be the source of the problem (and will require patching Boost).

Boost does store on disk the filename unescaped, e.g. it stores it in unicode, not by escaping the characters (ex: %CE%BC%CF%80%CE%BF%CF%85).

Here is a test using Greek, Cyrillic and Latin accents: https://www.bidon.ca/fr/μπου-χου-добър-ден-éàĉç
> 1 votes

---
Tags: caching
---


# Question
Title: How to configure boost for multisite configuration
I installed the Boost module in my site. The site is running on multisite configuration having subdomains like

http://site1.example.com

http://site2.example.com

http://site3.example.com

http://site4.example.com

After enabling the Boost module in all subdomains. And also edited the .htaccess rule generated for a subdomain.

in the document root www.example.com/public\_html/cache/normal i can see 4 directories and relevant cached pages for each sub domains inside these directories site1.example.com site2.example.com site3.example.com site4.example.com

But cannot see the boost comment at the end of page in any subdomain. In short I would say "Boost module is not working". Am I doing right boost configuration for multisite configuration. Actually I don't know what extra stuffs is needed for boost to work in multisite configuration

here is my .htaccess generated rule for each subdomain placed in .htaccess file in root folder

```
  ### BOOST START ###

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTPS} on [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=3]

  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html,E=no-gzip:1]

  # NORMAL
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

  ### BOOST END ###

```

# Answer
Boost works out of the box with multi-site. If your cache files are being generated (they appear in /cache/normal/site1.example.org/), but not served (boost comment in the footer of the page, or X-Cached-By in the HTTP headers), then there is an issue with your .htaccess configuration.

You can debug your htaccess rules by enabling the rewrite log:

```
RewriteLog "/tmp/rewrite.log"
RewriteLogLevel 2

```

This can generate a lot of logs, use with great care in production.

Also check this post on how to debug htaccess rules:
https://stackoverflow.com/questions/9153262/tips-for-debugging-htaccess-rewrite-rules
> 2 votes

---
Tags: caching
---


# Question
Title: Should a site be in maintenance mode when running the Drush Up command?
**I'm not asking if I can update my website with Drush. I'm not asking if Drush can make it in maintenance mode.**

My question is ... if I'm using the command `drush up` to update my Drupal core or a module is the best practice to put my website on maintenance mode or does not matter?

In the past, I update all my modules without putting my website in maintenance mode, and so far I have not any problems, but I'm looking for the best practice.

BTW, I already test my Drupal core update in a Dev environment, and everything is working fine.

# Answer
The first bit of advice here is to always run `drush up` on a dev or staging site first, before running it on a production site. Sometimes, due to bugs or incompatibilities, upgrades can break a previously-working site. It is therefore always best to test your upgrade before bringing it live. After testing, it is also best if you move the exact files that you tested from dev to live rather than run `drush up` again. You never know, someone might publish a new release while you are testing!

When you run `drush up` on your test site, you will notice at the end that Drush will report either "No database updates", or it will run an updatedb, and you will see a report on the database changes that you made.

If there are no database updates required, then generally speaking, it is safe to update your code without putting your site in maintenance mode. Note, however, that there is a small risk that a web request might be processed when only some of the files in your site have been upgraded. Since it only takes a small amount of time to `git pull` or rsync your files, this is only likely to be a problem if your site gets a lot of traffic. If you are concerned about this, you could put your site into maintenance mode, or better yet, put up an 'in progress' page by adjusting your web server's configuration.

If database updates are required, it is a good idea to put your site into maintenance mode before updating it. After copying the files to your production system, run `drush updatedb` to run the database updates. When database updates are required, it is common for them to do operations such as add new columns or tables to your database. The new code in core or your contrib modules may assume these schema changes have been made, and may crash if run prior to the completion of the database update. `drush updatedb` can take a little while to run, so it is more likely that you might serve a web request before it finishes.

Note that if there ever is a problem, it would only be observed by a small number of clients, and would be fixed with a simple page refresh in the browser. Since you are probably watching your updatedb run, you would probably never see these failures yourself. It is best to keep your site clean from transient failures, though, so maintenance mode is the safer option.

It is a good idea to script the update operation, so that it will run smoothly and easily every time. See drush\_deploy and upgradepath for two example projects that do this.
> 9 votes

---
Tags: drush, updating, maintenance-mode
---


# Question
Title: Drop-down select instead of selection box in custom field widget
I am creating a custom field for phone numbers. The field creates a phone record that contains the type of phone contact (work, home, etc), as well as the number and an extension... much like Apple's "Contacts" app.

The problem I am having is for the phone type drop-down list. Instead of showing a nice drop-down select list like this example of a publishing status...

I end up with a selection box like this...

Here is what my hook\_field\_widget\_info() looks like...

```
/**
 * Implements hook_field_widget_form().
 */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $element['label'] = array(
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(
      t('home'),
      t('work'),
      t('main'),
      t('mobile'),
      t('other'),
    )),
    '#size' => 12,
    '#default_value' => isset($items[$delta]['label']) ? $items[$delta]['label'] : 'home',
  );

  $element['number'] = array(
    '#type' => 'textfield',
    '#title' => t('Number'),
    '#size' => 16,
    '#default_value' => isset($items[$delta]['number']) ? $items[$delta]['number'] : '',
  );

  $element['ext'] = array(
    '#type' => 'textfield',
    '#field_prefix' => t('ext'),
    '#size' => 6,
    '#default_value' => isset($items[$delta]['ext']) ? $items[$delta]['ext'] : '',
  );

  $element['primary'] = array(
    '#type' => 'ckeckbox',
    '#default_value' => isset($items[$delta]['primary']) ? $items[$delta]['primary'] : 0,
    '#return_value' => 1,
  );

  return $element;
}

```

I can see how the selection box style select element can be useful for multiple selects, but this is just a single select. I'd like to see a drop-down element. I must be missing something here, but I haven't figured out what it could be. Any ideas?

# Answer
Okay, I figured it out and it was much easier than I thought... It's the "size" attribute. I deleted the size attribute, ('#size' =\> 12,), and I have a drop-down select list. I suppose it just came to posting the question here for me to figure it out on my own. :P
> 1 votes

---
Tags: entities
---