# Question
Title: How to add contact us form in to front-page?
I need to add `contact` form in the front page but I don't know how. there are some modules like Contact Form On Node that inserts this form in the node page but I only want it to be in the front page. how do I can do this ?

thanks

# Answer
> 12 votes
* You can use Contact Form Blocks module, in case if you want to use the core contact form.
* Alternatively, you can create your contact form using Webform module which supports embedding the form in a block, which you can then display wherever you want.
* Also, you can display your existing contact form in a custom block, writing a custom module. In that case, you need to implement 2 hooks:

and then use the function `drupal_get_form` to retrieve the form for rendering. (See this for some more info)

# Answer
> 4 votes
The general solution using `webform` is this:

**Step 1**: Go to your webform and click on edit.

**Step 2**: Then go to the tab 'Webform'.

**Step 3**: At the top of the webform menu click on 'Form settings'.

**Step 4**: Go all the way to the bottom and click on 'Advanced Settings'.

**Step 5**: Make sure you click on the checkbox that says 'Available as block'.

**Step 6**: Go to /admin/structure/block. You can either hover over the 'Configure' link or click on the click to see the block id. It will look something like this 'client-block-341'.

**Step 7**: Use this snippet code to put into the template file you want to output the webform.

```
<?php
    $block = module_invoke('webform', 'block_view', 'client-block-341');
    print render($block['content']);
?>

```

This is the source of this solution.

# Answer
> 0 votes
First you have to install contact module inbuilt in drupal 7.

You Need to follow this refference link to install contact module:

http://www.inmotionhosting.com/support/edu/drupal-7/contact-us-page/how-to-install-the-contact-module-in-drupal?tsrc=rsbedu

http://www.inmotionhosting.com/support/edu/drupal-7/contact-us-page/configuring-the-contact-form-in-drupal?tsrc=rsbedu

http://www.inmotionhosting.com/support/edu/drupal-7/contact-us-page/adding-the-contact-form-to-the-menu-in-drupal?tsrc=rsbedu

Now you have to create one either block or node to showing contact form.

**contact form to a node,**

1. Open template.php in your theme folder and add the following code. Replace \[THEME NAME\] with the name of your theme. Replace the value of $nid with the actual ID of your node.

```
/**
 * Implements preprocess_node().
 */
function [THEME NAME]_preprocess_node(&$vars) {
  // Print contact form on contact page.
  $nid = 7;
  if ($vars['node']->nid == $nid && module_exists('contact')) {
    module_load_include('inc', 'contact', 'contact.pages');
    $contact_form = drupal_get_form('contact_site_form');
    $vars['contact_form'] = render($contact_form);
  }
}

```
2. Open node.tpl.php in your theme folder (if you don't have it, copy it from your base theme or from modules/node). Add the following code to the spot where you would like the contact form to appear.

```
if (!empty($contact_form)) {
  print $contact_form;
}

```
3. Clear all caches.

==== OR ====

**contact form to a block**

1). Open template.php in your theme folder and add the following code. Replace \[THEME NAME\] with the name of your theme. Replace the value of $module and $delta with the actual string values.

Hint: To locate these values go to admin/structure/block and click on the "configure" link next to the block you want to print. The strings will be shown in the URL as such: admin/structure/block/manage/\[module\]/\[delta\]/configure.

```
    /**
     * Implements preprocess_block().
     */
    function [THEME NAME]_preprocess_block(&$vars) {
      // Preprocess the Contact form block.
      $module = 'block';
      $delta = 3;
      if ($vars['block']->module == $module && $vars['block']->delta == $delta) {
        module_load_include('inc', 'contact', 'contact.pages');
        $contact_form = drupal_get_form('contact_site_form');
        $vars['content'] = render($contact_form);
      }
    }

```

2). Clear all caches.

---
Tags: 7, forms
---


# Question
Title: Pre-populate a user reference field during drupal commerce checkout - buying a gift for a user without manual username entry
I am creating a gift shop website where users can buy gifts for other users. So on every user profile i want to add a link "buy gift for this user" which takes you to the product page. After adding items to cart and checkout, a "gift recipient" (user-reference) field is already pre-filled with the name of the user from whose profile the shopping was initiated (not the name of the logged in user). Is this sort of thing possible in drupal 7? How can i achieve such? Thanks.

# Answer
> 1 votes
I don't know ready solution from the box for your use case but it's possible to implement it with Drupal Commerce and Line items functionality.

You can extend Line Item with the user reference field "gift recipient". User value will be saved on line item but not a product. Than everything is in your hands. E.g. you can click on option "Include this field on "Add to Cart" form. Or you can prepopulate this field using special get parameter in the "buy gift for this user" link.

For more information about extending Line Items see the video: http://vimeo.com/31459435

---
Tags: 7, commerce
---


# Question
Title: Is it possible to define hook functions in template.php instead of the module?
Theme functions are defined in the `template.php` but is it possible to define hook functions in there? for example There is a content type called `phone-book`, its add content form ID is `phone-book-node`, I want it to redirect to my custom page when it is submitted. so I created this function in the `template.php` :

```
function MYTHEME_form_phone_book_node_form_alter(&$form, &$form_state, $form_id) {
$form_state['redirect'] = 'go/some/where';
}

```

but it doesn't work. I don't know if it is totally impossible to define such hook functions inside `template.php` or something is wrong with my code.

# Answer
> 11 votes
Yes, you can implement *any* alter hook in a theme, as well as `hook_theme()` and preprocess hooks.

Adding `$form_state['redirect']` won't do anything there, though. You need to do that in a submit handler:

```
function MYTHEME_form_phone_book_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYTHEME_phone_book_node_form_submit';
}

function MYTHEME_phone_book_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'go/some/where';
}

```

To ensure that your hook is running, get the Devel module installed and add `dpm('alive');` in there. Then clear the caches (to be sure) and refresh the page a couple of times. If you don't see the debug message, the hook isn't being called, and it might be named incorrectly.

---
Tags: theming, hooks, forms
---


# Question
Title: #validate not overriding the submit function
I'm creating a form in my own module (call it `mymodule`) and using a `#validate` property to clear the form. In my form definition, after calling hook\_menu and hook\_form,

```
function mymodule_myform($form_state){
$form['main']=array(
    '#type'=>'fieldset',
    '#title'=>t('Information'),
    '#collapsible'=>TRUE,
    '#collapsed'=>FALSE,
);
$form['main']['title']=array(
    '#description'=>t('Enter title.'),
    '#type'=>'textfield',
    '#size'=>50,
    '#default_value'=>'default',
);
$form['submit']=array(
        '#type'=>'submit',
        '#value'=>'Submit',
);
    $form['clear']=array(
        '#type'=>'submit',
        '#value'=>'Reset form',
        '#validate'=>array('mymodule_myform_clear') //redirects to the _clear function defined below
);
    return $form;
}
    function mymodule_myform_clear($form, $form_state) {
        unset($form_state['values']);
        $form_state['rebuild']=TRUE; //clears the form
    }

    function mymodule_myform_submit($form, &$form_state) {
        $values=$form_state['values'];
        die('the value you submitted: '.$values['title']);

```

Both functions get called when the Reset from button is pressed. Why is the `#validate` property not doing its job?

# Answer
> 4 votes
Like Clive said resetting `$form_state['input']` is the solution, however I'd rather handle both actions in the submit function:

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

  if($form_state['clicked_button']['#value'] == $form['clear']['#value']) {
    $form_state['input'] = array();
    $form_state['rebuild'] = TRUE;
  } else {
    $values = $form_state['values'];
    die('the value you submitted: '.$values['title']);
  }

}

```

---
Tags: forms
---


title: node_presave doesn't work

text:
# Question
Title: node_presave doesn't work
I'm trying to do something before my invoice saves. In my invoice module I have:

```
function invoice_node_presave($node) {
  var_dump($node); die;
  if ($node->type == 'invoice') {
    // If true we are creating a new invoice
    if (intval($node->invoice_number) == 0) {
      // Get new invoice number
      if (intval($node->user_defined_invoice_number) > 0) {
        $node->invoice_number = $node->user_defined_invoice_number;
      }
      else {
        $node->invoice_number = _invoice_get_new_invoice_number();
      }
    }
  }
  ......
}

