title: Merge two view in one page

text:
# Question
Title: Merge two view in one page
I have create two view

```
[1] testimonial_image
[2] testimonial_text

```

Now i want to display this both view in custom created .tpl file .i.e

```
page--alltestimonial.tpl.php

```

\[1\] testimonial\_image -\> display all images of testimonial

\[2\] testimonial\_text -\> display all text description of testimonial.

How can i merge in one page?

# Answer
This is the way I would approach this. I would create the two views using a block display. And place the two blocks display on the page created. Then you can create the custom page file and theme it. You can add the blocks using the default blocks page (**admin/structure/block**), or the context module.

In case you do not know how to create a block display, on your views UI page,
> 3 votes

# Answer
You can use the Views attach module.

> *Note: This module has been deprecated for Drupal 7 in favor of its phoenix, EVA.*
>
> This module provides two additional Views display plugins, "Profile" and "Node content". These displays do not display on a page but get "attached" to either a user page or nodes of specified types. These views are not stored with the user or node, the way viewreference.module would, so they can be globally-reconfigured.
>
> ### Usage tips
>
> Many people have asked how to use this module to show content related to the node or user to which a view is attached. The answer is to use Arguments. Even though attached views have no path, they still get to make use of arguments.
>
> 1. Create a nodereference field on some node type. Create several nodes of that type that nodereference to some other node
> 2. Create a new "Node content" display; configure it as desired
> 3. Add an argument for the nodereference field you created in step 1
> 4. Set the default value of that argument to "Node ID from URL"
> 5. Set the display to show on node types that are pointed to by that nodereference field
> 6. Profit
> 0 votes

# Answer
I would consider Viewfield, which, as the name implies, essentially makes views fieldable. Attach a viewfield to a node type, allow multiple values, and you could conceivably attach as many views as you want to a node page.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to know which module is responsible for each database query?
I enable the devel module and set it to **Display query log**.

Then on every page load I get a list of the generated sql queries. You can see an example of that list in the capture I uploaded. So far so good.

Is there any way to know which module is responsible for each database queries (in case that the query is generated by a module)?

If this is not possible. Is there any way to do an analysis of all enabled modules to see how them are affecting the general performance of the site?

# Answer
For any modules you download from drupal.org, you can click on the function link within the **where** column and it will direct you to api.drupal.org and you can see the module there.

I couldn't find any settings that would enable showing where the call originated (file path) if the module wasn't an 'official' contrib. A little digging and you can find the information within the devel.module. Specifically, `devel_query_table()` receives `$queries` as its first argument. `$queries` contains the rows that will be displayed and it does have the file path.

I created a quick patch to test this (Doing this does not imply that i think you should modify contrib modules in a production environment):

```
diff --git a/sites/all/modules/devel/devel.module b/sites/all/modules/devel/devel.module
index 0ebdef4..dd6aaa8 100644
--- a/sites/all/modules/devel/devel.module
+++ b/sites/all/modules/devel/devel.module
@@ -1482,7 +1482,7 @@ function _devel_print_object($obj, $prefix = NULL, $parents = NULL, $object = FA
*/
 function devel_query_table($queries, $counts) {
   $version = devel_get_core_version(VERSION);
 -  $header = array ('ms', '#', 'where', 'ops', 'query', 'target');
 +  $header = array ('ms', '#', 'what', 'ops', 'query', 'target', 'where');
    $i = 0;
   $api = variable_get('devel_api_url', 'api.drupal.org');
   foreach ($queries as $query) {
 @@ -1514,7 +1514,8 @@ function devel_query_table($queries, $counts) {
   'id' => "devel-query-$i",
   'data' => $placeholders . $args . $explain,
 );
 -    $cell[$i][] = $query['target'];
 +    $cell[$i][] = $query['target'];
 +    $cell[$i][] = '<div style="overflow-x:scroll">' . check_plain($query['caller']['file']) . '</div>';
      $i++;
     unset($diff, $count, $ops);
 }

```

Here is the raw output on pastebin: http://pastebin.com/Ww5CkQsL

And a screenshot of the un-styled results:

This is a little rough looking as there are style sheets involved, but it gets the information.

Even better would be if the **where** column builder checked for the availability of the function on d.o but I'll digress, as I feel we may be entering, 'file an issue (feature request)' territory.
> 3 votes

---
Tags: database, debugging
---


# Question
Title: How to give edit permission only to specific fields in node edit in?
I have content type with some cck fields:

```
- task time
- task status
- task executor
- task category

```

and of course title/body and other drupal node default fields.

each node of this content type will be assigned to a user selected from site users in task executor field.

I want the when the executor logins view all fields of assigned to task(node) but only can change (edit) the value of task status field. node edit doesn't do that.

I try to use 'Content Permissions' of cck module but it is not what I really need. it doesn't have control on title and body field and also the user can only see the fields he has edit permission on them in node edit page.

What can I do?

I hope I could explain my question clearly.

Thank you.

# Answer
> 1 votes
You can use the Field Permissions module. It allows you to set permission for each field for every user type. It works simply fine.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> ### Features
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

---
Tags: 6, entities
---


# Question
Title: How do I solve the "table '.cache' doesn't exist" error?
My friend's site shows the following error message:

> user warning: Table '.cache' doesn't exist

I am working with zero documentation pertaining to the previous person's work on the site; I'm not sure what has been mucked around with.

How can I fix this?

# Answer
> 1 votes
To recreate this table for Drupal 6, execute the follwing in a SQL tool:

```
delimiter $$

CREATE TABLE `cache` (
  `cid` varchar(255) NOT NULL DEFAULT '',
  `data` longblob,
  `expire` int(11) NOT NULL DEFAULT '0',
  `created` int(11) NOT NULL DEFAULT '0',
  `headers` text,
  `serialized` smallint(6) NOT NULL DEFAULT '0',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

```

You may need to adjust this if the rest of the database is MyISAM (someone should confirm the `CREATE` statememt; I converted all of my Drupal 6 sites to InnoDB).

For Drupal 7, use

delimiter $$

```
CREATE TABLE `cache` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...'$$

```

It is possible that the old webmaster `DROP`ed this table thinking it would save space. Drupal will mostly work with without this table. Then try to clear caches from admin/config/development/performance When you do this, you should get some exceptions from any other missing cache tables.

# Answer
> 0 votes
The error message clearly points to a missing database table. Install a fresh (matching) version of Drupal on any environment, and copy over the database schema for the missing table(s) from the new install to existing site. If it's just the cache tables, you don't need to worry about any of the table data.

# Answer
> 0 votes
I think you need to look at your database (using phpMyAdmin or whatever tool is provided with your hosting service) and see if it isn't completely wiped. While your error only proves that the "cache" table is missing, that's probably the first table being queried by any given request and it's hard to think of a bug that would erase that table and leave the rest of the database intact.

All of which strongly implies deliberation. If you're *extremely* lucky, Mr. Ex-webmaster simply threw a wrench in the gearworks when he left by deleting a table that Drupal needs to function but doesn't contain any irreplaceable information. But if he went that far it would have been just as easy for him to adopt a scorched earth policy. In either case, I hope you have your database backed up somewhere.

---
Tags: database
---


title: How to Edit Content in $content['main']

text:
# Question
Title: How to Edit Content in $content['main']
I am maintaining a Drupal 7 site that was developed by another developer and I'm trying to move the search field on the results page to appear under the H1. Currently the site has a search field that appears at the very top (above the top navigation) \> after the user submits a keyword in the search field, they are taken to the Results page which has a second search field that appears right above the H1.

I know that the second search field on the Results page is within the $content\['main'\], but I can't seem to locate how to move the search field to save my life! The script in the template.tpl.php file that contains the $content\['main'\] is pasted below. I've checked the MySQL database (field\_revision, field\_data, & node tables), Structure (Panels, Mini Panels, Views, Pages, & Blocks), and content types -- all to no avail.

```
<?php if (!empty($content['main'])): ?>
<?php print render($content['main']); ?>

<? // debugging  ?>
<pre><?php print_r($node); ?></pre>
<?php
print '<div>var_dump <br/>';
var_dump($content);
print '</div>';
?>
<? // debugging  ?>

```

Output from debugging script that was pasted below the $content\['main'\]

```
var_dump
array(5) { ["search"]=> string(798) "

" ["header"]=> string(0) "" ["main"]=> string(4492) "

```

I've looked into Where does Drupal store the content of a node's body? but haven't found the search field in any of the suggestion yet.

# Answer
The header normally comes from the page, and the search field comes from the form. In order to place the h1 under the search field I'm usually using the next steps:

1. Hide the title on the search results page using the theme\_preprocess\_page
2. Use the search-results.tpl.php to insert the title under the search field
> 0 votes

---
Tags: nodes
---


# Question
Title: How can I get Beautytips Module to work with Views field output?
I have uploaded the module Beautytips, and enabled it as usual. I have a content type called Solicitation. From among many fields I have the two main fields (Title and Remarks). I listened to a tutorial video, but it seems it takes one too far than my simple needs. I have a view in which I made the Remarks field to be excluded from view and I followed that field with the title and and I set option ( Output this field as a link) and I filled the the (Alt text:) with \[field\_remarks\_value\] . I have a block view. When I hover on the title I get only ordinary tooltip, while in the setup I selected the Transparent style. I guess I am missing something that I must fill like a selector that I must fill somewhere. Can someone with expertise in this help me. I would be much appreciating.

# Answer
You can do this with the BeautyTips module but its not the default behaviour as it does not have Views integration built-in. Fortunately, your BeautyTips use case is rather simple so the approach outlined here will work for you. Specifically, you want to edit your 'Title' field to rewrite it to add a custom trigger class like this:

```
<span class='btytp' title='[markup]'>[title]</span>

```

and then add this to the header of the view:

```
<?php
drupal_add_js (
  '$(document).ready(function()
  {
    $(".btytp").bt();
  }); ',
    'inline');
?>

```

However, by doing this you're effectively bypassing the BeautyTips module altogether and won't be using the built-in styles the module provides. Fortunately, this is easy to fix. If you look in the modules file, you'll see all of the styles defined as Arrays that are then converted into a javascript array and used to instantiate the beautytips instance. So for example, if I were using the Hulu style, I would find this array:

