# Question
Title: Changing user register/login pages into secure sub domain
I need to change my user registration and login pages into a secure sub domain of my site, how is it possible ? In detail,

When user logon to http://www.mysite.com/admin that must be redirected to https://admin.mysite.com and he can login from there to our main site .Is it possible ?

# Answer
Yes it is possible through Services module.

First you need to redirect http://www.mysite.com/admin URL to https://admin.mysite.com/ URL either through Apache redirect or through drupal redirection. Then you will capture all the information of user at this site (https://admin.mysite.com/) and consume the same at http://www.mysite.com/admin site through services module.

You can send user information in JSON or XML format, some other formats are also available there these too are more in use.

Now let's take a example:

**Site: https://admin.mysite.com/** 1. Created user signup page here with some fields. Here I am taking following fields and send these fields data using JSON to respective URL (http://www.mysite.com/user-register/user/register).

```
{
    "name": "testuser",
    "pass": "12346",
    "mail": "test@example.com",
    "conf_mail": "test@example.com",
    "field_mobile_number": {
        "und": [
            {
                "value": 12345678
            }
        ]
    },
}

```

2. Similarly for Sign in page, create form with two fields name and password and prepare following JSON that we would consume to this URL (http://www.mysite.com/user-register/user/login).

```
{
    "username": "admin",
    "password": "admin123"
}

```

That's done from this site. Now move on to another site.

**Site: http://www.mysite.com/**

1. Enabled Services module.
2. Create services end point.
3. For more security you can also use Oauth module.
4. Please go through following tutorial and follow the same steps and you would be ready to consume above services on this site.

Register User with Services (JSON) with Custom Fields

http://www.wdtutorials.com/2013/04/11/drupal-7-tutorial-web-services-basics
> 0 votes

---
Tags: users
---


# Question
Title: hide result on same node in block (view)
I have 3 pages, vacation1, vacation2, vacation3. Under each page there is a block-view with fields (title, image, summary) that links to the other pages. I want to have on vacation1 links to vacation2 and vacation3, but my views show all the results. I wan't to filter out the result of the current node. How can I set the filter for this?

# Answer
You need to use the contextual filter option here. You can get current page nid using contextual filter as shown in screen shot and can filter out the result.
> 1 votes

---
Tags: views
---


# Question
Title: Limited fields at registration time and full profile after logged in
I want to display limited fields at registration time say username email and password
And when user get registered then he can edit his profile with rest of the fields like Phone no., Address, Date of birth etc.
I tried adding field in admin/config/people
But that fields are visible at the time of registration.

How can I do that any help....
I am using drupal 7

# Answer
> 1 votes
You can do this without installing another module. It's good practice to avoid installing additional modules if you don't have to.

1) Go to the Manage Fields screen for user accounts at admin/config/people/accounts/fields

2) Edit the fields you want to hide/display from the user registration form. There is a setting at the top of the form called "Display on User Registration Form". View the attached screenshot for example.

3) If a field is marked as "required", it has to be displayed on the user registration form.

Certain form fields on the user registration form are not managed through the "Manage Fields" screen. So they can't be changed without getting in to modules. These include username, password, and a few others depending on your set up. But fields that you add yourself, like phone number, address, etc., can be edited.

# Answer
> 0 votes
You can use https://drupal.org/project/profile2 module for this. Once you get installed this module, go to `admin/structure/profiles/add`

AS shown in screenshot, don't enabled this option. `Show during user account registration.`

Now you can give any name to your profile and can add all other fields that you want to fill from user after registration. One more thing if in future you want to show these all fields at the time of registration, just enable `Show during user account registration.` option.

---
Tags: 7, users
---


title: Menu tab with count

text:
# Question
Title: Menu tab with count
I am trying to add a menu tab on the user profile page with the # of blog posts someone has made.

Ex: Blogs (3)

```
/**
* Implementation of hook_menu
*/
function menutab_followers_menu() {
$view = views_get_view( 'blogs_written' );
$view->execute();
$count = count( $view->result );
    $items['user/%user/blogs'] = array(
        'title' => t('Blogs @count', array('@count' => $count)),
        'page callback' => 'menutab_blogs_linkspage',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        );
    return $items;
}

```

For some reason it won't use the contextual filter. It displays Blogs (0) instead of Blogs (3) I have it set the views contextual filter to raw value, path 2, and use url alias. Ex: mywebsite.com/users/admin

If I insert the view in the profile page using Display Suite, it works fine, it displays all 3 items on the page. Also, if I set the contextual filter to a fix value and type "Admin" it displays Blogs (3) on the menu tab. But I don't want that, since it would display that to every user.

# Answer
> 2 votes
Use the "title callback" menu property instead of "title", and then use a function to generate the title. Before executing the view, set the argument as shown in the example below.

```
function menutab_followers_menu() {
    $items = array();
    $items['user/%user/blogs'] = array(
        'title callback' => 'menutab_followers_blogs_title_callback',
        'title arguments' => array(1),
        'page callback' => 'menutab_blogs_linkspage',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );
    return $items;
}

function menutab_followers_blogs_title_callback($account) {
    $view = views_get_view('blogs_written');
    $view->set_arguments(array($account->uid));
    $view->execute();
    $count = count($view->result);
    return t('Blogs @count', array('@count' => $count));
}

```

Also, instead of executing the view to get the count, a better approach would be to use a simple database query. An example would be:

```
$count = db_query("SELECT COUNT(*) FROM node WHERE uid = :uid AND type = :type", array(':uid' => $account->uid, ':type' => 'blog'))->fetchField();

```

---
Tags: routes
---


# Question
Title: Using theme_preprocess_node i'm trying to add a class to all images on the page
My code below is not working and i'm not sure why. I've tried a few variants. according to the KPR variables output, the image I'm trying to access is here.

$variables\['field\_about\_image'\]\[0\]

i think the 0 signifies it is the first (and only in this case) image on the page w/ the machine field name 'field\_about\_image'. so i wrote my code as:

```
function myTheme_preprocess_node(&$variables){
    if($variables['type']=='basic_page_with_pic') {
echo '<script>alert("my func running")</script>'; //Verified it's working
    $variables['field_about_image'][0]['class'] = 'myclass;
}
}

```

i've also tried this, just to get a class attribute added

```
$variables['field_about_image'][0][] = 'class';

```

also the title attribute comes up as empty. so just as an execrcise i tried this.

```
$variables['field_about_image'][0]['title'] = 'some title;

```

any help on how to do this would be greatly appreciated!

# Answer
From what I can tell, hook\_preprocess\_node() won't let you add both classes and title attributes to images from image fields. Try using hook\_preprocess\_field() as in the example below:

```
function myTheme_preprocess_field(&$variables) {
  if (($variables['element']['#field_name'] == 'field_about_image') && ($variables['element']['#bundle'] == 'basic_page_with_pic')) {
    $variables['items'][0]['#item']['title'] = t('This is the title text that will display when hovering.');
    $variables['items'][0]['#item']['attributes']['class'][] = 'class1';
    $variables['items'][0]['#item']['attributes']['class'][] = 'class2';
  }
}

```

Be sure to clear your cache.
> 0 votes

---
Tags: theming
---


# Question
Title: Toggling view modes of Views results with Display Suite
I asked a similar question about a month or so ago, and the answer was to use the Views Modes module. That module required the PURL module. The problem is the PURL module leaves parameters on your URL all over the site, and have not figured out a way to turn it off. Others have posted a support issue and it goes ignored.

So, I'm back to the drawing board. I have nodes that are rendered, using view modes defined in Display Suite. Is there a way I can toggle between view modes in Views? What I'm really trying to do is provide a bunch of filter checkboxes, along with the ability to toggle between view modes, but I need to find a solution for the view modes first.

Is there a module that makes this easy, or do I need to write some code. If I do need to write some code, how should I approach it?

# Answer
> 2 votes
Solution that I use sometimes.

1. Create a content type with one or more multiple-value block reference fields.
This is like a "cheap" version of panels..
2. Create your views displays as blocks. One for each version.
3. Create a custom module to define a block that acts as the "switcher" between the two. Put some dummy content for now.
4. Create two nodes with the block reference.
    * One that has the switcher and the Views display A.
    * One that has the switcher and the Views display B.
5. Set url aliases for both nodes.
6. Flesh out the "switcher" block. E.g. make it keep the url query parameters. Make it look different depending on whether you are on A or B.
7. If you want, you can have a separate block for the exposed filters, that you also add via the blockreference.
8. Use Display suite or some other way to arrange the different blocks on the page.

The benefit of block reference + ds over theme regions is that you don't spam your theme regions with one-page-only blocks.

# Answer
> 1 votes
Just an idea and I might be mis-understanding what you need here but could you create multiple views, one for each view you need, expose the filters on them and then combine all these views with the quicktabs module?

# Answer
> 1 votes
So, it seems the general idea will be to have multiple views displays, and something to switch between those views displays.

The problem seems to be

1. How to create the switcher.
2. How to display the switcher in the intended location next to the exposed filters.

One solution could be hook\_form\_views\_exposed\_form\_alter() to sneak the switcher into the form.

EDIT: Another solution can be to put the switcher as custom html in the View header. Or you can write your own Views header plugin to have it reusable.

# Answer
> 0 votes
What about creating a custom select that appends arguments to the current url, and then implementing hook\_entity\_view\_mode\_alter and checking the paths?