```

As you see I have a `var_dump($node)` & a `die;` . This works perfect. But then when I want to add the following in my `template.php` :

```
function xmed_node_presave($node){
  dump($node); die;
  if (($node->type == 'invoice')) { //node has not been saved
      dpr($node); die;
  }

```

}

He doesn't die. He just runs... Also the rest of functions in my `template.php` like function `xmed_preprocess_page(&$vars)` work.

# Answer
If you see below code in node.module node\_save() function..

```
module_invoke_all('node_presave', $node);

```

It's only invoked if you implement it in modules..

* Create a folder called 'custom' in sites/all/modules
* Create a folder called 'mynodeactions' in above custom folder
* Create a file called mynodeaactions.info inside above folder with

below code

```
name = My Node Actions
description = A custom module to tackle different node actions
core = 7.x
package = Custom

```
* Create a file called mynodeactions.module inside 'mynodeactions' folder with

below code

```
<?php

function mynodeactions_node_presave($node){

}

?>

```

For more information See the Creating Drupal 7.x modules if you're not sure
> 4 votes

# Answer
`hook_node_presave()` is only invoked for modules, so you can't implement it in a theme.

It'll need to go in a custom module instead.

From a best practice point of view, that sort of logic definitely shouldn't be at the theme layer, it should be in a module.
> 4 votes

---
Tags: nodes, users, theming
---


title: Comment form not working in Drupal 7.x

text:
# Question
Title: Comment form not working in Drupal 7.x
Primary tabs

```
View(active tab)
Edit

```

**Status message**

Forum topic Comment form not working has been created. Posted by jassics on February 8, 2014 at 9:49pm

I am facing problem in commenting over blog or forum contents. It is simply showing this error:

**Error**

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

```

While checking error log I got this:

> EntityMetadataWrapperException: Unable to get the data property format as the parent data structure is not set. in EntityStructureWrapper-\>getPropertyValue() (line 438 of /home6/cusatalu/public\_html/sites/all/modules/entity/includes/entity.wrapper.inc).

and when I checked filedsets I saw these warnings

> Notice: Undefined index: comment\_node\_panel in \_field\_ui\_bundle\_admin\_path() (line 325 of /home6/cusatalu/public\_html/modules/field\_ui/field\_ui.module). Notice: Undefined index: comment\_node\_panel in field\_ui\_fields\_list() (line 35 of /home6/cusatalu/public\_html/modules/field\_ui/field\_ui.admin.inc).

Hope, someone is familiar with this error and would help me to fix soon.

I posted this in Drupal official site too.

# Answer
> 0 votes
First problem see: https://drupal.org/node/1909078#comment-8718835

"While I could be mistaken, I'm pretty sure that the error regarding "Unable to get the data property format..." (note the emphasis on format) when inserting a comment is due to code in:

message\_notify/plugins/notifier/abstract.inc

Specifically these lines:

```
// Get the format from the field. We assume the first delta is the
// same as the rest.
if (empty($wrapper->{$field_name}->format)) {
  $wrapper->{$field_name}->set($output[$view_mode]);
}
else {
  $format = $wrapper->type->{MESSAGE_FIELD_MESSAGE_TEXT}->get(0)->format->value();
  $wrapper->{$field_name}->set(array('value' => $output[$view_mode], 'format' => $format));

```

}

The error occurs in the "comment insert" message type for the field\_message\_rendered\_body field (and not the field\_message\_rendered\_subject field) since it's a textarea that by default allows filtered text types to be selected (i.e. in Managed Fields, select the rendered body field and you'll see "Filtered text (user selects text format)" checked under "Text processing"). I haven't investigated fully yet but the bug can be avoided by selecting "Plain text" under "text processing" in the meantime (which will bypass the empty $wrapper-\>type-\>{MESSAGE\_FIELD\_MESSAGE\_TEXT}-\>get(0)-\>format-\>value() in the ELSE statement)."

---
Tags: 7
---


# Question
Title: Granting access based on an entity reference field using rules
I have two content type one called audit and one called non-conformance, a non conformance is raised after an audit has been complete.

An audit contains an entity reference field called auditee which references a user, I would like to give edit access to the non conformance based on the the content of the auditee field in on the content type audit.

Thanks

# Answer
> 2 votes
This should do the trick for you. You only have to write the code for extract\_uid\_from\_audit(); if you don't know how we can help as well.

```
function mymodule_node_access($node, $op, $account) {
    if(!empty($node->type) && ($node->type == "non_conformance")
             && $op=='update') ){
        $uid = extract_uid_from_audit($node);
        if($uid = $account->uid)
             return NODE_ACCESS_ALLOW;
    }
}

```

# Answer
> 1 votes
You can do this with a couple of modules + a view that uses an entity reference display.

If you add the "Node access user reference" module, you can create a view that lists users of a specific role (I guess they would have a role like auditees?). Details from project page:

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

When you configure the auditee entity reference field, you can use that view to populate the field and you can set the field so that those auditee users have varying degrees of access. It's also a good idea to allow the original authors of the to continue having permissions of view, edit, delete.

---
Tags: rules, entities
---


title: How to tell if XML Sitemap is correct?