```
  $styles['hulu'] = array(
    'fill' => '#F4F4F4',
    'strokeStyle' => '#666666',
    'spikeLength' => 20,
    'spikeGirth' => 10,
    'width' => 350,
    'overlap' => 0,
    'centerPointY' => 1,
    'cornerRadius' => 0,
    'cssStyles' => array(
      'fontFamily' => '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
      'fontSize' => '12px',
      'padding' => '10px 14px'
    ),
    'shadow' => TRUE,
    'shadowColor' => 'rgba(0,0,0,.5)',
    'shadowBlur' => 8,
    'shadowOffsetX' => 4,
    'shadowOffsetY' => 4,
  );

```

All of the values here are what you need to pass to javascript when you invoke it on your own. So, to do this using the code we already have with the Hulu style, that would look like:

```
<?php
drupal_add_js (
  '$(document).ready(function()
  {
    $(".btytp").bt({
        fill: '#F4F4F4',
        strokeStyle: '#666',
        spikeLength: '20',
        spikeGirth: '10',
        width: 350,
        cornerRadius: 0,
        cornerPointY: 1,
        strokeWidth: 0,
        cssStyles: {
                fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
                fontSize: '12px',
                padding: '10px 14px'
        },
        shadow: true,
        shadowColor: 'rgba(0,0,0,.5)',
        shadowBlur: 8,
        shadowOffsetX: 4,
        shadowOffsetY: 4,
        shadowBlur: 8,
    });
  }); ',
    'inline');
?>

```
> 1 votes

---
Tags: views, 6
---


# Question
Title: Path to theme within a module / jQuery context?
I've written a custom D7 module as a companion to a theme I've contributed to drupal.org and in the module, I effect output of the logo image with some basic jQuery as such:

```
$("li.purple").click(function () {
$('#logo-img').attr('src', '/sites/all/themes/mytheme/images/logo-purple.png');
});

$("li.green").click(function () {
$('#logo-img').attr('src', '/sites/all/themes/mytheme/images/logo-green.png');
});

```

etc...

Now this works fine but ideally I'd like not to have to hard code the theme path as above, it would be great to have a variable instead.

I did some searching and found a drupal docs page, "Pass the theme path to javascript", but I can't really make heads or tails of it within the context of what I'm trying to do. There's a preprocess function on the aforementioned docs page that supposedly can tell jQuery what the path to the theme is but I don't quiet understand the usage in terms of actually creating a theme path variable. So from this:

```
function my_module_preprocess_page(&$vars) {
  drupal_add_js('jQuery.extend(Drupal.settings, { "pathToTheme": "' . path_to_theme() . '" });', 'inline');
}

```

I need to extract the path variable and put into this:

```
$("li.green").click(function () {
$('#logo-img').attr('src', pathToTheme + '/images/logo-purple.png');
});

```

... However, I get this error:

```
Uncaught ReferenceError: pathToTheme is not defined

```

... so I'm just struggling how to get this to work or if it's even possible.

# Answer
Use `Drupal.settings.pathToTheme`.

```
$("li.green").click(function () {
 $('#logo-img').attr('src', Drupal.settings.pathToTheme + '/images/logo-purple.png');
});

```

Also, `theme_preprocess_page(&$vars)` should be in template.php as `your_theme_preprocess_page(&$vars)`;

Good idea to not hard code the theme path, that path structure wouldn't work for all set-ups.
> 2 votes

# Answer
Personally, I think that building up paths in JS should be avoided. I used to do this, but lately, run into the problem that can result.

When you glue together a path in JS, you bypass the API. In your particular example, it would mean that your image couldn't be server up from a CDN.

I would do something like

```
function MYTHEME_preprocess_page (&variables) {
  $path = drupal_get_path('theme', 'MYTHEME');

  drupal_add_js(array(
    'MYTHEME' => array(
      'logoSrc' => file_create_url($path . '/images/logo.png'),
    ),
  ), 'setting');
}

```

in your theme, and then in your JS

```
$("li.green").click(function () {
  $('#logo-img').attr('src', Drupal.settings.MYTHEME.logoSrc);
});

```

Also note that in the Drupal Javascript API, the jQuery context and settings are passed into behaviors, so you can do something like:

```
(function ($, Drupal, undefined) {
  Drupal.behaviors.MYTHEME = {
    attach: function (context, settings) {
      $("li.green", context).click(function () {
        $('#logo-img', context).attr('src', settings.MYTHEME.logoSrc);
      });
    }
  };

})(jQuery, Drupal);

```

in your theme Javascript.
> 2 votes

---
Tags: 7, javascript, theming
---


# Question
Title: How can I render a block in the sidebar in php?
I'm using the Zen theme and I'm trying to keep as much in code as possible. I'm currently using context to render the block, but I like my php :)

I'm aware of

```
$block = module_invoke('views', 'block_view', 'name_of_view_display');
print render($block);

// and this
$block = block_load('views', 'name_of_view-name_of_view_display');
$output = _block_get_renderable_array(_block_render_blocks(array($block)));

```

which works perfectly in most cases. My page.tpl file says

```
<?php if ($sidebar_first || $sidebar_second): ?>
  <aside class="sidebars">
    <?php print $sidebar_first; ?>
    <?php print $sidebar_second; ?>
  </aside>
<?php endif; ?>

```

So, clearly, my $sidebar\_second variable is empty. I tried to render the block in a theme\_preprocess\_page function, adding the block to the $vars\['page'\]\['sidebar\_second'\] array, but no luck so far.

Any ideas?

Thanks, Brett

# Answer
If you need to assign block to region programmatically you can implement hook\_block\_info\_alter

```
function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  if (isset($blocks['views']['name_of_view-name_of_view_display'])) {
    // assign block to region
    $blocks['views']['name_of_view-name_of_view_display']['region'] = 'sidebar_second';
  }
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: node permission based on a cck user reference field
I have a cck user reference field in a content type in drupal 6. I want only the user selected by that field can view the node content.

How can I achieve this?

# Answer
Install the User Reference Access module - it directly addresses this requirement:

> This module works with CCK userreference fields and the node\_access module to add additional grants to nodes.
>
> To enable userref\_access on a node, edit the userreference field for the node type and check the "Use User Reference Access" box.
>
> Any users that are referenced by this field will be given view permissions for the node, all other useres will be denied access to the node.
> 1 votes

---
Tags: 6, entities, users
---


# Question
Title: adding multiple content elements to a page?
I am coming from TYPO3 and like Drupal a lot so far. Especially how easy it is to define custom content elements with the fields feature.

But what I kind of miss is this:

In TYPO3 you have pages which can be filled with content elements of various kinds (text, text with images, tables, forms,...). I like this a lot. It's versatile and harder to mess something up for the editors compared to simply having a "page" where you have a big text area you have to work in.

What the best way to achieve something similar in Drupal?

Edit: Here are two example screenshots of the TYPO3 backend: http://www.aemka.de/fileadmin/\_migrated/pics/Backend\_2\_02.png http://www.form4.de/typo3temp/pics/faa6f10095.jpg

Yes, it seems like those panels are exactly what I am looking for. Thank you! :)

# Answer
It seems you are looking for https://drupal.org/project/panels. It gives you the ability to add various types of content.
> 2 votes

---
Tags: entities, nodes, 7
---


# Question
Title: How do you expose/display a product type's custom field in a product display?
I created a custom field in my product type, but how do i get it to display on my product display when my item is selected? The field doesnt show up in managed display in the product display.

# Answer
I have been through my settings for my product & it's display to check my settings. I have several fields added to my product which I display on product display. I have Display Suite module enabled at my instance.

So what I have done is - I have checked *Full content* in my custom display setting tab at my product as well as product display in manage display. You can also do **Product -\> Manage display -\> custom display setting -\> full content(check)** & save.

I have enabled all fields in my product in `full content` tab, which looks like --

After that when I visit my **product display -\> manage display -\> full page**, I find those field, which I have enabled to be visible. It looks like --
> 0 votes

---
Tags: 7, entities, commerce
---


# Question
Title: How can I change the Add to Cart button text on specific product forms?
What is the easiest way to change the Add to cart form button text to something custom? I want to change the text only on certain product types. How should I approach this?

# Answer
> 1 votes
Take help of hook\_form\_alter. Get the ID of the form for the product display where you are trying to change the text & do something like this --

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Check Out');//Put the text which you want to make appear instead of "Add to cart".
  }
}

```

I also have several product display with custom text for "Add to cart". It took some time for me figure out the easy way. Have Fun :)

# Answer
> -1 votes
The module works great.stringoverrrides

---
Tags: 7, commerce
---


# Question
Title: How do I generate an order using the "Add to Cart" button in a custom PHP page?
In Drupal Commerce Kickstart, I used custom PHP page in Drupal root folder. As per requirements, I chose custom PHP Code to show products in different logic pattern. I am getting product id value for each product in that page. Now, I need "Add to cart" button which should generate order number and redirect it to checkout page directly.

How do I generate an order using the "Add to Cart" button in a custom PHP page?

# Answer
> 1 votes
Though I prefer the Commerce Add To Cart Filter module to adding a "Add to cart" button anywhere in my content by mentioning the product ID with the suggested method, since you need PHP code, I am copying my old code which I don't use anymore; maybe it can help you.

```
function MYMODULE_commerce_menu() {
  $items = array();
  $items['mysite/trial-buy'] = array(
    'title' => 'Trial Plan',
    'page callback' => 'MYMODULE_add_single_product',
    'access arguments' => array('view published content'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MYMODULE_add_single_product(){
  global $user;
  $product_id = 59;//This is my product ID, place your's here.
  $order = commerce_order_new($user->uid, 'checkout_checkout');
  commerce_order_save($order);
  $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  commerce_line_item_save($line_item);
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;
  commerce_order_save($order);
  drupal_goto('checkout/' . $order->order_id);//Forward to checkout. You can have your method here.
}

```

This is the code I came out with the help of Commerce guys documentation when I was working with some custom need like yours.

---
Tags: commerce
---


