# Question
Title: Customizing the node create form using a template file
I have created a template file for my content type, but I don't know how to get form design in that page.

My content type name is wallpaper, and I created the *page--node--add--wallpaper.tpl.php* template file. How do I access the node title, or the node body, in the template file?

# Answer
If you want to design the form then use `hook_form_alter` you will get form `array`. If you want to design the node page then user `node--content_type.tpl.php`.
> 1 votes

# Answer
You need to create custom module

First, alter the original form

```
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'node_wallpaper_form') {
    $form['#theme'] = 'your_theme_name';
  }
}

function YOURMODULENAME_theme() {
  return array(
    'your_theme_name' => array(
      'variables' => array('form' => NULL),
      'template' => 'template_file_name',
    ),
  );
}

```

In the template\_file\_name.tpl.php put fields :

```
print drupal_render($form['field_name']);

//Drupal needs to render form_id, form token etc as well so also put this:
print drupal_render_children($form);

```
> 0 votes

# Answer
`node.tpl.php` is the base node template.

If you look at the source code you can find all variables to render values in that `.tpl` file.

Available variables:

* **$title**: the (sanitized) title of the node.
* **$content**: An array of node items. Use render($content) to print them all, or print a subset such as render($content\['field\_example'\]). Use hide($content\['field\_example'\]) to temporarily suppress the printing of a given element.
* **$user\_picture**: The node author's picture from user-picture.tpl.php.
* **$date**: Formatted creation date. Preprocess functions can reformat it by calling format\_date() with the desired parameters on the $created variable.
* **$name**: Themed username of node author output from theme\_username().
* **$node\_url**: Direct URL of the current node.
* **$display\_submitted**: Whether submission information should be displayed.
* **$submitted**: Submission information created from $name and $date during template\_preprocess\_node().
* **$classes**: String of classes that can be used to style contextually through CSS. It can be manipulated through the variable $classes\_array from preprocess functions. The default values can be one or more of the following:
    + **node**: The current template type; for example, "theming hook".
    + **node-\[type\]**: The current node type. For example, if the node is a "Blog entry" it would result in "node-blog". Note that the machine name will often be in a short form of the human readable label.
    + **node-teaser**: Nodes in teaser form.
    + **node-preview**: Nodes in preview mode.

The following are controlled through the node publishing options.

+ **node-promoted**: Nodes promoted to the front page.
    + **node-sticky**: Nodes ordered above other non-sticky nodes in teaser listings.
    + **node-unpublished**: Unpublished nodes visible only to administrators.
* **$title\_prefix (array)**: An array containing additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.
* **$title\_suffix (array)**: An array containing additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

Other variables:

* **$node**: Full node object. Contains data that may not be safe.
* **$type**: Node type; for example, story, page, blog, etc.
* **$comment\_count**: Number of comments attached to the node.
* **$uid**: User ID of the node author.
* **$created**: Time the node was published formatted in Unix timestamp.
* **$classes\_array**: Array of html class attribute values. It is flattened into a string within the variable $classes.
* **$zebra**: Outputs either "even" or "odd". Useful for zebra striping in teaser listings.
* **$id**: Position of the node. Increments each time it's output.
> -1 votes

---
Tags: theming, nodes
---


title: Drupal Newbie - Upgrade Questions

text:
# Question
Title: Drupal Newbie - Upgrade Questions
I am a Drupal newcomer and have been tasked with updating a Drupal site.

The currently installed version is 7.2.1

I have taken a full backup of both SQL and files so I am safe if anything goes wrong.

My question is the upgrade for Drupal a manual one, as in, do I have to download the update and FTP it over? I am used to Wordpress being a one-click affair!

Also, is there anything I should be aware of?

# Answer
Yes, the update is manual. (As someone new to Drupal, you may not know about the command line tool drush, which is as close as we get to being a one-click affair. Drush is awesome, and once you get more familiar with Drupal, you should learn it. It makes your work much more efficient.)

Re the previous answer, 'Download these updates' only works for contributed modules and not for core.

The instructions on drupal.org are excellent. But before you start, here are a couple of pieces of useful information.

* Do not get confused by the instructions at the top of the page sending you to upGRADE instructions. An upGRADE means moving from one version of Drupal to another, e.g., Drupal 6 to Drupal 7, and is a much bigger deal. An upDATE moves you up by minor versions, e.g., Drupal 7.2.1 to 7.28.
* Because you are new to Drupal, it would probably be a good idea to make sure the previous developer did not make the classic error of putting contributed modules and themes in with core modules. When you do the update you will delete all files EXCEPT \[drupal root\]/sites, which is where contributed modules, and site-specific files live. On your site, go to admin/reports/updates/list. Open another window in whatever file browser you use, and look at the Drupal file structure. The list of modules in the update list should match up to folders in \[drupal root\]/sites/all/modules. If instead you find those folders in \[drupal root\]/modules, you have bigger problems than can be answered here. (Same goes for themes.)
* If you have a development and/or staging site in addition to the live site, do the updates there first. If you don't have non-live sites, you should create them. You can do updates on a live site, but it's much preferable to test them first.

Sorry, long answer. There's a lot more good stuff on drupal.org, but it can be hard to find. I usually use Google to search drupal.org.
> 1 votes

# Answer
You can use Update manager module (enable it on *admin/modules*) and then go to *admin/modules/update* to see what needs to be updated and then get it automatically updated with 'Download these updates' button (after ticking the checkboxes for modules/core that you desire to update).

As a rule of thumb, if your site is not extensively complicated or it does not rely heavily on some version-specific code, you should be safe to update.
> 0 votes

---
Tags: updating, upgrading
---


title: Sending a single email from a view

text:
# Question
Title: Sending a single email from a view
I have a view where each page is a contract. My client wants a button on the page that says "Send me more information." The button will send two emails, one to the customer saying "We'll get back to you" and one to my client. My client's email needs to contain several fields from the view. (User email and name and node title at least.)

I've looked at various ways to do this, and none are quite right.

* Views Send opens a message form. I want the customer to do nothing more than click the button.
* Webform would be good but I don't know how to pass the data from the view into a hidden field on the form.
* Rules would work but I can't figure out what the event would be to trigger sending the emails.

I am an experienced site builder but really know zip about PHP, so I can't make a custom module.

Does anyone have any good ideas for what seems like a simple thing to do? Am I missing something obvious?

# Answer
First thought that comes to mind:

I presume you have your view setup with an argument to create the different pages. Something like `/productinformation/%`

You could setup a second views display with an extended URL like `/productinformation/%/senddetails`

You can now make a couple of rules, whenever someone accesses `/productinformation/%/senddetails` you send the emails and redirect them back to `/productinformation/%`

When you send emails using rules you have access to tokens. This should give you access to things like the User Email or Page title. This is the part I'm not sure about, I don't know if you can get all the information you require through these tokens. Good luck!
> 0 votes

---
Tags: views, rules, webforms, emails
---


# Question
Title: How to have multiple instances of a field collection on single content type?
I have a content type where I would like to use a field collection to group some fields (radio buttons and textfield). I need many of these on the content type with only the label being different.

I was hoping to make one field collection entity and have multiple instances of it on the one content type, but field collection does not support this.

Basically, I need many instances of a group of fields on a single content type. How can I accomplish this?

# Answer
> 1 votes
After trying a few different things this is what I ended up doing.

I set the field collection field on my node to allow 50. I used a form alter to put more numbers in the select box.

I then added my needed fields to this field collection including a dummy field with a default value so all the 50 rows are saved and displayed every time. (this dummy field is never displayed)

I then themed the field collection field table and mapped each row to a label in an array.

# Answer
> 1 votes
There is an issue for that: https://drupal.org/node/1569970
You can try and help that issue get moving.

Or you can give up and create several Field Collection bundles. If you go down that route, you could possibly use Bundle Copy, but it doesn't currently support Field Collections. Luckily, there is an issue for that: https://drupal.org/node/1589118
And that issue has some patches and some testing, so I'd probably just try it.

---
Tags: 7, entities
---


# Question
Title: Why does webform module uses $node->webform as a property?
Why does webform module uses $node-\>webform as a property instead of $node-\>type\['webform'\] or something like that?

# Answer
> 1 votes
because webform is not integrated to drupal entity concept

check entity form module that is integrated with drupal entity https://drupal.org/project/entityform

---
Tags: nodes, webforms
---


# Question
Title: Is it possible to protect content types with captcha?
I would like to protect some pages of my Drupal 7 website with a riddler captcha, to protect those pages from all who can not solve the riddle, but don't make it necessary to login to see the content. As I am using Organic Groups it would be the best, to protect all content that is part of a group by such a riddle. To make my goals more clear and avoid misunderstandings:

* I want to protect pages in a soft way against unauthorized access.
* I don't want the audience to login to my side, because for my use case that would be too complicated.
* I don't need high security.

Does anybody know how to do that, what would be the most elegant way. Does anybody have a better idea?

# Answer
you may create custom module https://stackoverflow.com/questions/3434134/restrict-node-with-captcha

combine hook\_node\_view\_alter with http://drupalcontrib.org/api/drupal/contributions!captcha!captcha\_api.txt/7
> 0 votes

---
Tags: 7, organic-groups, users, captcha
---


title: Drupal 7 Jumplist using Views Module

text:
# Question
Title: Drupal 7 Jumplist using Views Module
I am trying to set up a `jumplist` on my site that has a list of `taxonomy` terms from a list I've called Categories. I have the `jumplist` displaying correctly but when I select a term from the list and navigate to it I get this message:

```
Page Not Found
The requested page "/cms/ca2/Video%20Editing" could not be found.

```

I would like that it would bring up a list of all the nodes that I have assigned to the category I've selected from the list but can't seem to figure out how to do it.

Could anyone help me with this issue.

Many thanks.

My site I am trying to implement this on. You can see the jumplist on the right sidebar with the title Categories List

http://jciadt.com/cms/ca2/

# Answer
try to use rewrite field option on your Views to rewrite content link as absolute URL or try using node/\[nid\] format on the href
> 0 votes

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


title: Drupal VIEWS API?