text:
# Question
Title: How to tell if XML Sitemap is correct?
I have installed the XML Sitemap module, and enabled the xmlsitemap\_menu sub-module. I found how to add the main menu to the sitemap (via this site - no thanks to the module's documentation). When I go to the XML Sitemap admin page, it lists `mysite/sitemap.xml` as having 91 links and 1 pages. Shouldn't the page count be higher? Also, I would like to view the generated output, but when I click the `sitemap.xml` link, all I get is a table with link to the front page.

How can I see the actual XML or sitemap output?

# Answer
To make sure you have the content types that you want in your sitemap, you can enable `xmlsitemap_node`. After enabling, visit each content types configuration page and select "Include" under the xmlsitemap tab.

After setting each content type, you can check the Included/Excluded status for all content types under the xmlsitemap module config page.

Once that is complete, you can run cron manually to regenerate the sitemap links. Check `www.yoursite.com/sitemap.xml` to view the newly generated sitemap.
> 1 votes

---
Tags: xml-sitemap
---


# Question
Title: Views - adding relationship adds duplicate row for each relation
Sorry if the title is a little vague, I don't know how else to describe it in the space.

I have a view that shows Drupal Commerce orders. I am trying to add the SKUs of each product in an order as a field for filtering reasons. However, when I add a relationship to reference line items in the orders, I end up with duplicate rows, one for every line item in an order. I've tried aggregation and making queries distinct, neither of which do what I want.

# Answer
Do this:

Add relationships:
1. Commerce Order: Referenced line items
2. Commerce Line item: Referenced products

In Other set Set Aggregation to Yes

Include fields:
1. Commerce Line Item: Line item ID, set aggregation to COUNT and tick Exclude from display
2. Commerce Product: SKU, set aggregation to COUNT and tick Exclude from display.

Add a Filter criteria:
1. Commerce Product: SKU. Expose it to the visitor to your liking, and leave aggregation type to Group results together.

Now you will have only one row returned with no duplicates and you can filter SKU
> 2 votes

---
Tags: views
---


# Question
Title: Drupal Commerce: Authorize.net payment from manual order
I would like to handle manual phone orders from my Drupal Commerce site. But the Authorize.Net rule does not appear in the Payment tab for admin/manually created orders. It even disclaims this for the SIM/DPM rule I'm using.

So what do I do? I sense this has something to do with a requirement of SIM/DPM being that credit cards aren't stored locally. That's ok with me, I just need to run the credit card they gave me on the phone, I don't need it stored.

I really just need to be on the payment step of the checkout form for them. What is it about the SIM/DPM limitation that prevents me doing that step from the admin page?

# Answer
> 0 votes
It's really just a simple matter that the payment terminal form doesn't fully imitate the checkout form on the front end, so redirected payment methods or direct post payment methods are not going to be supportable there.

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


title: Block on user profile only

text:
# Question
Title: Block on user profile only
I have blocks for several profile types that links to users photos videos etc. (think myspace)

With arguments it works nice, block is visible only on page created by userXY and leads to other content made by userXY.

But, when userXY logs into his account and goes to "My account" it leads to www.example.com/user

Now blocks from all profile types are visible and they lead to false urls. The correct block is also there and works well but i can't find a way to limit other blocks not to be shown here.

I am using profile2, tokens and real name module.

Other problem which was thinking of to solve the issue was to change pattern for /user into /role/realname or anything that will change from default /user but nothing seems to work (pattern is ignored).

# Answer
I think you have 2 main options:

You can use some custom PHP to control the blocks visibility. Something like:

```
global $user;
$account = user_load($user->uid);
if($account->profile_type[LANGUAGE_NONE][0]['value'] == 'some value') return true;
return false;

```

Or I think this is a good use case for the Context module. This allows you to create different "contexts" that your blocks should appear in. An example from the Context help file says:

You want to create a "pressroom" section of your site. You have a press room view that displays press release nodes, but you also want to tie a book with media resources tightly to this section. You would also like a contact block you've made to appear whenever a user is in the pressroom section.

1. Add a new context on admin/build/context
2. Under "Conditions", associate the pressroom nodetype, the pressroom view, and the media kit book with the context.
3. Under "Reactions \> Menu", choose the pressroom menu item to be set active.
4. Under "Reactions \> Blocks", add the contact block to a region.
5. Save the context.
> 0 votes

# Answer
In the end i made 2 identical blocks in views, one to show only on /user\* and other to show everywhere else where it is in relationship with user-role type except /user\*
> 0 votes

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


title: Responsive menu breakpoints

text:
# Question
Title: Responsive menu breakpoints
I want to change the breakpoint of the Bootstrap Responsive Menu, from 768px to 900px. There is a simple way to do this by modifying @grid-breakpoint in variables.less; I have installed the less module, but yet changes there are not having any effect.

The code for the media query is being called in bootstrap.min.css via CDN. Can someone help? How do you recompile the CSS after making changes to the .less file?

On Bootstrap's site you can configure what you want and download; in Drupal this isn't the case, nor is there any config in the admin UI, to make these simple changes.

# Answer
You can override the set media queries in your custom css or less files. For the menu, you need to change at least two classes like so:

To hide the menu in a wider breakpoint (\> 768)

```
@media (max-width: 900px){
  .navbar-toggle {
    display: none;
  }
  .navbar-collapse.collapse {
    display: block;
  }
}

```

To hide the menu in a smaller breakpoint (\< 768) you have to override everything from your breakpoint up to 768:

```
@media (min-width: 480px) and (max-width: 768px){
  .navbar-toggle {
    display: none;
  }
  .navbar-collapse.collapse {
    display: block;
  }
}

```
> 2 votes

---
Tags: theming
---


title: Display Multistep Progress

text:
# Question
Title: Display Multistep Progress
I've created a multistep form to add new customer details when they sign up. So for example, step 1 is personal details. step 2 is contact details. Step 3 in social network details.

Only the fields in step 1 are mandatory so the user can skip steps 2 and 3 and finish registration.

1. How do I display a progress bar whilst the user is using the form?
2. I was wondering if I could display a 'Profile completion' percentage in a view to show the user they've only completed x% amount of their profile?

Something like this from LinkedIn:

Thanks, Rumman

# Answer
> 1 votes
You can try using Profile Complete Percent module..

Project page says

> Profile Complete Percent (PCP) is an add-on to the core Profile module or the Profile2 module. It allows administrators to select profile fields as mandatory for a user to achieve a 100% profile completeness status.

---
Tags: views, forms
---


title: Search by node ID

text:
# Question
Title: Search by node ID
I am using the Search module and I would love to add a function to it which gives a user the possibility to enter a node ID in the search field and look for it. Is there any chance to take this effect?

# Answer
> 0 votes
* Create a view with page display
* Add Filter Node : ID
* Expose Above Filter to user

Please find the view exported below which you can import using views import functionality..

```
$view = new view();
$view->name = 'search_by_node_id';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Search By Node ID';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Search By Node ID';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Nid */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['exposed'] = TRUE;
$handler->display->display_options['filters']['nid']['expose']['operator_id'] = 'nid_op';
$handler->display->display_options['filters']['nid']['expose']['label'] = 'Node ID';
$handler->display->display_options['filters']['nid']['expose']['operator'] = 'nid_op';
$handler->display->display_options['filters']['nid']['expose']['identifier'] = 'nid';
$handler->display->display_options['filters']['nid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'search-by-node-id';
$translatables['search_by_node_id'] = array(
  t('Master'),
  t('Search By Node ID'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Node ID'),
  t('Page'),
);

```
* Navigate to 'search-by-node-id' to see results once you import view..

---
Tags: nodes, search
---


title: Contact Form is not sending mails

text:
# Question
Title: Contact Form is not sending mails
I am new to Drupal. I am using Drupal 7 version in the WAMP local server. I had installed the customized Drupal theme in Drupal 7. In that customized theme i have a contact form but it is not sending emails. I did checked the email address at the contact form in structure(Admit toolbar) and also i checked the people authentication but i did not found the way to send an email in the contact form. Could you please assist me to get a solution for this.

# Answer
> 0 votes
May be mail server is not properly configured on your system. So go for alternative :

You can use SMTP Authentication Support module and configure it.

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

After proper configure you can send mail using external mail server like gmail, hotmail, yahoo etc.

Gmail smtp confguration are :

```
SMTP Port: 465
SMTP SERVER : smtp.gmail.com
Use encrypted protocol : SSL

```

Other configuration detail visit here After all configuration your project will be able to send mail.

---
Tags: forms, emails
---


title: How to use Views on custom route?

text:
# Question
Title: How to use Views on custom route?
Views require "Use AJAX" in order to display exposed filters when using Block display. I think this is necessary to avoid submitting/influencing other form elements on the current page.

I have a page that is a View but my page has to have a certain route name because my app relies on it. So I've used Block display for the Views instead of the Page display.

But I want the user to see the filtering arguments in URL so he can save the search or link to it. So obviously I will have to use the Page display for my view. But how can I use the Views with mine route?

---

Is is a good idea to create a Page view with some dummy path and load the View's route and get it's content and display it via mine route controller?

---

At first I've used the config option mentioned by Daniel Wehner but I ended up with using a custom filtering form + query tag. This gave me much better flexibility and customization options than Views' exposed filters.

# Answer
There are a couple of things you can try out:

1. Write a display plugin for views which extends the page one and allows you to specficy the route name in the UI. Note: views already uses a option in the view yml file 'route\_name' if it is available:

```
display:
 page_1:
   display_options:
     path: node
     route_name: hallo_world

```

So you could just hack your yml file and be done.
2. Use the route alter event and simply rename the route generated by views:

```
protected function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get("view.$view_id.$display_id")) {
    $collection->remove("view.$view_id.$display_id"); // not sure about the method name.
    $collection->add('hey.this.is.my.cystom.route.name', $route);
  }
}

```
3. Be okay with the name views generates, as it won't change over time.
> 3 votes

---
Tags: views, 8, routes
---


# Question
Title: Help understanding how to modify lay out of pages within drupal
I have built my website locally and I am trying to have three pictures display on all pages of the website. Those three pictures need to be on one line:

Now I have the pictures as such:

* picture 1
* picture 2
* picture 3

I need:

> picture 1, picture 2, picture 3

I understand that I need to create a css file that will alter the structure of all the pages to display the pictures. I have done that following example on the net.

```
.field-type-image {
  float: left;
  padding-left:20px;
}

```

Now I have edited the .info file of my website to link the style.css but the pictures are still not showing the way I want. Moreover, they are only showing on one page.

What am I missing here ?

I have used firebug to try to find the css page on which I could have made the change for the pictures to appear but there were none. That is why I decided to create the style.css

# Answer
> 1 votes
I assume you are embedding the images in a block which you then show on all your pages.

If you reference a background-image from your style sheet as in url(../images/hello.jpg) all works fine because the style sheet, no matter what page you are looking at, references images from the style sheet directory as a base . If you embed an image tag on a page your img url will not be correct for pages of different depths as the page's url changes, and it is the page url that is the base. You have two quick solutions:

1. Pathalogic module - it is a text input filter that will rewrite your embedded anchor and image paths automatically
2. PHP Filter - It is also a text input filter. Rewrite the path using the l() function, or concatenate it onto $base\_url in a PHP snippet. This method is not preferred and support for the PHP Filter has been dropped in Drupal 8.

**And as to the css and theming problems:**

Marinelli is using a 960 grid system. There are lots of information on the web available on that and I suggest you read up on that.

In short, you must add appropriate classes to your images which will then take care of the css on your behalf. To float 3 images horizontally you need to add the following classes to your images.

image 1. class="alpha grid\_4"
image 2. class="grid\_4"
image 3. class="grid\_4 omega"

And depending on your use case you might need to do a clearfix on the parent container.

---
Tags: theming
---


# Question
Title: Ability for user to flag or select multiple nodes from view listing
I am creating a page where I have a view listing about **100 nodes of a specific content type** and then underneath that I have a contact form. When visitors (logged out users) come to my site I would like them to be able to select some nodes from this view that they like. Either with a checkbox next to each one of them or by some other flagging system. When they then complete my form the specific nodes they have chosen will be sent with the form submission.

Possible Solutions:

1. Create a template file for the view and add in a checkbox in front of each node.
2. Use the flags module and pass the selected nodes when submitting.

I've never done something like this before so any help would be appreciated!

# Answer
> 0 votes
Here is a solution with webform and flags:

**1. Create a small module.** You can create a very simple module for it - an info file and a module file with your functions. https://drupal.org/node/1074360

**2. Implement hook\_webform\_submission\_presave().** This will intercept the form data on the webform submission form submission form before it gets saved in the database.

**3. Get the flags that the current user flagged with flag\_get\_user\_flags().** You will receive an array of flags, that you can process as you like, add to form results array for later use, or, if you have a hidden text area called 'flags' in your form, insert that data there as a formatted text.

So, in totality, it will be something like this:

```
function leadflag_webform_submission_presave($node, &$submission) {
  $nodes_list = '';
  $title = '';
  // Get the flags.
  $flags = flag_get_user_flags('node');
  // Get the nodes.
  if (!empty($flags)) {
    $flags = $flags['flag_name'];
    foreach ($flags as $flag) {
        $nid = $flag->entity_id;
      // Get node data. Delete to not get node titles.
      $node = node_load($nid);
      $title = $node->title;
      // Combine data.
      $nodes_list .= 'node/' . $nid . ' ' . $title . ",\n";
    }
  }

  // Update some component's value before it is saved.
  $component_id = 4;
  $submission->data[$component_id][0] = $nodes_list;
}

```

This function gets flagged nodes and populates the webform component 4 with node/nids and titles, like this:

```
node/10 Node Title of node 10,
node/21 Node Title of node 21, etc

```

The function gets the flags and puts them in form component 4. You need to hover your mouse over your textarea component edit link on the webform components edit page to see what component number it actually is, in the edit link url. Replace the component number in code with your actual component number.

There is a section (lines 13-15), that loads nodes to get their titles. Doing node loads is somewhat an expensive function. It's Ok unless you expect dozens of submissions per minute though. But to not have node\_loads, and to only have a list like 'node/10, node/15' without titles, you can delete these lines.

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


title: Get view machine name programmatically

text:
# Question
Title: Get view machine name programmatically
I am using a code

```
<?php
print $view->display['view_machine_name']->handler->options['title'];
?>

```

I put machine name in view\_machine\_name and everything work but I have few displays with different machine names and in other cases I still print same title. Can I get a function which takes the view machine name?

# Answer
> 2 votes
You can try views\_get\_page\_view() function, Which return Views object and you can get current views name on `$views_page->name`

---
Tags: views
---


title: When should I use an existing field?

text:
# Question
Title: When should I use an existing field?
While adding new fields to a content type, When should I resue an existing field? for example if I need an image field for my content type is it always a good idea to re-use an existing image field?

# Answer
Consider the benefits and drawbacks of reusing fields:

* **Performance**: There's a slight performance gain from reusing fields. However, for most sites with moderate numbers of fields, it's a negligible difference.
* **Maintainability**: In theory, if you re-use the same field for the same purpose on multiple content types, then if you decide to change its functionality later, you only have to change it in one place. Similarly, if you want to theme it the same way across entities, you only have to use a single selector. In practice, this rarely happens, and more often the converse is true- you've used the same field in multiple places, and then realize that they actually need to behave differently.
* **Setup**: Obviously, it takes less time to re-add an existing field than to add a new one.
* **Portability**: If you export fields with Features, it's best to not reuse them between entities unless absolutely necessary. Technically, there's nothing wrong with reusing fields (since you can export field bases and field instances separately), but in practice it tends to just lead to confusion and circular dependencies. If you choose not to reuse fields, then you have the luxury of being able to prefix them with the content type / bundle they are attached to, e.g. "field\_article\_image", "field\_page\_taxonomy", etc..., which eases portability and maintenance.

In case it's not clear from my tone there, my preference is to never reuse fields unless it's totally, completely, 100% clear that they really are, and forever will be, used for the same purpose.
> 11 votes

---
Tags: 7, entities
---


# Question
Title: Entity Reference View Widget Ajax Modal Error
I am using the Entity Reference View widget. But having some issues with it.

The widget is showing up with a Add Item button on the node creation form, however when i click on that Add Item button it throws an ajax error which i am posting below:

This happens only for the front end version of the node creation form where the user does not have access to the admin theme and the user is presented with the node creation form using the Bartik theme.

But if i click on that Add Item button from the admin version of the node creation form the modal window appears.

**The ajax error output:**

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /drupal/system/ajax
StatusText: OK
ResponseText: string(18) "activity_node_form"
string(38) "entityreference_view_widget_modal_form"
[{"command":"settings","settings":{"basePath":"\/drupal\/","pathPrefix":"","ajaxPageState":{"theme":"bartik","theme_token":"6j38qKKVNPN5klA-SwBBSrbDCPUHdBtZhm24TI-uqD4","js":{"sites\/all\/modules\/contrib\/views\/js\/base.js":1,"sites\/all\/modules\/contrib\/views\/js\/ajax_view.js":1}},"datePopup":{"edit-field-due-date-und-0-value--2-datepicker-popup-0":{"func":"datepicker","settings":{"changeMonth":true,"changeYear":true,"autoPopUp":"focus","closeAtTop":false,"speed":"immediate","firstDay":0,"dateFormat":"mm\/dd\/yy","yearRange":"+0:+3","fromTo":false,"defaultDate":"0y"}},"edit-field-due-date-und-0-value--2-datepicker-popup-1":{"func":"datepicker","settings":{"changeMonth":true,"changeYear":true,"autoPopUp":"focus","closeAtTop":false,"speed":"immediate","firstDay":0,"dateFormat":"mm\/dd\/yy","yearRange":"+0:+3","fromTo":false,"defaultDate":"0y"}}},"CToolsModal":{"loadingText":"Loading...","closeText":"Close Window","closeImage":"\u003Cimg typeof=\u0022foaf:Image\u0022 src=\u0022http:\/\/localhost\/drupal\/sites\/all\/modules\/contrib\/ctools\/images\/icon-close-window.png\u0022 alt=\u0022Close window\u0022 title=\u0022Close window\u0022 \/\u003E","throbber":"\u003Cimg typeof=\u0022foaf:Image\u0022 src=\u0022http:\/\/localhost\/drupal\/sites\/all\/modules\/contrib\/ctools\/images\/throbber.gif\u0022 alt=\u0022Loading\u0022 title=\u0022Loading...\u0022 \/\u003E"},"views":{"ajax_path":"\/drupal\/views\/ajax","ajaxViews":{"views_dom_id:3133a30022520ec477a4278110a71fcb":{"view_name":"tester_view","view_display_id":"entityreference_view_widget_1","view_args":"","view_path":"system\/ajax","view_base_path":null,"view_dom_id":"3133a30022520ec477a4278110a71fcb","pager_element":0}}},"ajax":{"edit-button-add":{"callback":"entityreference_view_widget_ajax","event":"mousedown","keypress":true,"prevent":"click","url":"\/drupal\/system\/ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Submit"}}}},"merge":true},{"command":"insert","method":"prepend","selector":"head","data":"\u003Cscript type=\u0022text\/javascript\u0022 src=\u0022http:\/\/localhost\/drupal\/sites\/all\/modules\/contrib\/views\/js\/base.js?n4lxu8\u0022\u003E\u003C\/script\u003E\n\u003Cscript type=\u0022text\/javascript\u0022 src=\u0022http:\/\/localhost\/drupal\/sites\/all\/modules\/contrib\/views\/js\/ajax_view.js?n4lxu8\u0022\u003E\u003C\/script\u003E\n","settings":null},{"command":"modal_display","title":"tester view","output":"\u003Cform action=\u0022\/drupal\/system\/ajax\u0022 method=\u0022post\u0022 id=\u0022entityreference-view-widget-modal-form\u0022 accept-charset=\u0022UTF-8\u0022\u003E\u003Cdiv\u003E\u003Cdiv class=\u0022view view-tester-view view-id-tester_view view-display-id-entityreference_view_widget_1 view-dom-id-3133a30022520ec477a4278110a71fcb\u0022\u003E\n        \n  \n  \n      \u003Cdiv class=\u0022view-content\u0022\u003E\n      \u003Ctable class=\u0022views-table cols-0\u0022 \u003E\n       \u003Ctbody\u003E\n          \u003Ctr class=\u0022odd contextual-links-region views-row-first\u0022\u003E\n                  \u003Ctd class=\u0022views-field views-field-title\u0022 \u003E\n            lead for areeb 1          \u003C\/td\u003E\n                  \u003Ctd class=\u0022views-field views-field-contextual-links\u0022 \u003E\n                      \u003C\/td\u003E\n              \u003C\/tr\u003E\n          \u003Ctr class=\u0022even contextual-links-region\u0022\u003E\n                  \u003Ctd class=\u0022views-field views-field-title\u0022 \u003E\n            lead two          \u003C\/td\u003E\n                  \u003Ctd class=\u0022views-field views-field-contextual-links\u0022 \u003E\n                      \u003C\/td\u003E\n              \u003C\/tr\u003E\n          \u003Ctr class=\u0022odd contextual-links-region views-row-last\u0022\u003E\n                  \u003Ctd class=\u0022views-field views-field-title\u0022 \u003E\n            lead one          \u003C\/td\u003E\n                  \u003Ctd class=\u0022views-field views-field-contextual-links\u0022 \u003E\n                      \u003C\/td\u003E\n              \u003C\/tr\u003E\n      \u003C\/tbody\u003E\n\u003C\/table\u003E\n    \u003C\/div\u003E\n  \n  \n  \n  \n  \n  \n\u003C\/div\u003E\u003Cinput id=\u0022ervw-modal-form-selected-entity-ids\u0022 type=\u0022hidden\u0022 name=\u0022selected_entity_ids\u0022 value=\u0022\u0022 \/\u003E\n\u003Cdiv class=\u0022entityreference-view-widget-modal-submit form-wrapper\u0022 data-table-id=\u0022field-lead-values\u0022 id=\u0022edit-submit--3\u0022\u003E\u003Cinput class=\u0022button form-submit\u0022 type=\u0022submit\u0022 id=\u0022edit-button-add\u0022 name=\u0022op\u0022 value=\u0022Submit\u0022 \/\u003E\u003C\/div\u003E\u003Cinput type=\u0022hidden\u0022 name=\u0022form_build_id\u0022 value=\u0022form-iY6e3YhFi5F8G4fqw1e0aetgY3uHlKlZ9CwzGhgRj5A\u0022 \/\u003E\n\u003Cinput type=\u0022hidden\u0022 name=\u0022form_token\u0022 value=\u0022_qcVVA7uU-ngfULgfXXYi7_tAAHXOwVlefqAj6QAIJ8\u0022 \/\u003E\n\u003Cinput type=\u0022hidden\u0022 name=\u0022form_id\u0022 value=\u0022entityreference_view_widget_modal_form\u0022 \/\u003E\n\u003C\/div\u003E\u003C\/form\u003E"}]