# Question
Title: Remove home page navigation from logo at checkout
Usually users can go to front/home page from anywhere by clicking on the logo. But if I see some e-commerce site, they restrict it when we go for any steps of checkout. I also want to do the same. If somebody clicks on checkout & URL form something like $base\_url/checkout\*, I want to remove home/front page navigation link from logo. How can it be done ?

# Answer
I have created three `page.tpl.php` with name - `page--checkout.tpl.php`, `page--checkout--review.tpl.php`, `page--checkout--shipping.tpl.php`.

These were being called on the every steps of checkout process in my instance.

After that everything was easy. I had control over each elements of page. I removed unwanted region as well as navigation to HOME from site logo.
> 1 votes

# Answer
A good method of doing this is with the context module and context layouts.

Context module: https://drupal.org/project/context

You can specify two layouts, one for main and one for checkout.

Heres a vid about it. http://www.youtube.com/watch?v=rzBpjZ\_ZRfo
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to make one field's appearance on form depend on another field
Please I need to create a field whose appearance on my form depends on the field immediately preceding it.

For example in field A the user is asked a true or false/yes or no question. E.g Do you like the English premiership?

If he answers true, a previously hidden field B (which is a taxonomy term)is presented to the user e.g Choose your preferred English Premiership club.

If he answers no, nothing happens.

P.S. Both field will be created via Profile 2 module.

Thank you.

# Answer
You are looking for Conditional Fields module.

Description on module page says -

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
> 0 votes

---
Tags: entities
---


title: Display of content-type

text:
# Question
Title: Display of content-type
I've got custom content-type with several groups and fields.

I want to change default display of that content-type. In which file can I find appropriate code?

# Answer
You need to create that file - copy the node.tpl.php file to

```
node--your_content_type.tpl.php

```

and take it from there. Here's the relevant page from the handbook for Drupal 7

https://drupal.org/node/1089656

Alternatively, if you're just getting started with node templates, you may find it easier to install and enable the content templates module so you can add and modify node templates from the administrator backend:

https://drupal.org/project/contemplate

> The Content Template (a.k.a. ConTemplate) module allows modification of Drupal's teaser and body fields using administrator defined templates. These templates use PHP code and all of the node object variables are available for use in the template. An example node object is displayed and it is as simple as clicking on its properties to add them to the current template.
> 4 votes

# Answer
As I see your question is regarding styling of fields. You can take help from module Field Formatter Class. It lets you apply class for field on manage display.

If you are intended to have control over your field by help of template files, then copy field.tpl.php from **$base\_url/modules/field/theme** and put that into your theme folder.

Change the name to have effect on your particular field like field--FIELDNAME.tpl.php, where FIELDNAME will be machine name of your field, for example field--body.tpl.php.

Insert/modify the CSS classes in there and style accordingly.
> 0 votes

# Answer
Try something like `hide($content['field_group-machine_name']['field_machine_name'])` inside the template file for your content type, for all the fields that are before the fields you want to render; then render those fields using `print $content['field_group-machine_name']['field_machine_name']` and render the rest of the content.

By the way, why don't you just change the order in the content type display?
> 0 votes

---
Tags: 7, nodes
---


title: Custom entity operation links

text:
# Question
Title: Custom entity operation links
I've built a couple of custom entities in Drupal 8

* Vendor, defined as such:

```
/**
 * Defines the vendor entity.
 *
 * @EntityType(
 *   id = "vendor",
 *   label = @Translation("Vendor"),
 *   module = "vendor",
 *   controllers = {
 *     "storage" = "Drupal\vendor\VendorStorageController",
 *     "render" = "Drupal\Core\Entity\EntityRenderController",
 *     "form" = {
 *       "default" = "Drupal\vendor\VendorFormController",
 *       "delete" = "Drupal\vendor\Form\VendorDeleteForm"
 *     }
 *   },
 *   base_table = "vendor",
 *   uri_callback = "vendor_uri",
 *   translatable = FALSE,
 *   fieldable = TRUE,
 *   entity_keys = {
 *     "id" = "vendor_id",
 *     "uuid" = "uuid",
 *     "label" = "name",
 *     "bundle" = "type"
 *   },
 *   bundle_keys = {
 *     "type" = "type"
 *   },
 *   route_base_path = "admin/vendors/types/manage/{bundle}"
 * )
 */

```
* and VendorType:

```
/**
 * Defines the vendor type entity.
 *
 * @EntityType(
 *   id = "vendor_type",
 *   label = @Translation("Vendor Type"),
 *   module = "vendor",
 *   controllers = {
 *     "storage" = "Drupal\vendor\VendorTypeStorageController",
 *     "access" = "Drupal\vendor\VendorTypeAccessController",
 *     "list" = "Drupal\Core\Config\Entity\ConfigEntityListController",
 *     "form" = {
 *       "default" = "Drupal\vendor\VendorTypeFormController",
 *       "delete" = "Drupal\vendor\Form\VendorTypeDeleteForm"
 *     }
 *   },
 *   config_prefix = "vendor.type",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "label" = "label"
 *   }
 * )
 */

```

`VendorType` is a config entity and serves as the bundle for `Vendor`, in exactly the same way that the core `Node`/`NodeType` entity types do. I have all the boilerplate code in place mimicking the Node/NodeType relationship.

Everything's up and running, the entities work great in every respect, but I can't figure out a small detail. On the "Content types" admin page, the action links in the right hand column of each row have the "Manage Fields/Manage Display/etc" links, plus the usual "Edit/Delete" as inherited from `EntityFormController::actions()`.

On my `VendorType` overview form, I only see the Edit and Delete links, not the field-specific ones.