text:
# Question
Title: Drupal VIEWS API?
I know there is the VIEWS API -- but what I am looking for is a method I can call passing the view by machine name and receive the raw PHP array (not rendered) -- where is the obvious function? :)

# Answer
That should be `views_get_view_result` which takes the view machine name and display id as arguments and returns the response as an array containing the result object
> 1 votes

---
Tags: views
---


# Question
Title: How do I link a thumbnail image to its content programatically?
I have the following php code in a rule. It displays a picture that was uploaded by a user.

How do I link the thumbnail to the content?

```
$imgpath = file_load(($node->field_image['und'][0]['fid']))->uri;
print theme_image_style(array( 'path' => $imgpath, 'style_name' => 'thumbnail'));

```

# Answer
> 4 votes
Something like this...

```
$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

```

---
Tags: media
---


title: Multiple Fields For Node Data

text:
# Question
Title: Multiple Fields For Node Data
I am creating a content type for events. One of the parts of data I want to have is for speakers. With the speakers I want to have their name, image, company, and bio. I want to be able to more than one speaker similar to a multivalue text field where you can simply click add another item.

Can this be done in Drupal 7, and if so how?

# Answer
You can use the Field collection module which lets you the possibility the regroup multiple fields (name, image, company, bio) into one collection (speaker). On that collection, you can put the `number of values` to unlimited.
> 1 votes

# Answer
Yes you can. in event content type create a text field *speaker* and in the setting if this field there is a drop down list which specifies number of values, set it to unlimited. in this way you can have any number of speakers

you are not done yet! create another content type called speaker and add any field that speakers may have.

create a view of event content type and set relationship between speaker field and speaker content type.
> 0 votes

# Answer
1. Create a content type for speakers and add your fields (name, image, company etc).
2. In your events content type add an entityreference field with unlimited values to reference the "speaker" node-type entity.

Having the "speakers" as a node type will allow you to do things such as:

* have a speaker's profile page that lists all events they have participated in.
* Have a list of speakers on the events page with links to their full profile pages so that users can learn more about them.

The above can be done by creating a block via views and adding it to a region or, by creating a views attachment field which is displayed as a normal field on the node-type of your choice (EVA: Entity Views Attachment). Since you'll be using views, the data you display is up to you i.e. name, photo, link to profile etc.
> 0 votes

# Answer
In response to this question, Mike Vranckx is technically correct. But other users surfing in here wondering how to get 'Add Additional Item' functionality to a field do not necessarily need a Field Collection to accomplish that.

If you only want to have multiple, dynamic instances of one field...

From the 'Manage Fields' area of the content-type, find the field you want to have multiple instances of and click 'Edit'. At the bottom of that following page, you will see 'Number of Values'. Set it to 'unlimited' in the drop-down and, magically, the 'Add Additional Items' will appear under that field when content editors add nodes with this content-type.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Some fields are not indexing in apache solr index
I have taxonomy term and date type fields in content type. But they are not displaying in facets list in admin section.

While accessing this url `http://localhost:8983/solr/select` I noted that these fields are not indexing to the apache solr search index.

There is one other taxonomy term reference field and that field is indexing properly.

Any one who have some idea about this?

# Answer
I had the `search_index` view mode was enabled and I have only enabled that one term reference field in `search_index` therefore only that field was indexing and not others.

So I enabled other fields `search_index` which I wanted to be indexed and it solve my problem.

So if you have enabled this `search_index` view mode for your content type then only those will be indexed which are enabled in this view mode.
> 0 votes

---
Tags: 7, search
---


# Question
Title: How to convert URL aliases back to node ID
I wonder how to convert a URL path back to it's own node (node/nid). I wish to get the original node ID from a given path. e.g.

path = "news/my-news"

..and trace it back to get it's own original URL, e.g. 65. Please advise. Thanks.

# Answer
GokulNK has already given the answer to use `drupal_get_normal_path()`. If you are working on any path alias that is different than the current path, use that.

If you want to get the non-aliased path of the **current page/path**, simply use `$_GET['q']`. Drupal path aliases are mod\_rewrites but you still can find the internal path from `$_GET['q']`. For node paths or any structured paths and if you want to get the node ID or something, now don't `explode('/', $_GET['q'])` :)

Meet `arg()`.

* `Aliased path: content/my-new-page`
* `$_GET['q']: node/69`
* `arg(0) = node`
* `arg(1) = 69`
* `drupal_get_normal_path('content/my-new-page')` (Probably require some db trips unless cached)
> 3 votes

# Answer
You can use drupal\_get\_normal\_path function.

> Return value
>
> The internal path represented by the alias, or the original alias if no internal path was found.
> 3 votes

# Answer
All the URl path are stored in database so you can configure it in admin/config/search/path whether your are using pathauto or writing your own url alises. Deleting from admin setting may convert a URL path back to it's own node (node/nid).
> 0 votes

---
Tags: uri
---


# Question
Title: drupal not detecting function in custom module's inc file
I have a custom module, in my module call `commerce_discount_add_line_item()` function, it exists in `commerce_discount.rules.inc`, this modules is installed correctly and status is enabled but when I call it returns:

> ( ! ) Fatal error: Call to undefined function commerce\_discount\_add\_line\_item().

It is strange, why has this happened?

# Answer
By default inc files are not included(only module files are included). They should be called explicitly like below before making a call to a function in that file.

```
module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');

```

Further Reading on inc files and how they differ from .module files : https://drupal.stackexchange.com/a/54069/4876
> 5 votes

# Answer
I hope you have included `commerce_discount.rules.inc` file in your module file.

You can use below code to include file, if you have not included files into your module file.

```
module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');

```
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Where does Drupal 7 clear my custom set cookies and how do I stop this?
I have parts of my website that are not controlled by drupal that set cookies.

When I access a drupal-run page, my cookies get cleared. I tried to investigate which script does this by placing print\_r($\_COOKIE) all over the place in html.tpl.php, but no luck.

Anybody know whats happening here and how I could set my own custom cookies with PHP in drupal template files?

cheers

# Answer
> 1 votes
Please find more about setting cookies using php setcookie function.

As explained in above link, please look into third and fourth params in above function

**Path**

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

**Domain**

The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

**Please check your code where you are setting cookies matches Drupal Site Domain name and Path where you are trying to access or print them.**

You can set cookies in Drupal using user\_cookie\_save function.

For Example

```
user_cookie_save(array('key'=>'value'));
print $_COOKIE['Drupal_visitor_key']; //outputs value

```

---
Tags: theming, caching, cookies
---


# Question
Title: Is there any ideas on webform mutile values on same field?
In webform select components, we can set multiple attributes but not for filed like textfield or numbers.

So I want to ask is there any ideas on that, so let user can add more value on same field. Such as:

Telephone number, the web visitors may not have only one ,and we should allows multiple for that.

We found that the webform has store multiple values in database which can come from in the form used like telephone\[\], but do not in the validation.

We do not want to changes the validation rules but we want to have a multiple attributes on textfied.

Is there any idea?

Thanks.

# Answer
There is module for doing this: Try the Multivalue Settings module.

> This module adds some useful settings for fields that can contain multiple values. You can specify:
>
> * Number of values allowed
> * Number of values required
> * Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
> * Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra.)
> 2 votes

# Answer
You can just try Webform Multiple.

> Webform Multiple (WFM) is a Drupal 7 module allowing Webform components to have more than one value.
>
> The user completing the form can add instances of the component with an 'Add another item' button.

Hope it can help you
> 0 votes

---
Tags: webforms
---


# Question
Title: Don't show a field when a more important field is shown in a View Drupal 7
On my homepage blog messages from the users are shown. When a user adds a Youtube movie and/or one or more pictures these are shown as a preview. The thing is though that when a user picks a movie and one or more pictures the home page message show the Youtube movie and the picture. But when both are added to a blog message I only want to see the youtube preview, so Youtube is more important than the picture so the picture should not be shown. When there are only pictures 1 picture is shown (this works fine). How can I change something in my View to make it prioritize Youtube over the picture so it doesn't the picture when there is a Youtube movie.

Screenie of what I have now, so the picture has to leave: http://imageshack.com/a/img844/1833/bqer.jpg

I have a multisite setup with 11 websites so the easiest solution is welcome :)

Thanks in advance!

# Answer
Use the Views Conditional module. It does exactly what you want to achieve.

> How to use Views Conditional in your Views:
>
> 1. Create a view. Add some fields under "FIELDS".
> 2. Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
> 3. Add and configure fields...
> 4. Choose a field to run a condition against, and provide values accordingly.
> 5. Save, views conditional handles the logic and returns as specified.
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: Restricting Video upload to mp4 format alone - in media module
I have been struggling put restriction for uploading video to upload only mp4 videos in media module, other media content like image etc. can be uploaded, but I need to put restriction for video type alone.

I am newbie in Drupal, can some one help me in this, what are the places I need to change in media module.

I would really appreciate any help on this. I did found `sites\all\modules\media\includes\media.pages.inc` file which had a function `media_add_upload_validate($form, &$form_state)` also then I found `sites\all\modules\media\includes\media.variables.inc` which had function `media_variable_default` and `media_variable_get`. Then I got lost. I am not sure if these are the correct files where I need to make the changes. Also I was wondering if I have to make change in Drupal core module to do the video upload restriction to mp4 perfectly.

Thanks

# Answer
Go to admin/config/media/browser to change settings.
> 1 votes

---
Tags: 7, media
---


title: add Solr search box in views filter

text:
# Question
Title: add Solr search box in views filter
I have succesfully installed solr and it is working fine, but my main search in my drupal site is based on views exposed filters, is there a way to add the solr search in views filters, so it interacts with them?

I am using views to setup an advanced search, by exposing filters, i want to add one that uses solr, so in total solr search is used together with views filter and i get corresponding results from files too.

# Answer
You can try using Apache Solr Views module.

Project page says

> In order to get the facet blocks provided by the Apache solr Search Integration Project you need to set up either arguments or exposed filters for the blocks. For instance, you could set up an argument for node type and the Apache Solr Search: Filter by content type block will work.
> 0 votes

---
Tags: views, search
---


# Question
Title: Eliminate the "Upload" button in Webforms
There is a way to eliminate the "Upload" button in Webforms, just adding an "attach" button that uploads the file automatically when you push "send", like in the image.