```

# Answer
> 1 votes
Found the issue mintues after posting the question..

It turns out i had var\_dump being used in my template.php and it was causing the error.

I also tried disabling some development related modules such as **Deve**, as i read in some other questions where people had similar issues. Just wanted to post this here for future reference and anyone else who comes across it.

---
Tags: views, ajax, entities, javascript
---


# Question
Title: How to move an article to another place.
I just add 10 articles in my drupalwebsite, but now I want to change the place of my articles.

The article that I have added first is now at the bottom. This should be at the top. Everything is in reverse order. How can I change this?

Thx for helping.

# Answer
> 2 votes
* Promoted to home page content is ordered by created data.. So, Change authored date accordingly..
* Make them sticky by editing content and checking sticky at top of lists checkbox to place them on top of list in home page..
* If you are using views module you can set sort criteria..

---
Tags: nodes
---


title: Wrap Commerce widget attributes

text:
# Question
Title: Wrap Commerce widget attributes
Clicking on Whislist, it adds product to wishlist, and hides the wishlist button and replace it with text 'Already in wishlist' which I need to style and position, so to do that I at least need it to be in a div.

Is there a template?

# Answer
This video should sort you out. You need to use the hook form alter http://www.youtube.com/watch?v=xYMd6WDqxKY
> 1 votes

---
Tags: 7, theming, commerce
---


title: How to Create a Blank Page

text:
# Question
Title: How to Create a Blank Page
I need to create a completely blank page in Drupal. For simplicity sake the entire page should display the following:

```
<html>
    <body>
        <h2>Hello World!</h2>
    </body>
</html>

```

While I can normally just create a page outside of Drupal, this page will need to access some of Drupals functions such as db\_query. How can I create a completely blank page for a single url (e.g. http://www.example.com/blankpage)?

# Answer
I don't really advise this but here is a solution.

Create a php file in your Drupal root containing the following

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

```

That will give you access to the full Drupal api. You can then put whatever markup you wish underneath.

A better method (but more complicated) would be just to create a custom page callback in a module then you can use that to either bypass Drupals theming, or you can make it change the theme to a custom one that produces very basic markup (you'd have to create that yourself).

If you want any details on how to do that let me know :)
> 0 votes

# Answer
If you are wanting to create a blank page in drupal you need to do the following steps:

1.) Create a theme

2.) Next step is to create a template.php file that will contain html and page preprocessing using theme\_preprocess\_html and theme\_preprocess\_page