(ignore the missing delete buttons, those particular types can't be deleted; the delete link shows up for manually added types)

I've tried to track it down but it seems like the node module is getting these links added for "free" as it were, without implementing anything explicitly to add them.

What do I need to do to take advantage of this little nicety and get the field-specific links added automatically for my own entity types?

# Answer
Since the patch in Use hook\_entity\_operation\_alter() for manage fields and manage display links has been deployed, there is now a easier way to alter the operations visible in a list of entities. Also, the *Field UI* module automatically adds some operations.
Differently from what the patch in that issue shows, the hook to implement is `hook_entity_operation()`, which is implemented as follows, from the *Field UI* module.

```
function field_ui_entity_operation(EntityInterface $entity) {
  $operations = array();
  $info = $entity->getEntityType();
  // Add manage fields and display links if this entity type is the bundle
  // of another and that type has field UI enabled.
  if (($bundle_of = $info->getBundleOf()) && \Drupal::entityManager()->getDefinition($bundle_of)->get('field_ui_base_route')) {
    $account = \Drupal::currentUser();
    if ($account->hasPermission('administer ' . $bundle_of . ' fields')) {
      $operations['manage-fields'] = array(
        'title' => t('Manage fields'),
        'weight' => 15,
        'url' => Url::fromRoute("entity.{$bundle_of}.field_ui_fields", array(
          $entity->getEntityTypeId() => $entity->id(),
        )),
      );
    }
    if ($account->hasPermission('administer ' . $bundle_of . ' form display')) {
      $operations['manage-form-display'] = array(
        'title' => t('Manage form display'),
        'weight' => 20,
        'url' => Url::fromRoute("entity.entity_form_display.{$bundle_of}.default", array(
          $entity->getEntityTypeId() => $entity->id(),
        )),
      );
    }
    if ($account->hasPermission('administer ' . $bundle_of . ' display')) {
      $operations['manage-display'] = array(
        'title' => t('Manage display'),
        'weight' => 25,
        'url' => Url::fromRoute("entity.entity_view_display.{$bundle_of}.default", array(
          $entity->getEntityTypeId() => $entity->id(),
        )),
      );
    }
  }

  return $operations;
}

```

Before that patch was deployed, you had to implement a list controller and use its `getOperations()` method. For example, for nodes that is done in NodeTypeListController, whose NodeTypeListController::getOperations() method contains the following code.

```
  if ($this->moduleHandler->moduleExists('field_ui') && user_access('administer node fields')) {
    $operations['manage-fields'] = array(
      'title' => t('Manage fields'),
      'href' => $uri['path'] . '/fields',
      'options' => $uri['options'],
      'weight' => 0,
    );
  }
  if ($this->moduleHandler->moduleExists('field_ui') && user_access('administer node form display')) {
    $operations['manage-form-display'] = array(
      'title' => t('Manage form display'),
      'href' => $uri['path'] . '/form-display',
      'options' => $uri['options'],
      'weight' => 5,
    );
  }
  if ($this->moduleHandler->moduleExists('field_ui') && user_access('administer node display')) {
    $operations['manage-display'] = array(
      'title' => t('Manage display'),
      'href' => $uri['path'] . '/display',
      'options' => $uri['options'],
      'weight' => 10,
    );
  }

```

The description for the class simply says "Provides a listing of node types." Looking at the plugin annotation for the NodeType class, you could notice a reference to `NodeTypeListController`.

```
@EntityType(
  id = "node_type",
  label = @Translation("Content type"),
  module = "node",
  controllers = {
    "storage" = "Drupal\Core\Config\Entity\ConfigStorageController",
    "access" = "Drupal\node\NodeTypeAccessController",
    "form" = {
      "add" = "Drupal\node\NodeTypeFormController",
      "edit" = "Drupal\node\NodeTypeFormController",
      "delete" = "Drupal\node\Form\NodeTypeDeleteConfirm"
    },
    "list" = "Drupal\node\NodeTypeListController",
  },
  config_prefix = "node.type",
  entity_keys = {
    "id" = "type",
    "label" = "name",
    "uuid" = "uuid"
  }
)

```

The class defined as list controller for your Vendor Type entity uses the following code, for ConfigEntityListController::getOperations().

```
public function getOperations(EntityInterface $entity) {
  $operations = parent::getOperations($entity);
  $uri = $entity->uri();

  // Ensure the edit operation exists since it is access controlled.
  if (isset($operations['edit'])) {
    // For configuration entities edit path is the MENU_DEFAULT_LOCAL_TASK and
    // therefore should be accessed by the short route.
    $operations['edit']['href'] = $uri['path'];
  }

  if (isset($this->entityInfo['entity_keys']['status'])) {
    if (!$entity->status()) {
      $operations['enable'] = array(
        'title' => t('Enable'),
        'href' => $uri['path'] . '/enable',
        'options' => $uri['options'],
        'weight' => -10,
      );
    }
    else {
      $operations['disable'] = array(
        'title' => t('Disable'),
        'href' => $uri['path'] . '/disable',
        'options' => $uri['options'],
        'weight' => 20,
      );
    }
  }

  return $operations;
}

```

To get the same links, you should define a custom class that extends `ConfigEntityListController` and implements `EntityControllerInterface`, adding in the `getOperations()` method the necessary code.
> 12 votes

---
Tags: entities, 8
---


# Question
Title: How to convert the php array format to javascript array format
I uploaded the Beautytips module and I was able with some help from a member of this site to integrate some code into views, but I could not convert the PHP array format into JavaScript format. The code that I stopped at is the following.

```
drupal_add_js (
  '$(document).ready(function() {
    $(".btytp").bt(
        fill: '#F4F4F4',
        strokeStyle: '#666',
        spikeLength: '20',
        spikeGirth: '10',
        width: 350,
        cornerRadius: 0,
        cornerPointY: 1,
        strokeWidth: 0,
        cssStyles: {
          fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
          fontSize: '12px',
          padding: '10px 14px'
        },
        shadow: true,
        shadowColor: 'rgba(0,0,0,.5)',
        shadowBlur: 8,
        shadowOffsetX: 4,
        shadowOffsetY: 4,
        shadowBlur: 8,
    );
  });', 'inline');

```

This code should be used in the Basic Settings of a view block. I would be very grateful for any help in this regard, as I am not comfortable with JavaScript.

# Answer
> 0 votes
You've got the jquery mostly right, you're just missing the brackets that would indicate that its an array for the list of options that follow. Try this jsfiddle here, modified from the one you had sent earlier:

http://jsfiddle.net/xEPSs/10/

Note that for this jsfiddle, I've include the jquery 1.6.2 library and the beautytips library but removed your php code.

You've not got two options to include this in your view. You can add it as a separate javascript file through your theme to have it included on every page, or you can continue to add it in to the header of just that one view with this code:

```
drupal_add_js ('
$(document).ready(function() {
          $(".btytp").bt({
                fill: '#F4F4F4',
                strokeStyle: '#666',
                spikeLength: '20',
                spikeGirth: '10',
                width: 350,
                cornerRadius: 0,
                cornerPointY: 1,
                strokeWidth: 0,
                cssStyles: {
                    fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
                    fontSize: '12px',
                    padding: '10px 14px'
                },
                shadow: true,
                shadowColor: 'rgba(0,0,0,.5)',
                shadowBlur: 8,
                shadowOffsetX: 4,
                shadowOffsetY: 4,
                shadowBlur: 8,
        });
    });', 'inline');

```

---
Tags: views
---


title: db_merge() PDO error

text:
# Question
Title: db_merge() PDO error
The Error:

```
 PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, value) VALUES ('1', '1', 'mydata', '35')' at line 1: INSERT INTO {mytable} (uid, tid, key, value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => mydata [:db_insert_placeholder_3] => 35 ) in MyClass->save_myData() (line 145 of /path/to/my/stuff/my.class.php).

```

My Code:

```
db_merge( 'mytable' )
    ->key( array( 'uid' => $this->user->uid, 'tid' => $data['tid'] ) )
    ->insertfields(array(
           'uid' => $this->user->uid,
            'tid' => $data['tid'],
            'key'      => $key,
            'value'    => $value
    ) )
     ->updateFields( array( 'value' => $value ) )
     ->execute();

```

I've tried this with just the basic -\>fields() but my latest iteration here involves specifiying the inserted fields and updated fields separately (just ran across this while googling and thought it might help. Same error though.

Originally I was trying to use

```
db_query( "REPLACE INTO goal_data(uid,tid,key,value) VALUES( :uid,:tid,:key,:value)", array(
                ':uid'      => $this->user->uid,
                ':tid'      => $data['tid'],
                ':key'      => $key,
                ':value'    => $value
            ) );

```

It too was throwing an error saying that there were in invalid number of placeholders or something similar. There wasn't. The error was basically:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

```

Any thoughts on what I'm doing wrong? I don't get it, trying everything here and just keep getting errors.

Here's my table structure (very simple).

```
CREATE TABLE IF NOT EXISTS `mytable` (
  `uid` int(11) NOT NULL,
  `tid` int(11) NOT NULL,
  `key` varchar(255) NOT NULL,
  `value` longtext NOT NULL,
  PRIMARY KEY (`uid`,`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

```

# Answer
> 0 votes
The syntax error comes from `key` being a MySQL reserved keyword.
The best solution is to not use these keywords as identifiers.
Otherwise the workaround is to enclose them in backticks.

It may work like this:

```
  [...]
  ->insertFields(array(
           'uid' => $this->user->uid,
            'tid' => $data['tid'],
            '`key`'    => $key,
            'value'    => $value
    ) )
   [...]

```

However this fails at cross-database compatibility since the backtick is a MySQL-only syntax. Better rename the column if possible.

---
Tags: 7, database
---


# Question
Title: Change Input Field Value using Hook Form Alter (User Login Block)
How would I go about changing the input field value from e.g. 15 to 10 in the default User Login Block for Username and Password fields, using Hook Form Alter?

# Answer
Put this in your module:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    $form['name']['#size'] = 10;
    $form['pass']['#size'] = 10;
  }
}

```

Also hook\_form\_user\_login\_block\_alter can be used, then you don't need to check the form\_id.

Remember to clear the cache, if you are not already using hook\_form\_alter.
> 2 votes

---
Tags: forms
---


# Question
Title: How can I keep a long-running Drush script from gradually exhausting available RAM?
I've got a drush script that's used to clear out old, unpublished nodes that have come in from feedapi. The script is fairly simple: get all the nodes with status 0 of a certain type ("post") and age (older than 90 days), loop through them, delete each one.

The script runs through about 4,000 nodes at a time, then exhausts the memory available to its PHP process. I can watch the script's footprint grow from `top` and the 4,000 node limit is somewhat consistent. I've got over 100,000 nodes to work through, though, so I don't think it will be practical to just jack up the RAM available to the process long enough to get a run out of it.

Is there anything I can add at the bottom of each iteration to release the RAM it's consuming?

# Answer
> 1 votes
Other Options: http://groups.drupal.org/node/189694

# Answer
> 2 votes
You could use the Drupal batch API and call it from Drush. You could use the Drush batchTest unit test as another reference on how to use the batch API from Drush.

# Answer
> 0 votes
How about getting only a fraction of the nodes at a time from the DB, say 3000 at a time, using SQL's LIMIT (and OFFSET) commands in your SELECT query? Then simply loop over those "chunks".

---
Tags: drush
---


title: auto complete fields from selection

text:
# Question
Title: auto complete fields from selection
I have taxonomy term with 2 fields: a and b. I have two taxonomy terms.

* term1: a1 and b1
* term2: a2 and b2

I have a content type with 3 fields; the first one is from a selected list from the taxonomy terms (term reference). When I choose the first field, I need that the related taxonomy terms appear on the second and third fields. For example, if I choose term2, I need that the terms a2 and b2 appear automatically in the other fields.

Is it possible?

# Answer
> 0 votes
Ok, if somebody are interested in it I've found this post that solve my question:

Auto-Fill from on content type to another

---
Tags: entities
---


# Question
Title: Show a Unique Header Image based on Path in Drupal 7
I'm trying to customize the header with an image for each path; if not, put a default image. I found a way to do Lullabot, but it is for Drupal 6.

Is there any option for Dupal 7?

### theme-settings.php

```
/**
* Implementation of hook_settings() for themes.
*/
function MYTHEMENAME_settings($settings) {
    // This ensures that a 'files' directory exists if it hasn't
    // already been been created.
    file_check_directory(file_directory_path(),
        FILE_CREATE_DIRECTORY, 'file_directory_path');
    // Check for a freshly uploaded header image, save it to the
    // filesystem, and grab its full path for later use.
if ($file = file_save_upload('header_image',
    array('file_validate_is_image' => array()))) {
$parts = pathinfo($file->filename);
$filename = 'MYTHEMENAME_header_image.'. $parts['extension'];
if (file_copy($file, $filename, FILE_EXISTS_REPLACE)) {
    $settings['header_image_path'] = $file->filepath;
    }
}

// Define the settings-related FormAPI elements.
$form = array();
$form['header_image'] = array(
    '#type' => 'file',
    '#title' => t('Header image'),
    '#maxlength' => 40,
);
$form['header_image_path'] = array(
    '#type' => 'value',
    '#value' => !empty($settings['header_image_path']) ?
    $settings['header_image_path'] : '',
);
if (!empty($settings['header_image_path'])) {
$form['header_image_preview'] = array(
    '#type' => 'markup',
    '#value' => !empty($settings['header_image_path']) ?
        theme('image', $settings['header_image_path']) : '',
    );
}
return $form;
}

```

### template.php

```
/**
* Implementation of hook_preprocess_page().
*/
function MYTHEMENAME_preprocess_page(&$variables) {
  $settings = theme_get_settings('MYTHEMENAME');
  if (!empty($settings['header_image_path'])) {
    $vars['header_image_path'] = $settings['header_image_path'];
  }
  else {
    $variables['header_image_path'] = path_to_theme().'/head.jpg';
  }
}

```

I tried using the Header image module but it is not working; the other option I have is to make a content type with a view and relate them to the nid.

Which option do you recommend?

# Answer
If you want to define your header image in appearance settings form:

**theme-settings.php**

```
**
 * Implements hook_form_system_theme_settings_alter().
 *
 * @param $form
 *   Nested array of form elements that comprise the form.
 * @param $form_state
 *   A keyed array containing the current state of the form.
 */
function YOURTHEME_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  // We are editing the $form in place, so we don't need to return anything.
  $form['YOURTHEME_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('YOUR THEME Theme Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  // display settings
  $form['YOURTHEME_settings']['display'] = array(
    '#type' => 'fieldset',
    '#title' => 'Display options'
  );

  $form['YOURTHEME_settings']['display']['header_type'] = array(
    '#type' => 'select',
    '#title' => t('Type of header'),
    '#default_value' => theme_get_setting('header_type'),
    '#options' => array(
      'default'   => t('Default header'),
      'christmas' => t('Christmas header'),
      'easter'    => t('Easter header'),
    ),
    '#description'   => t("Select type of header"),
  );
}

```

**template.php**

```
/**
 * Override or insert variables into the page templates.
 */
function YOURTHEME_preprocess_page(&$variables) {

  // header image
  switch (theme_get_setting('header_type')) {
    case 'christmas' : $variables['header_image'] = path_to_theme() . '/header-christmas.jpg';
      break;
    case 'easter' : $variables['header_image'] = path_to_theme() . '/header-easter.jpg';
      break;
    default: path_to_theme() . '/header-default.jpg';
  }
}

```

**Alternatively** You can use css to define header image paths, so instead preprocessing page variables, use template\_preprocess\_html to provide appropriate body classes:

```
/**
 * Override or insert variables into the html templates.
 */
function YOURTHEME_preprocess_html(&$variables) {
  // add holiday classes to body
  switch (theme_get_setting('header_type')){
    case 'christmas' : $variables['classes_array'][] = 'header-christmas'; break;
    case 'easter' : $variables['classes_array'][] = 'header-easter'; break;
  }
}

```

**css**

```
/* HOLIDAY HEADERS */
.header-christmas #page_header { }
.header-easter #page_header { }

```
> 0 votes

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


# Question
Title: Show a block if the page content has a specific taxonomy term
I've got a content type (**Brands**) and a taxonomy vocab (**Product Type**) with a few options, so you can "tag" a brand with a specific product type. Using Views I'm filtering my content on my pages depending on the taxonomy term.

I've got a Views block (I'm also using this block as a dropdown in my navigation with the Menu Views module) that lists all the brands tagged with a specific taxonomy term. What I want now is that this block also shows up in my right sidebar on all the pages that display content of 'Brands' and are tagged with a specific term from my taxonomy vocab.

Example (menu structure):

```
* Product Type A
  - Brand 1
  - Brand 2
  - Brand 3
* Product Type B
  - Brand 2
  - Brand 4
  - Brand 5

```

If I'm on the 'Brand 1'-page, the 'Brands' list under **Product Type A** should show up in my right sidebar.

I can't filter using the 'normal' way since its the same content type, and the same taxonony vocab. And by the 'normal' way I mean using a URL pattern for the content type and then use `contenttype/*` on my block config page.

Sidenote: I'm also adding a class to my `<body>` using `hook_preprocess_html()` for all the brand pages. So all the brands tagged with **Product Type A** have a class of `product-type-a` on their `<body>` field. Is there a way so show/hide blocks depending on a class through code?

Thanks.

# Answer
You need to add two contextual filters to your view block:

**Important:** Use `this block (override)` for all these settings.

```
Content: Nid

```

Provide default value: Content ID from URL

More:check: exclude.

*This contextual filter will exclude `Brand X` from the list if you're visiting `Brand X` page.*

```
Content: Has taxonomy term ID

```

Provide default value: Taxonomy term ID from URL

check: Load default filter from node page, that's good for related taxonomy blocks.

When the filter value IS available or a default is provided:

Override title: Type here your `block title` using `%1` for the first argument, `%2` for the second, etc.

*This contextual filter will list all your brands from current visited Product type*
> 0 votes

---
Tags: views, taxonomy-terms, routes, blocks
---


# Question
Title: How to get the custom class added to a view
Views let people to add custom css class to a display. I'm looking to get this information and add to the body tag.

I try with this two functions and the dpm() function from devel:

```
views_get_view('name');
views_get_page_view();

```

But I'm not able to find the custom class that I add to the view.

Do you have any idea how to get this information?

# Answer
> 0 votes
If you only need to get this information, you can use template\_preprocess\_views\_view

```
/**
 * Preprocess the primary theme implementation for a view.
 */
function YOURTHEME_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'your_view_name' :
      // print out the array with all options to see what you're dealing with
      drupal_set_message('<pre>' . print_r($view->display['display_name']->display_options, true) . '</pre>');
      break;
  }
}