```
function mymodule_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node') {
    if (arg(0) == 'myview' && arg(1) == 'mode' && arg(2) == 'custom') {
      $view_mode = 'custom_view_mode';
    }
  }
}

```

There must be a cleaner way to do this. But this should work.

---
Tags: 7, views, display-suite
---


# Question
Title: How to display nodes in a view, each row using a preselected view mode ?
I would like to create a view that displays a number of nodes, each using its own chosen view mode.

I've installed the Display Suite module and created a number of view modes. Using the Views module, I've created a view that displays a number of entities/nodes and I can set a view mode for each row, or a default view mode for all rows.

However, I would like the view to somehow use the view mode that has been selected when creating the content itself (under the display settings tab).

So far I have no idea how to achieve this. Could anyone give me some pointers?

# Answer
First you need to save the view mode for each entity (e.g. in a field).

Implementing hook\_entity\_view\_mode\_alter you can override the view mode:

```
function mymodule_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node') {
    $entity = $context['entity']
    if (get the view mode of $entity) {
      $view_mode = 'custom_view_mode';
    }
  }
}

```

Remember to do a check to run this in your view only, otherwise this will affect the node everywhere.
> 0 votes

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


# Question
Title: HTML stored in text field and not rendered in view
I'm trying to render HTML that's stored in a text field in a view. The output looks like this

```
<div class="wrapper">My text</div>

```

If I inspect it, it's wrapped in quotes so it's treated as a string. How do I parse this on the front end?

# Answer
> 0 votes
I've never used this, but you could try the Simple Field Formatter

---
Tags: views
---


# Question
Title: How can I enable unauthenticated user to activate himself?
How can I enable unauthenticated user to activate himself? not to wait for administrator activation.

# Answer
Provided we're talking about Drupal 7:

1. Navigate to: *Administration » Configuration » People » Account settings*.
2. Under: "Registration and cancellation. Who can register accounts?", check the radio button for "Visitors".
3. Click "Save configuration" at the bottom of the page.
> 0 votes

---
Tags: users
---


# Question
Title: How do i take a specific node and turn it into a block
I created a content type of which there is only one node of, and i want to add to sidebar left. How can that be done? i would prefer not have to use a module to do this., thanks

# Answer
I would suggest using views for this.

1. Create a "Content" view and choose your content type in the "Show" dropdown
2. Uncheck "Create a page" and check "Create a block"
3. Choose "Unformatted list" and "Full posts"
4. Limit the block to 1 "items per page"
5. Click the Continue & Edit button
6. Add a contextual filter for Content: NID
7. Provide a default argument of Fixed value and enter the Node ID of the node you want to display within the block

*Optionally, you can choose to create a fields based view instead of full posts which would allow you a little more control over the layout of the nodes content within the block.*

If you are set on not using ANY modules to do this then you'll want to look into https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook\_block\_view\_MODULE\_DELTA\_alter/7 which would allow you to override a blocks output in your themes template.php.

```
/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function YOURTHEME_block_view_block_BLOCKDELTA_alter(&$data, $block) {
  $data['content'] = drupal_render(node_view(node_load($nid)));
}

```
> 0 votes

# Answer
Use Node Block. I know it's a module and you didn't want to use one, but it's lightweight and will probably do exactly what you want.
> 0 votes

---
Tags: nodes, blocks
---


# Question
Title: Programmatic filefield value/Default Filefield value
I have a module that takes a file uploaded to an entity, changes it and then saves the new version on my server in a folder based on the user id and entity title.

```
$where = 'private://' . $user->uid . '/';

```

This is all working fine.

I would like to have a field on the entity that displays this new file (it's an audio file).

I have tried writing the process of attaching the file into the module itself several times but have had no luck.

My next idea was to have Rules do this for me but unfortunately when it comes to setting the data value for a filefield Rules will not let you use PHP or Tokens so all I can do is set it to the value of an existing filefield.

My third idea was to have the entity's field have a default value and use tokens that reflect the location of the file e.g \[uid\]/\[title\] but filefield does not allow default values.

I have also tried writing a module that updates the entity field values but I can't seem to get this to work either.

Does anyone have any ideas on where you go from here? Does anyone know how this can be done?

# Answer
> 0 votes
The new version of the file should be saved as a managed file. This will provide a file object that has a fid which in turn can be used by the file field.

Here are the docs for the function used to save a managed file.

https://api.drupal.org/api/drupal/includes%21file.inc/function/file\_save\_data/7

The value for a file field contains the following

fid - The fid property of the file object returned by file\_save\_data.

description - The description may be used as the label of the link to the file.

display - Determines whether a file should be displayed when outputting field content.

---
Tags: rules, tokens, files
---


title: Unable to set URL alias

text:
# Question
Title: Unable to set URL alias
I am running into a problem with url alias in my `drupal 7` installation:

I have a `drupal 7 installation` which uses a purchased theme. This theme has a portfolio section (in its demo installation with dummy data). I updated the demo installation and changed all sections are required by my project - everything works out fine.

Now the portfolio section has a url called `http://<my_drupal_site>/portfolio/4` I need it to be `http://<my_drupal_site>/branch-locator`. Things I have tried/noticed so far:

* I checked the `node table`, the `url_alias table`, the `admin > content section` as well as `admin > search > url_alias` there is nothing related to `portfolio/4`. When I open the corresponding block it does not have any body/code in it (I believe that is because it is a block that is part of the theme). When I open the view, I still am not able to find anything where `portfolio/4` is mentioned.
* The only place where I found `portfolio/4` was in `menu_router table` which had an entry for the same. I updated this record to `branch-locator` and everything worked fine for a few minutes. Then it showed me a `404 error`. When I went back to the `menu_router table` I found that `portfolio/4` was back again in place of `branch-locator`. (I read somewhere that `menu_router table` gets cleaned and recreated somehow - not sure how)

So my question is, how can I have `portfolio/4` get rendered as `branch-locator`? Since this is a custom theme I know it will be hard for anyone to give an exact answer how to solve this, but any pointers will be VERY much appreciated!!

P.S - I am not sure what tags to add..If you feel this question can be better tagged, please do so :)

# Answer
Sounds to me like you just have to add an URL alias for ´portfolio/4´.

1. Go to Configuration \> Search and metadata \> URL aliases.
2. Click "Add alias".
3. Enter `portfolio/4` as "Existing system path" and `branch-locator` as "Path alias".
4. Hit Save and it should be ok.

If you want nodes to have a similar path alias, e.g. `branch-locator/node-title`, you should look into the Pathauto module.

Cheers,
> 1 votes

---
Tags: uri
---


# Question
Title: How do I create an "About us" page and make it appear in the main menu?
I have created a custom page `page--about.tpl.php`.
And want that page to hook it in menu.
I have gone through hook\_menu but didn't get my answer.
I also read page template suggestion.
Tell me how I can do that.

# Answer
I think there are some confusions here.

First: Custom`.tpl.php`-files are not custom pages. They are custom *templates* for pages, and unless you need to have a different style or layout on your "about" page, there is no need for it.

Second: The `hook_menu` function has nothing to do with this, it is (mostly) for setting up callback functions for forms and hooking those forms up to the menu router system.

To create an "about" page for your site and make it appear in your site's main menu is *much* simpler. Do as follows.

1. First create your "About" page as a "Basic page" on your site. To do so, navigate to *Home » Add content » Create Basic page* and just create the page. When done, press "Save".
2. Make a note of the node path of this page. Let's say it is `node/69`.
3. Navigate to *Administration » Structure » Menus*. To the right of "Main menu", click "add link".
4. In the field "Menu link title", fill in the desired title (e.g. "About us").
5. In the field "Path", fill in the node path (e.g. `node/69` if that was the path you made of note of in step 2).
6. Click "Save".
7. Clear all caches (you always do this after changing the appearance of a Drupal site).

After going through the steps above, a tab linking to the "About us" page shall appear in the main menu.

If you want a custom *layout* for this page, you can create this as a template file. If the node path to the page is `node/69`, the file should be named `page--node--69.tpl.php.`
> 2 votes

---
Tags: 7, nodes, routes
---


title: Combine Multiple Content Types and View

text:
# Question
Title: Combine Multiple Content Types and View
I have need to create a page with following information. Personal Information, Address and Contract Information.

One Personal Information will have multiple address and multiple Contract information. I am thinking of creating three content types. The personal information page will have add address and add contract buttons which will popup the respective content type. When the address or contract popup is closed then control is passed to the Personal Information page, here I should be able to view the contact and address information just added in tabular format. I thought it may be a view.

My question is, Is it possible to achieve this kind of work in Drupal 7? If yes how can I do it. It will be nice to have some information so that I can look into the right direction. Some example sites would be help full.

Thanks

# Answer
> 0 votes
Instead of creating new content types. You can create fields and use FieldCollection module to group as many field as you like.

and show (Display) it using FieldCollection Views module.

Find demo here,

FieldCollection Demo

FieldCollection Views Demo

---
Tags: views, nodes
---


# Question
Title: Exclude content referenced by content whose author is current logged in user
I try to solve question - answer scenario with views.
2 content types: question and answer. (answer is connected to question by entityreference)
User can check themes of interests (taxonomy) in profile and a view is displayed in his profile with relevant questions.
Creating this view was simple: I made a user view with UID as contextual filter and added a entity reference relationship and taxonomy term:content with term. Then it is easy to display list of relevant questions.

Problem: I want to filter out questions already answered by current user. In other words - to filter out all questions which are referenced from answer content type and answer's author is current user.