3.) You will make your theme suggestions and route them to a custom html.tpl.php and page.tpl.php file. Normally these will be your themes page and html templates where you render regions and any other changes. But in your case you want it to be blank so you can provide your own markup. Note this is not advised and is NOT best practices in drupal.

Here is an example of the template.php file rendering page--logout.tpl.php and html--logout.tpl.php

Note the mytheme is the name of your theme and you are going to add your information to the theme\_hook\_suggestions array. Drupal finds the most specific or in this case I prepended it to the beginning using array\_unshift

```
function MYTHEME_preprocess_page(&$variables){
  array_unshift($variables['theme_hook_suggestions'], "page__logout");
}

function MYTHEME_preprocess_html(&$variables){
  array_unshift($variables['theme_hook_suggestions'], "html__logout");
}

```
> 0 votes

---
Tags: hooks, 7, theming
---


# Question
Title: Disable encoded url showing non encoded url's content
My drupal website is indexed in Google and I found a link to http://mysite.com/node/345%3Fpage%3D1?page=2 while searching

When I click it it shows content of http://mysite.com/node/345?page=2

This may be due to some site or sitemap pointing to the url http://mysite.com/node/345%3Fpage%3D1?page=2. And Google indexing it.

**But** in drupal http://mysite.com/node/345%3Fpage%3D1?page=2 must show a page not found!

Any solution?

**The Question CLEARLY:**

why the url http://mysite.com/node/345%3Fpage%3D1 showing the content of http://mysite.com/node/345 instead of throwing an "not found" error?

Drupal is not considering "345%3Fpage%3D1" as the node id

# Answer
Finally I think I found a solution:

**Please correct me if I am wrong!**

Now its adding a canonical meta tag for **nodes** and for **forums** together **with the page variable**.

in my template.php I changed bartik\_preprocess\_node function and added bartik\_preprocess\_forums function.

```
function bartik_preprocess_node(&$variables) {
  //start added by me
    $uri = entity_uri('node', $variables['node']);
    if($GLOBALS['pager_page_array'][0] != 0){
        $uri['options']['query']['page'] = $GLOBALS['pager_page_array'][0];
    }
    // Set the node path as the canonical URL to prevent duplicate content.
    drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
    // Set the non-aliased path as a default shortlink.
    drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  //end added by me

  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
}

//added by me
function bartik_preprocess_forums(&$variables) {
    $uri = array();
    $uri['path'] = 'forum';
    if($variables['tid'] != 0){
        $uri['path'] = 'forum/'.$variables['tid'];
    }
    $uri['options'] = array();
    if(isset($GLOBALS['pager_page_array']) && $GLOBALS['pager_page_array'][0] != 0){
        $uri['options']['query']['page'] = $GLOBALS['pager_page_array'][0];
    }

    drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
}

```

**Also I removed the lines that adds the canonical meta tag in the node.module (But may not be a good idea to alter core modules).**

Therefor: mysite.com/node/345%3Fpage%3D3 would have a canonical as

```
<link rel="canonical" href="/node/345">

```

and mysite.com/node/345%3Fpage%3D3?page=2 would have a canonical as

```
<link rel="canonical" href="/node/345?page=2">

```

Similarly for the forum topic pages.
> 1 votes

# Answer
Using URL encoding to append a query string to an URL doesn't change the address of the URL. `%3F`, is just a slighly obscure way to write "?", and `%3D` is just a slighly obscure way to write "=".

So the URL:

```
http://mysite.com/node/345%3Fpage%3D1

```

is equivalent to this URL:

```
http://mysite.com/node/345?page=1

```

Wikipedia says:

> Reserved characters that have no reserved purpose in a particular context may also be percent-encoded but are *not semantically different* from those that are not.

So what happens is this: When that URL (`http://mysite.com/node/345%3Fpage%3D1`) is requested, page 1 of `http://mysite.com/node/345` is actually requested. If `node/345` exists on your site, Drupal will show it. If there are no pages defined, it doesn't matter, because Drupal by default ignores anything in the query string part of the URL that it does not recognise.

You wrote:

> Drupal is not considering `345%3Fpage%3D1` as the node id.

That is the correct behaviour. The node id is "345". What follows is what is known as a query string. A query string starts with either `?` or `%3F`. Those two ways of starting a query string are semantically equivalent.

This is how *all* Drupal sites works, if a non-existing pagination is specified in the query-string part of the URL, it is just ignored. Take a look of the following three URLs:

Notice that they *all* go to `node/2182323` on Drupal.org. That is because there is no page 42 for that node (there are actually no extra pages for that node).

As far as I know, there is no *simple* way to change this default behaviour to return a "Page not found" (404) response when there is no match for the query string part of the URL.
> 1 votes

---
Tags: uri
---


title: How to move read more

text:
# Question
Title: How to move read more
I have 10 articles in my website and on the bottom of my article there's a read more button. Now, I want the button after the first line of my article, but how I do that? Look at the picture.. I want the button after the text in bold.

Is it possible with views?

# Answer
Use views.

Create a new view for content type Articles, using fields.

Add fields for Title, Image, and any other content you wish to show.

Add field "read more" link, define what you want the link text to be.

Re-arrange fields to render the "read more" link wherever you like.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to add options to a select list of a content type?
I built a module that creates a form and let the user to add a variable called `unit` into database. Now this `unit` should be the `options` of select list of a content type. the form id of the content type is `phone_book_node_form`, but the problem is I can't add options to the select list. this is the firebug output of the form (content type)

the name of the select list field is `field_phone_yegan`. I tried this function in `template.php`

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id){
    switch ($form_id){
        case 'phone_book_node_form':
            $form['field_phone_yegan'] = array(
                '#options' => array('yes'=>t('yes'),'no'=>t('no'))
            );
            break;
    }
}

```

nut nothing was added to the select list. I also tested

```
$form['edit-field-phone-yegan-und'] = array(
                '#options' => array('yes'=>t('yes'),'no'=>t('no'))
            );

$form['field_phone_yegan[und]'] = array(
                '#options' => array('yes'=>t('yes'),'no'=>t('no'))
            );

```

but it didn't work. How do I can add options to this content type select list?

# Answer
It sounds like using a taxonomy would be more appropriate here. Taxonomies allow lists and terms can be automatically created from user input, in this example something like the Select (or other) module would be of use. Details from project page:

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.
> 1 votes

# Answer
I found it, first I should install the cck\_select\_or\_other module , it provides us two usefull textareas:

```
1. PHP Code

```

This textarea accepts php code and the php code should return an associative array which is used as options in the field. in my case this code works :

```
2. Other

```

The second, option `Other` is automatically added in the select list and by clicking on it, a textfield appears and lets you to insert your option.
> 0 votes

---
Tags: nodes, hooks, forms
---


# Question
Title: Printing Region With Content in Custom HTML
I am creating a custom first page that is blank and built up from scratch. However I want to print certain regions (e.g. the footer) on this page. How can I grab the region information/content and print it in the html in the welcomegeneratepage function.

```
<?php

//Create the redirect page
function module_name_menu() {
    $items['welcometest'] = array(
        'title' => 'Redirecting',
        'access callback' => TRUE,
        'delivery callback' => 'welcome_blank_page'
    );
    return $items;
}

//Function generate the redirect page
function welcome_blank_page() {
    //Get the redirect URL
    //Generate the HTML for the page
    $html = welcomegeneratepage();
    print $html;
}

//Generates the page html
function welcomegeneratepage() {
    print $footer;
    $html = "<html>
                <head>
                    <link rel=\"stylesheet\" type=\"text/css\" href=\"".drupal_get_path('module', 'module_name')."/css/module_name.css\">
                    <link rel=\"shortcut icon\" href=\"".variable_get('file_'.file_default_scheme().'_path',conf_path().'/files')."/favicon.ico\" type=\"image/vnd.microsoft.icon\" />
                </head>
                <title>
                        Welcome to ".variable_get('site_name')."
                </title>
                <body>
                   <div class=\"welcomecontent\">
                       <div class=\"welcomemessage\">
                           <h2>Welcome</h2>
                       </div>
                   </div>
                </body>
             </html>";
    return $html;
}

```

# Answer
> 1 votes
I haven't had any need for a blank page before, but couldn't you just create a new .tpl.php for the front?

Under site configuration, set a node as your front page, then create a copy of page.tpl.php and name it page--node--1.tpl.php (or whatever node ID you have) .

Delete all the divs and containers to make the page blank, and then render regions in php like normal.

> print render($page\['your\_region'\]);

---
Tags: hooks, blocks, routes, theming
---


title: hook_schema duplicate unique keys

text:
# Question
Title: hook_schema duplicate unique keys
I am reading book 'Drupal 7 module development'.

I am try to follow book to create a `hook_schema` (I delete some line for better read):

```
function artwork_schema() {
     $schema['artwork'] = array(
       'unique keys' => array(
         'aid_vid' => array('aid', 'vid'), // there is an 'aid'
         'aid'     => array('aid') // there is also an 'aid'
         ),
     );
     return $schema;
   }

```

what it is the meaning of the 2 `aid`?

Does mysql can create duplicate unique index?

# Answer
A field that is not defined as unique key or primary key is allowed to have the same value in different records of that database table. So, if you don't want to have the same value of aid in two different records, you need to define it as unique key, if it is not already the primary key.

Notice that the line defining aid\_vid as unique key would allow the following records.

```
aid  | vid  ! other_field
-------------------------
1      3      10
1      4      22
2      4      14