# Answer
> 1 votes
First, it's worth to remember that file will be uploaded when you push form's submit button, if user haven't uploaded it yet.

Second, you could use AutoUpload module:

> AutoUpload is a user interface (UI) enhancement that initiates automatic upload of files minimizing the number of clicks required by a user.
>
> Currently, users must select files, then press the "Upload" button. We found users often don't realize a button press is necessary and mistakenly think their image is uploaded when it's not.
>
> This module removes the extra button press and hides the "Upload" button via JavaScript for a quicker, automatic file upload. When JavaScript is not enabled, it falls back to the "Upload" button.

I must admit that this module conflicted with my custom modules and themes, but as a code sample it was perfect. It's GPL, so tailoring it to your custom needs is perfectly legal.

---
Tags: webforms, theming
---


# Question
Title: Create bundles programmatically using ECK (Entity Construction Kit)
The ECK module allows users to create custom entities.

When using this modules UI it is possible to create an entity type, and then attach multiple bundles to the entity.

It is also possible to create new entity types via code. This page shows an example which is as follows:

```
$entity_type =  new EntityType();
$entity_type->name = "eck_employee";
$entity_type->label = "Employee";
// Following line is taken from the eck_example.install file
$entity_type->addProperty('name', 'Name', 'text');
$entity_type->save();

```

This doesn't however show how to create and attach bundles.

Is it possible to attach bundles to entities when creating them via code (using ECK)?

# Answer
> 3 votes
I just found a blog article here which gives an example on how to do exactly this:

After creating the entity type with the example code I gave in the question a bundle can be created as simply as this:

```
$entity_type_bundle = new Bundle();
$entity_type_bundle->name = 'eck_employee';
$entity_type_bundle->entity_type = 'eck_employee';
$entity_type_bundle->save();

```

---
Tags: 7, entities
---


# Question
Title: Modifying integer field to decimal gives error when editing field information
I have implemented php code to update a field from integer to decimal. However when trying to modify the field name from UI, it gives error:

Attempt to update field Maximum Temperature failed: field\_sql\_storage cannot change the schema for an existing field with data.

The system behaves well when editing existing field data or creating a new one.

Please find the code executed via hook\_update\_N() below:

```
/**
* Modify the integer field of nursing notes temperature field
* to decimal field with precision and scale
*/
function ji_custom_update_7001() {

  // Manual database changes.
  db_query("UPDATE {field_config} SET type = 'number_decimal'
      WHERE field_name = 'field_nursing_note_max_temp'");

  $new_field = array(
    'type' => 'numeric',
    'precision' => 10,
    'scale' => 2,
    'not null' => FALSE,
  );

  db_change_field('field_data_field_nursing_note_max_temp', 'field_nursing_note_max_temp_value'
    , 'field_nursing_note_max_temp_value', $new_field);

  db_change_field('field_revision_field_nursing_note_max_temp', 'field_nursing_note_max_temp_value'
    , 'field_nursing_note_max_temp_value', $new_field);

  // Clear caches.
  field_cache_clear(TRUE);
}

```

# Answer
> 0 votes
If the only tables that you have updated are `field_config`, `field_data_field_nursing_note_max_temp` and `field_revision_field_nursing_note_max_temp` then you missed one: `field_config_instance`.

Without being able to explain in detail how your manual mingling with the database produces the error, I'll try to outline what I understand.

The error you're seeing is produced in field\_sql\_storage\_field\_update\_forbid. This is a hook implementation that is called by the Field CRUD API in order to give modules the chance to object the updating of a field:

```
// See if any module forbids the update by throwing an exception.
foreach (module_implements('field_update_forbid') as $module) {
  $function = $module . '_field_update_forbid';
  $function($field, $prior_field, $has_data);
}

```

The hook function receives three argumentes, the first is the current field definition coming from the field settings form, the second is the prior field defintion which is read from the `field_config_instance` table:

```
$prior_field = field_read_field($field['field_name']);

```

I assume that those two arrays differ and produce the error that you are encountering.

So I'd say, welcome to field hell! It's in general not advisable to mingle directly with the fields underlying table structure and column definitions. If you need to change a field, it might be a lot better to create a temporary field and migrate the data using API functions in batch scripts for example. That sounds like more work in the first place, but it will spare you these kinds of inconsistencies.

---
Tags: hooks, updating
---


# Question
Title: Can I skip or bypass translation when creating a form #options elements?
I know I must use t() function in Drupal, but my particular task involves a great number of values in Russian, for which I do not want to enter values as t('Moscow') and then manually translate strings into Russian. There are tons of Russian names and I just want to use them directly. Is it possible?

When I try, my select element options just appear blank.

```
...
       $form['selected'] = array(
           '#type' => 'select',
           '#title' => t('Selected'),
           '#options' => array(
              0 => 'Чебоксары',
              1 => 'Москва',
           ),
...

```

# Answer
> 1 votes
Using `t()` is considered a good practice, but it is in no way required by Form API.

Your code should work all right. Be sure your code files are properly saved as UTF-8 and transferred using "binary" mode, to prevent misinterpretation of non-ASCII characters.

---
Tags: forms, i18n-l10n
---


# Question
Title: Transforming a Webform upload field into a single Attach button
I want to transform the entire **"Browse No file selected Upload"** to a button like **"Submit"** nellens.com/home/content/contact, using CSS, I don´t know if this is possible. It is made with Webforms!

# Answer
I found these 2 tutorials, with this I can manipulate the upload field only with CSS, without touching the PHP code:

http://jsfiddle.net/gabrieleromanato/mxq9R/

http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

With this, it creates the link based on an image as background that imitate the form of the button.

Thanks again to @Mołot for helping.
> 0 votes

---
Tags: forms, webforms, theming
---


# Question
Title: How do I translate British English strings into US English?
I have created my own custom module. All of my outputted strings are wrapped in t functions. I have enabled Locale in core. I need to alter some of my module's strings and some field labels too, slightly, just a word here and there, form British English into US English.

What I'm trying to acheive is: if my site is being viewed in the US I want that to be automatically detected, and the adjusted strings/field labels displayed.

Thanks.

**Solution:** Install `ip2country` module. This provides a function called `ip2country_get_country` which returns an ISO 3166 two-character country code based on the user's IP address. Create a helper function that returns a boolean TRUE/FALSE is the country code is 'US'. Then just use if-else constructs to translate the required text.

# Answer
First, I'm not sure about what this means "I cannot see any of the strings from my custom module." ... so my answer here may not be useful. but here goes:

Machines don't care about what the similarities are, variations of english might as well be chinese and spanish.. which works in our favour here!

Assuming (US) english is your primary/default language, translate only the strings you want in to the Queen's English: admin/config/regional/translate/translate

You may have to do some interesting stuff to make detection/selection work, but I think that's a new question.
> 0 votes

# Answer
There are two modules that may help you:

stringoverrides

or

stringoverrides\_advanced
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to add an image field to a programmatically created form?
Basically I want to create a block with my module which's edit page has a few content fields and two image upload fields. When visiting the node where this block is rendered, I want to render the images with a certain **image style**, while on the edit form it would be cool to show the images as a thumbnail preview.

I am adding a field like described here: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#managed\_file but this makes me **curious**:

> New files are uploaded with a status of 0 and are treated as temporary files which are removed after 6 hours via cron. Your module is responsible for changing the $file objects status to FILE\_STATUS\_PERMANENT and saving the new status to the database.

Also, what is the difference of `managed_file` and `file` when I want to provide an image upload field?

Currently I have in hook\_block\_configure:

```
$form['left']['image'] = array(
        '#type' => 'managed_file',
        '#title' => 'test',
    );

```

Where do I define how this image shall be rendered (image style)? Do I have to set that permanent flag?

Thanks

# Answer
> 3 votes
You cannot use fields from the Field API in forms of the Form API directly, as Fields can be used directly in entities, and entities can be used directly with forms.

Instead, you can use the approach described here, as Clive kindly pointed out. Alternatively, you can use ctools\_field\_invoke\_field() function of CTools module too.

The two fields 'file' and 'managed\_file' of the Form API are similar, with the difference that the latter provides a progress upload widget. Also, managed\_file will add the file entry to a table with the same name. Beyond that, there is some work involved in order to render the file on a page, and that is not the imagefield of the Field API.

# Answer
> 1 votes
> Also, what is the difference of managed\_file and file when I want to provide an image upload field?

There isn't a difference for what you're doing. managed files let you control more aspects of the file, like using it in other places, applying rules, etc.

> Where do I define how this image shall be rendered (image style)?

Hmm.. not sure I understand. image styles are handled on output, not during upload.

> Do I have to set that permanent flag? you do, but afaik that will be set when your form is saved.

# Answer
> 0 votes
Put this piece of code into block: $fid is a file id.

```
$img = file_load($fid);
$blockcontent = theme('image_style',array('style_name' => 'YOURSTYLENAME', 'path' => $img->uri));

```

---
Tags: forms, media
---


# Question
Title: Can you disable drush pm-update for a site?
Can you disable `drush pm-update` for a particular site in drushrc.php?

I have a server which houses the DEV and LIVE versions of the site. Work is done directly on the DEV site. Changes to the LIVE site are deployed via `git pull` from a shared remote on the same filesystem.

In an effort to prevent **Doing Something Stupid™**, and running a `pm-update` and `pm-updatecode` on the LIVE site, I would like to disable these commands for that site.

The `$command_specific[]` syntax allows you to specify persistent options for commands (like `--no-core`), but I would like to fully disable `pm-update` and `pm-updatecode` for this particular site.

Is this possible?

# Answer
> 4 votes
You can disable the core Update module on the live site, and then should prevent being able run pm-update on live:

> $ drush pm-disable update
> The following extensions will be disabled: update
> Do you really want to continue? (y/n): y
> update was disabled successfully. \[ok\]
> $ drush pm-update
> Command pm-update needs the following modules installed/enabled to run: update. \[error\]
> The drush command 'pm-update' could not be executed. \[error\]

# Answer
> 2 votes
You can implement drush\_hook\_pre\_COMMAND which says

> Run before a specific command executes. Logging an error stops command execution.
>
> Logging an error stops command execution, and the rollback function (if any) for each hook implementation is invoked, in addition to the validate rollback.