```

But if you will need to override this custom class, you'll need to use hook\_views\_pre\_render()

```
function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view' :

      // override the view settings
      // for example: $view->field['fieldname']->options['label'] = 'Some label';

      break;
  }
}

```

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


# Question
Title: Whats the difference between a 'page', a 'panel', and a 'handler'?
I am porting a site over and looking through the code, and in a module there are folders for pages, handlers, and plugins/layouts (containing panels layouts) . The pages and handler folders contain .inc files. They are exports of pages and panels etc. However, what is the definitive difference between a handler, panel, and page? Thanks

# Answer
If you navigate to admin/structure/panels. It gives a short description.

**Panel page**

Panel pages can be used as landing pages. They have a URL path, accept arguments and can have menu entries.

**Custom content** Custom content panes are basic HTML you enter that can be reused in all of your panels.
> 0 votes

---
Tags: panels, 7
---


# Question
Title: Customize Login Widget (set Default values in login input fileds)
I added the login widget block to a page

I want to set the default value text "username" and "password" to the input fields.

It currently looks like **1**. I want it to look like **2**

# Answer
There are a couple modules for this (quotes included are from their project pages):

* In Field Labels:

> ... creates integration with the In-Field Labels jQuery Plugin.
* Compact Forms:

> ... presents text fields for selected forms in a more compact fashion using jQuery.
>
> The form item/element fields are overlaid with their respective labels. When the user focuses a field the label fades away nicely, and if the field is left empty the label fades back in again.
>
> By default, only the user login block is switched to compact style, but the behavior can be added to any form by adding the corresponding CSS ids to the Compact Forms configuration.
>
> + Degrades back to the original form when JavaScript is switched off.
>     + Fields like textareas and checkboxes are currently not affected.
>     + Inspired by A List Apart.
> 1 votes

---
Tags: users
---


# Question
Title: How do I create a Zen's sub-theme using Drush?
I am trying to install Zen theme and create a new sub-theme from STARTERKIT. I am using the following Drush commands.

```
drush dl zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

```

The first two commands work; the third one throws an error:

> The drush command 'Name machine\_name' could not be found

Does anyone know how to do this?

EDIT

My mistake must be that I'm running Drush from my local machine. I downloaded Drush for Windows from the Drush site. I should be running it on my server where my Drupal site is right?

# Answer
> 8 votes
Reading How to build your own sub-theme (7.x-5.x) using Drush, I get that the commands should be the following ones.

```
drush dl zen
drush en zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

```

In order, the commands:

* Download the Zen theme
* Enable it
* Clear the cache
* Create the sub-theme The reason of the second command is explained in the linked page.

> ### Ensure drush knows about the zen command
>
> After you have downloaded Zen and placed it in your sites/all/themes directory, you need to enable the Zen theme and clear Drupal's (and Drush's) cache so that it will notice the Zen drush command. Type `drush en zen` followed by `drush cc all`.

As for running Drush on the remote server or in the local server, see this answer from one of the Drush maintainers for How to use Drush in remote server?

> It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed. This is possible because the Drush commands `drush rsync` and `drush sql-sync` work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.
>
> In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias. Otherwise, Drush will try to use Drush on the remote system to look up these values. See example.aliases.drushrc.php for more information.
>
> Note that it is really useful to be able to at least run `drush updatedb` on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster. The Resources page on drush.org lists some hosting providers that are Drush-friendly.

Keep in mind that you could create the theme on your local site, and then copy the files over the remote site, or in a git repository that you then use when deploying your server.

# Answer
> 1 votes
This was the solution I chose (although I ticked the answer that directly answered my question):

As Clive commented Drush needs to invoked in the Drupal environment itself. Seems obvious now, but it didn't occur to me initially. Instead of carrying on developing in my server space I decided to start developing my sites on my local machine. I downloaded and installed the Acquia Dev Desktop on my Windows PC. To get the Drush command line you can use the Drush Windows Installer. Now you're ready to go.

Start the Drush command line. Choose the directory where you want to install Zen, for example:

```
C:\ProgramData\Drush> cd c:\users\sites\mysite\sites\all\themes

```

I had to create the 'themes' folder (the Acquia install didn't create it for me). These are the commands I used to install Zen, create a sub-theme and enable the sub-theme (see kiamlaluno's answer for more info):

```
C:\Users\Sites\mysite\sites\all\themes> drush dl zen
C:\Users\Sites\mysite\sites\all\themes> drush cc all
C:\Users\Sites\mysite\sites\all\themes> drush zen "mysubtheme" --without-rtl
C:\Users\Sites\mysite\sites\all\themes> drush en mysubtheme