```

Only the line defining aid as unique key avoids two records have the same value for the aid field.
> 0 votes

---
Tags: database
---


# Question
Title: Outputting front page to a different url
I currently have this site tobyNews that is up and running with Drupal 7. However, while in the process of giving the site a mobile version, I thought maybe it would be easier if the front page content that is displayed when you first visit the site was simply output to another page, like m.tobynews.com . Is there any way to sort of add another output without altering the main page?

# Answer
> 0 votes
I would personally suggest putting breakpoints into the CSS and making the site adaptive. You would save yourself a lot of time building a separate mobile site.

Plus, especially with adaptive widths, and not fixed widths, you allow your site to display nicely on all sizes of device screen, and when a user reduces the size of their browser window on a desktop.

Alternatively, To detect a device and show a different site e.g. m.yoursite.com have a look at this answer.

---
Tags: 7
---


title: Move php in views to module

text:
# Question
Title: Move php in views to module
now and then i use php in views. Now i do this only when it's the only option. I often use this for specific action links (action links are links like: edit delete).

Now i don't want to save php in my database, it doesn't belong there. So i was wondering if their was an other option to add those action links i generate with php to each row. The action links need data from the current row.

Thx Nuctorn

# Answer
> 11 votes
You definitely want to create a views handler with your custom php code. This is the standard way to do custom php stuff on views module.

Here you have an example:

mymodule.info

```
...
files[] = views/handlers/views_handler_field_node_link_custom_stuff.inc
...

```

mymodule.module

```
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/views',
  );
}

```

In MYMODULE/views/mymodule.views.inc:

```
function mymodule_views_data() {
  $data['node']['custom_stuff'] = array(
    'field' => array(
      'title' => t('Custom link'),
      'help' => t('Provide a custom content link.'),
      'handler' => 'views_handler_field_node_custom_stuff',
    ),
  );
  return $data;
}

```

MYMODULE/views/handlers/'views\_handler\_field\_node\_link\_custom\_stuff.inc

```
/**
 * Field handler to present some custom HTML.
 */
class views_handler_field_node_custom_stuff extends views_handler_field_node {
  function construct() {
    parent::construct();
    $this->additional_fields['type'] = 'type';
  }
  function query() {
  $this->ensure_my_table();
  $this->add_additional_fields();
  }
  function render($values) {
    $type = $this->get_value($values, 'type');
    $nid = $this->get_value($values, 'nid');
    return mymodule_print_my_link($nid, $type);
  }
};

```

# Answer
> 2 votes
You can insert these links in the template layer. In the view's advanced settings, in Advanced-\>Theme, you can see what template names can there be. Then, copy the corresponding template file over into your theme layer and add the needed links.

# Answer
> 1 votes
You should definitely try Views built-in contextual links. Simply add `Global: Contextual Links` fields to your view. First you can add `Content: Edit Link` and `Content: Delete Link` and exclude them from display. And then you can plant the `Global: Contextual Links` field with via a simple checkbox. Be sure to add the edit and delete fields strictly before (on top of) your `Global: contextual links` field.

---
Tags: views
---


# Question
Title: Call to undefined function ctools_ajax_text_button()
What I need is a link to click and open a form in a modal.

Call to undefined function ctools\_ajax\_text\_button() in ctools\includes\modal.inc on line 184

This is how I'm calling the function in hook\_page\_build() function.

```
ctools_include('modal');
ctools_modal_add_js();

$links[] = ctools_modal_text_button(t('Modal Login'), 'modal_forms/nojs/login', t('Login via modal'));

```

Also tried bellow:

```
$test = ctools_modal_text_button('Test Link', 'node/123', 'alt here', 'no-class');

```

# Answer
I forgot to add ajax :)

```
ctools_include('modal');

```

**ctools\_include('ajax');**

```
ctools_modal_add_js();

```
> 2 votes

---
Tags: 7, views, javascript, chaos-tool-suite
---


# Question
Title: EntityMetadataWrapperException when accessing empty entity body. How can I test if body is empty first?
The following call

```
$body = $entity->body->value->value();

```

throw the following error

```
EntityMetadataWrapperException : Unable to get the data property value as the parent data structure is not set. dans EntityStructureWrapper->getPropertyValue()

```

when the body is empty.

How can I prevent it?

# Answer
> 2 votes
Just simply see the value is empty

```
if($node_wrapper->body->value() != ""){
 //Evaluates true
}

```

or use a try catch

```
try{
 echo $entity->body->value->value();
}catch(Exception $e){
  echo "Value does not exist continue";
}

```

---
Tags: entities
---


title: How to clear export_module for a view

text:
# Question
Title: How to clear export_module for a view
I am unable to export a particular view via Features UI because this view is supposedly default by a different module. In features.ctools.inc line 164 - 172:

```
// If this object is provided as a default by a different module, don't
      // export and add that module as a dependency instead.
      if (!empty($object->export_module) && $object->export_module !== $module_name) {
        $export['dependencies'][$object->export_module] = $object->export_module;
        if (isset($export['features'][$component][$object_name])) {
          unset($export['features'][$component][$object_name]);
        }
      }
      // Otherwise, add the component.
      else {
        $export['features'][$component][$object_name] = $object_name;
      }

```

As you see from the code, my view is not being exported because it has different 'export\_module'. How to clear 'export\_module' for a particular view to enable it export via features. This is what i did:

1. ensure that the other feature doesn't export this view.
2. Ensured that the setting 'Allow conflicts to be added' is selected.
3. I have cleared cache,
4. Deleted the tables cache, cache\_view.

No result, the view i like to export via feature continue to come up with 'export\_module' different making impossible to export. Any help much appriciated

# Answer
> 0 votes
After removing MODULE-Name\_views\_default\_views() in file MODULE-Name.views\_default.inc, the view was exporting in another feature/module just fine.

My learning is that if you rename views that are part of some feature/module say X then these views become impossible to export from any another feature/module Y unless you manually delete them from the MODULE-X-Name\_views\_default\_views() in MODULE-X.views\_default.inc file

# Answer
> 0 votes
bum....the same behavior is whenever i have two features exporting the same a variable via strongarm. This is really limiting me having a theme and then multiple different sites extending it....or having module(plugin) to share across multiple sites. Any suggestions how to remove this behavior where its possible to export a variable, view, etc that is shared between two or more features beside changing the core code?

---
Tags: views, chaos-tool-suite
---


# Question
Title: How should I store a static key pairs list?
I wish to store around 200 static key value pairs.

A few ways i can think of, are the following:

```
 - Using `variable_set()`
 - Using a custom table
 - Using a cache
 - Defining a constant in code
 - hard-coding the key pairs

```

The list will be referenced on every node. I am using the Views module as well.

How should I store the key pairs list in my case?

# Answer
* Regarding Using variable\_get and variable\_set

I would suggest storing them in variables tables using variable\_set in serailized format.. Store your 200 pairs data in an array using variable\_get function...

Variables are cached in cache\_bootstrap table so that performance will be improved.

* Regarding Custom Table

You will lose the cache ability and managing the rows like edit/insert will be a pain since you need to build logic to retrieve and update results.

* Regarding Cache Table

It will be a temporary storage. If some one clears all cache you will lose the data.

* Regarding Constant in Code

Yes.. You can use constants too.. I am not sure performance impact vs using variables.

* Regarding Hardcoded in code

I believe it's same as using constants. But, If you are trying to hardcode everywhere then you will end up with redundant code which will result in update - data consistency problem.

If you think in Drupal way i will say variables is the way to go using variable\_get and variable\_set..
> 2 votes

# Answer
Depends on how much return on invest this has. A few questions I'd throw out to myself if I were in your shoes:

* How often will this data change?
* Will I have to query individual parts of this data?
* How large is the contents for each key?

For the most part, if it's something simple, 200 keys isn't that many if the contents isn't huge. If you don't need to query the data, I'd just use the variable\_get approach and maybe a getter function that used a static variable for request context caching. If you need to to query the data, apply permissions, include it in the display, or index in search then I'd say make a custom entity and have the key and value as properties.
> 2 votes

---
Tags: 7
---


title: Form With Inline Input Boexes

text:
# Question
Title: Form With Inline Input Boexes
I am trying to create a form that will have the input boxes inline and next to one another. I have created the following module but nothing seems to help. Can anyone help to solve this issue? Also the form doesn't seem to be reacting to changes in the size parameters.

```
function name_search_block_info() {
    $blocks['name_search'] = array(
        'info' => t('Name Search Block'),
    );
    return $blocks;
}

function name_search_block_view($delta='')
{
     $block = array();
     switch($delta)
     {
        case 'name_search':
          $block['subject'] = t("Search Form");
          $block['content'] = "<div class=\"searchform\">".drupal_render(drupal_get_form('name_search_custom_search_form'))."</div>";
          break;
     }
     return $block;
 }

function name_search_custom_search_form($form_state) {
  $form = array();

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' =>array('placeholder' => t('Search')),
    '#maxlength' => 64,
    '#size' => 32,
    '#required' => TRUE,
    '#id' => 'searchfield',
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $form['location'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' =>array('placeholder' => t('Zip')),
    '#maxlength' => 5,
    '#size' => 7,
    '#required' => TRUE,
    '#id' => 'locationfield',
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );

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

  return $form;
}

function name_search_custom_search_form_submit($form, &$form_state) {
  $redirect_url = 'search/node/';
  $redirect_url .= 'type:' . $form_state['values']['type'];
  $redirect_url .= ' category:' . $form_state['values']['category'];
  $redirect_url .= ' %' . $form_state['values']['keyword'] . '%';

  $form_state['redirect'] = $redirect_url;
}

```

# Answer
> 0 votes
No need to add prefix/suffix markup, just add a container or fieldset and use CSS to float them inside.

---
Tags: 7, forms, theming
---


# Question
Title: Get data from a field using query in Computed field and use it as an array
I have a content type wherein the user will add holidays.

It has Holiday Date field(field\_holiday\_date).

How can I get the dates in that column using query and use it as an array in Computed field?

Thanks for you help!

# Answer
You can pass any value of node or something else in jquery like

```
$node_id = 5;
$node = node_load($node_id);
$settings = array(
    'title' => $node->title,
    'custom-data' => 'ABC',
);
drupal_add_js(array('mymodule' => $settings), 'setting');
drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js', 'file');