By implementing above hook in custom module and throwing an error should disable command.

As said in above answer Disabling module will be best option in above case.. But , I believe above hook will be handy if only drush command need to be disabled instead of module itself.. Most of the cases module disable may not be good option since it's functionality may be required to run drupal.. For example to disable user-add-role command we cannot disable user module.

One more way is to configure in drush configuration file as explained here

```
/**
 * Specify the modules to ignore when searching for command files (*.drush.inc)
 * inside a Drupal site.
 */
# $options['ignored-modules'] = array('module1', 'module2');

```

---
Tags: drush
---


title: function defined in module not global?

text:
# Question
Title: function defined in module not global?
I created a module in order to define a few functions that I would like to use from a workflow rule. The workflow rule is triggered by an event and runs a php code snippet. The php snippet that it runs is simply a function call to the function that I defined in my module.

However each time my rule executes the code, I see an error in the httpd error\_log - `call to undefined function`. I ran the module through php lint, and I enabled it, flushed caches, and even restarted httpd for good measure. Still I get the error "`PHP Fatal error: Call to undefined function`" in the log.

I'm new to modules and Drupal programming so I must be missing something, but I thought functions defined in drupal modules (modulename.module) are global?

BTW I followed the instructions here.

Edit1: I defined my functions in module.module (not .inc...)

# Answer
> 4 votes
I usually define my modules functions in a separate .inc file, and when i need them somewhere (usually sub-modules) i first include them with module\_load\_include( file-extension, module-name, file-path)

You can add the module\_load\_include() call at top of your snippet, or, if you need those function in many other places in your module hook\_init() and make it avaible to every page.

---
Tags: 7
---