I tried to add new relationship - content referencing content from xy field, tried to add contextual filter - node author. None of this seems to work.
EDIT: adding contextual filter user:author with excluded option works ONLY if there is reference (answer) made by current user. If other content(answer) by other user is referencing the content(question), it shows the question in the list again. Of course, because context filter only removes current user's nodes.

I need views to exclude content by other users as well. Does someone know answer to this? thank you

# Answer
Try this,

1. Add a contextual filter of `Content: Author uid`.
2. Under "WHEN THE FILTER VALUE IS *NOT* AVAILABLE", select "provide default value", and then select "User ID from logged in user".
3. Under **MORE**, select "Exclude".
4. Save.

P.S. This should work. Haven't tried myself.
> 0 votes

---
Tags: 7, views
---


title: How to use contact module of Drupal 7?

text:
# Question
Title: How to use contact module of Drupal 7?
I want to use drupal 7 core module for contact.
I want to use it as block so that I can add a contact form to the right sidebar of your website which should be shown at every page. or render it anywhere in the page
I saw this on drupal site and tried to use it.

```
<?php
print drupal_get_form('contact_mail_page');
?>

```

It is showing me this

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'contact_mail_page' not found or invalid function name in drupal_retrieve_form() (line 841

```

So any suggestion how I can use this.

# Answer
> 1 votes
use this code

```
<?php
if(!function_exists('contact_site_page')) {
  require_once drupal_get_path('module', 'contact').'/contact.pages.inc';
  $output = drupal_get_form('contact_site_form');
  print drupal_render($output);
}
?>

```

and put `print drupal_render($output);` where ever you want to put the contact form.

as another solution you can also assign a region for where you want the contact form to be then place the form in there.

---
Tags: 7, emails
---


title: I cannot access drupal.org

text:
# Question
Title: I cannot access drupal.org
I haven't been able to access drupal.org for the past few days. When using Chrome I get: 'This webpage is not available'. I have no problems with accessing any other site.

Oddly enough when I use a proxy I have no problem. I've cleared my cache in both IE and chrome but still no luck. I don't believe my IP address has been blacklisted so beyond that I don't know. This is true when I try on my phone too so perhaps it is IP address related?

# Answer
For what it is worth here is a link to Chromebook help for "This webpage is not available".

Assuming you've typed in the right URL, it looks like Chrome will give you this error message if it thinks the site takes too long to respond. The help page also suggests:

* Clear your cookies.
* Adjust your proxy settings

You could also try to use another browser to access the site (both Firefox and MSIE work OK for me).
> 1 votes

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


# Question
Title: How to hook contact form of drupal 7 for custom styling?
how can I alter my contact form for adding custom classes
I am using contact form of Drupal 7 core module.

# Answer
> 1 votes
It can been done by `$form_id`

```
 function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
        if( $form_id == 'contact_site_form' ){
    //PUT YOUR STYLING HERE
    }
}

```

# Answer
> 2 votes
Or you can use hook\_form\_FORM\_ID\_alter() to get the specific contact form. hook\_form\_alter() will run for every form on the page.

```
function MYMODULE_form_contact_site_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#attributes']['class'] = array('class1', 'class2');

  $form['mail']['#attributes']['class'] = array('class1', 'class2');

  $form['subject']['#attributes']['class'] = array('class1', 'class2');

  $form['message']['#attributes']['class'] = array('class1', 'class2');

  // add class to the overall form
  $form['#attributes']['class'] = array('class1');
}

```

If you don't know how to use custom modules, you'd have to research that first. Dropping this function in and replacing MYMODULE with your module name will make this work.

---
Tags: 7, forms, emails
---


# Question
Title: drupal_add_js not work in form validation failed
I add js file with `drupal_add_js` in `hook_form_alter`, it is ok and I see it in list of js loaded in page, but when I submit form and form not validate and return to that form (after validation failed) I don't see js files that added to form, why this happened? and how can add my js file in that form after validation failed ?

some part of my code

```
function mymodle_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'news_node_form') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js'); //, array('scope' => 'footer','weight' => 10));
  }
}

```

code work correctly in add and edit form, but when form submit and validation failed it show validation error but my js file not loaded in page (I checked html source and check firebug script files), but there is not my js file,

# Answer
> 7 votes
Javascripts are lost when the form is rebuilt when using drupal\_add\_js(). Use $form\['#attached'\] instead. Also, it's better to use hook\_form\_FORM\_ID\_alter() instead of a general hook\_form\_alter(). hook\_form\_alter() will run for every form on the page. Try using the below:

```
function mymodule_form_news_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js',
  );
}

```

---
Tags: forms, javascript
---


title: Wrap node template

text:
# Question
Title: Wrap node template
Using the blog module, I'm setting a custom template for the individual blog articles (`node--blog.tpl.php`) which contains a list item and the content inside.

However, I can't figure out where I should be putting my wrapping `<ul>` tag? If I put it in either `page.tpl.php` or `region--content.tpl.php` then the entire page content is (understandably) wrapped including pagination and other elements. I just need to wrap the list items.

Thanks and please be gentle with a newb :)

EDIT: code

**page.tpl.php**

```
...
<?php print render($page['content']); ?>
...

```

**region--content.tpl.php**

```
<?php if ($content): ?>
 <div class="<?php print $classes; ?>">
  <ul class="blog-list">
   <?php print $content; ?>
  </ul>
 </div>
<?php endif; ?>

```

**node--blog.tpl.php**

```
...
<li>
 #content#
</li>
....

```

# Answer
Taking a guess that you're talking about the /blog page, the content is built in `blog_page_last()`. The nodes themselves will be in `$build['nodes']` when that function returns.

As with pretty much everything in Drupal there are a bunch of different ways to alter that content; I think the easiest in this case would be to use `hook_page_alter()`:

```
function MYMODULE_page_alter(&$page) {
  if (current_path() == 'blog') {
    $page['content']['system_main']['nodes']['#prefix'] = '<ul>';
    $page['content']['system_main']['nodes']['#suffix'] = '</ul>';
  }
}