```

And get that value in jquery like (you have to put this code in mymodule.js)

```
(function($) {
        Drupal.behaviors.mymodule = {
            attach: function(context, settings) {
                var title = Drupal.settings.mymodule.title;
                console.log(title); // or perform some operation as you prefer
                var custom_data = Drupal.settings.mymodule.custom-data;
                console.log(custom_data );
            }
        };
    }(jQuery));

```
> 0 votes

---
Tags: entities, theming
---


# Question
Title: How do I add a cachebreaker to a specific image style in drupal 7?
I have one image style on my site that I need to add a cache breaker to.

Ideally I just want to add `. '#' . time()` to the end of the `src` URL.

For instance everywhere the large style is shown the src url is currently something like:

```
/sites/default/files/styles/large/public/image.jpg?itok=kdkdFf

```

With cachebreaker:

```
/sites/default/files/styles/large/public/image.jpg?itok=kdkdFf#1398670388

```

How do I go about doing this? hook\_node\_alter?

More info:

I set up a test image editor at `http://blakedesign.co.nz/editor/` via Chrome uploading an image and then editing it works fine the modified image shows up in the preview.

On Firefox or IE it actually does work but the old unedited image gets redisplayed from memory.

This can be circumvented if a unique cachebreaker is appended to the source url every time the image is viewed.

# Answer
1. Use `template_preprocess_field()` to set a flag with `drupal_static()` when a particular style is being used. This function needs to sit in your themes template.php:

```
function MYTHEME_preprocess_field(&$variables) {
  // Check field type is an image.
  if($variables['element']['#field_type'] == 'image') {
    // Loop over each image.
    foreach($variables['items'] as $k => $item) {
      // Check the image style is the one we want to append a timestamp to.
      if($variables['element'][$k]['#image_style'] == 'timestamp') {
        // Set a flag to say to modify this URL.
        $append_ts = &drupal_static('append_ts', TRUE);
        $append_ts = TRUE;
      }
    }
  }
}

```
2. Then we can use `hook_file_url_alter()` to modify the URL if the flag is set. This function can live in your themes template.php or a custom module.

```
function MYMODULE_OR_MYTHEME_file_url_alter(&$uri) {
  // Fetch our flag we set in bartik_preprocess_field.
  $append_ts = &drupal_static('append_ts', FALSE);
  // Fetch an array of URI's that this function has already processed.
  $processed_uris = &drupal_static(__FUNCTION__, array());
  // If the flag is true and we've not already processed this URI...
  if ($append_ts && !in_array($uri, $processed_uris)) {
    // Add this URI to our processed list.
    $processed_uris[] = $uri;
    // Set flag to false so we only edit this URL.
    $append_ts = FALSE;
    // And finally create the new URL with a timestamp.
    $uri = file_create_url($uri) . '?t=' . time();
  }
}

```

The use of the flag in this instance is necessary as we can't check what style the image is using in `hook_file_url_alter()`, but it is possible in `template_preprocess_field()`.

---

**To append a timestamp to the image on the edit node page**

1. Use `hook_theme_registry_alter()` to add a preprocess function to the image\_widget:

```
function MYMODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['image_widget']['preprocess functions'][] = 'image_widget_preproccess';
}

```
2. In the preprocess load the field instance config settings, and then check them to see which image style is being used. If the correct one then make changes to the markup to add a timestamp:

```
function image_widget_preproccess(&$element) {

  $entity_type = $element['element']['#entity_type'];
  $field_name = $element['element']['#field_name'];
  $bundle_name = $element['element']['#bundle'];

  $field_instance_info = field_info_instance($entity_type, $field_name, $bundle_name);

  if($field_instance_info['display']['default']['settings']['image_style'] == 'timestamp' && isset($element['element']['preview']['#markup'])) {
    $element['element']['preview']['#markup'] = str_replace('?itok', '?t='.time().'&itok', $element['element']['preview']['#markup']);
  }

}

```
> 4 votes

---
Tags: 7, caching, media
---


# Question
Title: Is it possible to call a function but disable that functions hook calls?
In this answer I wanted to alter a URL using `hook_file_url_alter()`, and within my implementation of that hook I needed to convert the URI to a URL.

Normally this would be done with a call to `file_create_url()` but that is not possible here as it would trigger my hook causing an endless loop.

I can see at the top of `drupal_alter()` it is using the static variable `$drupal_static_fast` which makes me think maybe there is a way of using this to temporarily disable a hook being called, but I'm not sure.

# Answer
> 3 votes
You can't stop the hooks from being invoked unless you edit `drupal_alter` (or `file_create_url`) directly.

But you *can* use static vars to short circuit your own implementation so it only runs once for a given `$uri`:

```
function MYMODULE_file_url_alter(&$uri) {
  $processed_uris = &drupal_static(__FUNCTION__, array());

  if (!in_array($uri, $processed_uris)) {
    $processed_uris[] = $uri;

    // Even though this call will re-invoke the current function, the URI has been
    // processed, so no infinite loop.
    $foo = file_create_url($uri);
  }
}

```

---
Tags: 7, hooks
---


title: Views: How do you view the query?

text:
# Question
Title: Views: How do you view the query?
How do you view the query that a 'View' is using to gather data from the database?

# Answer
> 16 votes
Go to `admin/structure/views/settings`, check `Show information and statistics about the view during live preview` and then `Show the SQL query` checkbox that will appear below.

# Answer
> 2 votes
If you want to see a preview of the query being used when viewing the view as opposed to editing it you can use `hook_views_pre_execute()`:

```
function MYMODULE_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}

```

The `dpq()` function is provided by the devel module so you will need to have that installed for this to work.

---
Tags: 7, views
---


# Question
Title: I can't turn off/pause automatic slideshow when there is only 1 picture (using lightbox2)
I am using lightbox2 and it is a wonderful module. The only issue that I have is that I cannot seem to find a way to turn off the automatic diashow when there is only 1 picture.

When 5 pictures are added to a blogmessage there is a slideshow, 1 by 1 the pictures are shown. This can be paused in case someone wants to have a longer look at a picture. When there is only 1 picture it is not possible to pause. It is possible but I have to configure a button, standard is Space button. But my users do not know this. How can achieve this without a keyboard key?

**What I want:** I want to make sure that when there is only 1 picture it can also be paused. So you don't have to click on the thumbnail of the picture again to see it in deatil.

I hope that is somewhat clear. Thanks in advance!

# Answer
> -1 votes
when there is only one picture then it won't go off untill click somewhere else on the screen ... for better understanding go to lightbox configurations...

---
Tags: javascript
---


title: Test doesn't show up

text:
# Question
Title: Test doesn't show up
I have created a test orb.test for my module and placed it within the module directory. Installed the Simple Test module. When I visit the /admin/config/development/testing my test orb.test its not listed. Here is the code for my test

```
class OrbTestCase extends DrupalWebTestCase {
  protected $privileged_user;

public static function getInfo() {
  return array(
    'name' => 'Orb Test Case',
    'description' => 'Ensure that Online Booking functions properly',
    'group' => 'Examples',
  );
}

public function setUp() {
    parent::setUp('orb');
    $this->privileged_user = $this->drupalCreateUser(array('allow online  reservations'));
    $this->drupalLogin($this->privileged_user);
}

public function testorbroomavailability() {
  $this->drupalGet('orb');
  $this->assertText('Room Status');
}
}

```

Have I missed something here?

EDIT 5th August 2014: My tests written and placed in of my modules do not show up in the list of tests (admin/config/development/testing)

# Answer
> 1 votes
Your test class look OK.

There is no need to install or enable the **Simple test** module if you're using Drupal 7. Instead, you should enable the core **Testing** module. (Don't know if installing **Simple test** will make a difference, but it were *not* present when I went through the routine described below.)

Provided it exists inside your module's directory, you're using Drupal 7, have enabled the core **Testing** module, cleared the cache, and made sure to declare your test file with the correct name in your module's `.info`-file, nothing should stop it from appearing in the list included in the "Examples" group when you visit `/admin/config/development/testing`.

Here is how it looks on my site (after I've gone through the steps outlined above):

---
Tags: testing
---


# Question
Title: Is it possible to run a Drupal 7 on 2 domains?
I'm not sure is it about the server or Drupal. Anyway, my Drupal was installed inside the directory "/public\_html" folder. We are pointing "mysiteA.com" and "mysiteB.com" into this directory.

Both urls look the same but only "mysiteB.com" is able to login. And "mysiteA.com" is showing "access denied" after submit the login form. The question is, Drupal is showing "mysiteB.com" domain inside the "configuration \> Site information". Is there a way to change it to be "mysiteA.com" or both(not sure is it possible)?

# Answer
Let's back up and debug this from the top:

**Confirm that both sites actually point to the same Drupal installation.**

* Open up a terminal or command prompt. Ping mysitea.com and mysiteb.com. Confirm that the IP address is the same for both domains.
* Create a dummy file test.html in the Drupal root. Confirm that you can access it from both mysitea.com and mysiteb.com.

**Confirm both sites actually use the same database**

* Look in the sites directory. The only two directories should be "default" and "all". If you see mysitea.com or mysiteb.com, it's possible you are using different DBs.

**Figure out what Drupal config is causing the error**

* Confirm that you don't have any domain-related modules installed (domain access).
* See if clearing all cookies after switching to the second domain let's you log in. i.e., is the problem that you can't ever log in to one of the domains, or that you just can't log in to them one after another? This could be due to the cookie domain.

Try setting $cookie\_domain in settings.php for each site.

EDIT: Now I see that you tagged your post "domain-access", so I'm assuming you are using that module. Why didn't you say that in your post? That's kind of a critical thing to know if your problem is related to accessing a site on two domains ;) I'm pretty sure it's just a misconfiguration or bad permissions related to Domain Access. Try disabling it and see if you can access both sites.
> 4 votes

# Answer
It seem like something to do with Cookie domain like what @danepowell said above. So I added the following code. Now, it's working!

on file "sites/default/settings.php", I added

```
$cookie_domain = '.mysiteA.com';

```

then I copy the file "sites/default/settings.php" to "sites/mysiteB.com/settings.php", and change the cookie\_domain to

```
$cookie_domain = '.mysiteB.com';

```
> 1 votes

---
Tags: domain-access
---


title: Drupal timezone and database

text:
# Question
Title: Drupal timezone and database
I have a content type with datetime field. When I save node, in database I have 2014-04-28 11:00:00 for instance. But when I edit the node i have 2014-04-28 13:00:00. I guess that it has something to do with timezones.

Now the problem is that i have lot of nodes and i have to get the time from database. I don't want to node\_load or anything like that.

The question is - is it possible to extract 2014-04-28 13:00:00 datetime from database with MySQL query? Or any work around where I don't have to use node\_load?

Any input will be appreciated :)