```

There is no command for setting the theme as default as far as I know, but everything else seems to be done. Much quicker than doing it manually!

---
Tags: drush, theming
---


title: Module for putting blocks in menus

text:
# Question
Title: Module for putting blocks in menus
Is there any module that allows me to put a block in a menu?
I wanted to add some related content, or a big image about the link.

# Answer
> 0 votes
You could also try the OM Maximenu module.

> "Maximize your main navigation by adding text, images, videos, slideshow, tabs, menu blocks, user info ..."
>
> That is now possible by using OM Maximenu which can create menus with all other module blocks you want as attachments, modules like views, slideshow, menu, user, nice menus, quicktabs, and custom blocks with tables, lists, images, videos, etc.

# Answer
> 1 votes
Sure; these are called 'megamenus' or 'meganavs' and there is a module directly for this: the Megamenu module.

> Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs. Primarily, mega menus have two advantages:
>
> 1. The information architecture of your navigation is made clearer and is visible all at once
> 2. The amount of clicking, searching, and navigating is reduced
>
> This module allows you to build mega menus by leveraging jQuery and the existing Drupal menu system. Megamenu takes a Drupal menu that is 3 levels deep, and converts it into a categorized 3-level mega menu, which is placed into your site as a block.

The 7.2-x branch allows "embeded blocks within mega menus"

# Answer
> 1 votes
You'll want to try out menu attach block. As advertised, it attaches a block to a menu item:

> Menu Attach Block allows you to attach blocks to standard core Drupal menu items. This is especially useful for creating complex dropdown menus and mega menus.

---
Tags: 6, blocks
---


# Question
Title: How to convert Drupal Field Collection to Node?
I am using Drupal 7 and have a Field Collection that I would like to convert to a custom content type (Node) with the exact same fields. What is the best way to do this? The field collection has the following field types: Postal address, Geolocation, Term reference, Text, Office hours, List (text), Integer.

Unfortunately I am running into too many issues with some of my fields and the Field Collection module. For example, I cannot create a View and use "Has taxonomy terms (with depth)" on a term reference inside a Field Collection. If I switch to two separate fields for the taxonomy term (e.g. State and City) and try using the Reference field option limit module, the fields do not update inside a Field Collection.

I created a custom content type and have successfully been able to create and access the data as needed using Inline Entity Form. Can I modify the database directly? I noticed the Field Collection items do no exist in the Node table. I can create entries in the Node table but I'm wondering if I'll be missing something.

# Answer
This sounds like a job for the Migrate module: https://drupal.org/project/migrate

I don't know if it can do what you need out of the box, but at least in the issue queue there are discussions about migrating between fields and field collections.

Migrate Field Collections documentation page: https://drupal.org/node/1900640

Editing the database directly is rarely a good idea.
> 1 votes

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


title: Behaviour of display links in views

text:
# Question
Title: Behaviour of display links in views
I have defined a new content type with comments. When I create a new view (page) consisting of the x most recent posts of this content type I see this:

* I choose: Show content | Teasers + display links. I get an overview page consisting of teasers and each teaser has the Add new comment link (as well as the Read More link). This I understand.
* I choose: Show content | Full content + display links. I get an overview page consisting of full content and only nodes with comments have the Add new comment link. This I do not understand. Why is the Add new comment link not visible for each node? And how can I make it visible (in node.tpl.php?)

Any help would be greatly appreciated!

# Answer
> 0 votes
Adding comments in Full content view mode happens, not through a link, but in the comment form that is displayed below the node (assuming it is set to be displayed in the content type's comment settings), but you need to switch on the Display comments checkbox in the Page: Row style options dialog.

You're right, Display links will print the add comment link in Teaser mode. If you have Full content mode and have both Display links and Display comments on, then you get both the link AND the form, which is akward. I don't know why it is that way.

---
Tags: views, comments
---


title: Login page when using a Zen's sub theme

text:
# Question
Title: Login page when using a Zen's sub theme
I've created a website based on a Drupal 7 Zen subtheme and now I would like to create a login page for the administrator. When I navigate to http://mysite.com/?q=user, I return to the main page as specified in the page.tpl.php file. I would like to have a manual login page, so I tried following the following tutorial: https://drupal.org/node/350634. My template.php looks like this:

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

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'camuse') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'camuse_preprocess_user_login'
    ),
  );

  return $items;
}

function camuse_preprocess_user_login(&$vars) {
  $vars['intro_text'] = t('This is my awesome login form');
}

```

And my user-login.tpl.php file like this:

```
<p><?php print render($intro_text); ?></p>
<div class="camuse-user-login-form-wrapper">
<?php print drupal_render_children($form) ?>
</div>

```

However, when I navigate to http://mywebsite.com/?q=user, I still go to the home page. I don't know what I'm doing wrong here, I've checked the names and everything seems fine. Could anyone help me with this?

# Answer
> 0 votes
You have to change the name of your template file to **user--login.tpl.php**, place this file in the **templates** folder of **camuse** theme and **clear all caches**.

---
Tags: users, theming
---


title: Classes get stripped out: why?

text:
# Question
Title: Classes get stripped out: why?
I am pasting the following code into the text editor.

```
<ul class="faqs">
<li class="navbookmark"><a href="#er1">ABC</a></li>
</ul>

```

After the initial save everything looks fine in preview mode. However, if I go back in to edit the page, the styles applied to ul and li tags get stripped out, and the source looks like this.

```
<ul>
    <li><a href="#er1">ABC</a></li>
</ul>

```

How do I prevent this from happening?

# Answer
> 1 votes
I haven't met this problem before. I did Google search and found this link Classes being stripped in CKeditor. Maybe your problems come from CKeditor and you just configure the allowedContent for CKeditor.

---
Tags: wysiwyg, files
---


# Question
Title: the menu is not being displayed when the first parameter is user
My problem is as follows the path user/%user\_uid\_only\_optional/profile is not displayed. If I try a variation of this and instead of having user, I replace user with usr the menu items is displayed. I know there was an issue with the page callback and I understand the issue of why it didnt work. That a boolean variable is not an expectable parameter for the page callback.

* Line 1: line one is taken from the pro development book.
* Line 2: line two shows the title (the title is displayed this line works)
* Line 3: description is correct i checked syntax
* Line 4: the page callback seems fine unless this isn't the correct format. I am quite sure that it follows what is in the
documentation.
* Line 5: the number of arguments are needed is one. Since I have only one %
* Line 6: access arguments seems to be ok i checked the different permission in drupal under users and that is the edit person that i
used.
* Line 7: I looked at the menu type and it discusses at the parents level if you want to use the local version of the menu you type

```
$items['usr/%currentuser/edit'] = array(
    'title' => 'Profile', // The link text
    'description' => 'My Profile',
    'page callback' => 'editprofile', // the function to be called when link is clicked [below]
    'page arguments' => array(1), // arguments for the callback function 'profile_use_page'
    'access arguments' => array('edit own profile'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu', // You'll need to have a menu named my_menu for this to work
                              // If not specified, it will default to 'navigation'
  );

```

```
    function editprofile($user_id) {
      return 'user_id'. $user_id;
    }

```

# Answer
> 1 votes
From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7:

"page callback": The **function** to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

So page callback has to be omitted to fallback on the parents callback or has to be a function.

# Answer
> 0 votes
There is a typo in the code shown by the book: It should be user/%user\_uid\_optional/profile.

Even if you correct that, the code is not working. In fact, when you use that wildcard, you are telling to Drupal that *user* could be followed by a user ID or nothing, and then by *profile*. If it is followed by a user ID, the path is fine (e.g. user/1/profile), but when there isn't a user ID the path would become user//profile.

If you look at the code used by blog\_menu(), you will notice it defines the following menu items.

```
  $items['blog/%user_uid_optional'] = array(
    'title' => 'My blog',
    'page callback' => 'blog_page_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'file' => 'blog.pages.inc',
  );
  $items['blog/%user/feed'] = array(
    'title' => 'Blogs',
    'page callback' => 'blog_feed_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'type' => MENU_CALLBACK,
    'file' => 'blog.pages.inc',
  );

```

In your case, the path should be user/%user/profile, in the same way the Blog module is using blog/%user/feed.

---
Tags: routes
---


# Question
Title: Issues with theme on moving drupal website to new server
I have never used drupal before, and just have been tasked with moving a drupal website to a new server. I've moved the files and database successfully - had a bit of a fight with clean urls which were a pain to switch off, new host did not have them enabled.

The website is mostly working fine, except themes. Anything theme related (images etc) is not loading. If the direct url of a theme item is placed into the browser address bar it is opened successfully. I have a feeling its to do with the first item after the temporary address of the new server, the /~balliolj part, but have no clue where to fix this.

Old website: http://www.ballioljcr.org/ New website: `http://31.193.134.90/~balliolj/`

I'm trying to get everything working as before prior to moving the domain, hence the temp address.

Any input on how to fix this would be greatly appreciated

# Answer
At https://groups.drupal.org/node/104694 having a tilde in the url was successfully solved usign RewriteBase /~user on the .htaccess file.
> 0 votes

# Answer
1. Please use HTTP Fox on Firefox browser to check if they are 404 errors.
2. If you find 404 errors then it is understood that images are missing from the theme's directory.
3. To solve: Just open a working website and save the images to your local machine.
4. Upload the downloaded images to the same directories on your new server.
5. Once this is done, flush the drupal site cache once.
6. Images will show-up.
> 0 votes

---
Tags: installation
---


# Question
Title: How do I alter a boolean value and display a string in views output?
Whats the best way to override a simple 0/1 boolean field in views output so instead of 0/1 it would output "Hello" or "Goodbye"?

EDIT: To improve on my question:

Whats the best way to add further options to the default view boolean handler? For example ...

```
$default_formats = array(
  'yes-no' => array(t('Yes'), t('No')),
  'true-false' => array(t('True'), t('False')),
  'on-off' => array(t('On'), t('Off')),
  'enabled-disabled' => array(t('Enabled'), t('Disabled')),
  'boolean' => array(1, 0),
  'unicode-yes-no' => array('✔', '✖'),
  'drunk-sober' => array(t('Drunk'), t('Sober')),
  'hello-goodbye' => array(t('Hello'), t('Goodbye')),
);

```

# Answer
> 2 votes
Well, that was a lot easier than I thought. Basically took a gander into node.views.inc and got the answer.

```
function MYMODULE_views_data_alter(&$data) {
  $data['MYENTITY']['MYFIELD'] = array(
    'title' => t('MYFIELD'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
      'output formats' => array(
        'drunk-sober' => array(t('Drunk'), t('Sober')),
      ),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      'label' => t('MYFIELD'),
      'type' => 'yes-no',
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
}

```

# Answer
> 1 votes
Another Option that I used was to rewrite the output of the field and apply the answer as a class. Then I was able to style the class with either class name. I wanted to show a different icon depending on true/false, so set the bg accordingly

```
<div class="youclass-[replacement_flag]"></div>

```

---
Tags: views, hooks
---


# Question
Title: How do I go about creating a paid subscription product with Drupal Commerce?
I am trying to set up a paid subscription to an email list using Drupal Commerce with payment via PayPal.

One of the way I came up with is upon completion of an order, a user will be redirected to a subscribe page and her role will be updated to view the form.

I am looking for pointers to functions, existing modules or any advise on how to achieve this.

Thanks,

~ahimsauzi

# Answer
Is the mailing list internal or using an external provider like MailChimp or Constant Contact? If you're giving the user access to an external provider's form that will work but it may also allow them to work around it (for example if they want to share it with their friends).

The most secure way would be to use an API call/period import (for external services) or direct update (for internal mailings) using a conditional action or module that's triggered by completed orders.