```
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: Adding AJAX to drupal commerce checkout pane
I need to add dependable fields to Drupal Commerce checkout. I wrote my own module to do this but AJAX seems to not work. Here is the code of my module:

```
function moje_panele_pane_checkout_form($form, &$form_state) {
  //parent item
  $form['sposob_dostawy'] = array(
    '#type' => 'select',
    '#title' => t('Wybierz sposób dostawy'),
    '#options' => array(
      0 => t('Kurier'),
      1 => t('Odbiór osobisty'),
    ),
    '#ajax' => array(
    'callback' => 'my_checkout_ajax_callback',
    'wrapper' => 'dane-do-odbioru',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  //child markup
  $form['dane_do_odbioru'] = array(
    '#title' => t("Dane do odbioru"),
    '#prefix' => '<div id="dane-do-odbioru">',
    '#suffix' => '</div>',
    '#type' => 'markup',
  );
  //dependent field
  if ($form_state['values']['moje_panele_pane']['sposob_dostawy'] == 1) {
    $form['dane_do_odbioru'] = array(
      '#title' => t("Dane do odbioru"),
      '#prefix' => '<div id="dane-do-odbioru">',
      '#suffix' => '</div>',
      '#type' => 'fieldset',
    );
    $form['dane_do_odbioru']['imie'] = array(
      '#type' => 'textfield',
      '#title' => t('Imię'),
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
    );
  return $form;
}

//my AJAX callback
function my_checkout_ajax_callback($form, $form_state) {
  return $form['dane_do_odbioru'];
}

```

The above code works fine on normal Drupal page, but I cannot make it work on checkout page as a pane.

What am I doing wrong?

# Answer
I think it might have to be related with the classes on the checkout form, if you check the commerce shipping module - it has a good ajax example on replacements - you can see how it does:

```
// Add a radios element to let the customer select a shipping service.
$pane_form['shipping_service'] = array(
  '#type' => 'radios',
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'commerce_shipping_pane_service_details_refresh',
    'wrapper' => 'commerce-shipping-service-details',
  ),
);

```

And then it forces the class with a prefix:

```
$pane_form['service_details']['#prefix'] = '<div id="commerce-shipping-service-details">';
$pane_form['service_details']['#suffix'] = '</div>';

```

The ajax callback is the usual one:

```
/**
 * Ajax callback: Returns the shipping details form elements that match the
 * currently selected shipping service.
 */
function commerce_shipping_pane_service_details_refresh($form, $form_state) {
  return $form['commerce_shipping']['service_details'];
}

```

So definitely possible, check the css classes you're dealing with.
> 1 votes

---
Tags: commerce, ajax
---


title: Colorbox Iframe Resizing

text:
# Question
Title: Colorbox Iframe Resizing
I am trying to resize an colorbox containing an iframe. The following code works fine on normal sites but in Drupal it is having problems. Can anyone suggest what I am doing wrong? The colorbox is supposed to resize to the size of the content plus a specified offset in the Resize function.

```
(function($) {
    $.fn.formToWizard = function(options) {
        options = $.extend({
            submitButton: ""
        }, options);

        //Resize the colorbox
        function Resize_Box(){
            var x = $("body").width();
            var y = $("body").height()+30;
            parent.$.fn.colorbox.resize({
                innerWidth: 600,
                innerHeight: y
            });
        }

        var element = this;

        var steps = $(element).find("fieldset");
        var count = steps.size();
        var submmitButtonName = "#" + options.submitButton;
        $(submmitButtonName).hide();

        // 2
        $(element).before("<div class='nav-container'><div class='inner-container'><ul id='steps'></ul></div></div>");

        steps.each(function(i) {
            $(this).wrap("<div id='step" + i + "'></div>");
            $(this).append("<p id='step" + i + "commands'></p>");

            // 2
            var name = $(this).find("legend").html();
            $("#steps").append("<li id='stepDesc" + i + "'><div class='circle'></div></li>");

            if (i == 0) {
                createNextButton(i);
                selectStep(i);
            }
            else if (i == count - 1) {
                $("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
            else {
                $("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
            Resize_Box();
        });

        //Create the previous button
        function createPrevButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Prev' class='prev'>< Back</a>");

            $("#" + stepName + "Prev").bind("click", function(e) {
                $("#" + stepName).hide();
                $("#step" + (i - 1)).show();
                $(submmitButtonName).hide();
                selectStep(i - 1);
                //Only resize if going back to the first step since it has fewer options
                if(i==1){
                    Resize_Box();
                }
            });
        }

        //Create the next button
        function createNextButton(i) {
            var stepName = "step" + i;
            if(i != count-1)
            {
                $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next notvalid'>Next ></a>");
                $("#" + stepName + "Next").bind("click", function(e) {
                    var currentq = document.querySelector('div#step'+i+' input[type=radio]').name;
                    if($('input[name='+currentq+']:checked').length > 0) {
                        $("#" + stepName).hide();
                        $("#step" + (i + 1)).show();
                        if (i + 2 == count)
                            $(submmitButtonName).show();
                        selectStep(i + 1);
                        //Only resize if going from the first step since all other steps have more options
                        if(i == 0) {
                            Resize_Box();
                        }
                    }
                });
            } else {
                $("#" + stepName + "commands").append("<input id='SaveAccount' type='submit' value='Submit' class='next notvalid'/>");
            }
        }

        function selectStep(i) {
            $("#steps li").removeClass("current");
            $("#stepDesc" + i).addClass("current");
        }
    }
})(jQuery);

```

# Answer
> 0 votes
Try replacing $ with jQuery. By default I don't believe Drupal allows the $ as a shortcut due to potential compatibility issues with other libraries.

---
Tags: javascript
---


# Question
Title: not show any picture in full html ,filtered html mode
when i upload or post a link image in article post or basic post not show anything but when i use the img tag and address show image!enter image description here

# Answer
> 0 votes
Based on the comments - try a module that inserts images into the body of a content type.

---
Tags: media, .htaccess
---


# Question
Title: How can I alter ctools access plugin expectancies?
How can I tell a access plugin to expect a different argument plugin? Surely there isn't a one to one ratio.

So I'm working with panels. I've written a custom argument plugin that will take the node name from the URL and send back a node context. The problem I'm having now is that since I have "Selection Rule" on my page variant that is looking for a node of a specific type. "Selection Rules" are indeed access plugins. So with this said, the "Node: type" access rule requires a "Node" type context.

I'm providing that... the only thing is when the plugin sets up it's access rules it's looking for the following argument:

What my plugin is providing for some reason I haven't found out yet is the following: `argument_node_name_1`

node\_name.inc is the name of my file, by which if I remember correctly what provides the system name because as far as I can tell is some magic provided by ctools.

I can however us the entity\_id argument plugin and of course this all works, but then I don't get to use the node name in the URL.

# Answer
Ok, so here is the answer...

The problem is that we were working on an existing panel page. We made the argument plugin in the middle of working on this page. So we went to "arguments" and switched out the correct argument with Node: Name instead of Node: Id which we had before.

What we didn't do was go through each of our variants and click "Save" on the "Selection Rules" tab. What was up was the old argument was still saved in those slots even though it didn't show up in the drop-down. It took me a while to realize this because I was thinking the "Access" handler settings were being "generated" vs being "stored". I literally worked my way back to the feature I made of the panel page hunting this down, and when I saw it... the UI to Feature translation started clicking in my brain.

In short, the feature I thought I needed isn't needed. All that was needed was to clear the fog of ignorance...

With that said, in an interface such as Views. If a handler such as this was to no longer be available, a "Broken" identifier would then show up. I'm thinking something similar would have clarified a lot here... or at least some kind of validation.

Added a bug report: https://drupal.org/node/2282539
> 1 votes

---
Tags: panels, chaos-tool-suite
---


title: Quiz question update issues

text:
# Question
Title: Quiz question update issues
I discovered the quiz module a few hours ago and began experimenting.

I setup a quiz node and added one multipleoption question. I added three options to the question.

**The problem is when I edit the question and add to the existing 3 options, the forth and fifth options do not showup when viewing the quiz question - only the original three questions show.**

Instead a new "multiple choie question" node is created - not what I intended nor asked for.

Can anyone help me understand and fix this issue?

PS: If anyone knows of a better alternative to the quiz module, please let me know.

# Answer
> 1 votes
You are dealing with a caching issue. I just added the quiz module to a fresh install of Drupal 7.28, made a quiz with one question with three choices, and when I viewed it there were three options. So far so good. Then, I went back and added two options to that question, but when I viewed it I didn't see the two new options show up.

All I had to do was take one version of the quiz and the next time I loaded the quiz the new options showed up. I suspect each user gets a cached version of the quiz when they start taking it, which would make sense in that you don't want to have a different/changed quiz for someone who is halfway through taking one.

I haven't used the quiz module at all, but it looks like it has steady, active development, which is good. You could look into Drupal Webform module as an alternative or search for Drupal Learning Management Systems, if an LMS is really what you are building.

---
Tags: 7, quiz
---


# Question
Title: How to show new added filed to comment table in comment form page
I am writing a module which is adding a new filed to comment table, and in the comment form I want a new filed to be displayed, saying: : " Which paragraph you want to put comment on?".

I have already added the new filed to comment table, I just do not know what hook should I use, so this new filed will be also shown on comment form.

# Answer
> 1 votes
First, you need to make sure Drupal knows about your paragraph field. Adding it to the database alone won't work. Use hook\_schema\_alter() to alter the DB schema information for the comment table. Do this by adding something like the below to your module's install file (a PHP file you name mymodule.install in your module's folder):

```
function MYMODULE_schema_alter(&$schema) {
    $schema['comment']['fields']['paragraph'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'default' => 0,
        'description' => 'Paragraph of the comment.',
    );
}

```

Be sure to flush your caches to update the schema.

Now you need to alter the comment form, and process the paragraph value. Something like the below should work:

```
function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
    $form['paragraph'] = array(
        '#type' => 'textfield',
        '#title' => t('Which paragraph you want to put comment on?'),
        '#required' => FALSE,
        '#size' => 10,
        '#maxlength' => 2,
        '#default_value' => !empty($form['#entity']->paragraph) ? $form['#entity']->paragraph : NULL, // set the default value to the current paragraph value
        '#weight' => $form['subject']['#weight'] + 1, // place after the subject field by setting the weight to +1 of subject weight
    );

    $form['#validate'][] = 'MYMODULE_form_comment_form_validate';
    $form['#submit'][] = 'MYMODULE_form_comment_form_submit';
}

function MYMODULE_form_comment_form_validate(&$form, &$form_state) {
    if (!is_numeric($form_state['values']['paragraph'])) {
        // Validate the paragraph value to make sure it is numeric. Non-numeric values will break because we created paragraph as an integer field
        form_set_error('paragraph', t('Only numeric values are allowed for paragraph number.'));
    }
}

function MYMODULE_form_comment_form_submit(&$form, &$form_state) {
    // update the paragraph field in the comment table
    db_update('comment')
    ->fields(
        array(
            'paragraph' => $form_state['values']['paragraph'],
        )
    )
    ->condition('cid', $form_state['comment']->cid)
    ->execute();
}

```

---
Tags: comments
---


title: New DB field won't appear in Views

text:
# Question
Title: New DB field won't appear in Views
I am trying to hack a crowdfunding module for Ubercart so that it lets certain vital pieces of information, such as funding goals and the amount already contributed, be displayed on the project pages.

I figured that a good way to do this would be to create a view that would display this information, and then make that the default view for the relevant node-type. Unfortunately, I can't get any fields from the uc\_crowdfunding table to appear in the view editor. I even followed this guide should do the trick, as was suggested in this answer.

My added code is as follows:

uc\_crowdfunding.module

```
/**
 * Implements hook_views_api()
 */
function uc_crowdfunding_views_api() {
  return array(
    'api' => '3.0',
    'path' => drupal_get_path('module', 'uc_crowdfunding') . '/views',
  );
}

```

uc\_crowdfunding.views.inc

```
    /**
     * @file
     * Views hooks for UC crowdfunding projects.
     */

    /**
     * Implements hook_views_data().
     */
    function uc_crowdfunding_views_data() {
      $data['uc_crowdfunding_products'] = array(
        'table' => array(
          'group' => 'Crowdfunding: Crowdfunding products',
          'base' => array(),
        ),
        'cfid' => array(),
        'pfid' => array(),
        'dateline' => array(),
        'target' => array(),
        'type' => array(),
      );
      $data['uc_crowdfunding_products']['table']['base'] = array(
        'field' => 'cfid',
        'title' => t('Crowdfunding product'),
        'help' => t('Data for each crowdfunding product.'),
      );

      // Let's join some tables, eh?
      $data['uc_product_features'] = array(
        'pfid' => array(),
        'nid' => array(),
        'fid' => array(),
        'description' => array(),
      );
      $data['uc_product_features']['join']['uc_crowdfunding_products'] = array(
        'left_field' => 'nid',
        'field' => 'nid',
      );

      // Here are some fields
      $data['uc_crowdfunding_products']['target'] = array(
        'title' => t('Fundraising goal'),
        'help' => t('I guess that this is the amount of money that you\'re supposed to raise, huh?'),
        'field' => array(
          'handler' => 'views_handler_field_numeric',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort_group_by_numeric',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
      );

      return $data;
    }

```

**EDIT**: There was also this piece of code, which I had commented out earlier for some reason:

```
$data['uc_products']['join']['uc_crowdfunding_products'] = array(
  'left_table' => 'uc_product_features',
  'left_field' => 'nid',
  'field' => 'nid',
);

```

# Answer
You might want to go about this in a different way, like adding a views handler to the module, but I took the question as how to get data from "uc\_crowdfunding\_products" table into Views. It also seems like the tables mentioned had Node IDs so I made a relationship there. You were pretty close with your code.

Before getting too fancy with relationships and joins, make sure the following basic code works. It adds the ability to list the target field from the products table and some field from the features table with any node associated with them. You'll want to add the node revisions tables if you have revisions on your site. You can also look at the Data project to give you an idea of how to adopt database tables into Drupal.

```
/**
 * @file
 * Views hooks for UC crowdfunding projects.
 */

/**
 * Implements hook_views_data().
 */
function uc_crowdfunding_views_data() {
  $data['uc_crowdfunding_products'] = array(
    'table' => array(
      'group' => 'Crowdfunding',
      'base' => array(
        'field' => 'nid',
        'title' => t('Crowdfunding Products'),
        'help' => t('Data for each crowdfunding product.'),
        ),
      'join' => array(
        'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
         ),
      ),
    ),
  );

  $data['uc_crowdfunding_products']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['uc_crowdfunding_products']['target'] = array(
    'title' => t('Crowdfunding Target'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['uc_product_features'] = array(
    'table' => array(
      'group' => 'Crowdfunding',
      'base' => array(
        'field' => 'nid',
        'title' => t('Crowdfunding something'),
        'help' => t('Data for each crowdfunding product.'),
        ),
      'join' => array(
        'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
         ),
      ),
    ),
  );

  $data['uc_product_features']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['uc_product_features']['some_field'] = array(
    'title' => t('Crowdfunding field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  return $data;
}

```
> 0 votes

---
Tags: views, ubercart
---


title: Does Drupal 7 require Drush 7?

text:
# Question
Title: Does Drupal 7 require Drush 7?
In a Drupal 7 project I'm working on I need to install Drush in order to perform a variety of operations. The only trouble I see is that the latest Drush installer for windows only goes up to version 6. I can install Drush 7 using cygwin, but I want to verify that I'm not missing something. It seems logical that the Drush versions might be synced up with the Drupal version, but perhaps there is some cross version compatibility or something else I'm missing.

If I want to use drush commands on a drupal 7 site do I need to use Drush version 7?

If so is cygwin probably the best way to get Drush 7 up and running on a windows 8 machine?

# Answer
Drush and what version(s) of Drupal are supported per version of Drush are clearly explained here:

http://docs.drush.org/en/master/install/
> 3 votes

---
Tags: 7, drush
---


title: Drupal database and SQL

text:
# Question
Title: Drupal database and SQL
I have done lot of things with Drupal 7. Now I have something to do that can't be done with view interface (in my opinion) and I need to ues php and SQL. Now I am testing in view php field.

I have many node types, i.e. students, past\_study etc., with many custom fields.

the first problem I faced was the name of table, I though "node type name" i.e. students, past\_study should be use in **FROM** but after lot of hours wasting I discover each filed has its own table so have to open so many table like this

FROM field\_data\_field\_this, field\_data\_field\_that

Now the main problem is with WHERE clause I have student\_code in students node type and a reference field s\_code\_ref field in past\_study. I am not sure how to compere student\_code in student node type with s\_code\_ref.

```
WHERE student_code = s_code_ref

```

when s\_code\_ref is a reference entity field in past\_study

What I am doing is to adding a field with complicated calculation from the field of two node types and have to add this in a view with various other field from two node types.

my SQL is something like this

```
<?php
$result = db_query ('
  SELECT SUM((pstd.field_studyDate_value2 - pstd.field_studyDate_value) + (std.field_joiningDate_value - now()))  AS duration
  FROM field_data_field_past_study pstd, field_data_field_student std

  ');

```

std has single record for each student, and pstd may have 0 or more records for students. students name, code, etc are being displaying in the view with relationship of two node type.

my problem is that how to refer the student\_code in record line displaying in view and then using that in where clause to calculate the sum for that particular student\_code.

so I need something like

```
WHERE pstd.s_code_ref = the student_code of the current row.

```

besides I want to know if my approach to calculate this way is right or there is other better ways?

in short I have to calculate total past study duration from one node type (past\_study) then add duration of current study from another node type (student) and bringing the total study duration in a field for each student in a view.

Any help guidance will be appreciated.

# Answer
Solved

Finally I solved the problem with following codes

```
$eid = $row->id; // a variable to store row id
$sql = "SELECT SUM(field_past_std_date_value2 - field_past_std_date_value) as psd, field_std_pin_target_id as tid
FROM field_data_field_pas_std_date d JOIN field_data_field_std_pin p ON d.entity_id = p.entity_id
WHERE field_std_pin_target_id = $eid";

```

this bring me the total duration of past study of each student listed in my view. Although the problem is solved there may be better way to writer above squl. if anyone can give comments it will be highly appreciated. I'll continue improving my Drupal skills.
> 0 votes

---
Tags: views, database
---


# Question
Title: How to add more condition to my conditional field
im trying to add condition to my fields but it seems it can only accept 1 condition.

example : i have 1 select field for salutation(Mr., Ms., Mrs, Dr., etc) and 1 radio field for gender. if i select Mr. on the select field, the radio will automatically check Male button and other wise. if i select like Dr., Prof. or etc, the radio button will uncheck both button.

# Answer
You can use jquery to check and uncheck the field

```
$('#myCheckbox').attr('checked', true); // Checks it

```

$('#myCheckbox').attr('checked', false); // Unchecks it
> 0 votes

---
Tags: entities
---


title: How to print a region in views.tpl.php?

text:
# Question
Title: How to print a region in views.tpl.php?
I have a views-view-unformatted--viewsname--attachment.tpl.php. I want to print region in this file.

I added

```
function mytheme_preprocess_views_view(&$vars) {
   if ($blocks = block_get_blocks_by_region('regionname')) {
      $vars['region'] = $blocks;
  }
}

```

to `template.php`.

and added

```
echo render($region);

```

to `views-view-unformatted--viewsname--attachment.tpl.php` but print nothing.

What is wrong? How can I print region in `views.tpl.php`?

i tested this with mytheme\_preprocess\_html and html.tpl.php and it worked.

# Answer
> 3 votes
1. Create a new region in your theme's .info file.

```
regions[RegionName] = Region Name

```
2. Insert following code in your views-view-unformatted--viewsname--attachment.tpl.php template file to insert region between views rows:

```
print render(block_get_blocks_by_region('RegionName'));

```
3. And then put your block into this region.

For more reference go to this.

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


# Question
Title: Commerce- Is it possible to hide the radio button on payment select with only one payment type?
I just set up Drupal Commerce (not Kickstart) and am using the Commerce PayPal module to allow customers to pay for their orders. This is the only payment method available; however, there is a radio button displayed next to PayPal, as if there was another option that could be selected (although there is not).

How can I hide this option? I assume there is an option in the UI somewhere that I missed, because it is not standard practice to show a radio button when no choice is in fact possible.

It looks like this:

# Answer
> 4 votes
Here is a more elegant way:

```
function yourmodulename_form_commerce_checkout_form_review_alter(&$form, &$form_state, $form_id)
{
   $form['commerce_payment']['#access'] = FALSE;
}

```

I'm not confident if the payment selector might be put into another form in checkout settings. Then it might be part of the commerce\_checkout\_form\_checkout\_alter instead. Then do this:

```
function yourmodulename_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id)
{
    $form['commerce_payment']['#access'] = FALSE;
}

```

# Answer
> 3 votes
There is no way to remove that option as it suppose to be a select box widget. Your best bet is to hide it via css. just target it via the input element and do a display none.

any issues this might be a guide on styling radio buttons via css: http://www.andreapinchi.it/how-to-style-radio-buttons-with-pure-css/

# Answer
> 0 votes
Here's my solution for this (based on a comment above https://drupal.stackexchange.com/a/83460/31913):

```
function yourmodulename_form_commerce_checkout_form_review_alter(&$form, &$form_state, $form_id) {
  $form['commerce_payment']['payment_method']['#type'] = 'markup';
}

```

All we need is to change type from 'radios' to 'markup' and this does the trick.

Hope this helps.

---
Tags: commerce
---


# Question
Title: Importing Drupal Commerce Orders, Customers, Ship to and Bill to addresses
Has anyone successfully imported customers, orders, ship to, and bill to addresses using anything other than a custom module? If there a recipe for the process?

# Answer
> 2 votes
There's also Migrate Module ; but your question is vague regarding the source you are migrating from. This module supports different sources to migrate from

https://drupal.org/node/1006986

# Answer
> 1 votes
Depending on what you need, but I would go with Migrate module. You've got a commerce migrate module and if you're coming from Ubercart, you have commerce migrate ubercart already baked in - also useful if you want to look for examples. You're going to need to build your own migrate classes, check the getting started with migrate guide in drupal.org.

Another alternative is using Feeds module, it will be probably simpler but less robust/customizable, you've got a commerce feeds module but the order support is not quite there.

---
Tags: commerce
---


# Question
Title: how should I add textfield ie jump pagination in views mini pagination of drupal
I have created views of gallery by view. View has provided pagination option. I choose mini pager.

I want to implement **Jump Pagination** here. How should I add in view pagination?

# Answer
> 2 votes
Try the Pretty Pagination module . I think This is what you are looking for.

> This module extends the default pagination into a more flexible format. It allows the user to jump to any specific page in the content just by entering the desired page number in an input box and hitting the ENTER key. The result is easier navigation, especially with sites where the content is spread over numerous pages.

Another module is

Pagerer module. Using this module you can give direct input of the page to go to through a jQuery UI Slider.

> Pagerer is a module providing a collection of pager themes to enhance Drupal and Views standard pagers.
>
> **Features**:
>
> * multi-pane pager
> * Views pager plugin
> * control whether to display links to pages, to items, or to item ranges
> * **direct input of the page to go to through an input widget**
> * selection of the page to go to through a jQuery UI slider
> * selection of the page to go to through a client-side scrolling pager
> * links to progressively more distant pages (like +10, + 20, +100, +200)
> * adaptive logic links
> * specify text to be used to render page separators (like a vertical bar) and page breakers (like an ellipsis)
> * supports Views' AJAX enabled pager

---
Tags: views, paging
---


# Question
Title: How can I make Plupload in D7 start uploading automatically?
I'm using the Plupload integration module and the problem is that once the users select the files, they think that they have already uploaded the files. No matter how obvious, bold and huge you make that "Start upload" button, most of them just ignore it. Plus it is not a good user experience.

What I need is for the "Start upload" button to disappear and the upload of the files into Plupload should begin automatically as soon as the files are selected. Would someone be kind enough to suggest how can this be done?

# Answer
> 2 votes
As given in the readme file of this module add following autoupload property to your form element as shown below.

```
$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#autoupload' => TRUE,
);

```

I have tried it and in works fine.

---
Tags: media, files
---


# Question
Title: How do I ensure that a 'no results' view block is still refreshed by Block Refresh
I have Block Refresh enabled on my site. It does a great job refreshing content blocks unless the original block load contains zero results. If a block is loaded without results, and a new node (which should appear in the block) is created, the new node will not appear in the block unless the page is refreshed. It seems that the refresh code is not active unless the view is loaded with at least one item of content. Is there a way to ensure that the view always loads? I'm thinking that I need to change the 'no results' behavior in my view.

Edit =========

I am currently setting the 'no results' behavior to 'Global: Result summary' and setting the response to 'Empty'. This seems to work.

# Answer
> 0 votes
Set the 'No Results' behavior to 'Global: result summery' and add some text to give as a response. This will ensure that the view is rendered and active, even if there are no results.

This will allow block refresh to add new content as it become available.

---
Tags: 7, views, blocks, ajax
---


# Question
Title: form_submit() and form_validate() doesn't work for tableselect
I'm trying to create sort of slider that slides the user selected blocks. to do so I need to list all of the blocks and let the user to select them, I used `tableselect`. this is my `MODULE.module`

```
function deckslider_permission() {
return array(
        'administer deckslider' => array(
                'title' => t('Administer deckslider module'),
                'description' => t('Perform administration tasks for Trails module.'),
        ),
);
}

function deckslider_menu() {
$items['admin/config/deckslider'] = array(
        'title' => 'Deck Slider',
        'description' => 'deckslider configuration',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('deckslider_admin_settings'),
        'access arguments' => array('administer deckslider'),
        'file' => 'deckslider.admin.inc',
        'file path' => drupal_get_path('module', 'deckslider'),
);
return $items;
}

function select_blocks_submit(&$form, &$form_state, $form_id) {
dsm("Hello");
print "Hello";
}

function deckslider_form_select_blocks_alter(){
    $form['#submit'][]='my_submit';
}

function my_submit(){
    dsm("Hello");
    print "d";
}

```

and it is `deckslider.admin.inc`:

```
function deckslider_admin_settings() {
    global $theme;
    $blocks = _block_rehash($theme);
    $header = array(
        'title' => t('Block'),
    );

    $options = array();
    for ($i = 0 ; $i < count($blocks) ; $i++){
        $options[] = array('title' => t($blocks[$i]['info']));
    }

    $form['select_blocks'] = array(
        '#type' => "tableselect",
        '#header' => $header,
        '#options' => $options,
        '#multiple' => TRUE,
    );
    return system_settings_form($form);
}

```

The problem is the form has a default `save configuration` button and I can't trigger any function for its submission. this is the output

# Answer
> 1 votes
You either need to change the name of the submit handler so it matches Drupal's naming convention of `FORM_FUNCTION_submit`, e.g.

```
function deckslider_admin_settings_submit(&$form, &$form_state, $form_id) {
  dsm("Hello");
}

```

Or add the handler manually in your form function:

```
function deckslider_admin_settings($form, &$form_state) {
    global $theme;
    $blocks = _block_rehash($theme);
    $header = array(
        'title' => t('Block'),
    );

    $options = array();
    for ($i = 0 ; $i < count($blocks) ; $i++){
        $options[] = array('title' => t($blocks[$i]['info']));
    }

    $form['select_blocks'] = array(
        '#type' => "tableselect",
        '#header' => $header,
        '#options' => $options,
        '#multiple' => TRUE,
    );

    $form['#submit'][] = 'select_blocks_submit';

    return system_settings_form($form);
}

```

---
Tags: 7, forms
---


# Question
Title: When using rules to set an entity reference, do I use node or node:nid?
I am using rules to create nodes. Whenever a specific field on my target node-type is changed, a new new will be created and linked to the target node via entity reference field. I would like to know, when setting an entity reference field using rules, should I use the data selector 'node' or the data selector 'node:nid'?

# Answer
> 1 votes
When setting an entity reference with rules, there is no need to specify the nid field. setting the value to the node itself will work.

---
Tags: 7, rules, entities
---


# Question
Title: How do I create a flag so each user gets to set one flag on one instance of a content type?
I want to create a non-global flag which each user can use to 'flag' one (and only one) instance of a specific content type.

I have a view which displays a list of content with fields, including a flag link. I would like to set up my flag (or a rule with a flag) so that if a user clicks on a flag link, all other flags that that user has set (for that specific flag type) are reset.

This will be used for a 'favorite' type of flag, which can only be set on one instance of a specific content type.

# Answer
> 0 votes
Here is how I eventually solved this

Create a rule that does the following actions.

1. Loop through a list of all content that the flagging user has flagged (with the specified flag.)
2. Unflag ALL of the nodes in this list
3. Re-flag the node that triggered the event (F\flagged-node)

---
Tags: 7, rules, flags
---


# Question
Title: When two rules attempt a page redirect, which will actually happen?
I have a rule set up that redirects the user to a specific page after they edit a node. I have another rule that changes the value in a node, then redirects to a different page. My problem: because the second rule makes a change to a node, the first rule is triggered and the user is sent to the first rule's URL (instead of the second rule's URL.)

When two or more URL redirects are triggered by rules, which one is performed? Does this change if a rule is triggered within another rule? How can I fix my problem?

# Answer
> 0 votes
This is what I learned about rules and saved content:

Rules will temporarily save all changes that you make to a node, then save them all after the last action of a rule is performed. Because of this, the node will normally be saved after a rule is 'completed.' You can override this by calling the "Save Entity" action, which saves the entity right then.

Because the node is saved last, any rules that are triggered by the save will normally happen after the rule that triggers it has ended.

This can be changed by using the "Save Entity" action.

# Answer
> 3 votes
try changing the order (weight) of each rule under its settings:

Weight

Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight.

EDIT: it's a little convoluted, but you could create a temporary variable within the node to control things - for example, a hidden boolean field or flag that is changed to true when editing - the rule checks for this as a Data Comparison in a condition. Have the change field and redirect Rule set the boolean but not redirect, then create two rules on save - one if the field is set, and one if the field is not. For the rule if the field is set, then add an action that resets the fields value.

---
Tags: 7, rules
---


# Question
Title: Drupal Front end Form with fields with option to add More Fields
I want to create a Form in the frontend, so user can able to add the data in the form and submit the data. Then i have to display all the data submitted by the user using that form. Just like a Internal Messaging system. I want a Add Reports Form and i want to list all the reports in a page ( View Reports). I planned to create a content type ( Reports), After that i will be able to add the fields. Upto this i know how to do. But i want to know how to have a row with three fields with add button, then if user click on the button, i want to append a new row with same three fields. Just like Multiple Image upload. I have screenshot. In screen one, i have a add button above a row with three fields. In the screen two which is taken after clicking the "add button" , It displays the same add button with two rows with same three fields .

Screen 1 :

Screen 2 :

Any help would be greatly appreciated.

# Answer
Assuming that "Name of Stocklists", "Sales as on Date", and "Closing Stock Value" are all CCK fields, you should be able to do this using Field Collection (https://drupal.org/project/field\_collection).

1) Install Field Collection

2) Create a field collection field on your Report content type. Use the embedded widget. Be sure to make the field multi-value / unlimited values.

3) Go to admin/structure/field-collections and click Manage Fields for the field collection you created.

4) Add the 3 stock text fields to the field collection.

5) Now on the Report add/edit forms, you'll have the "Add Another Item" button.

To align the fields in a row, you should be able to use CSS. To make the button a +, you should be able to use hook\_form\_alter() or hook\_form\_report\_node\_form\_alter().
> 2 votes

# Answer
You can try Inline Entity Form.
> -1 votes

---
Tags: entities
---


# Question
Title: How do I create and set fields in multiple nodes using a rules loop
I have created a RULES loop. It loops over a set of flagged nodes (using the action 'Fetch Node flagged by user') and attempts to create a new node for each flagged node. Finally, the new node is linked to its related 'loop' node via entity reference.

My problem is: The action that creates the new node ('Create a new entity', which is called within the loop) assigns the new node to a static variable name (mine is: entity\_created). Because of this, the loop only creates one new node and only saves data from the final loop node into it.

Is there a way to either create this variable dynamically or is there a way to reset the value of entity\_created so that it can be used to create multiple nodes?

# Answer
Create a sub-rule which does the node creation and call it from within the loop. This should provide enough separation to keep the nodes from interfering with each other. Also, use "Save entity" action to lock the new nodes in place during the loop, instead of at the end of the rule.
> 0 votes

---
Tags: 7, rules
---


title: How to create data types via module

text:
# Question
Title: How to create data types via module
I am writing a module that will create the data types for my site. I am using hook\_node\_info to create the type itself, then I am using field\_create\_field and field\_create\_instance to add fields. field\_create\_field and field\_create\_instance are functions, so I am wondering which hook they should go into. My two best guesses at this point are either hook\_node\_info or hook\_install. The api seems to indicate hook\_install, but I find this confusing. hook\_install happens before hook\_node\_info, so how can you add fields to a content type that does not exist yet? Also hook\_node\_info happens every page load, but hook\_install only happens once (at the time that the module is installed.) Am I creating my content type correctly or am I missing something?

# Answer
> 0 votes
Instead of attempting to create your datatype module from scratch, use the Features module to store your content type settings in a feature generated module. This is faster, but may not cover all of the options that you need (field order, field groups or autotitle.)

---
Tags: 7, hooks, nodes
---


# Question
Title: How to create a button that sets a node value
I would like to create a set of buttons or text links on my site that set the value of a node field and/or create additional nodes. Currently, I am using a combination of flags and rules to do this (when a flag is set, do the following...) This works fine, but it feels a bit cumbersome. The flag has no other purpose other than triggering an action. Is there a module specifically for doing this (including ajax) or is there another simpler way to perform this activity?

# Answer
There is a Field Button module that creates and renders a button. You can then write a rule that is triggered by button clicks. This works great if you only need one or two buttons on a page. However, this module has trouble figuring out which node the button belongs to (and therefor may not be a good option for lists of nodes & buttons rendered by views.)

Another option is the Rules Link module. This module does roughly the same thing. It is not as pretty, but it has better rule integration.
> 0 votes

---
Tags: 7, entities, nodes, rules, flags
---


# Question
Title: Arguments in url break other view on same page
Whenever I go to a url that has parameters in for example www.sitename.com?page=1

It breaks another view that uses contextual filter and looks like this

Why is this happening?

# Answer
> 0 votes
Turns out. If you have a view page with a pager and another view block with a pager on the same page, they conflict.

---
Tags: views
---


# Question
Title: How do you automatically perform several back-to-back migrations in a set order?
I am using the Migrate module to transfer 400,000 items to a new Drupal 7 site. I had a lot of problems in my first attempt because the database table was too large to import in one go. To get around this problem, I created several (around 100) smaller migrations which each did a piece of the migration. This works fine (so far) but the migrations must be done is a specific order. I would like to set up something that will run each migration, one after the other, in a set order. The entire process will take several hours, and I would like to set it up and let it run on its own. How can I do this?

Also, if there is a way create a single migration that can break down one big table query into several smaller queries, I would like to know about it.

Here is a sample of my module activation code (note, the big 400,000 table is not referred to here):

```
function mig_contacts_enable() {

    for ($i=0; $i<10; $i++) {
        $index = substr((1000+$i), 1);
        Migration::registerMigration('ProspectImport', "prospect_import_$index", array('rank' => $i));
    }

    for ($i=0; $i<1; $i++) {
        $index = substr((1000+$i), 1);
        Migration::registerMigration('CustomerImport', "customer_import_$index", array('rank' => $i));
    }

    for ($i=0; $i<1; $i++) {
        $index = substr((1000+$i), 1);
        Migration::registerMigration('CustomerContactImport', "customer_contact_import_$index", array('rank' => $i));
    }

...

```

# Answer
When you activate a migration module that contains multiple migrations, they are installed in alphabetical order. This is the order that they are executed in when you use the UI or:

drush mi --all

I have added a single letter as a prefix to my migration. This allowed me to arrange my migrations as needed.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: How do I set the creation time of a node during a migration using the Migrate module?
I am building a migration and it is important that each new node has the same creation time stamp as the cosponsoring data in the old system. How do I set the creation time of a node during a migration using the Migrate module? I am assuming that it is set by a specific call to `addFieldMapping()`

# Answer
I've been using prepareRow in my class to solve this kind of problem .

First of all I add a new Source Field to the MigrateSourceSQL

```
$source_fields = array(
  'created' => t('the created date'),

```

then in `prepareRow` I added the php for the timestamp and attached it to the row.

```
$row->changed = $nowtimestamp;

```

And then assign with `addFieldMapping`

```
$this->addFieldMapping('field_created_date', 'changed' );

```

This seems to work fine for me.
> 1 votes

# Answer
After creating your migration module and activating it, you will find one or more migration entries in your migration menu (found at admin/content/migrate.) Click on the migration that you are working on. On the next screen, click on the Destination link in the sidebar menu.

This will display a list of all available migration field names, including creation time.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Am I able to remove unneeded field/migration tables from the database manually?
I have been working on my site for three months now and I have noticed that the number of empty tables in my database has grown considerably. Upon closer inspection, I saw that these tables were use by fields belonging to content types that have been removed from the site. Apparently Drupal does a bad job of removing field tables when you simply delete a content type. Is it OK for me to delete these tables manually, or will doing this break code (I have been seeing plenty of mysterious, field related errors lately.) If so, is there anything else besides the field table that I can remove?

The same question is also asked about the migration tables. Can I get rid of them if they don't go away?

# Answer
> 1 votes
Yes, use

```
drush migrate-deregister --orphans

```

This should get rid of all migration tracking tables that are not longer being referred to.

---
Tags: 7, entities
---


# Question
Title: Permission settings for Edit Node Link to show up?
I have a view that includes the `Node: Edit link` field. When the view gets rendered and the user is logged-in, only an Admin can see the link. What permission settings do I need to have enabled for that link to show up in a role with custom permissions?

**Additional details:**

`Edit link` was added to view in the standard way. See screenshot:

# Answer
go to:

> admin/people/permissions

and check:

> Content type name: Edit own content.

if you want that this role can edit **ANY** content of this type, not only their own conent, then check:

> Content type name: Edit any content.
> 1 votes

# Answer
Another factor to consider is whether your site is multilingual. *If so, providing role access to a given content type may not be enough*.

For example, if **Entity Translation** is used, you would want to check permissions settings under that heading on the admin/permissions/people page. This was stumping me on a site recently.

As always, **exercise extreme caution** as to how much control you give users. Even excepting malicious intent, a lot of things can go awry in the hands of inexperienced users.
> 0 votes

# Answer
If you look at the code for the Views handler on the node edit link field, it performs a simple node\_access check for update permission on the node.

```
class views_handler_field_node_link_edit extends views_handler_field_node_link {

  /**
   * Renders the link.
   */
  function render_link($node, $values) {
    // Ensure user has access to edit this node.
    if (!node_access('update', $node)) {
      return;
    }

    $this->options['alter']['make_link'] = TRUE;
    $this->options['alter']['path'] = "node/$node->nid/edit";
    $this->options['alter']['query'] = drupal_get_destination();

    $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
    return $text;
  }
}

```

So it's not something with Views -- other users just don't have permission to edit the content. And giving "Edit Any Content" permission to all users is not a good idea.

If you want to display the link regardless of whether or not they have access, just create a new Custom Field that is formatted as a link to the edit screen:

1) Click Add Fields for the view

2) Add the node NID number, and a Custom Text Field

3) make sure the node NID number is listed before the Custom Text field so that you can use it as a replacement.

4) Add a a custom field with the below value:

```
<a href="/node/[nid]/edit">Edit</a>

```
> 0 votes

---
Tags: views, nodes, users
---


# Question
Title: How can I get the english node title printed on the translated nodes edit page.
Something along the lines of this

```
function THEME_AMENDS_form_alter(&$form, &$form_state, $form_id) {
   global $language;
   $lang = $language->language;
   $translations = translation_node_get_translations($base_node->tnid);
   $translated_node = (isset($translations[$lang])?node_load($translations[$lang]->nid):$base_node);
}

```

I want on the backend of the translated node above the form the english node title to be printed for reference only.

So say we have a contact page, I want on the (spanish) node in the backend above the content edit form "Page Title: Contact" to be printed above where the field for the translated title of the spanish node would be in which the user would translate the title to "contacto".

*Basic layout below:*

**Page Title: Contact**

Node title field: \[Contacto\] \<-- input box

# Answer
> 0 votes
Soluton

```
if($form_id == 'content_page_node_form') {
    $nid = (isset($form['nid']['#value'])) ? $form['nid']['#value'] : false;
    if($nid) {
        $node = node_load($nid);

        if($node) {
            $lang = 'en';
            $translations = translation_node_get_translations($node->tnid);
            $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
            $translated_title = '<h3>English Translation: ' . $translated_node->title . '</h3>';
        }
    }

    $form['#prefix'] = (isset($translated_title) && $translated_node->title != $node->title) ? $translated_title : '';
}

```

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


# Question
Title: Sending emails on a specified interval, based on a date field
So I'm trying to create a schedule that will send an email to a user on a few dates - on their birthday (in the system), and on whatever registration dates they have for a program (NOT their user registration - this is a separate date field).

So there will be between 2 and 11 date fields per person.

I would like to send an email on a certain interval - say, on their birthday, or a year after one of their other registrations.

How would I go about this? Rules doesn't seem to have any specific "send based on date field value" condition. I'm seeing something about possibly running on drush cron and checking date fields individually, but wouldn't this get resource intensive with a high number of users with up to 11 fields?

How is this (I would think fairly normal) use case usually dealt with?

# Answer
I've built a similar feature for the Commerce Recurring module, but instead of sending mails, it creates orders. Here's how I did it.

Interval field module would become handy so you can control how often the action happens (sending mails i.e.).

You could create your own cron event or just rely in the Drupal one, here's a the rule used for generating orders, yours would probably be simpler:

```
  $rule = rules_reaction_rule();
  $rule->label = t('Generate recurring orders on cron run');
  $rule->tags = array('Commerce recurring');
  $rule->active = TRUE;
  $rule
    ->event('commerce_recurring_cron')
    ->action('commerce_recurring_get_due_items', array(
      'number_items' => 5,
      'timestamp:select' => 'site:current-date',
      'provides' => array('commerce_recurring_entities', 'commerce_recurring_entity'),
    ));

  $actions = array(
    'commerce_recurring:select' => 'current-recurring-entity',
    'timestamp:select' => 'site:current-date',
  );

  $loop = rules_loop(array(
    'list:select' => 'commerce-recurring-entities',
    'item:var' => 'current_recurring_entity',
    'item:label' => t('Current recurring entity'),
  ))->action('commerce_recurring_provide_order_properties', array('commerce_recurring:select' => 'current-recurring-entity'))
  ->action('commerce_recurring_generate_order_from_recurring', $actions);
  $rule->action($loop);

  $rules['commerce_recurring_cron_generate_orders'] = $rule;

```

The calculation of the due entities (commerce\_recurring\_get\_due\_items) is a rules action that calls this function, based in Entity Field Query to calculate those entities "due" to actions:

```
/**
 * Return recurring entities with due dates.
 */
function commerce_recurring_rules_get_due_items($number_items = 0, $due_date = NULL) {
  if (empty($due_date)) {
    $due_date = new DateObject();
    $due_date = $due_date->getTimestamp();
  }

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'commerce_recurring', '=');
  $query->propertyCondition('status', TRUE, '=');
  $query->propertyCondition('due_date', $due_date, '<');
  if ($number_items > 0) {
    $query->range(0, $number_items);
  }
  $result = $query->execute();

  $recurring_entities = array();
  if (!empty($result['commerce_recurring'])) {
    foreach($result['commerce_recurring'] as $recurring_entity) {
      $recurring_entities[] = entity_load_single('commerce_recurring', $recurring_entity->id);
    }
  }

  return array('commerce_recurring_entities' => $recurring_entities);
}

```
> 2 votes

---
Tags: rules, datetime, emails
---


title: Reverse translation

text:
# Question
Title: Reverse translation
I have a problem. My multilingual site have 'Italian' as default language and I have a problem with the taxonomy name translation.

In views when I add taxonomy name field this is always displayed in Italian ad never translated so I think to sobstitute the name field to a php field like

```
<?php print t($row->name); ?>

```

but $row-\>name is italian and the t() function assume this string in english and translate it when the site is 'IT'

I tryed to use taxonomy context but drupal double the entry

How can I have in my damn view a field with the right taxonomy name? Can I tell drupal 'translate from IT to EN when the site is English'?

# Answer
This is how I did it for an array of untranslated terms:

```
foreach ($terms as $term => $str) {
  $translation = db_query("SELECT t.translation FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = 'en' WHERE s.source = :source", array(':source' => $str))->fetchAll();
  $terms[$term] = $translation[1]->translation;
}

```
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: How do I programmatically change the body text format on the page content type to full HTML?
I have a custom install profile and I must programmatically change the body text format on the page content type to full HTML. However, I didn't manage to find how to do it.

How can I do it?

# Answer
> 6 votes
You can do it with `hook_element_info_alter`, here is a snippet.

```
<?php
/**
 * Implements hook_element_info_alter().
 *
 * Sets the text format processor to a custom callback function.
 * This code is taken from the Better Formats module.
 */
function MODULENAME_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'MODULENAME_filter_process_format';
      }
    }
  }
}

/**
 * Callback for MODULENAME_element_info_alter().
 */
function MODULENAME_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change the default text format of the 'field_company_spotlight' field to
  // 'Media HTML'.
  if ($element['#bundle'] == 'company' && $element['#field_name'] == 'field_company_spotlight') {
    $element['format']['format']['#default_value'] = 'media_html';
  }
  return $element;
}
?>

```

As THIS post suggests you could try

```
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'filtered_html';

```

in your `hook_form_alter` or in `hook_FORM_ID_alter`

Also there is Better Formats module

> Better formats is a module to add more flexibility to Drupal's core input format system.

# Answer
> 2 votes
Nikhil M's 2nd answer is best -

```
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';

```

no need for hook\_element\_info

# Answer
> -1 votes
you only need one line of code

$result = db\_query('UPDATE field\_data\_body SET body\_format='full\_html' WHERE `bundle`='page');

---
Tags: 7, entities, input-formats
---


# Question
Title: How To Add Button To Commerce POS Command Pane?
My module needs to implement a custom payment workflow. I want to add a button to the Commerce POS command pane to perform a task, then modify the order entity according to the result of the task.

# Answer
Implement the hook hook\_commerce\_pos\_commands().
> 0 votes

---
Tags: commerce
---


title: Views with multiple languages

text:
# Question
Title: Views with multiple languages
I'm building a multi-lingual site with drupal 7. I see that you can "translate" a page. How do I translate a view? The url `http://mysite.com/view` is a view, but I don't see the "translate" button.

# Answer
> 4 votes
Since views are dynamic lists of content, you don't directly translate the view. Rather, you make the view select content of the current user's language. This can be done using the i18n module, and the i18n views module.

Once you have these installed, you add a filter to your view, under the node translation group.

# Answer
> 2 votes
The comment above is correct but, if you are using the Entity Translation module instead of the core Content Translation module, then you need to use the Advanced / Other language filter instead of the "regular" filter mentioned above.

# Answer
> 1 votes
Make sure you note that some fields have a field and a translated field.

Example: *Taxonomy Term: Name* vs. **Taxonomy Term: Name (translated)** are two totally distinct fields.

The token replacement is even different: *\[name\]* vs. **\[name\_i18n\]**

I just went through and fixed several views. Wondering if there is a quick fix I could apply to check all views for these kinds of fields... this could take a while.

---
Tags: views, i18n-l10n
---


# Question
Title: How to make content private and only for certain roles to see
I have a content type called **collection** and 2 user roles: **role1** and **role2**. role1 users can create collections. What I want to do is to allow role1 users to indicate whether they want their collection remain private (in which case only logged in users and hence role2 users can see it) or let it remain public, in which case anonymous users can see the content. Each collection is really just a collection of pictures. I am using Drupal 6.

# Answer
> 3 votes
There are a couple options (and more, I'm sure):

http://drupal.org/project/nodeaccess (easier to set up, but more manually intensive for the end user)

or

http://drupal.org/project/taxonomy\_access (a little bit more to set up, but easier on ur end users)

# Answer
> 0 votes
Update + tips for new readers:

Other modules to consider on Drupal 7:

'**Organic Groups**': \- http://drupal.org/project/og

'**Groups, Community and Co**' (...): \- http://drupal.org/project/gcc

And also '**Taxonomy Access Control Lite**' ('tac\_lite') and '**Content Access**' ('content\_access')

---
Tags: users
---


# Question
Title: which page/code renders admin/config in drupal 7
I have a very basic question. In my drupal 7 installation when I go to `admin/config` the page does not render and all I get is a `1` printed out. I am sure someone die a `die()` on this page. But I am not sure which page is loaded when `admin/config` is rendered. Can anyone point me which possible page/code I should be looking at?

# Answer
The page that normally come up when the path is `admin/config` is inserted into the site by the core **system** module's implementation of `hook_menu()`.

The callback function that actually produces the page is `system_admin_config_page()`.

However, unless you (or somebody else) has hacked core (and we **don't** that, right?) these functions are not the cause of the problem.

Here's a link to the SOP for debugging Blank pages or "white screen of death" (WSOD).
> 2 votes

# Answer
if you think you may have put a die() in somewhere and forgotten where, here's a nice grep command to search files for a string.

```
grep -rHin 'die()' *

```

…and run this from the command line, it will search recursively through directories.
> 0 votes

---
Tags: 7
---