# Answer
What version of Drupal is this?

It's against best practices to go directly to the database but if you really need to I don't see why you can't query the field's table. What problems are you having?

When entering data for a field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

You may wanted to use format\_date to convert your time. See: https://api.drupal.org/api/drupal/includes!common.inc/function/format\_date/7

## UPDATE:

I don't know what source you time is in, either a timestamp or formatted date/time. In your example you're using `2014-04-28 11:00:00` so lets convert that to a unix timestamp:

```
  $newdate = new DateTime('2014-04-28 11:00:00 UTC', new DateTimeZone(date_default_timezone_get()));
  $unixts = $newdate->getTimestamp();
  $siteDate = format_date($unixts, 'small', '', date_default_timezone_get());

```
> 2 votes

# Answer
Gergely Lekli did a fantastic write-up on using views to avoid node\_load() in Drupal 7.

By his calculations, using views was 6 fold faster.

With views I believe you will find it easier to output with the appropriate timezone as well.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: How do I set different front pages for domain access sub sites?
I am using the Domain Access module and would like to have two distinct front pages. The primary one works as expected, and I have a separate front page template. The secondary domain front page is not picking up the front page template; instead, it is displaying the breadcrumbs and heading just like the secondary pages.

How do I configure the module so that the secondary domain picks up the front page template?

# Answer
You didn't mention versions, so I will assume the most recent: Drupal 7 and Domain Access 7.x-3.9.

The preferred method requires that your 'secondary front page', as you call it, has a different path than your primary front page.

Make sure the Domain Settings module (part of the Domain Access package) is enabled. This will allow you to specify domain-specific configuration options on several admin forms.

Now, when you go to /admin/config/system/site-information, you will see a fieldset at the bottom of the page saying "Domain-specific settings". Choose the domain for which you want a different front page. Under "Default front page" higher up the form, enter the path of your secondary front page and click the save button.
> 5 votes

# Answer
I'm not sure the answer above answer the question. The problem is not to define several frontpage. The problem is that he want to change the template depending on the domain.

So I think he would like to have several page.tpl.php files, one for each domain, to be able to remove breadcrumb and things he don't want on one of this domain.
> 0 votes

---
Tags: domain-access
---


# Question
Title: Is it possible to change the field type in a node form afterwards?
I have an instance here where an existing textfield in a node form should be limited to enter only three possible values. I though it might be possible to alter the field to #type =\> 'select' and attach my '#options' as well. So I altered the form to:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD']['#type'] = 'select';
    $form['field_MYFIELD']['#title'] = 'Enter a value';
    $form['field_MYFIELD']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
  }
}

```

But when I now try to create a form like that, all I get is this error:

```
Fatal error: Cannot create references to/from string offsets nor overloaded objects in /Users/Shared/www/drupal.dev/includes/common.inc on line 6606

```

Is it even possible to change an existing field type like I want with a small custom module? Do I have to alter the submit function then as well? Please help!

# Answer
The answer is: Yes! It is possible. All I did wrong when altering the form is that I changed the `'#type'` of the container instead of changing the type of the textfield itself. I had to go one level deeper:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#type'] = 'select';
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
    // #select doesn't need #size and #maxlength
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#size']);
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#maxlength']);
  }
}

```
> 3 votes

# Answer
You can write a field formatter that will render select box for this field. It's very simple and didn't take many time to use it. API here: https://api.drupal.org/api/drupal/modules!field!field.api.php/group/field\_formatter/7

I can help with this if you need.
> 0 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Get non-standard user attributes in layout
I want to show the amount of credits the user has. I know the $user object has the following properties:

```
uid - name - pass - mail - theme - signature - signature_format - created - access - login - status - timezone - language - picture - init - data - sid - ssid - hostname - timestamp - cache - session - roles

```

But I have also extended user properties like `address street, address city, user credits, ...` . But how can I print those properties in my layout theme? They are also not in my users table in my database.

# Answer
> 1 votes
You can use the `user_load()` to load all additional fields.

E.g.

```
global $user;
$account = user_load($user->uid);
$street = $account->field_address_street[LANGUAGE_NONE][0]['value'];

```

# Answer
> 1 votes
First, to access the additional user fields you will need to load the full user object using an available user id with the user\_load() function.

```
global $user; //This contains the basic information for your current user.

$account = user_load($user->uid); //$account now includes all of your custom account fields.

```

Now that you have the fully loaded user object you will need to choose a template to modify.

Depending on where the values need to be, this could be one of many templates. I highly recommend checking out the Theme Developer module to help find preprocessing functions and available templates to override.

There is some fantastic information on setting up variables for use in a template here.

Example snip:

```
<?php
function drop_preprocess_foo(&$variables) {
  // Do not do this unless you mean to:
  $variables['foo_list'] = array('list item 4');
  // Instead do this:
  $variables['foo_list'][] = 'list item 4';
}
?>

```

---
Tags: 7, users, theming
---


# Question
Title: Want to build a widget which gives price history on Drupal 7
We have our site built on Drupal 7. We want to make a widget which gives price history chart.

I found a module named Commerce Price History. Can this module be used with Drupal 7 or it can be used only with Drupal commerce.

Is there any other Drupal Module which can achieve the same.

# Answer
> 0 votes
I've just come across a module called Track Field Changes which may be ideal for you needs.

I found the documentation a bit lacking however but to get it to work I:

1. Install module
2. Visit /admin/config/system/track\_field\_changes and select your product node type
3. Save the configuration and then product will appear as a menu item in the left menu. Click it.
4. Select the price field and again save the configuration.
5. Create a new view that shows content of the type of your products.
6. Add the field called "Field Tracker: Value After (Value After)"

This will then show a log of all of your price changes. To then turn this into a graph check out the Views Charts module.

---
Tags: commerce, charts
---


# Question
Title: Does the Data Export module support exposed filters?
I am looking to use the *Data Export* module to export data to CSV files. However, I need the users to be able to filter the data first with exposed filters and then download the filtered results.

From what I can see, the module seems to be an all or nothing module.

Does anyone know if it is configurable?

# Answer
> 21 votes
When you create a Data Export view, there is an option to attach it to another view. You can choose to attach it to another page in the same view and all the filters used would be affected by the export. A new icon would be shown at the bottom of the view to download the exported data.

In the following screenshot, I attached it to a view page.

>

# Answer
> 3 votes
Hope this tutorial might help you!

Here's a summary:

1. Create a view for the content type you're interested in (i.e : article)
2. Add the data export display and a page display.
3. Add all needed fields in your data export display.
4. Add the date popup calendar in “Filter criteria” and tick on the exposed filter option.
5. In the Data export display just below the path option you'll find "attach" where you need to attach your page display in it.
6. Select "*Parent sort*" in the data export display settings.
7. Navigate to the path you've given in the page display , and you'll see the date filtering field which contains a date popup and an orange button called 'csv' or 'xls' embedded below your filtered contents.

---
Tags: 7, views
---


# Question
Title: How do I can change the default description of elements?
I'm trying to change the default descriptions in different pages like (add users). I tried `devel themer` to find out where there descriptions are came from but it showed nothing. for example look at this picture (add user) :

how do I can change the texts displayed by red line?

---

**Update**

I tested this code in `template.php`

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id){
if($form_id == "user_register_form"){
    $form['account']['name'] = array(
            '#title' => t('New username'),
            '#description' => t('New description'),
    );
    }
}

```

# Answer
> 1 votes
In your code your overwriting the whole name array - you only want to update 2 properties:

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id){
  if($form_id == "user_register_form"){
    // Here just target the #title attributes - not the whole name array
    $form['account']['name']['#title'] = t('New username');
    // Same here with description.
    $form['account']['name']['#description'] = t('New description');
  }
}

```

# Answer
> 1 votes
you can find the descriptions at `user.module` under user directory (in modules directory)

you can find those descriptions under `user_account_form` function

Ex, **E-mail address** field description below.

```
$form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

```

But it's better to Use `hook_form_alter` to achieve it

---
Tags: 7, theming, forms
---


# Question
Title: Change value input field according to other fields
I have 10 input fields when you create a product (= node). I have an input field amount, price & reduction and sell price. So when the field amount, price & reduction are filled in I want to automatically fill in the sell price field.

Is there a module for this or should I just write some javascript to do this?

I've seen the Computed Field but I haven't tried it yet.

# Answer
you can adopt a method like this

```
$(document).ready(function(){
    $('#a1').keyup(calculate);
    $('#a2').keyup(calculate);
});
function calculate(e)
{
    $('#a3').val($('#a1').val() * $('#a2').val());
}

```

using js
> 1 votes

---
Tags: 7, forms, javascript, input-formats
---