**Edit for further details:** Mailchimp does indeed have an API - http://apidocs.mailchimp.com/ \- and a Drupal module at http://drupal.org/project/mailchimp so the current functionality is half-way there. I would go the last step and create a custom module that adds subscribers to Mailchimp when they complete their order. At that point it's still a one-time thing, so for bonus points on recurring payments you could keep track of the subscribers and remove them from Mailchimp using the API if they stop paying.

It would take a little coding but it's a realistic setup. I can't see anything you can do without any coding unless the Mailchimp module allows you to set up a page that can then be limited to the role of users who paid (and then you still have an extra manual step).
> 1 votes

# Answer
After evaluating various options for building a memembership site with Drupal,
I've decided to use the Membership Suite.

The module was well-supported and implementation went successfully and easily, including visual customization.

At the time of my check, Drupal Commerce had various subscription extensions (search the Commerce extensions list for the word subscription and you will find them) but none of them fully supported my use-case of multiple subscription products per site, with multiple gateways.
> 0 votes

---
Tags: commerce, notifications
---


title: contact form in popup block

text:
# Question
Title: contact form in popup block
I want to show the contact form in popup. How should I actually do it? I tried to create a module and call the function in it. But I am confused on how to implement \*hook\_block\_view()\*

Is there any other way to this?

This is my first drupal project. And later do I realize that I am not having template.php in my theme folder.

This is what I have done.
1. I had made a block in my page, named 'popup\_this'.
2. I made a module named 'popup' and made to display in this block.
3. I had activate the module named 'contact' in the site. It is called in the link '?q=contact'.
4. I am trying to call this form in my custom module.

I don't know how to implement the function popup\_block\_view().

Thanking you in advance

# Answer
You don't need to write a custom module. You can use the popups api module. All you will have to do is assign the link a class called as "popups". Refer to the api if you want to do it the custom way as well using the popup api.

Summary of the module

> API for building modal ajax dialogs. Its focus is on putting forms inside of ajax popup dialogs. Current example can present pages as popups (of the lightbox type). This is amazingly useful for things like confirmation pages. And the best part is it can be applied retroactively to a page without needing to modify the generating module, and (of course) it degrades gracefully.
> 0 votes

# Answer
The Ctoosl Modal module, included on the ctools project, is the most popular way to popup modal forms on Drupal, with lots of addon modules. One of those addon modules is the modal\_forms module which directly supports popup contact forms.
> 0 votes

---
Tags: 6, blocks, emails
---


title: popup window in drupal

text:
# Question
Title: popup window in drupal
I want a module to load in pop-up window. Ex. i have a module where the page callback will be a form. when user clicks on a link in my website. only the form has to load in the popup window like the lightbox 2 functionality.

i will generate a form in my custom module and i want the form to be displayed in the front-end of the site in a light box.. without other regions(header,footer,right,left) of the page.

# Answer
got answer from one of my friend. have to use page-\[path\].tpl.php created in theme page and use it with regular lightbox or any other js.
> 1 votes

# Answer
Check out the Popups module, it may be what you are looking for.
> 3 votes

# Answer
There are basicly two alternatives:

1. Using the Ctoosl Modal module. This module, included on the ctools project, is the most popular way to popup modal forms on Drupal, with lots of addon modules (like modal\_forms). Here is a nice tutorial.
2. Using a custom module. You may find the following modules helpful:

* popup\_message \- which seems well supported.
    * popup\_announcement \- this is a new module which seems closer to what you search for, with full html support, but with only a few downloads.
> 1 votes

# Answer
I did something similar using this: http://flowplayer.org/tools/overlay/index.html
> 0 votes

---
Tags: 6, ajax
---


# Question
Title: Adding <li> to options on node edit and node create screen
I have an option field on my content types that allows you to select several items in a taxonomy vocabulary. The list has several child and parent items and it is really hard to read.

Is there a way I can add html around these checklist elements so that I can format them better with CSS?

I have attached a screenshot for more info.

# Answer
There is the Taxonomy Term Reference Tree module that will format terms hierarchically.

> This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

This module produces nested ul lists, which seems optimal for styling hierarchies, if needed.
> 2 votes

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


# Question
Title: How to remove Field Group module label length limit?
How to remove Field Group module label length limit (which is 128 characters). Is there any module to change the default length?

# Answer
> 1 votes
Try this module remove field length limit

> * Removes field label length limit (which is 128 characters).
> * The module supports entity field labels and views field labels.

Or you could also write a custom module

```
function yourmodule_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'your_form_id'){
    $form['your_field_name']['label']['#maxlength'] = 255;
  }
}

```

---
Tags: 7, entities
---


# Question
Title: how to load Ckeditor with IMCE file browser through javascript
I have installed CKeditor and IMCE modules for Drupal7. Now when i click on a button in my page, i want to load the ckeditor with IMCE support (File browser option).

How to achieve this with javascript? So far, i am loading the ckeditor this way, but it is not showing a file browser button for image:

```
CKEDITOR.replace('text_'+id, {
    width: 630,
    height: 300
});

CKEDITOR.config.toolbar = [
    ['Bold','Italic','Underline']
];

CKEDITOR.config.extraPlugins = 'imce';

```

The strange thing is that, the Image dialog has "Browse Server" button for the textarea under the form that is created with Drupal Form API, but when i try to apply ckeditor for a custom textarea through javascript, i don't see the "Browse Server" button for Image dialog.

# Answer
Finally i figured it myself, after referring to some of the Drupal forum posts, like **this one**. I removed the 'Image' button in ckeditor toolbar, and instead used the 'IMCE' button. I realized that i must

1. Assign a profile to the users under: admin/config/media/imce
2. Under admin/config/content/ckeditor/edit/Full \> Editor Appearance, add 'IMCE' button in the 'Used Buttons' area and check the option "Plugin for inserting files from imce without image dialog" under Plugins. (assuming that i am using 'Full' ckeditor profile)
3. Under admin/config/content/ckeditor/edit/Full \> File browser settings \> select 'IMCE' for all File browser type options.
4. Include the 'IMCE' option while applying the ckeditor for the textarea, like:

CKEDITOR.config.toolbar = \[\['Bold','Italic','Underline', '-','JustifyLeft','JustifyCenter','JustifyRight','-','IMCE','Undo','Redo'\]\];

Finally this is what i achieved in the editor:
> 3 votes

---
Tags: 7, javascript, wysiwyg, files
---


# Question
Title: Correct way to create Departments/Categories cck selectors in Drupal 7?
**1. My Scenario:**

I'm building a shopping cart and using Ubercart+Drupal 7 for it.

Manufacturers will be able to log in and create their own products with

* Product attributes {Name, SKU, price etc}
* Department + Category - can be multiple
* a brand

A product can exist in multiple Department/Categories too.

Sample screenshot: http://picpaste.com/pics/menu.1375842751.png (wanted to post here but low reputation, can an admin post it here pls?)

**2. Elaboration of the situation**

I'm having trouble figuring out the most correct, stable and fastest way to set up Department/Categories with the following goals and criteria:

2i. Product - CCK fields for adding Department, Categories to product:

* Select a department, and it's associated category (Dep+Cat)
* There are going to be about 12 Deps, 15 Cats each = 180 categories. I do not want to list this as an entire taxonomy dropdown - confusing and ugly. My thought right now is to have two multi-select boxes side by side - "Department" with 12 items & "Category". To illustrate, here's a simple wireframe: http://picpaste.com/Add\_dept\_cat.png
* As per the wireframe, manufacturers can list the product in multiple related departments and categories.

2ii. Add / Create + Add brand to product \- Add an existing brand to the product \- If brand doesn't exist, add a new brand and add it to the product \- Brands are attached to the manufacturers who created them

2iii. I'm searching and finding modules such as taxonomy\_menu, taxonomy\_hierarchy and content\_taxonomy. However a lot of them look like they are not stable or supported for Drupal 7. Even if they are ok, I'm not sure if I'm heading in the right direction by using these modules.

2iv. Shoppers (Authenticated users) should be able to see the main menu on top which actually lists the departments available. On hovering, a particular department's categories & brands within are shown. They can click a department from the menu or drill down to category or brand. On selecting one of these three, the product listing comes up -- if department, shows department items, allowing filtering by brand/category -- if category selected, e.g "moisturisers", shows all items and allows filtering by brand --- if brand selected, shows all items for that brand in this department / category, allows you to move up and see all items for the brand in this department, and in other departments..

**3. Question**

Having said all that, my question is more to do with the CCK input fields of department, categories & brands and the underlying taxonomy / menu structures and modules. For 2iii, any tips are welcome, but I'm not at that stage yet anyways so I'm not looking at that yet.

I'm having trouble with

* how I should structure my data in taxonomies or other structures (menus?)
* how to create the cck fields for the manufacturer to add multiple department / categories to his product
* how he can add a brand to his product or create and add a new brand to his product

Ideally I want to achieve the above with modules in the most Drupal-correct, stable and fastest way possible, without having to write any code.

Thanks

Edit: one more question. If user adds multiple "Department-category" to a product, how to allow one of it to be the "main"?

# Answer
> 0 votes
Your concern is true. Anyone that tried to build an eshop with multiple categories had the same question in the beggining.

> 1) how I should structure my data in taxonomies or other structures (menus?)

You can create a large taxonomy tree the way I see it on the screenshot. Use taxonomy\_manager for better UI. Also to display the taxonomy trees as mega menus you can search for "mega menu" in the drupalmodules.com you will find many such modules.

> 2) how to create the cck fields for the manufacturer to add multiple department / categories to his product

You can use the Hierarchical\_select module. It is a must for such functionality.

> 3) how he can add a brand to his product or create and add a new brand to his product

Create a new Vocabulary for Brands and add a field with autocomplete. You can use Hierarchical Select also. It has an option (with proper permissions) to add a term if it does not exist.

# Answer
> 0 votes
For megamenus, here's an excellent click-by-click tutorial: http://www.cmsquickstart.com/blog/drupal-theme-design-tutorial-2-mega-menus

---
Tags: taxonomy-terms, routes, entities, ubercart
---


# Question
Title: How to include a juery ui file in drupal 7?
In my code for drupal 6 I had added the following js, **jquery-ui** and css files