# Question
Title: Batch API on a Dreamhost dedicated server
I am on a Dreamhost dedicated server. I use it to host Drupal sites that our company creates. We recently moved on to this server from another hosting company and have noticed that Batch API features do not work for Drupal 6 or 7. (This same dataset that's failing worked on our last server)

What is the difference? I have upped `max_allowed_packet` to `100mb`, I have increased the Apache timeout to 900 seconds, and have changed the following PHP vars to some pretty high amounts:

```
max_execution_time = 1600
max_input_time = 1600
memory_limit = 2048M
post_max_size = 2048M

```

It still won't seem to work. It hangs on initialize and gives me the following message:

> An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging information follows. Path: /batch?render=overlay&id=3329&op=do StatusText: Forbidden ResponseText: Access denied

I can run them in the background with Drush, however I have to run core-cron several times over and over to make the import work. This works for some items, but is not ideal as some clients like to use Views Bulk Operations on their sites for managing content.

My server is the top of the line server with 16GB of memory.

# Answer
I solved this by updating "FcgidIOTimeout" in httpd.conf. I set it to an hour.
> 1 votes

---
Tags: 7, batch-operations
---


# Question
Title: Pulling in a title from multiple content types
Currently I have 3 content types: Program, Chapter, Item. The program content type has a node reference field to contain multiple chapters and the chapters content type has a node reference to contain multiple items.

I now have a view that lists some items, but I also want to pull in the program title that is referencing that item.

For example:

Program = Fruit Chapter = Pear Item = Cutting a Pear

I want to list the title of "Cutting a pear" and also the program "fruit" title.

In my view for my items I tried creating a relationship to tie in the "program", but the only relationship that I can use is the "Chapter" because I guess its directly related to the item. The program is not tied to it in any way.

Any ideas how I can pull in the program title information when its not directly related to the item?

# Answer
I would put this as a comment, but I'm new so I can't comment on things yet, but what you could do is add the relationship of the chapter, then add a field using that relationship that shows the node reference that the chapter has to the program. As long as you're using that relationship, it should show the proper program.
> 1 votes

---
Tags: 7, views
---


title: taxonomy term is not working

text:
# Question
Title: taxonomy term is not working
when i am added any query code is added in blocks our taxonomy term is not working they give two kind of errors:

1. PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'term' in 'where clause' when i clicking on taxonomy term
2. Notice: Trying to get property of non-object in eval() when i am added code in blocks Here is my code:

```
$nid=arg(1);

$tid=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
INNER JOIN taxonomy_term_data td ON th.tid=td.tid
INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
WHERE td.vid = '6' AND th.parent = '0'  AND book.entity_id = $nid
")->FetchField();

print $tid->Name;
$child=taxonomy_get_children($tid);
 foreach($child as $t)
 {
$link = l($t->name, 'taxonomy/term/' . $t->tid)."<br>";
print $link;
}

```

# Answer
I can't see any 'term' in your where clausole, so it's probably because you forgot the single quote around $nid.

oh, when i have query problems, the first thing i do is printing them on screen to see what I'm sending to the db, you wont believe what i managed to write some times, but i blame my keyboard \>\_\>
> 0 votes

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


# Question
Title: Where in the table is it stored that /drupal/foo is actually /node/47 in order to mass query to remove /drupal and just leave the /foo part?
/drupal is broken on all the websites, but I want to go into the database and mass query to remove the /drupal and just leave the /foo part.

# Answer
The table you want is `{url_alias}`. The `{url_alias.source}`column is the internal path (eg node/123), the `{url_alias.alias}` is the alias itself.

Mucking with the database directly isn't recommended, though. Your best bet is to use Pathauto and Globalredirect. The first will allow you to set up patterns, the second will redirect nodes to the alias.

You then use the Delete Aliases (admin/config/search/path/delete\_bulk) link and then Bulk Update (admin/config/search/path/update\_bulk) to make the new ones.

If you must do this manually, I suggest looking into the what the Path include provides as an API, and using that.

Also be sure that you don't actually have a problem with a `$base_url` being set incorrectly in your settings.php
> 3 votes

---
Tags: database
---


# Question
Title: Set up varnish, but is the content really from cache?
I set up varnish in my site and after the set up, checked the http header for an anonymous user. This was the response:

> Status: HTTP/1.1 200 OK Server: Apache/2.2.15 (CentOS)
> X-Powered-By: PHP/5.3.3
> X-Drupal-Cache: MISS
> Cache-Control: max-age=0, no-cache Content-Language: en
> Link: http://www.website.com/; rel="canonical",http://www.website.com/; rel="shortlink",https://plus.google.com/u/0/b/randomnumber/randomnumber/; rel="publisher"
> Vary: Accept-Encoding X-Mod-Pagespeed: 1.6.29.7-3566
> Content-Encoding: gzip
> Content-Type: text/html; charset=utf-8
> Content-Length: 15365
> Date: Sat, 08 Feb 2014 20:53:08 GMT
> X-Varnish: 658699528
> Age: 0
> Via: 1.1 varnish Connection: close

This is what isvarnishworking.com has got to say on this:

> Varnish appears to be responding at that url, but the Cache-Control header's "max-age" value is less than 1, which means that Varnish will never serve content from cache at this url.

This means that the purpose of me setting up varnish is not served. Is this correct? Varnishstat shows a hit to miss ratio of 50% which is good enough to start with:

```
83  Client connections accepted
     230  Client requests received
      21  Cache hits
      49  Cache misses
     210  Backend conn. success
     164  Fetch with Length
       1  Fetch wanted close
      39  N struct sess_mem
       1  N struct sess
      37  N struct object
      37  N struct objectcore
      26  N struct objecthead
      90  N struct smf
      16  N large free smf
       1  N struct vbe_conn
       2  N worker threads
      12  N worker threads created
  375315  N worker threads limited
     104  N overflowed work requests
       1  N backends
      12  N expired objects
       8  N LRU moved objects
     184  Objects sent with write
      82  Total Sessions
     230  Total Requests
     160  Total pass
     209  Total fetch
   84600  Total header bytes
 1377549  Total body bytes
       8  Session Closed
     223  Session Linger
     224  Session herd
   19641  SHM records
    1662  SHM writes
       1  SHM MTX contention
     213  allocator requests
      74  outstanding allocations
  409600  bytes allocated 10439155712  bytes free
     210  Backend requests made
       1  N vcl total
       1  N vcl available
       1  N total active purges
       1  N new purges added
      70  HCB Lookups without lock
      35  HCB Lookups with lock
      35  HCB Inserts
     752  Client uptime
      44  Fetch no body (304)

```

Here is a screeshot of the admin/configure/development/performance page:

http://awesomescreenshot.com/01e2bplzef

# Answer
Fixed it by making sure that settings.php contains the following lines and rebooting afterwords:

```
$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');

$conf['cache_class_cache_page'] = 'VarnishCache';

$conf['page_cache_invoke_hooks'] = FALSE;

$conf['reverse_proxy'] = TRUE;

$conf['cache'] = 1;

$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';

$conf['reverse_proxy_addresses'] = array('127.0.0.1');

```
> 1 votes

# Answer
Your content is not from cache.

See the X-Varnish header;

```
X-Varnish: 658699528

```

If the content was served by Varnish, you'd have two numbers there. Not just one.

Have you looked at using the Varnish module? I'm not sure what version of Drupal you're using though.
> 1 votes

---
Tags: caching, proxies
---


# Question
Title: Complex form - merge of two with single callback
I have a complex form of two logical parts, which I have placed in different functions (`my_module_partner_form` & `my_module_fields_form`). Both forms have submit handlers (`my_module_partner_form` \- 1 submit, `my_module_fields_form` \- 2 different submits). I would like to display those on one page.

So my solution was the following:

# Create a menu item like the following:

```
$items['complex-form/%/%/%'] = array(
    'title'         => 'Complex Form',
    'page callback'     => 'drupal_get_form',
    'page arguments'    => array('my_module_complex_form', 1, 2, 3),
    'access callback'   => 'my_module_complex_form_custom_access',
    'access arguments'  => array(1, 2, 3),
    'type'          => MENU_NORMAL_ITEM,
    'file'          => 'includes/some_file.inc',
);

```

# Create a callback function to handle it

```
function my_module_complex_form($form, &$form_state, $param1, $param2, $param3)
{
    // ... some irrelevant code here ...

    $form = array();
    $form = drupal_get_form('my_module_partner_form', $someParam);
    $form += drupal_get_form('my_module_fields_form', $someParam);

    return $form;
}

```

# Here are the forms itself (code obfuscated)

```
function my_module_fields_form($form, &$form_state, $param1)
{
    // ... some irrelevant code here ...

    $form['save_all'] = array(
        '#type'     => 'submit',
        '#value'    => 'Update',
    );
    $form['save_with_no_changes'] = array(
        '#type'     => 'submit',
        '#value'    => 'Save with no changes',
    );

    return $form;
}

function my_module_partner_form($form, &$form_state, $param1)
{
    // ... some irrelevant code here ...

    $form['save_profile'] = array(
        '#type'     => 'submit',
        '#value'    => 'Save contact details',
    );

    return $form;
}

```

SO, the question is: what am I missing, as the submit function for each of the functions (except for the `my_module_complex_form_submit` \- why?) is being called, but I can not identify which button was clicked.

# What I *have* already tried, not to waist your time:

* reading `$form_state['clicked_button']['#value']` \- always the same - "Update".
* creating custom `#submit` elements for each button - this will not work as I only need one handler to work each time. Please correct me if I missed smth in the workflow.

Any ideas welcome.

# Answer
> 1 votes
When you submit a form, either by clicking a button or pressing enter, the first (by default) submit button is assumed clicked, that's why the value is always "Update".

When you submit a form, every enabled element of the form is submitted, so the #submit parameter doesn't do for you.

The complex\_form\_submit is not executed because you are building it using two forms with their own \_submit. This way, the drupal\_get\_form() call doesn't link the complex form submit to the complex form.

---

ok, because of the reasons above, you can't proceed like that, but you still have several options:

## option 1

I'm assuming that when you save, you're looking for the #value of some select/textfield/etc of your field\_form, but when you save without changes, you use the #default\_value of said elements for example.

If this is the case, can you consider the option to turn the save\_without\_change button from a submit to a reset button?

This way, the user will revert all changes to the form elements, then click on save, and you will only need one \_submit callback that just save the #value. You should still split field and partner forms like shown at the bottom of page anyway.

Drupal wont let you create reset buttons, but you can specify one like this:

```
$['reset'] = array( '#markup'=>'<button type="reset">Revert changes</button>');

```

if #markup doesn't work, use #prefix instead.

## option 2

Split the field form into two forms.

The save form will be exactly like the field one, but with a button less.

The save without changes form instead, will only have the missing button, and will store the form parameters or default values you need into elements like:

```
$['#val1'] = $val1;

```

that wont be rendered, but that you can use inside its submit for its logic.

## option 3

if you really want to keep the field form like that, the only workaround i can think of is adding a hidden checkbox to your field form, and adding an onclick event to one of the two save buttons.

The event will call a JavaScript function that change the checkbox value.

Later on, inside your field\_form\_submit, you can use the checkbox value to evaluate which button was clicked and execute the correct logic.

downside: JavaScript have to be enabled. you still split partner and field forms.

## split

The problem here is that the two "sub" forms don't really exist anymore, they are rendered as one, which you should be able to confirm inspecting the resulting html.

If you need that only one submit is sent, don't mix them up.

Use my\_module\_complex\_form as page callback, fix arguments accordingly, and inside render each form with drupal\_render():

```
function my_module_complex_form(.....)
{
  // ... some irrelevant code here ...

  $f1 = drupal_get_form('my_module_partner_form', $someParam);
  $f2 = drupal_get_form('my_module_fields_form', $someOtherParam);

  $page = drupal_render($f1);
  $page .= drupal_render($f2);

  return $page;
}

```

---
Tags: 7, forms
---


# Question
Title: How to attach profile type to specific user role?
I have multiple profile types and multiple user roles. I want to combine specific profile types with users of specific roles. For example, customer roles have their own profiles, content authors have their own profiles, etc.

Is there a way to assign them together?

# Answer
> -1 votes
I was able to do this with permissions.

---
Tags: 7, users
---


# Question
Title: Drupal views - 2 latest reports and related content
My Drupal site contains a certain type of report, and these reports sometimes have 1 or more amendments, which will have field\_related\_content pointing to the report they're amending.

I'm trying to set up a view that will display the latest two reports, plus any amendments to those reports, but I haven't been able to figure out how to do it.

Can Views filters refer to results from other filters?

# Answer
You can create view in a view using View Field View (https://drupal.org/project/views\_field\_view):

* Create a view of reports
* Create a view of amendments which takes a contextual filter of node id and filters amendments which have a field reference with that node id value
* Put the view amendments view in a view of reports as a field (using above mentioned module - see it's documentation for more specific info if necessary)

Btw. just a thought - isn't it possible for you to switch the architecture and have the node reference field in the document content type, referencing the amendments? - this way you wouldn't need a view in a view and it would be easier to display it.
> 2 votes

---
Tags: views
---


# Question
Title: My if statements are working everywhere except in my hook_block_view function
I am trying to make a custom form block in drupal. I want it to display my form, then after submitting, show the results. I have an if statement in the `hook_block_view` function saying if my form has been filled out to set `$block['content']` to "Form Submitted". This doesn't work though, it just displays the form again. I have the same if statement in my hook\_form\_submitted function to either set `drupal_set_messag`e to either 'Submitted' or to display what was put into the form. After submitting, when the page reloads, The form still displays, `$block['content']` does not get set, but `drupal_set_message()` does. What am I doing wrong?

Just thought of something, my `block_view()` only passes `($delta = '')` is it just that `$form_state['values']` is not being passed through the function?

```
<?php

/**
 * @file
 *
 */

 /**
 * Implements hook_block_info().
 */

 function search_engine_block_info() {
     $blocks = array();
     $blocks['search_engine'] = array(
        'info' => t('Search Engine'),
        'cache'=> DRUPAL_CACHE_GLOBAL,
    );
    return $blocks;
 }

 /**
 * Implements hook_block_view().
 */

 function search_engine_block_view($delta = ''){
     $block = array();
     switch ($delta) {
     case 'search_engine':
         $block['subject'] = t('Search Engine');
         //Check to see if the form has been submitted.  If not, show form, or else show results.
         if(!isset($form_state['values']['searchInput'])){
            $block['content'] = drupal_get_form('search_engine_form');
         }else{
            $block['content'] = 'Form Submitted';
         }
     }
     return $block;
 }

 /**
 * Implements hook_form.
 */

 function search_engine_form ($form, &$form_state){
    $form['searchOptions'] = array(
        '#type'     => 'select',
        '#title'    => t('You can search by GWF Number, name, email address or phone number.'),
        '#options'  => array(
            'gwf'           => t('GWF Number'),
            'applicant_email'   => t('Email Address'),
            'name'          => t('Name'),
            'phone_number'      => t('Phone Number'),
            ),
        '#value'    => 'gwf',
    );
    $form['searchInput'] = array(
        '#type'     => 'textfield',
        '#title'    => t(''),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value'=> t('Submit'),
        );
    return $form;
 }

 /**
 * Implements hook_form_submit.
 */

 function search_engine_form_submit($form, &$form_state){
    if(isset($form_state['values']['submit'])){
        drupal_set_message('Sumbmitted!!');
    }else{
        drupal_set_message($form_state['values']['searchOptions']);
    }
 }

```

# Answer
`$form_state['values']['searchInput']` is undefined in that function so this will never work. You could remove the if in this function and let `search_engine_form` return HTML if it is submitted. You can add it inside the if you're using for the message display.

You maybe have to use the `#rebuild` option on that form, so it gets rebuild.
> 2 votes

---
Tags: forms
---


# Question
Title: How do I make a Views jump menu to anchor links?
I would like to make a jump menu in Views that is displayed as an attachment to the same Views page, which displays a list of documents. I would like the jump menu to display the titles of all the documents, and have the destination for each link be an anchor tag on the same page, adjacent to the actual document.

I have applied output rewriting (in the Page display) to each document title, like this: `<a id="[title]">[title]</a>`. In my jump menu display, attached to the top of the page display, I can rewrite the output of the title field to be `mypage#[title]`, and that works, but the items in the jump menu are ugly.

What do I need to do in order to make the items in the jump menu display simply as `[title]`, but jump to `mypage#[title]`?

Thanks!

# Answer
> 0 votes
Add another title field for the document, which will have no rewriting at all and hide it from the output (checkbox "Exclude from display"). Then use this second title field when for displaying in jump menu.

---
Tags: views, 7
---


# Question
Title: Prepopulate a custom user field on registration?
I have created a custom field on the user entity. I would like to prepopulate this field with the value 0. So, when the user goes to their account page after registration the field is already filled in, which they are then free to change. Just like the username and email. The only way I can think to do this is to alter the registration form. I added this to my module, but when I created a new user, a new row did not appear in the field table. My module function:

```
function MYMODULE_form_user_register_alter(&$form, &$form_state, $form_id) {
  $form['account']['field_MYFIELD'][LANGUAGE_NONE][0] = array(
    '#type' => 'value',
    '#value' => 0,
  );
}

```

Where am I going wrong, or is there a better approach. Thanks.

# Answer
> 1 votes
Value field is only used for hidden purpose, it will not populate to user. Check below link

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#val

# Answer
> 1 votes
I had to figure this out not too long ago. Make sure you have the Field Permissions module installed. I created a new field for user accounts from `admin/config/people/accounts/fields`, and with the help of the Field Permissions module, set the permissions so that the only permission allowed for field is `create own value` for an **anonymous user**, and `edit own value` was checked for whatever role the user will have after registration. I made sure to check `Display on user registration form`, of course. I then hid the field via CSS `display: none`. Now here's the cool part:

To fill it in, you append text to the user/register url, like so:

```
user/register?edit[field_YOURFIELD][und][0][value]=FIELDVALUE

```

`FIELDVALUE` would be `0` in your case. I'm not sure `[und][0]` applies to your field, but based on the info you've provided, you'll know what's going on :)

Then, when the user has successfully registered, they can go in to their account and edit it.

---
Tags: users
---


# Question
Title: Programmatically created content type don't have a delete link
I'm developing a module that creates new content types through form that I created (not in hook\_install):

```
function create_new_content_type($type, $name){
    $t = get_t();

    $new_node = array(
        'type' => $type,
        'name' => $name,
        'base' => 'node_content',
        //'description' => 'This is an example node type with a few fields.',
    );
    $content_type = node_type_set_defaults($new_node);
    node_add_body_field($content_type);

    // Check if we create content type or update.
    $status = node_type_save($content_type);

    // Replacement rule for the messages.
    $t_args = array('%name' => $content_type->name);

    if ($status == SAVED_NEW) { // create case
        watchdog('node', 'Added content type %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
        return true;
    }

    return false;
}

```

When I go to `admin/structure/types` these I don't see the delete link.
I found here some similar questions that suggest to remove with `/admin/structure/types/manage/<content-type-name>/delete` but it's not a good solution for me.
Is it possible to display that link?

**EDIT:** This is what I mean:

# Answer
> 1 votes
You could always take the dull axe approach and use a page\_alter, eg, something along the lines of

```
function YOURMODULE_page_alter(&$page) {

  if ($_GET['q']=='admin/structure/types') {

    $page['content']['system_main']['node_table']['#rows'][]=array(
      'Foo <small>(Machine name: foo)</small><div class="description">Here is my description of foo</div>',
      array('data' => l(t('edit'), 'admin/structure/types/manage/foo')),
      array('data' => l(t('manage fields'), 'admin/structure/types/manage/foo/fields')),
      array('data' => l(t('manage display'), 'admin/structure/types/manage/foo/display')),
      array('data' => l(t('delete'), 'admin/structure/types/manage/foo/delete')),
    );

  }

}

```

which will create a row for type `foo`.

Per additions to the question: since the row is showing up but just without the `delete` link, you can go in and create it similarly, eg,

```
$page['content']['system_main']['node_table']['#rows'][NUM][4]=array('data' => l('delete', 'admin/structure/types/manage/foo/delete'));

```

where `NUM` is the row number where your content type is found. You might also want to check out Adding an operation to Content Types and the page\_alter() there on a possible way you might be able to easily figure out `NUM`.

Another addition:

Could you just do this in your module:

```
$info = array(
    'type' => $type,
    'name' => $name,
    'base' => 'node_content',
    'custom' => TRUE, // fake it out to think it was made via the UI...
);
$content_type = node_type_set_defaults($info);

```

A cursory glance through the code and node\_type\_set\_defaults() suggests that the only thing this does is allow this delete link to be presented in this very form.

---
Tags: 7, nodes
---


# Question
Title: what will be the cause of redirection loop while accessing view settings page
I have drupal 7.14 setup installed with views module. Whenever i am trying to access "admin/structure/views" the site goes into redirection loop and not opening the views setting page also same behavior is showing for Linkit Profiles settings page.

I can add views by directly calling this url "/admin/structure/views/add" but not able to edit as they are not listing but i need to know why the views settings page not showing.

**Solutions which i already tried:**

* Uninstalled views module and again installed.
* run update.php
* cleared views cache from database

But it doesn't give me any result any guesses why this is happening.

# Answer
> 0 votes
Five things I would check:

1. .htaccess rewrite rule?
2. Faulty alias? Check the table `url_alias` for any entry that contains `admin/structure/views`.
3. Redirect? If you have any redirect modules installed (globalredirect, redirect), check if there is a redirect set for the path in question.
4. Otherwise check the table `menu_router`, look for the path in the `path` column and see which function is set in the `page_callback` column. In D7 with Views 3 this should be `ctools_export_ui_switcher_page`.
5. Check your servers access and error logs to see if there's anything suspicious.

# Answer
> 0 votes
Do you have jQuery Update module installed? I recently had some issues when editing views due to using a version of jQuery (1.9 I think) set by the jQuery Update module. What fixed it for me was installing the dev version of the module, which gives you the option of specifying a different version of jQuery - 1.5 in my case - to be used solely within the admin theme while at the same time using the more recent version for the rest of the site.

---
Tags: views, caching, redirection
---


# Question
Title: Print ALT tag from an Image FIeld in a Custom Field Template
I'm attempting to create a custom field template for an image field with mutliple values. My field name is field\_photo\_slidshow

My field template name is: field--field-photo-slideshow.php and I've got it coded like this to produce a Flexslider slideshow:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php if (!$label_hidden): ?>
<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:     </div>
<?php endif; ?>
<div class="flexslider"<?php print $content_attributes; ?>>
<ul class="slides">
<?php foreach ($items as $delta => $item): ?>
<li class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>
<!-- <p class="flex-caption">Caption</p> -->
</li>
<?php endforeach; ?>
</ul>
</div>
</div>

```

And this does what I want so far -- creates and unordered list of the rendered images. But now, I want to add an optional caption, derived from the Image fields alt tag -- but I have no idea how to render the ALT tag from a given image in the above code in the field tempalte. That part of the code, in theory, would something like this:

```
<?php foreach ($items as $delta => $item): ?>
<li class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>
<p class="caption">ALT TEXT FROM IMAGE FIELD</p>
</li>
<?php endforeach; ?>

```

Doe anyone have any idea out to print out that alt text in the field template code?

thank you, Nathaniel

# Answer
If you install Devel module and use dpm($item); in your code, you will see the structure of $item. Alt is in `$item['#item']['alt']`.

See for example Modify tpl file to print the path to the image instead of the image itself?.
> 2 votes

# Answer
For me it works;

```
print $item['data']['alt'];

```

So for you rhis:

```
<?php foreach ($items as $delta => $item): ?>
<li class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>
<p class="caption"><?php print $item['data']['alt']; ?></p>
</li>
<?php endforeach; ?>

```
> 0 votes

---
Tags: entities, theming, media
---


# Question
Title: Availability Calendars - change amount of months shown to visitor
I need to make some changes to a website that is using the 'Availability Calendars' module(available on https://drupal.org/project/availability\_calendars ).

On the website a calender is shown to the visiting person that highlights any available date for 2014. I now need to have the months for 2015 to show up in the calender too.

But I can't find the option to make 2015 visible for the visitors. Using google I found this: http://drupalcode.org/project/availability\_calendars.git/blob/273d12c0ad811341615197a8601797f3003f52e9:/README.txt

It says "Choose the global settings for the availability calendars under Administer -\> Site configuration -\> Availability calendars. You can choose how many months will be shown for each node and whether or not to display the calendars on the node page itself".

But when I go to "nl/admin/config/content/availability-calendar" I only can set the 'labels' and add a css-class to those labels. There is a link to "nl/admin/config/content/availability-calendar/styling" but that only has options to set the font-weight,color, font-size, etc...

I then went to look in the content types ( under 'Structure --\> content types') but the option isn't showing up there either.

So the problem is I need to change the amount of months shown to the user (who is not logged it) on the front-end of the site for 2014 and 2015. But I can't find any option to change the amount of months shown. Can anyone point me in the correct direction? Or do I need a different module to do this? If so what module would I need for this?

# Answer
It turns out I just needed to enable the 'Field UI' module. So basicly I did this to solve my problem:

* Enable to 'Field UI' module
* Go through to "Structure --\> content types"
* Go to the 'Manage display' tab
> 0 votes

---
Tags: 7
---


title: Facet block based on other facet choice

text:
# Question
Title: Facet block based on other facet choice
I have a site where search is based on Search API (mysql server). I have two fields in my content type (brand and model) and I have created two faced block based on these fields. They work.

Now I want to make visible the model's facet block only when users have chose the brand (from the faced block).

Is this possible without a custom module or PHP code that searches in `$_GET` the brand chosen from the users?

# Answer
Better is later than never :)

Try to use "dependencies" from context menu of facet block.
> 0 votes

---
Tags: 7, search
---


# Question
Title: How to keep labels displayed for all facet filters
I have Search API with Facets API set up. For my checkbox selections, how can I prevent the facets from hiding when they aren't available? I want all of the facets to be listed, even if not available.

I can't seem to find an easy way to do this.

EDIT: I may have incorrectly used the term "facets" here. I mean to say filter options. So, if blue, red, and green are options, but the only available results are blue, I still want red and green to display as check boxes.

# Answer
Try to set this option

on facet settings form.
> 4 votes

---
Tags: 7, search
---


# Question
Title: Hook for the "Welcome (awaiting approval)" email
I need to modify the email for "Welcome (Awaiting Approval)."

I know I can use hook\_mail\_alter(), but I don't know what the ID is for "Welcome (Awaiting Approval)," nor do I know how I can directly access a user's profile2 fields.

I assume I have to do something like:

```
function module_mail_alter(&$message) {
  if ($message['id'] == 'welcome_waiting_approval') {
    global $user;
    $fid = $user['firm']['firm_id'];
    $message['body'][] = "Your Firm's ID is: $fid";
  }
}

```

# Answer
> 4 votes
I have used the Maillog / Mail Developer module to debug things such as your question.

To find the message ID, simply use code similar to the following one:

```
function YOURMODULE_mail_alter(&$message) {
  dpm($message['id']); // Assuming Devel module is installed.
  // Or just ...
  print $message['id']; exit;
}

```

Hooks are run for every module they are declared in; if you don't know the message id, simply create the hook and output the message id it finds. (Exiting might actually be a bad idea if your sending many types of messages—you didn't state that—because then the code might stop short of the exact message ID you're searching for.) Since the hook is declared, it will run for each outgoing message.

To access the user's 2 profile fields, they are just fields as long as you have a user object you can access them:

```
function MYMODULE_mail_alter(&$message) {
  global $user; // Get's a reference to the logged in user.
  if ($message['id'] == 'welcome_message_approval') {
    $message['body'][] = t("Your Firm's ID is: @firm", array('@firm' => $user->firm);
  }
}

```

To easily access fields I recommend the Field data extraction module.

I believe the Profile2 module should "eagerly" load the profile fields. If they are not in the global user object because of lazy loading, then you should be able to get at them by calling field\_attach\_load().

# Answer
> 0 votes
You can modify all the users' mail on admin/config/people/accounts.

# Answer
> 0 votes
Also incredibly useful in this case is a neat module called Mail Control http://drupal.org/project/mailcontrol

It gives you a checkbox so you don't have to send the New User Welcome emails at all, then you can handle this with Rules or your favorite method.

# Answer
> 0 votes
You can use function `hook_user_presave` for alter any mail related to registration.

If you want to alter awaiting approval mail then this condition will be helpful

```
function module_name_user_presave(&$edit, $account, $category) {
    if($account->is_new) {
        //add mail you want to send as awaiting approval
        //and disable mail from account setting
    }
}

```

hope this will be helpful

---
Tags: 7, emails, users
---


# Question
Title: Custom exposed filter with single on/off checkbox doesn't respect the default value and the $_GET parameter
I've created a custom filter with a checkbox exposed field in my module.

```
class my_module_helper_handler_filter_timetracking_children extends views_handler_filter {

  /*...*/

  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show subtasks'),
      '#default_value' => isset($this->value) ? $this->value : NULL,
    );
    return $form;
  }

  /*...*/

}

```

When by default in Views UI settings checkbox is disabled, everything works fine; when it's enabled, it doesn't work. It doesn't respect the default value and the $\_GET parameter.

I can't understand this strange behavior of single on/off checkboxes in exposed filters in a view.

I also tried using `'#attributes' => array('checked'=>'checked')`, but the filter didn't work correctly.

Might somebody can show his code how to create custom exposed filter with single checkbox? Or give usefull link

# Answer
Views doesn't handle the default checkbox state because when you load your view page for the first time (or if the user clicks the Reset button), the URL doesn't have any parameter in it, so that the $\_GET parameter is useless. Here is a complete form definition that will handle the checkbox, whether the URL has parameters or not:

```
class my_module_helper_handler_filter_timetracking_children extends views_handler_filter {

  /*...*/

  function value_form(&$form, &$form_state) {

    $params = my_module_get_params();

    // First time the view is loaded (or user click the Reset button), URL doesn't have parameters
    if(!$params) {
      $value = 1; // checkbox checked by default
    }
    // If URL has parameters
    else {
      // If our filter is present in the URL as parameter and its value is '1'
      if (isset($params['timetracking_children']) && $params['timetracking_children'] == 1) {
        $value = 1;
      }
      else {
        $value = 0;
      }
    }

    $form['value'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show subtasks'),
      '#default_value' => isset($this->value) ? $this->value : NULL,
      '#value' => $value,
    );
    return $form;
  }

  /*...*/

}

function my_module_get_params() {
  global $base_url;
  $query = array();

  $url = $base_url.request_uri();
  $url = parse_url($url);

  if(isset($url['query'])) {
    parse_str($url['query'],$query);
  }

  return $query;
}

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Is it possible to use random submission number for webform?
In order not to let users know how many webforms are submitted, can the `$sid` config to increase by a random range?

# Answer
You are probably looking for something like Webform Submission UUID module:

> This module provides a UUID integration for Webform Submissions

UUIDs are hashes that looks random and are not based on submission order, so they would meet your need. Note that this module is in dev version only, so you can expect errors. On the other hand it's GPL, so you can use it as an example how to interact with submission IDs.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Defining a constant via a function provided by another module?
In my custom module I want to define a constant which takes its value from a function provided by another module. When I call this function in my module I get a 'call to undefined function' error. Curiously, if I call the function from inside another function, I don't get an error and it works fine. It's as if all module functions get loaded at the same time and then executed, but anything that is not a function gets executed first before the functions become available.

```
// MY_MODULE.module

$var = FUNCTION_FROM_OTHER_MODULE();
define('MY_CONSTANT', $var);

// use MY_CONSTANT in the other hooks and functions of MY_MODULE

```

Why am I getting this error and how can I set my constant with this function? Hope this makes sense. thanks.

# Answer
> 1 votes
You can use the standard global keyword provided by PHP. This is better placed somewhere early in a page load. One that I can think of is hook\_menu or hook\_init.

Personally though I would strongly recommend to use the variable\_get() function provided by Drupal.

---
Tags: 7
---


# Question
Title: How can I add a taxonomy terms as a CSS class to my views?
I would like to add a taxonomy term as a CSS class to each view result. How can I do that?

# Answer
You can add a field with the taxonomy term and then exclude it from the view.

Then add as many fields you wish to present, such as Title.

Finally, add a global: custom text, and specify for example:

```
<div class="[field_tags]">[title]</div>

```

Replace with your field names obviously. You can consult the "replacement patterns" that the Views module kindly provides.
> 2 votes

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


title: Drush on Windows trouble

text:
# Question
Title: Drush on Windows trouble
I had installed Drush for Windows and trying use it.

I open directory (in CLI, in my example: `Z:\home\www\drush-test`) where I want install drupal and run `drush dl` command:

```
Z:\home\drush-test\www>drush dl
Install location Z:/drush/drupal-7.25 already exists. Do you want to overwrite it? (y/n):

```

But i need install drupal to `Z:\home\drush-test\www` **not** `Z:/drush/drupal-7.25` (this directory where Drush installed)

Also I trying using `drush status` in my old project (drupal installed). Drush don't see my drupal:

```
Z:\home\comp\www>drush status
X-Powered-By: PHP/5.3.13
Content-type: text/html; charset=utf-8

 PHP executable        :  php.exe
 PHP configuration     :  Z:\usr\local\php5\php.ini
 PHP OS                :  WINNT
 Drush version         :  7.0-dev
 Drush configuration   :
 Drush alias files     :

Z:\home\comp\www>ls
CHANGELOG.txt       LICENSE.txt      cron.php     nbproject   update.php
COPYRIGHT.txt       MAINTAINERS.txt  includes     profiles    web.config
INSTALL.mysql.txt   README.txt       index.php    robots.txt  xmlrpc.php
INSTALL.pgsql.txt   UPGRADE.txt      install.php  scripts
INSTALL.sqlite.txt  __files          misc         sites
INSTALL.txt         authorize.php    modules      themes

Z:\home\comp\www>

```

(Drupal 7 installed in this directory)

Windows 8.1, PHP 5.3

# Answer
Reinstalling Drush for Windows fix this problem.
> 0 votes

---
Tags: 7, drush
---


title: How do I clean cached paths to modules?

text:
# Question
Title: How do I clean cached paths to modules?
I foolishly did this, when updating a module:

```
# cd /var/www/drupal7/modules
# mv MODULE MODULE.old
# wget <MODULE_URL> -O - | tar xfvz -

```

After refreshing the module list, I still get the old module's version because, surprise, it found the MODULE.old subdirectory first. Or last. Or whatever.

I can of course do

```
# rm -r MODULE.old
# ln -s MODULE MODULE.old

```

but that's a temporary measure at best.

How do I remove these MODULE.old directories? `drush cc` also tries to access them and won't run if they're not there!

# Answer
The best way to do this is to disable the module, remove the '.old' folder and then re-enable the module. Unless disabling the module is destructive, this is the course of action I would recommend.

Otherwise you need to call registry\_rebuild, though as you've realised you can't do this from a module because your site won't bootstrap. There is drush command made just for this case which you can find at https://drupal.org/project/registry\_rebuild

If none of this works, you will need to manually edit the database ; you will need to manually edit the 'system' table and clear the system cache. Not recomended.

Whichever option you go for, make a backup of your database first!
> 3 votes

# Answer
Since `drush rr` does not work in my setup for whatever reason, I ended up hacking a temporary path cleanup function to bootstrap.inc.

```
--- /usr/share/drupal7/includes/bootstrap.inc       2014-02-13 11:26:07.710709587 +0000
+++ /tmp/boots      2014-02-13 11:26:04.722628976 +0000
@@ -3100,6 +3100,21 @@
  *   TRUE if the resource was found, FALSE if not.
  *   NULL if either of the REGISTRY_* constants is passed in as $type.
  */
+
+function _fixpath($fn) {
+  $last = "";
+  $pieces = explode("/", $fn);
+  $p = array();
+  foreach ($pieces as $pp) {
+    if (fnmatch("*.old",$pp)) { $pp = substr($pp,0,-4); }
+    if ($pp == "OLD") { continue; }
+    if ($last == $pp) { continue; }
+    $last = $pp;
+    $p[] = $pp;
+  }
+  return implode("/",$p);
+}
+
 function _registry_check_code($type, $name = NULL) {
   static $lookup_cache, $cache_update_needed;

@@ -3136,7 +3152,7 @@
   $cache_key = $type[0] . $name;
   if (isset($lookup_cache[$cache_key])) {
     if ($lookup_cache[$cache_key]) {
-      require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
+      require_once DRUPAL_ROOT . '/' . _fixpath($lookup_cache[$cache_key]);
     }
     return (bool) $lookup_cache[$cache_key];
   }
@@ -3158,7 +3174,7 @@
   $lookup_cache[$cache_key] = $file;

   if ($file) {
-    require_once DRUPAL_ROOT . '/' . $file;
+    require_once DRUPAL_ROOT . '/' . _fixpath($file);
     return TRUE;
   }
   else {

```

After running `drush cc` I could remove that hack.
> 0 votes

---
Tags: 7, caching, files
---


# Question
Title: Any way to use the Scheduler module with the Bean module?
I use the https://drupal.org/project/scheduler module with standar content types.

But I see no integration with the Bean module

Is there any way to use the Scheduler module with the Bean module?

If not, are there any other module for this. I need to set both publishing and unpublishing dates for bean nodes.

# Answer
Scheduler,

> ...allows **nodes** to be published and unpublished on specified dates.

As for Bean,

> Bean is an acronym that stands for **Block Entities Aren't Nodes**.

Emphasis mine in both.

So no, you can't use Scheduler with Bean as Bean doesn't use nodes. There's no such concept as "bean nodes".

I doubt you'll find a pre-built module with arbitrary scheduling for any type of entity. Being 'published' is a concept specific to the node entity type; not all entity types have that characteristic, so I doubt you'll find anything generic.

You'll probably need to write something from scratch. The code for scheduler will be the best starting point, but it'll need to be adapted to work with entities (or at least the Bean entity type).
> 0 votes

---
Tags: blocks
---


# Question
Title: How do I customize the html of each field in a view?
I have a custom theme and I want to edit the HTML of a view. I am able to create template overrides but I get stuck, it seems like the editable part of a view does not go deep enough.

I have a view displaying all of a content type. The content type has the following fields a name, an image, a link, and a description. I want to edit all of these with custom elements, classes, ids, etc and change the order of them. However the deepest I can get into a view is the `$row` variable, which already has this content formatted.

I've ran a function called `views_get_current_view()`. When I run it's return through print\_r I see the information I need deep inside of it, but when I try to grab that information Drupal runs out of memory, I do not want to allocate more memory and I don't think that's the best way to solve the problem.

Long story short - I'm trying to get the fields of each node in a view and customize their html, when I get that data from a view it seems to already be already coded.

Thanks

# Answer
> 0 votes
If you are create any content type and select any content type name ex : your created a "news" is content type and many field as a 'id','name' etc.

after you have add a one php file name as a 'node--news.tpl.php'

and clear caches

this file always call a news content data

---
Tags: views, theming
---


title: hook_field_schema not being used

text:
# Question
Title: hook_field_schema not being used
I'm trying to create a field with an additional property (or column) to define an extra relationship to a taxonomy term.

I have this in my module file:

```
/**
 * Implements hook_field_info().
 */
function emtr_field_info() {
    return array(
        // We name our field as the associative name of the array.
        'field_emtr_denominations' => array(
            'label' => t('Denominations'),
            'description' => t('Field linked to target entity as well as denomination taxonomy term holding denomnation value.'),
            'default_widget' => 'number',
            'default_formatter' => 'number_decimal',
        ),
    );
}

```

And this in my install file:

```
/**
 * Implements hook_field_schema().
 */
function emtr_field_schema($field) {
    $columns = array(
        'denomination_value' => array(
            'type' => 'int',
            'not null' => FALSE,
        ),
        'denomination_tid' => array(
            'type' => 'int',
            'not null' => TRUE,
            'default' => 0,
        ),
    );
    $indexes = array(
        'denomination_tid' => array('denomination_tid'),
    );
    return array(
        'columns' => $columns,
        'indexes' => $indexes,
    );
}

/**
 * Implements hook_enable().
 */
function emtr_enable() {

    field_cache_clear();
    field_associate_fields('emtr');

    if (field_info_field('emtr_denominations')) return;

    // Create a field for denominations to be used by safe checks and till reads
    $field = array(
        'field_name' => 'emtr_denominations',
        'type' => 'field_emtr_denominations',
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
        'translatable' => FALSE,
    );
    field_create_field($field);

    // Attach the emtr_denominations reference field to safe checks instance
    $instance = array(
        'field_name' => 'emtr_denominations',
        'entity_type' => 'emtr_safe_check',
        'bundle' => 'emtr_safe_check',
        'label' => 'Denominations',
        'required' => false,
        'widget' => array(
            'type' => 'number'
        ),
        'settings' => array(
            'target_type' => 'emtr_safe_check',
            'handler_settings' => array('target_bundles' => NULL),
        ),
        'display' => array(
            'default' => array('label' => 'inline', 'type' => 'number_integer'),
        ),
    );
    field_create_instance($instance);
}

```

But after uninstalling and re-enabling my module (drush devel-reinstall emtr -y ) a table called field\_data\_emtr\_denominations is created but it does not have my 2 custom columns.

At what point in this process should I tell Drupal to use my custom field\_schema?

# Answer
You should remove function `emtr_enable()` out of the `.install` file, and place its code in a more proper hook where the field is meaningful to be created, like for instance `hook_node_type_insert()` or EntityAPIController-derived class for your entity bundle, etc. It depends on what one wants to achieve really.
> 0 votes

---
Tags: 7, hooks, entities
---


# Question
Title: how to write views for our own custom module?
I am new to drupal. I have created one form submission module like this

```
 <?php
function form_test_permission()
{
return array(
'submit_form_test' =>array(
'title' =>('submit_form_test'),
'description' =>('submit the form_test form'),
),
);
}
function form_test_menu() {
$items=array();
$items['application']=array(
'title' =>'Application Form',
'type' =>MENU_NORMAL_ITEM,
'access arguments' => array('submit_form_test'),
'page callback' =>'drupal_get_form',
'page arguments' => array('form_test_form'),
);
return $items;
}

function form_test_form($form,&$form_state){
$form['firstname'] =array(
'#title' =>t('Firstname'),
'#type' => 'textfield',
);
$form['lastname'] =array(
'#title' =>t('Lastname'),
'#type' => 'textfield',
);
$form['addr']=array(
'#title' =>t('Address'),
'#type' => 'textfield',
);
$form['age']=array(
'#title' =>t('Age'),
'#type' => 'textfield',
);
$form['submit']=array(
'#value' => 'submit',
'#type'=> 'submit',
);
return $form;
}
function form_test_form_submit($form,&$form_state) {
$ft_id=db_insert('form_test')
->fields(array(
'firstname' => $form_state['values']['firstname'],
'lastname' =>$form_state['values']['lastname'],
'addr'=>$form_state['values']['addr'],
'age'=>$form_state['values']['age']
))
->execute();
drupal_set_message(t('Saved.'));
}

```

if I go like localhost/drupal-example/application.. this module works.. But I want to display this module in front page.I referred a lot. But it doesn't works. Can anyone guide me how to write a view function in this module?

# Answer
> 2 votes
In order to be able to use a custom module's table with Views, you need to use hook\_views\_data().

Even better, I would recommend that you invest some time to learn about entities. Entities are much better for most and thay can be almost immediately used in views.

To define a custom view into your module, put it in file `module.views_default.inc` (replacing with your module name), in a function module\_views\_default\_views().

---
Tags: 7, views
---


# Question
Title: Form Submission values in Hook Form Alter method
I wrote a custom method to do some set of operations when a webform is submitted and that is working fine. However I need to access some fields values that has been submitted in the Webform.

The fields in the Webform are: 'phone' , 'emailid'. I need to access these variables in the method `custom_example_some_function`. I tried playing around with some arrays, but that didn't worked out.

```
function custom_example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_22') {
       $form['#submit'][] = 'custom_example_some_function';
  }
}

function custom_example_some_function($form, &$form_state) {
// Do something
// echo $phoneNumberFromForm;
// echo $emailidFromForm;
}

```

# Answer
> 1 votes
You'll find submitted values in `$form_state['values']`, eg

```
$foo = $form_state['values']['bar'];

```

# Answer
> 0 votes
If I understand correctly, you want to edit your $form array values. Now they are passed and locally scoped in \*function custom\_example\_some\_function($form, &$form\_state)\*

Try changing it to `function custom_example_some_function(&$form, &$form_state)` so that you're able to alter your $form array.

---
Tags: webforms, forms
---


title: how to set a taxonomy term active?

text:
# Question
Title: how to set a taxonomy term active?
In my block i have different taxonomy term: term A -term B --term c ---term D when i am on term b it is set to active or bold if i am on term d then it is set to active and bold. this is already been used `$options = array();
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2) == $t->tid) {
 $options = array('attributes' => array('class' => 'active'));
}`

i am new in drupal anyone tell me how it is possible?

# Answer
> 0 votes
The arg() function is taking argument parts from the url. /taxonomy/term/2 means: arg(0) = taxonomy arg(1) = term arg(2) = 2

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


# Question
Title: drupal remove individual paragraph tags of the tokens of my replacement patterns in a View
I want to **rewrite results** in a View and use **replacement patterns** to do this. The problem is that when I do this the **2 tokens** are displayed in a separate paragraph.

--\> \[views\_conditional\]\[field\_blg\_inhoud\]

What I have now: Views\_conditional text

Field\_blg\_inhoud text

What I want: Views\_conditional text Field\_blg\_inhoud text

I think I have to change a lot in my standaard CSS etc. but isn't there an easier way? Can I somehow ignore the

somehow?

# Answer
> 0 votes
You could uncheck the standard style settings for "add default classes" for each field.

This should place both tokens in one paragraph if you rewrite them in another field (e.g. global custom text).

---
Tags: 7, views, tokens
---


# Question
Title: Custom field values are not importing with Features
I would like to export example data(nodes) in feature for others to kick start some reusable module that i developed. The example data contains nodes with custom fields. The problem is that while nodes and default field values(title, body) are importing the values for the custom fields are not. I am new to features. I must be doing something wrong.

For the example data I have selected the nodes, field bases, field instances and rest of the dependencies detected, but this is not export/import the custom field values. I am guess i have to select some more StrongArm variable values since these custom field instances are shared across multiple nodes? if so, how do i detect the dependent variables to particular node instance?...strongarm does not provide any drush command for that purpose...Any help is much appreciated

p.s. Are you using features for exporting/importing Sample Data of you custom module? I may have taken the wrong approach

Features: 7.x-2.0, uuid\_features: 7.x-1.0-alpha3, strongarm: 7.x-2.0, Drupal: 7.26

# Answer
> 0 votes
To clarify, the custom fields of nodes that reference to Taxonomy elements did not export/import via features. The reason is that Taxonomy term references(tid) are stored by ID instead of UUID with stable version of uuid\_features and uuid as of Feb, 2014

The solution was to use dev version 7.x-1.x-dev for uuid as well as uuid\_feature module. This will export/import custom fields (term reference) into UUID instead ID that solved the problem

---
Tags: drush, features
---


# Question
Title: How do I access Session variables in Drupal that were set on non-drupal pages?
If I go `print_r($_SESSION)` on a drupal page (say `mysite.com/` )I only get `Session variables` set from drupal pages (which are none atm). I can set new ones and they'll show up.

```
Array
(

)

```

However If I `print_r($_SESSION)` on a non-drupal page (say `mysite.com/somefolder/index.php`) on the same domain I get a different (and desired) array:

```
Array
(
    [last_url] => /downloads/full.php
    [ip] => ::1
    [address1] =>
    [address2] => Australia
    [zip] =>
    [phone] =>
    [fax] =>
    [dealer] =>
    [referral] =>
    [software] =>
    [searchTerms] =>
    [user_type] => user
)

```

I have `session_start();` at the beginning of all files.

How does my site seemingly have two `$_SESSION arrays`? How can I access my `$_SESSION` vars set on non-drupal scripts within drupal pages?

Thanks

# Answer
> 1 votes
You also need to boostrap drupal before use drupal's sessions (here: Properly bootstrap drupal for standalone PHP file?)

---
Tags: theming, sessions, configuration, cookies
---