```
 jquery_ui_add('ui.draggable');
  drupal_add_css(drupal_get_path('module', 'ort') . '/js/jquery.alerts.css');
  drupal_add_js(drupal_get_path('module', 'ort') . '/js/jquery.alerts.js');
  drupal_add_js(drupal_get_path('module', 'ort') . '/js/ort.js');

```

For drupal 7 I have to write the above code.. I have read **that drupal 7 has jquery ui as part of core** so how should add the

```
jquery_ui_add('ui.draggable'); //drupal 6

```

code given above in drupal 7 ?

# Answer
> 2 votes
It should be `drupal_add_library('system', 'ui.draggable');`

---
Tags: 7, javascript
---


# Question
Title: Twitter module Oauth 'TwitterException' with message 'Unauthorized'
When trying to authenticate a Twitter account using the Twitter and OAuth modules, I get the following error

> Could not obtain a valid token from the Twitter API. Please review the configuration.

I have since found that The following error is recorded in Watchdog

> exception 'TwitterException' with message 'Unauthorized' in /var/www/html/sitex/public/sites/all/modules/twitter/twitter.lib.php:151 Stack trace: #0 /var/www/html/sitex/public/sites/all/modules/twitter/twitter.lib.php(114): Twitter-\>request('https://api.twi...') #1 /var/www/html/sitex/public/sites/all/modules/twitter/twitter.lib.php(51): Twitter-\>auth\_request('https://api.twi...', Array) #2 /var/www/html/sitex/public/sites/all/modules/twitter/twitter.pages.inc(343): Twitter-\>get\_request\_token()
>
> \[Abridged\]

Having checked out the URL which is generated and sent off by `drupal_http_request` I get the following error message

> Failed to validate oauth signature and token

I have checked the following

* Followed https://drupal.org/node/1346824
* Reinstalled both the Twitter and OAuth modules
* Ensured my OAuth Consumer key is correct
* Ensured my OAuth Consumer secret is correct
* Ensured I have Read & Write permissions
* Ensured my server time is within 5 minutes of Twitter's as per this thread
* Ensured my server is running extension=php\_openssl.dll
* Ensured my callback URL is correct - http://mywebsite.com/twitter/oauth

*Note that I am not on localhost, nor is my host behind .htaccess*

Visiting my callback URL results in the following error at `/admin/config/services/twitter`

> The connection to Twitter failed. Please try again.

* I am not on localhost, but have tried the suggested 127.0.0.1 callback URL regardless.
* I do a version compatible/containing "Patch 5" as mentioned here
* I'm using the following versions of the modules

+ Twitter 7.x-6.0-alpha2+1-dev (But have tried 7.x-5.8 too)
    + OAuth 7.x-3.1
    + Core 7.22

I haven't enabled the following- Do I need to?

* OAuth Provider UI
* Twitter actions
* Twitter Post
* Twitter Signin

I'd appreciate it if anyoneis able to provide insight!

Thanks

# Answer
This just started working with no change- I can only assume it was a temporary problem with Twitter at the time.

To some degree a useless answer, but the question gives others a list of things to try in the same situation and allows me to mark this question as resolved.
> 1 votes

---
Tags: 7, social-network
---


# Question
Title: How to test Mollom - want to test mollom_form_moderation?
I have a custom form that I'm protecting with Mollom. Once validated, the form results in an entity being created and some emails being sent.

If the form is valid, but Mollom says it should be moderated, I need the entity to be created with its "Held in moderation" field set, but no emails to be sent (I'll do this once an admin has said it's OK).

I have Mollom working and testing mode enabled. Putting "ham" in works. Putting "spam" in stops it dead. Putting "unsure" with an incorrect captcha stops it dead and putting "unsure" with a correct captcha allows it through.

I'm trying to find a test to make Mollom say "hold this in moderation" and call the moderation callback that I have set in `hook_mollom_form_info()`. None of the test cases above result in this callback being called.

# Answer
> 0 votes
You need to enable testing mode and configure the form protected by Mollom to Retain spam posts manual moderation, e.g. in the below screenshot you see I had it wrong.

Then submit the form with "spam" in the main field and it will call your moderation function.

---
Tags: 7, advertising
---


# Question
Title: How to enable Ckeditor for email templates?
I have installed HTML Mail module, to send HTML emails and it is working fine and sending email in HTML format. Now i wanted to load CKeditor for email templates textarea, as html email will be handled now.

I have googled it, but didn't find any solution yet. Is there any way I can enable the ckeditor for system email templates and webform email templates.

-- Thanks for your time.

# Answer
> 1 votes
I recently had the same issue and was able to accomplish this through a `hook_form_FORM_ID_form_alter();` in a custom module.

```
<?php

function MYMODULE_form_webform_email_edit_form_alter(&$form, &$form_state) {
  // This check will determine whether the form already has a ckeditor textarea on it, if not it will initialize ckeditor requirements.
  if (!function_exists('ckeditor_load_by_field')) {
    module_load_include('inc', 'ckeditor', 'includes/ckeditor.lib');
    $input_formats = ckeditor_profiles_compile();
    drupal_add_js(array('ckeditor' => array('input_formats' => $input_formats, 'plugins' => array())), 'setting');
  }

  // Set some vars.  Modify these as needed.
  $format_key = 'full_html';
  $element = $form['template']['template'];
  $element_id = 'edit-template--2';

  // The format array here is used within the ckeditor_load_by_field() function, without it things won't work.
  $format = array(
    '#options' => array(
      $format_key => $format_key,
    ),
    '#value' => $format_key,
  );

  // Both of the following keys are required for the textarea to become ckeditor-ified
  $element['#wysiwyg'] = TRUE;
  $element['#id'] = $element_id;

  // Run the ckeditor_load_by_field function which does all the magic.  Modify to match the $element var set above.
  $form['template']['template'] = ckeditor_load_by_field($element, $format);
}

```

# Answer
> 1 votes
Or you could just use `'#type' => 'text_format'` and set the `'#format' => 'full_html'` for the textarea.

Just keep in mind that the data stored in the field will be stored as an array with 'value' and 'format'. So when setting up your form you'll want to use something like this:

```
$prev_input = variable_get('my_ckeditor_field',array('value'=>'<b>booyah!</b><br/>Works as designed.', 'format' => 'full_html'));
$form['my_ckeditor_field'] = array(
  '#type' => 'text_format',
  '#title' => 'CKEditor Field',
  '#format' => $prev_input['format'],
  '#default_value' => $prev_input['value'],
);

```

Hope this helps anyone else looking to quickly and easily enable the wysiwyg of their choice on their FAPI textareas.

If you are attempting to change a plain text textarea generated by a module that is not your own, such as the Webform or HTML Mail modules, then use nicholas' method since it's your only option.

---
Tags: 7, emails, wysiwyg
---


# Question
Title: Remove confirmation page in Drupal Installation Profile
I'm doing some maintenance on a an installation profile I wrote for my small team. One of the annoyances that I am trying to remove is the confirmation page after the install is finished ("Congratulations! You have successfully installed Drupal"). Is there any to skip this page if the install is successful?

So far, the core `install_finished` function, seems to be the only thing I can find that actually handles this step. But I'd rather not kill kittens over this : )

# Answer
I've never tried it but the docs for `hook_install_tasks_alter()` suggest it's possible since `install_finished()` it one of those tasks

> Alter the full list of installation tasks.
>
> **Parameters**
>
> $tasks: An array of all available installation tasks, including those provided by Drupal core. You can modify this array to change or replace any part of the Drupal installation process that occurs after the installation profile is selected.

So in theory you should be able to replace the function for that entry with one that performs a redirect instead

```
function MYPROFILE_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_finished']['function'] = 'MYPROFILE_install_finished';
}

function MYPROFILE_install_finished(&$install_state) {
  // install_finished() still needs to run but we can discard the output.
  install_finished($install_state);
  drupal_goto('<front>');
}

```
> 5 votes

---
Tags: installation
---


# Question
Title: theme profile2 fields on registration form
I have two profile types teacher and student

so far I have used profile2 module and the profile 2 registration path module. I have the core fields added

I am trying to add profile2 fields to my user-registration template

So far my template looks like this

```
<?php
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
?>

<?php print drupal_render($form['account']['name']); // prints the username field ?>
<?php print drupal_render($form['account']['mail']); // prints the mail field ?>
<?php print drupal_render($form['account']['pass']); // prints the password fields ?>

<?php print drupal_render($form['actions']['submit']); // print the submit button ?>
password is not being displayed

```

I am not sure how i can add profile2 fields to my registration form.

# Answer
This link should help you in achieving it.
> 1 votes

# Answer
Given Andrew's link, I found the solution to get a profile form array.

First, check 'Show during user account registration' under your profile configuration.

Then call

```
drupal_get_form('user_register_form')

```

That's it !
> 1 votes

---
Tags: users
---


# Question
Title: How to create and display user content submission form and display it in a block?
I want to build a user feedback form to create a content type which can be outputted as a view page. What I discover is that, i can create a new content type in which anonymous user can add contents, but I need that form to be in a block on a sidebar.

# Answer
You can make use of the form block module.

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Since the drupal 7 version is still in development, make sure to test it on a development site before moving it to a live site.
> 1 votes

---
Tags: blocks
---


title: contextual menus on drupal

text:
# Question
Title: contextual menus on drupal
I have some questions about Drupal menus. I am interested to have a Contextual Menu in sense that its links change depending where the user is.

I have a Taxonomy Menu and I would like to show in the menu only the term links to the level where the user was. For instance,

* Product
    + cat1
    + cat2
        - cat2.1
        - cat2.2
    + cat3

If I have the taxonomy shown above, if I click on product the menu should list only cat1, cat2 and cat3 but if I click cat2 menu should list only cat2.1 and cat2.2

How can do this on Drupal?

Thanks in advance!

# Answer
If you mean literally only show that level, you can do this with Menu Block module using the Make the starting level follow the active menu item option.

If you mean that only that level should be expanded, you can do it like this: go to edit your Taxonomy Menu vocabulary. Under Taxonomy menu -\> Structure options, uncheck Auto expand menu items.

But I'm not sure if Taxonomy Menu can be used with Menu Block like this.
> 1 votes

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