# Question
Title: How do I create custom content types in drupal?
I need to create a content type that is similar to a textarea, but I need to do some server side formatting before it can go out to the page.

I want a user to be able to input a chunk of text, then if it's a link of a certain type, leave it be, if it's not a link, create a link of sorts out of it with some server side (PHP) magic.

Can this be done in Drupal? Can someone point me in the right direction?

# Answer
If I understand well your question, I guess that you can use Field validation module http://drupal.org/project/field\_validation for validate fields in Drupal 7

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.
>
> By using the hooks provided by this module, you can also define your own validation rules in your own modules.

this link could be useful to read about write complex rules to your field with Field validation module http://www.lullabot.com/articles/module-monday-field-validation

if you are a developer, RichForm http://drupal.org/project/richform is another module for validate fields:

> This module gives you a framework to easily make client side and server side validation in the same time. It increases the validation features of the Drupal Form API (FAPI). If you want to have a powerful tool for creating custom validation logic to any text field, without writing a tons of codes, this module is for you!

Also, Form API Validation seems a possible alternative http://drupal.org/project/fapi\_validation
> 0 votes

# Answer
Yes this can be done.

For the processing you'll need a custom module. Here's a tutorial to get you started with modules.

As for the specific functions you'll need all revolve around hook\_nodeapi (d6) or node api hooks (d7).
> 0 votes

---
Tags: nodes
---


# Question
Title: Search form escaping characters and spaces?
Drupal 7.

I'm thinking it must be in the htaccess file, as I just went live, and suddenly if I search for something like "two words" it ends up searching for "two%20words" and obviously I get no results.

Same goes for quotes, etc. Any ideas?

# Answer
> 1 votes
That wasn't entirely it - it was escaping with a %25 and passing it to the search form, causing no results. It was an issue with my htaccess, it's fixed.

---
Tags: 7, search, .htaccess
---


title: Admin overlay intermittently fails

text:
# Question
Title: Admin overlay intermittently fails
I wish I could provide a more specific example of this, or some event that seemed to trigger it, but here's the best I can do: I have happily used my admin overlay for most of my CMS work for months now in D7 with the Bartik theme. And the other day, mysteriously it became the case that when I am browsing my site, I will "fall out" of admin overlay mode sometimes.

I just am suddenly on a page as an anonymous viewer would be, with neither the overlay, nor the standard edit, track, etc. content tabs of an admin user. I can still hit the back button, to return to it, and I can still directly enter administrative menus, but an occasional page, and not always the same ones, cause me to fall out of admin mode.

Does this sound like any behavior anyone could identify, or help me identify a process in order to identify?

# Answer
> 0 votes
I think it was a PHP memory limit. I upped that, and don't seem to have this problem anymore.

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


# Question
Title: How to use metatags_quick to add no-cache meta tags in D7?
I'd like to add the following to the meta tags for a single page on my D7 site:

```
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

```

Taken from here

However, when I try to use metatags\_quick to accomplish this, it names all my metatags as

```
<meta name="Cache-Control" content="no-cache, no store, must revalidate">

```

with the "name=" attributes rather than "http-equiv". How can add these tags?

# Answer
> 3 votes
I want to say that, in some cases, you can add by template way your meta tags to your specific page.

you can locate `html.php.tpl` in `modules > system` file. copy and paste it inside your template directory. then add your meta tags using some php code to show these tags only in that specific page:

```
  <?php
  if(isset($_GET['q'])){
      $path = $_GET['q'];
      if(preg_match('/test/', $path)){
      ?>
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="0">
      <?
      }
  };
  ?>

```

(you can add this snippet before, for example, the `<title>` tag line)

remember that if you need your meta in more pages, you can replace the pattern of preg\_match() php function (in this example is `/test/`) for several pages (for example `/(test|another_test_page|another)/` )

**Update**: if you do not see changes, is very important **clear cache** to see changes.

**Update2** drupal\_get\_path\_alias() could be an useful function to get the current alias: Given an internal Drupal path, return the alias.

---
Tags: 7, caching, meta-tags
---


title: Make a Views form collapsible

text:
# Question
Title: Make a Views form collapsible
I have a search form in my header. Instead of using the core search, I used a custom block that takes the search string and passes it to the Advanced Search page, built in Views, where users can further filter their results. That's working.

What I want to do is have the form fields collapsed by default, with some text that says "Filter Results" that when you click it expands to show the fields.

How do I do this?

# Answer
Just use some JavaScript to hide the div, similar to the following code:

```
jQuery(document).ready(function() {
  $('.view-filters').click(function() {
    $(this).next().toggle('slow');
    return false;
  }).next().hide();
});

```
> 1 votes

# Answer
I think that you can add a collapse widget based in Jquery. there are several tutorials on Internet.

I will use this guide http://designgala.com/how-to-expand-collapse-toggle-div-layer-using-jquery/ to a fast adaptation of respective CSS rules and Jquery script to Drupal:

inside your `html.php.tpl` of your template (before `</head>` closing tag) you can add following code:

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<style type="text/css">
.layerToCollapse {
margin: 0;
padding: 0;
width: 500px;
}

.headingtoCollapse {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.contentToCollapse {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }
</style>

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery(".contentToCollapse").hide();
  //toggle the componenet with class msg_body
  jQuery(".headingtoCollapse").click(function()
  {
    jQuery(this).next(".contentToCollapse").slideToggle(500);
  });
});
</script>

```

and inside your `views-exposed-form.tpl.php` of your template directory, you can add the following divs **(with respective closing tags)** before `<div class="views-exposed-form">`

```
<div class="layerToCollapse">
<p class="headingtoCollapse">Colapse </p>
<div class="contentToCollapse">

... template code ...

</div><!--closing contentToCollapse div -->
</div><!--closing layerToCollapse div -->

```

was tested using Drupal 7.7 with template called `Seven`. Also remember that you can use (paste inside your template directory) the `views-exposed-form.tpl.php` located in .. `> modules > views > theme`. and `html.php.tpl` can be located in `modules > system`.
> 1 votes

# Answer
Try use Better Exposed Filters, which supports field collapsing.
> 0 votes

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


# Question
Title: How to add tags to View-created RSS feed?
How to add tags to View-created RSS feed?

I have added some tags to each of my articles, but the RSS feed generated by Views does not show the tags.

# Answer
> 1 votes
You can include them in the fields for the view display. If they are taxonomy terms, you can add them from the views fields list.

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


title: Drupal taxonomy problem

text:
# Question
Title: Drupal taxonomy problem
I had setup my new articles directory site in Drupal 6.2 2-3 months back. You can see the article directory taxonomy in the menu block in the left side bar. There are 26 categories in total like "Financial services, Food & Bevereges" etc. And each category has sub categories.

The problem is that frequently some categories or sub categories get automatically unchecked in the article directory menu bar. So I need to regularly count them and check them on if unchecked.

For example today I found automatically unchecked as shown in the following image which is screen shot at the path: admin/build/menu-customize/menu-articledirectory:

**I'm wondering why this could be happening. Any idea?**

# Answer
If you are using Taxonomy Menu then definitely there is a bug in it. And here is a the Link to define the reason.
> 1 votes

---
Tags: 6, taxonomy-terms
---


# Question
Title: How to force regions to render in Overlay
I've created a Seven-subtheme for use with the Admin Overlay and have added Header and Footer regions, however these do not render, despite showing on the "Demonstrate Regions" page.

I have tried to set `overlay_set_regions_to_render(array(...))` in `custommodule_init()` however this fails to influence anything.

# Answer
> 0 votes
I eventually found the code that does this in `overlay.module` and applied this to a custom module, using the hook:

```
function mymodule_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme') {
    $info['overlay_regions'][] = 'header';
    $info['overlay_regions'][] = 'footer';
  }
}

```

However getting this to take effect required visiting the modules page, I don't believe simply clearing the cache worked.

---
Tags: 7, theming, modal-dialogs
---


title: working with drupal project with team

text:
# Question
Title: working with drupal project with team
Till this date i was working all alone on drupal projects. Now i am into a team of 10-15 members. They are using common DB on a machine and different code base on each machine. So was wondering which is the best way to manage and work on drupal project when in a team ?

# Answer
Any control version tools: GIT, Mercury, SVN and etc for controlling team source.
Also drupal have prepared version of drupal installation for team working for tracking timelines, bugs, etc:
Drupal used as a project management tool
More version controlling tools reviewd here: http://www.smashingmagazine.com/2008/09/18/the-top-7-open-source-version-control-systems/
And there's many ready services (free or usually payment) for working with team in internet, try this search: http://www.google.ru/search?q=project+management, there I see basecamphq.com for example.
More hard thing is DB synchronizing, because it's depend on your tasks, for example, sometime merging portion of content and users are needed, sometime aren't. Some of system variables should be synchronized, some of these not. Some content type or fields are required, some just for test.

1. Hard solution is writing script (manual) in any language that have access to DBs and track changes.
2. Other solution is using Features module with some contributed, like Strongarm and etc. This module create module that have changes, where developers export their changes, so it can be controlled via Version control tools as usual plain file. You will just enable it, and their changes will applied to central site. Also with this (and not only) cool tool used: Drush, for me this is the best solution.
3. Also there's tools of synching depend on DB engine, Best tool for synchronizing MySQL databases for example.
> 7 votes

---
Tags: 7
---


# Question
Title: Calendar: How to limit the range of hours in Days display?
I´m using the calendar module in d7.

In the **Day** display it shows 01.00 to 23.00 in the hour column. How do I set it to be: 08.00 to 18.00?

I´m sure this is setteable in somewhere but I can´t find it...

I upload a picture which shows the hours to change:

# Answer
> 12 votes
Change the `Settings` of the Calendar format in the View and set the time grouping to `custom`. In the box, specify the intervals/start times that you want to show up starting at the hour you want to start at. See illustration below:

---
Tags: 7, datetime
---


# Question
Title: 22762 rows in my session table. What does this mean for the site, and what should I do about it?
Ok so the title is pretty self explanatory. There's thousands of rows in the session table. I see that the Persistent Login module is enabled. I don't know if this affects how the sessions are stored. Also, I note that 100+ users are quoted as being visitors at any one time, which seems very excessive for the user base and niche content of this site.

Please can someone advise the best course of action here? I assume I can truncate this table locally, but what's the long term action plan look like?

# Answer
> 2 votes
The long term action is to limit session lifetime. Look for the following line in your settings.php:

```
ini_set('session.gc_maxlifetime',   200000);

```

This parameter sets session life time, after which session is marked as garbage and will be deleted by garbage collector. Average session life time (not on drupal sites) is much less than 200000 seconds - something between 15 minutes and half an hour (900-1800). So, if you don't need long sessions, you can reduce ini\_set value and thus get less sessions stored in the sessions table

# Answer
> 1 votes
Likely, the thousands of rows are caused by anonymous sessions. Look at the sessions table, and see how many rows have `uid==0` vs `uid!=0`

```
SELECT COUNT(sid)
FROM sessions
WHERE uid = 0

SELECT COUNT(sid)
FROM sessions
WHERE uid != 0

```

Drupal 6 creates sessions for anonymous users during bootstrap.

Pressflow 6 and Drupal 7 only create sessions when you actually save something to `$_SESSION`.

There is a module, No Anonymous Sessions, that does what the its name says, but it can break some features and non-core modules.

That said, I would only worry if you are seeing (and measuring) actual performance impacts.

As long as your cron is running, the table should not grow without bounds. It you look at the table sizes, it is probably much smaller than the cache tables, search index, and watchdog tables.

---
Tags: database, performance, sessions
---


# Question
Title: drupal #default_value not working for #type radios
i am editing a form in drupal **7.1** and want to add a group of radios

```
    $form['yearofstudy']= array(
   '#title'=>'What is your year of study',
   '#type' => 'radios',
   '#options' => array(1=>'first year',2=>'second year',3=>'third year',4=>'fourth year',5=>'fifth year'),
   '#required' => true,
   '#default_value'=>array(1,0,0,0,0),
   );

```

The problem:
I intended the first option to be selected but this is what am getting

Please help.

# Answer
> 7 votes
A radio group can only have one radio selected. Did you try '1' as default value?

# Answer
> 3 votes
The working code to use:

```
$form['yearofstudy']= array(
  '#title'   => t('What is your year of study'),
  '#type'    => 'radios',
  '#options' => array(
     1 => t('first year'),
     2 => t('second year'),
     3 => t('third year'),
     4 => t('fourth year'),
     5 => t('fifth year')
  ),
  '#required'      => TRUE,
  '#default_value' => 1
);

```

p.s. also, according to drupal rules, we must use function t as in code above.

# Answer
> 1 votes
The definitive solution is here:

http://www.molecularsciences.org/drupal/making\_your\_checkboxes\_preselected\_in\_edit\_forms

The gist is to pass into #options an array of (name =\> name, name =\> name... ) and then the #default\_value an array of (tid =\> name, tid =\> name...) for only the selected options and this gives us pre-selected options.

---
Tags: forms
---


title: Message if view returns no results?

text:
# Question
Title: Message if view returns no results?
I have a view which generates pages based on taxonomy terms. I have set up a navigation which links to each term in my website. Is there a simple way way I can return a default message if the view is empty?

# Answer
> 2 votes
I believe you are looking for *Empty text* under Basic Settings. This will allow you to set some text (message) that will be displayed if the view returns no results.

You can choose any of your available input filters, the above is just an example.

---
Tags: views, 6
---


# Question
Title: getting around recursion when dumping a node?
I'm working on a template and I'm using `kpr()` from `devel` to look at the values defined in `$variables`. One of them is the node in question, and what gets displayed is a big infinity sign indicating recursion.

Is there any way to get around this to have a look at what data I actually have available in the node object?

What is it in the node that creates the recursion?

# Answer
You cannot get around this in the sense that `kpr($variables)` will always display this unless you hack the implementation of krumo (the library that `kpr` uses).

Use

```
kpr($variables['node'])

```

to display the node instead.

Also, the node page has a *devel* tab that does exactly this.
> 3 votes

---
Tags: theming, nodes, debugging
---


# Question
Title: Url aliases/global redirect not being used in Custom Blocks
This one's weird. Drupal 7.

I have a complex front page - lots of Views, also lots of custom blocks using code I wrote from scratch - functions that essentially query the database directly and output different lists of content.

For some reason, these custom lists aren't using the generated url aliases. They just link to node/#####. Further, Global Redirect isn't working for them either. What gives?

To see in action: http://www.ainonline.com.

You'll see most of the top stuff has the generated aliases. The ones in the middle towards the bottom, under the individual channels, use the system urls. Any ideas?

# Answer
Found the answer. Sort of surprising since I don't think it's uncommon to run Drupal from a subdirectory (im my case, "drupal") and hide the fact through .htaccess rewrites. Anyhow, doing exactly that breaks Global Redirect.

The fix is unfortunately hacking the module until it's addressed. See here: http://drupal.org/node/976214
> 1 votes

---
Tags: 7, views, path-aliases
---


title: How to tell if an image was updated

text:
# Question
Title: How to tell if an image was updated
I'm using images generated by Drupal (drupal 7) to feed an application. I'm then caching those images in the app. I'm trying to figure out a way to determine if the image has been updated since the last download, is there anyway to access this information about an image, without actually loading the image?

# Answer
You can use ETags - when the app receives an image, there will be an HTTP header that looks like:

```
ETag: "686897696a7c876b7e"

```

Whenever the app wants to check for a new image, perform a GET request with this header:

```
If-None-Match: "686897696a7c876b7e"

```

If the file is unchanged, your web server will respond with HTTP **304 Not Modified** status.
> 2 votes

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


# Question
Title: How do I modify the text on a breadcrumb?
How do I modify the text on a breadcrumb?

Is there a way to hook this generically so that I can change the text of any breadcrumb that is shown, regardless of the page?

# Answer
See How to get rid of the "/blog"-page that displays all user-blogs (or change the breadcrumb-link)? I think that you will find an example on how to change a specific text of your breadcrumb.

For example, in your template.php file you can use `phptemplate_breadcrumb()` to search and replace text:

```
function phptemplate_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    $breadcrumb = preg_replace("/old text/", "new text", $breadcrumb); // This line will search and replace text.
    return '<div class="breadcrumb">'. implode(' >> ', $breadcrumb) . '</div>';
  }
}
?>

```
> 1 votes

# Answer
I have used the Custom Breadcrumbs module on a number of projects. If you have the Pathauto module and consistent/clean URL aliases you can define the rules based on your address in the URL.
> 0 votes

---
Tags: breadcrumbs
---


title: Caching for every user

text:
# Question
Title: Caching for every user
In my website, users will be redirected to a "frontpage" page where they will be able to see the latest news, their special announcements, their own materials, etc. Now I have to use DB to retrieve all those information. I also want to use caching for this purpose so the data on their frontpage refresh every 3 hours let's say instead of each visit.

I am using the following function to achieve this:

```
function mymodule_cache($reset = FALSE) {
  static $my_data;
  global $user;
  if (!isset($my_data) || $reset) {
    if (!$reset && ($cache = cache_get('user_data:' . $user->uid)) && !empty($cache->data)) {
      $my_data = unserialize($cache->data);
    }
    else {
      $my_data = ... (This is where I do all the DB queries, etc.);
      cache_set('user_data:' . $user->uid, serialize($my_data), 'cache', time() + 10800);
    }
  }
  return $my_data;

```

}

now this works great, but my question is how if I have tons of users, let's say 10,000 users, would it be efficient to still using this caching method since we are filling up the table rows with data?

Or if not, what is the best solution?

Thanks Luca

# Answer
> 1 votes
In general, yes, you can do this. There is no limitation on the number of cache entries that can be stored. However, if using the default database cache backend, it can fill up your database and when additionally using the default cache bin, it can slow down other cache lookups. So, I would recommend:

Two additional tipps:

* Monitor the number reads/writes of that cache to see if the cache actually helps. If, say, 50% of the cache entries are only written and never read, you might want to consider to avoid caching this information.
* Especially when using a cache backend like Memcache (which has a smaller overhead for cache calls), it might be helpful to split the data up into several separate cache entries. There a number of benefits for this:

1. You can cache certain information longer than others (maybe there only is a new announcement every few days but multiple new comments/whatever per hour
    2. Some of the data might not even be user specific but only specific for the roles a user has or even global. So for example, all anouncements could be read from a single cache entry.
    3. You can use cache\_clear\_all() to clear specific caches on defined events. For example, clear all news caches if a new news is published. By doing this, all users will be able to see the news immediatly. If this is working well, you can increase the cache expiration time.

---
Tags: caching
---


title: Best way to assign a user to a node

text:
# Question
Title: Best way to assign a user to a node
I would like to associate users with a node (and make it possible for users to do this themselves) and have the result easily retrievable programmatically in a nice array( preferably with $node) and also have this in Views..

I found the following options so far

Flag has the advantage of having actions that show on node view as well, which is quite convenient.

# Answer
> 1 votes
It depends on your requirements.

What would *not* recommend is something custom like comma separated values in a textfield. Because that's probably the only option where you don't have built-in views/rules/.. support.

Most of the listed solutions require edit access to the node. If you don't want that, you'd need to write custom code which allows users to add themself.

The user and entity reference modules store their information directly in the field information of the node, which might not scale well if you expect dozens or even hundreds of linked users on a single node (because the edit form will get bigger with each referenced user). The new relation project doesn't have this limiation, because every connection is a separate relation entity, which points to both the node and the user. A possible downside of that might be the additional overhead you have, compared to a simple user reference field.

Flag then is quite different to the others. Users can add themself to a node with it easily, but there is no UI provided to add other users or manage users which flagged a specific node (AFAIK), although you might be able to build something using Views, VBO and so on.

# Answer
> 0 votes
If you're looking for "best"/most "supported" module, have a look for each one of them what are their development and maintenance statuses, when was the last commit, how many users use each of them (Usage statistics), how many issues (especially bug reports) are still opened, how (fast) maintainers react to their issues etc. This should give you quite clear picture.

---
Tags: 7, users
---


# Question
Title: Drupal 7 Site Structure - Moving From Wordpress
I need a little advice or guidance on the structure of Drupal 7. I have used Wordpress for a number of years and I know it very well. Moving to Drupal 7 has got me a bit confused if I'm honest. Take an example of a news page which may have a description and possibly an image at the top then afterwards gives a list of news posts.

In Wordpress (including the Magic Fields plugin to create custom fields) I would create a news page type and news post type. Each would have there own template file. In the news page template file I would output the fields of page then call the Wordpress loop which would give me the list of news posts.

In Drupal 7 I understand that I would create two new content types news page and news post. I would also have two template files - page--news-page.tpl.php and page--news-post.tpl.php. What is the best practise for getting a list of the content type "news post" (list of nodes)?

I've done some reading on this and looked into views. If I create a view to do this, would I set it to a block then call that block within my "page--news-page.tpl.php". Or is there something similar to the Wordpress Loop?

I understand you can create a view as a page but then I would not be able to have fields specific to that page - like the description and image.

# Answer
Views allows to add custom text (with a format, so it can contain html) before and after a view. This could be a possible option.

Alternatively, if you for example want multiple news pages (kind of like news categories although taxonomy might be a better option here), have a look at the EVA project, which seems to be the successor of Views attach. This allows to add a Views to a node (or another entity like a user).

To assign news items to a specific page and only display it there, you could add a node reference field to the news item node type and then pass the node id as an argument to the view (EVA supports that according to the project description). But again, using taxonomy might be a better option for a categorization like this.
> 1 votes

# Answer
Use Devel & Theme developer to get your template suggestions. That is as you create new content types you can create new .tpl.php files to target different aspects of it, the same is true for views if you go into the "theme information" link.
> 0 votes

---
Tags: views, theming, nodes
---


# Question
Title: Default to MyISAM instead of InnoDB in Drupal 7
Can I make Drupal default to MyISAM for new tables instead of InnoDB? Except for hacking the core, that is.

# Answer
> 2 votes
The quickest and dirtiest way to get all Drupal data into MyISAM perform the following:

Make a backup of /var/lib/mysql before doing these steps

step 1. mysqldump all data out of mysql

step 2. remove all folders and files from /var/lib/mysql, but leave the `/var/lib/mysql/mysql` alone because it contains user grants.

step 3. add this line in /etc/my.cnf

```
[mysqld]
skip-innodb

```

step 4. `service mysql restart`

step 5. reload mysqldump file back into data into mysql database

**UPDATE 2011-10-04 04:28 EDT**

step 1. **Set Default Storage Engine to MyISAM**

add this line in /etc/my.cnf

```
[mysqld]
default-storage-engine = MyISAM

```

step 2. `service mysql restart`

Give it a Try !!!

---
Tags: 7, database
---


# Question
Title: Theoretical limits of CCK (Field API) unlimited Multi Value Field - 170 000 values
I plan to have a large multi value field, in my case a node reference field, around 170 000 values.

I guess on node view I can hide the field, and just put in a Views block so the node can be viewed. Editing the node manually will be impossible, as the multi value fields have no paging and Drupal would just load the entire 170 000 values onto the screen. Any tips on solving this?

What I plan on having this is a content type "list" and a content type "item". In the items I will load an dictionary word lists, and in the "list" content type I will group them in different lists. I could use taxonomy as well, but nodes have a better permission control.

# Answer
> 3 votes
No chance, hiding doesn't help, drupal will still load all values even if the field is hidden.

You could add the reference field on the item type and then load them through a view.

Or use the relation project, but it's ui might break too.

# Answer
> 0 votes
If you use a node reference field, you can use the autocomplete widget. That way Drupal won't load all the values into the form. That is the suggested way if you have more than 20-100 values in regard to usability.

In terms of performance, the number of values won't matter since drupal will do a simple matching against available nodes and check if the selected value is valid. Autocomplete will be harder to use with 170k values, but performance should be more or less the same. (The query run don't depend on what's in the database)

---
Tags: entities, performance
---


# Question
Title: How to list comments of certain node in a PHP
How to list comments of certain node in a PHP ( preferably in XML / RSS format )?

# Answer
> 4 votes
You can use the Views module to create custom lists of nodes, comments, users etc. In your case, you will need to:

* create a view of comments
* add a 'Feed' display
* add a 'Contextual filter' for 'Comment: Nid' (this will allow you to specify the node ID in the url)
* set the feed url to something like comments/%/rss, where the % is a placeholder for the Node ID
* save the view

Now you can find an rss feed of comments for node 32 at http://example.com/comments/32/rss

Here is an export of such a view:

```
$view = new view;
$view->name = 'comments_rss';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'comments rss';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'comments rss';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 1;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['subject']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['subject']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['subject']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['subject']['alter']['trim'] = 0;
$handler->display->display_options['fields']['subject']['alter']['html'] = 0;
$handler->display->display_options['fields']['subject']['hide_empty'] = 0;
$handler->display->display_options['fields']['subject']['empty_zero'] = 0;
$handler->display->display_options['fields']['subject']['link_to_comment'] = 1;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Comment: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'comment';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'not found';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['nid']['not'] = 0;
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 0;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'comments/%';

/* Display: Feed */
$handler = $view->new_display('feed', 'Feed', 'feed');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'comment_rss';
$handler->display->display_options['path'] = 'comments/%/rss';
$handler->display->display_options['displays'] = array(
  'default' => 'default',
  'page' => 'page',
);

```

---
Tags: 7, comments
---


title: prevent user with ID 1 edit

text:
# Question
Title: prevent user with ID 1 edit
I would like to prevent admin site (user id 2) to remove or change password user with id 1 although i need to admin add users and edit another users. how to do this?

# Answer
> 2 votes
The User Protect module helped me.

# Answer
> 2 votes
This is a Drupal no, no. Leave root user alone. Just leave it. If you are worry about security, change the username admin, to something else (admin is the most commonly use name hacker try to use). Then just use uid 2 to administrate the site.

---
Tags: 7, users
---


# Question
Title: How to speed up Drupal 7 calls to _theme_process_registry?
Using xhprof php profiler I can see there is much more then 100000 calls to **function\_exists** each time user accesses a Drupal 7.8 page, mostly from **\_theme\_process\_registry**.

What to do to limit the number of or cache these calls ?

# Answer
> 2 votes
I found there is already an issue related to this on drupal.org: Performance: optimize building theme registry by using get\_defined\_functions() instead of function\_exists()

---
Tags: 7, performance, debugging
---


title: Search engine question

text:
# Question
Title: Search engine question
I have a site that has over 18,000 data items in a catalog. I am using Drupal 7 and the latest Views module to display the data. The data items contain an auto make, model, year, cv axle. My search query needs to be able to search this catalog in the following matter: If the EU click in an input box for "make," they can put in the search term (e.g. Ford) and all Ford models pull up. In addition, there is another search field next to the "Make" field for "Model" and another one for "Year." I want Drupal to add all the search terms together to alter the view. Right now, If the user types in one term and searches, it works; however, if the EU types in another term in the "Model" field say, the view that outputs will only include the last term searched. For example, I type in "Ford," and all Fords come up; if I add a term to the "Year" field (e.g. 1999), all 1999 autos come up, not just the Ford models of that year.

How do I create a search engine that spans terms across multiple fields (Make+Model+Year: OR however many search term the EU wishes to include) to filter what is output through Views?

Any help would be greatly appreciated!!

www.sutrack.biz=\> cv axle catalog link

# Answer
> 2 votes
You might considder using the search api module. It allows you to do full text search on the index you setup, it has support for facets integrates with Solr and a lot of other nice things. I can recommend it for some easy and powerful search. It also integrates with Views allowing you to easily customize search results.

# Answer
> 1 votes
In Drupal there are different ways to integrate Apache Solr to your system. I have chosen to use Search API as it has already built integration with views and you can create different types of indexes for our site.It shows how to add filters to your view, restricting what content is displayed.

# Answer
> 0 votes
In your view definition / Contextual filters / More have you enabled 'Allow multiple filter values to work together'?

---
Tags: views, search, database
---


# Question
Title: How do I change the Date module to get 'days back and forward'?
I want to restrict the dates a user can select when using past dates. I want a pop-up message when he tries to select a day +1 month from current date.

How can I do this? Do I need to override the module? If so, how?

# Answer
> 2 votes
You need to implement hook\_form\_alter() to add a new form validation handler. To avoid any conflict with the existing validation handler, you should probably remove the existing one added from the Date module, if there is one.

---
Tags: datetime
---


title: Drupal sub directory url

text:
# Question
Title: Drupal sub directory url
I just started using Drupal today and I couldn't help but notice (or I'm blind) there is no way to add a sub directory style URL besides using an alias. I want to have a category, for example, named "lessons" and then the next part of the URL would be the title of the lesson.

e.g. http://www.example.com/lessons/lesson1

It just seems like there should be a better way to accomplish this rather than using aliases manually. So my question is, is there a way to do this without aliases? I mean automatically so when I add new content (an Article), I can select the appropriate category it should be in. Thanks

# Answer
> 4 votes
http://drupal.org/project/pathauto

this module do what you want ... this module generate url automatically depending on the node title... and you can add prefix or suffix to the automatic url path that generated by this module

if you are using drupal 6 then you can configure this module from

http://yoursite.com/admin/build/path/pathauto

---
Tags: uri
---


# Question
Title: Importing and using overlay from jquery_plugin module
I am trying (and failing) to use the jquery overlay plugin from the jquery\_plugin module in Drupal 7.

I am using `drupal_add_library()` to add the plugin and drupal\_add\_js to add the code to generate the overlays.

The overlay trigger elements are area elements within a map.

Whenever I try and trigger the overlays, I get nothing - no errors or stacktraces or alerts, or messages in Firebug.

Here is the code - added directly into the page content.

```
drupal_add_library('jquery_plugin', 'overlay');
drupal_add_js('function($) {
    $(document).ready( function() {
        $(".overlayarea").overlay();
    });
}(jQuery); ','inline');

```

The map looks as the following:

```
<map name="globalmap">
    <area id="toronto" class="overlayarea" alt="Toronto" coords="94,195,6" shape="circle" rel="#tor_overlay" nohref />
    <area id="oxford" class="overlayarea" alt="Oxford" coords="576,147,6" shape="circle" rel="#oxf_overlay" nohref />
</map>

```

# Answer
> 0 votes
I fixed this by using the Colorbox module and the Imagemap plugin for TinyMCE. Adding `class="colorbox'` to the map area allowed me to use an overlay for that area.

# Answer
> 1 votes
Actually this module seems to be abandoned. Using drupal\_add\_library() works only if the module used `hook_library()`. I wanted to check it in the repository of jquery\_plugin, but these files aren't available. I don't know why.

If you want to use overlays, you can use directly the jQuery UI that is already included in Drupal 7.

# Answer
> 0 votes
I'm not familiar with using the jQuery plugin module; personally I simply add whatever I need to my theme.info file.

```
    scripts[] = js/jquery-tools1.42/jquery.tools.min.js

```

Then overlays are available sitewide.

---
Tags: 7, javascript, modal-dialogs
---


# Question
Title: Which hooks can alter the display of a node?
I have a custom content type in Drupal 7. It consists of a fixed number of images. I would like to make it so that when its viewed, it comes up as a form. Each image would have a text area underneath, and when a user hits 'submit', the text they entered are displayed below each image.

We're not going to store the text that they enter for the nodes. It's just going live for that form submission.

What hooks can I use to alter the display and functionality of my content type?

# Answer
It looks like the best solution is `hook_node_view()`. Unfortunately it gets called on all node renderings, so I'm putting in a check for my content type. The hook `hook_view()` also exists, but that's only for content types that are completely defined within the module.
> 4 votes

# Answer
I'm not 100% sure this is going to work, but the first thing I would try is to create a custom field formatter for image fields. The formatter should check if form data has been posted. If so, it displays the image with the posted text (using check\_plain(), of course). If not, it displays the image with the form field.
> 0 votes

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


# Question
Title: Can I make Drush use a pattern to name sql-sync dump files?
I'm using Drush to sync up my dev, staging and live sites using `rsync` and `sql-sync`. I want `sql-sync` to create a dump file named using a pattern. For example, I want the dump file to be named `site_database_name__date_time`. Looking in `example.drushrc.php` I saw you can use `@DATABASE` and `@DATE` for the `--result-file` option in `sql-dump`. I tried using the same pattern in my site alias definition but it didn't quite work. The dump file is created properly, using the replacement pattern. But when it tries to restore the database to the target site it throws an error saying there's no such file as "@DATABASE\_@DATE.sql". So it's not making the replacement when it does the restore phase of `sql-sync`. Is there a way to get this to work? Or am I taking the wrong approach here?

I realize the `sql-sync` documentation references a "temp" directory for these dump files, implying they aren't meant to be kept around. My thought is to keep them around for a record of what was used for each sync in case something goes wrong.

Below is an example of the site alias I'm using, which specifies the `%dump` path alias used by `sql-sync`.

```
$aliases['dev'] = array(
  'uri' => 'dev.example.com',
  'root' => '/home/websites/dev.example.com',
  'path-aliases' => array(
    '%files' => 'sites/files',
    '%dump' => '/home/username/tmp/drush/@DATABASE_@DATE',
  ),
  'command-specific' => array (
    'sql-sync' => array (
      'simulate' => '1',
      'structure-tables' => array(
        'custom' => array('cache', 'cache_filter', 'cache_menu',
          'cache_page', 'history', 'sessions', 'watchdog'),
      ),
    ),
  ),
);

```

# Answer
> 3 votes
If you use the '%dump-dir' directive, then drush will create a name for your dump file based on the name of the remote host and the name of the database. It is best to not include the date in the database name for remote sql-syncs, because the rsync operation will be faster if it can update only the incremental changes in the database dump, and this of course would not be possible if the filename changed on every operation.

If you want the date to appear in the database dump's filename so that it can also serve as a backup of your drupal site, you must also be careful to back up the files at the Drupal root as well. It is common for Drupal to simply fail (with errors or even a WSOD) if you try to use an sql database with a different version of the code (core or contrib) than was used to create the database.

An easy way to backup your database and files together is with the drush archive-dump command, which also has a convenient archive-restore command to go the other way.

Some combination of the above is probably a better solution than what you are trying to do in your question above. The exact feature you are looking for is not currently supported in drush. We could certainly consider feature requests to add that capability (ideally posted to the drush issue queue with a proposed patch already attached -- see `function drush_sql_dump_file` in commands/sql/sql.drush.inc), but there may be some reluctance to accept it, since the alternatives already described are probably better in most instances.

---
Tags: database, drush
---


# Question
Title: When I load an overlay to edit a node, how can I open a specific vertical tab?
I have a content type with field collections. I want to open an overlay to edit a node but switch to a tab for a specific field collection. Does anyone know how I can do this?

I can open the overlay with #overlay=node/16/edit, but this will just go to the first vertical tab.

# Answer
I took a look at vertical-tabs.js, and as best I can tell you'll have to add some JS to the page to trigger the click event on the correct link. On line 33, the Drupal.verticalTab object gets instantiated, but not assigned to a namespace where you can get to it later to run its focus() method. (This would be a good thing to fix in D8. Hmm.)

So basically, you need a .js file that does something like

```
(function ($) {
  Drupal.behaviors.yourModuleName = {
    attach: function (context, settings) {
      $('a:contains("Revision information")').click();
    }
  };
})(jQuery);

```

where "Revision information" is the actual text of the link that opens your vertical tab.

Note: There is some URL fragment handling in vertical-tabs.js, which I think is supposed to make it so that if you set the URL fragment to the id of a fieldset, that vertical tab will open automatically. It might be worth trying, but I couldn't get it to work even on a non-overlay page.
> 3 votes

---
Tags: nodes, modal-dialogs
---


# Question
Title: How to remove overlay hashtag and trailing menu from the parent overlay
Lets say for example we have activated contextual links & overlay modules and when clicking the edit button for the node, which is all the way bottom of the page, it open on overlay. Now when we look at the address bar the link now looks something like this `http://localhost:8888/node#overlay=node/25/edit%3Fdestination%3Dnode`

The problem with overlay is that it pushes the parent overlay to scroll all the way to the top and when I decide to "cancel" editing I have to scroll all the way to bottom again just to reach the node teaser. So I need to remove the this part from the link above `#overlay=node/25/edit%3Fdestination%3Dnode`

Now I guess it is being caused by jquery bbq feature. And looking into overlay module and her js files I find it very scary and dont know how to avoid this.

I need some help on where to look into this for starters like me.

# Answer
kiamlaluno is correct. What you're asking for can't be done in Drupal 7 with the core overlay. However, HTML5's history features make it possible to implement exactly what you're asking for, and it's something we could do for Drupal 8. I think it could even be done in contrib for Drupal 7, if someone had the inclination.

Meanwhile, ctools is a good option, or the dialog module.
> 0 votes

# Answer
If you remove the "#overlay=node/25/edit%3Fdestination%3Dnode" part from the module, you disable the overlay for that page.

if that is what you want to do, then you need to implement hook\_admin\_paths\_alter() in a module, using code similar to the following one (change "mymodule" with the effective short name of the module):

```
function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*/edit'] = FALSE;
}

```

The result returned from hook\_admin\_paths() is used from the Overlay module to decide when a page is rendered in an overlay. The implementation of that hook done by the Node module is the following one:

```
function node_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;
  }
}

```

The module that implements the hook I reported in the first code snippet should be enabled when the Overlay module is enabled; alternatively, that hook implementation should check if the Overlay module is enabled.

```
function mymodule_admin_paths_alter(&$paths) {
  if (module_exists("overlay")) {
    $paths['node/*/edit'] = FALSE;
  }
}

```

The information returned from `hook_admin_paths()` could be used from another module to render those pages in a different way, such as using an administrative theme; if the purpose is just to avoid the overlay is used to render that page, then the module should change the information returned by `hook_admin_paths()` only when the Overlay module is enabled.
> 3 votes

---
Tags: 7, javascript, modal-dialogs
---


# Question
Title: How can I hide the primary menu block to certain pages using PHP?
I tried this code to hide the primary menu block from certain pages using the following code:

```
// Only show block from types array and nodes array
$match = FALSE;
// Which node types
$types = array('page' => 1);
// Which nodes (by nid)
$nodes = array(1, 13);
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type]) && in_array($nid, $nodes)) {
        $match = TRUE;
  }
}
return $match;

```

Currently, the block is set to visible in the header section of the site; the theme being used is the Bluemarine theme.

Is there anything else that needs to be done?

Print Screen

https://i.stack.imgur.com/m6y4I.jpg

Menu Print Screem

https://i.stack.imgur.com/yUBD2.jpg

# Answer
> 2 votes
You can do it from the block configuration

1. go to admin/build/block
2. search for the block and click "configure"
3. in the "Page specific visibility settings" click on "Show on only the listed pages"
4. write the page that you want this block to be visible on E.g "news" this will make that block visible on http://www.examble.com/news

Is that what you mean?

**UPDATE:**

if you want to control tha appearance programatically do the following

1- Disable the primary links block from "admin/build/block"

2- enable the primary links menu from your theme configuration (now i suppose you see the menu in all the pages and you want to specify the pages that you want this menu to appear in)

3- open page.tpl.php file

4- go to line 24 you will find something like this

```
<?php if (isset($primary_links)) { ?><?php print theme('links', $primary_links, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?>

```

we will edit the following condition **if (isset($primary\_links))**

now you should know something if you have url like this http://yoursite.com/media/pictures

then the function arg(0) will return `media` and arg(1) will return `pictures`

another example

http://yoursite.com/admin

then the function arg(0) will return the first argument in your url which is `admin`

now lets back to the condition `if (isset($primary_links))`

we will edit it ... we wanna say to drupal if the first argument is equal to something then appear the menu else disable the menu

suppose that you want the menu to appeare in the page `user`

then you will edit the `if (isset($primary_links))` to be

`if (isset($primary_links) && (arg(0) == 'user') )`

suppose that you want this menu to appeare in page `user` and page `admin`

`if (isset($primary_links) && (arg(0) == 'user' || arg(0) == 'admin') )`

one more advanced example... if you want the menu to appeare only in `user/1` page and `admin` page

`if (isset($primary_links) && ( (arg(0) == 'user' && arg(1) == '1') || arg(0) == 'admin') )`

hope that will help you

---
Tags: theming, hooks
---


# Question
Title: What urls does a page manager intercept?
The custom page is set up to intercept /sections/%section. Will it intercept an URl such as '/section/section-1/articlename' or only '/section/section-1'

Regarding answer from Berdir: How do I get a custom page to ignore C and respond based upon /A/B regardless of what C value is presented? In my case, C is the name of a specific article of type /A/B and those settings determine the format to be applied to the page through panels. Is there a wildcard?.

# Answer
> 3 votes
It should work the same as hook\_menu() implementations and also react when additional path elements are passed to it.

Basically, when you have a request like A/B/C, the menu system first looks for A/B/C, then A/B and finally A until it finds a match.

---
Tags: 7, entities
---


# Question
Title: Using the jQuery Update module throws the "F is undefined" error
I am using the jQuery validate module (which is mandatory for client side validation module).

If I use that module, my existing functionality is not working well. It is throwing, "F is undefined" while using minified version or, "$.ui is not a function" with the normal version of jQuery.

I understood that version plays the problem here. How do I avoid the error message?

# Answer
I use jQuery Update on every site we make.

One typical problem it has, is that it can cause problems on admin pages. The issues for the module has a patch (http://drupal.org/node/775924#comment-3010750) that fixes the problem. You can also edit this to use any version of jQuery you want, as long as you place the proper versions in the module folder.
> 0 votes

---
Tags: javascript
---


title: Multilanguage database field setup

text:
# Question
Title: Multilanguage database field setup
We're looking to create a drupal commerce site with multiple languages for Drupal translated manually stored different translations in a seperate fields. Different fields would be displayed upon changing the language type.

i.e.

> field\_title (english) -\> field\_title\_fr (french) -\> field\_title\_gr (german)
>
> field\_description (english) -\> field\_title\_fr (french) -\> field\_title\_gr (german)
>
> field\_price (english) -\> field\_price (french) -\> etc...

* Is it possible to click a link to have the website trigger a language change?
* Also, how could you have drupal display a different field?
* Would this method be the drupal way of doing it ? Or is there a module for this already?

# Answer
> 2 votes
This post actually gives insight on how multilanguage fields work using internationalization: http://dominiquedecooman.com/blog/drupal-7-tip-get-field-values-entity-objects-nodes-users-taxonomy

As well as Gabor's Very authoritative one: http://hojtsy.hu/multilingual-drupal7

# Answer
> 1 votes
There is a number of **internationalization** modules and the list available here.

To trigger a language change you could use a **Language Switcher** module.

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


# Question
Title: Best APC settings to reduce page execution time
I have Drupal 7, apc with php-fpm and apache behind varnish and512 MB RAM.

I measure page execution time with devel module.

Database query time is low (62ms) compared to page execution time which is 854 ms. That means there is problem with PHP and APC settings.

My current settings are just

```
apc.shm_size = 64
apc.stat=1

```

How I can improve?

What are the best settings for Drupal given the above configuration?

Thanks

# Answer
> 12 votes
We run in a SVN push environment so we only clear the apc file cache with a script.

APC settings:

```
apc.ttl=604800
apc.user_ttl=3600
apc.shm_size=192M
apc.include_once_override=1
auto_globals_jit=Off
apc.num_files_hint = 2048

apc.stat_ctime = 0
apc.file_update_protection = 2
apc.stat = 0

```

PHP Script:

```
<?php
$return = apc_clear_cache('opcode');
echo var_export($return);

```

604800 = 1 week.

After this, getting xdebug/xhprof up and running and doing a cache grind of the site should let you know what's slowing down the site. In short analyzing the cache grind output is the best way to speed up Drupal. Below I'm listing what patches and modules we use to speed it up; in your case it will be different most likely.

**Drupal 6 Specific Answer Below**

Once you get past this point and realize the APC isn't going to give you what your looking for, switch to pressflow and give these patches a whirl:

Also try some of these modules as they improved our sites speed in a big way:

# Answer
> 3 votes
This is one of those "how long is a piece of string questions".

What is good for a high-volume site may not be the same for a low-volume site with a lot of modules, and may not be the same for a medium-volume site with only a few modules enabled. Other sites running on the server may also be eating into the memory that APC has available.

My starting point is

```
apc.enabled=1
apc.shm_segments=1
apc.shm_size=64
apc.ttl=7200
apc.user_ttl=7200
apc.num_files_hint=1024
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.enable_cli=1
apc.rfc1867=1

```

I then adjust the settings for the server, but again, there is no one size fits all set of settings.

Find apc.php (probably located at /usr/share/pear/apc.php), and install it in the DOCROOT for your Drupal install. Lock it down to your IP address via Apache config. Edit the username/password inside, and then browse to it. You will then see your APC stats.

Reconfigure the shm\_size parameter to minimize cache misses. Ideally, you want to give it just enough memory to never have a cache miss for a file, plus some additional memory for the APC user cache.

Optimize TTL to prevent cache churning. If you aren't editing files, you can bump up this number.

enable\_cli is handy when you use drush a lot, so that drush uses the cached files from APC.

rfc1867 is handy for file uploads.

I also noticed the php-fpm in the title. This complicates matters, and is really beyond the scope of Drupal Answers. You may get better responses at Server Fault, as a lot of the system configuration settings don't pertain to Drupal directly.

# Answer
> 2 votes
APC just improves loading and parsing of PHP files. A large part is also the execution time itself. There are many factors that can increase the execution time, including bugs (especially cache related bugs), internal overhead (e.g. drupal\_alter(), module\_implements()) and so on.

As you asked and was already suggested by mikeytown2, I'd use xhprof (I prefer it over xdebug these days as it provides direct, quick access to the result and requires no additional tools) to find out where your bottlenecks are.

I've recently written two blog posts about using xhprof within Drupal and typical bottlenecks, which you might find interesting.

---
Tags: 7, performance, caching
---


title: Drupal Taxonomy in D6 vs D7

text:
# Question
Title: Drupal Taxonomy in D6 vs D7
I'm building two very big sites using Drupal. Both will have plenty of vocabularies with up to 6-7 levels deep like this:

State-\>District-\>City-\>Area-\>office name-\>department

The taxonomy will have multiple parents from across vocabularies.

I'm working on D6 sites and managing taxonomy hierarchy isn't easy and is bit cumbersome with D6.

**I want to know if it'd be easier with D7 especially when it comes to managing terms with multiple parents.** Any idea?

# Answer
The UI for dealing with taxonomy term relationships hasn't changed much in Drupal 7 I think.

However, you might want to look into some contributed projects, for example Taxonomy manager, which exist for both D6 and D7. I don't know if it provides a solution for this, however.
> 1 votes

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


# Question
Title: Drupal: User personalization of Taxonomy terms
I have a requirement within Drupal to allow registered users to personalise the taxonomy terms that they see and use (leaving the defaults as they are) but haven't found any other information online on the best way to approach this - or if a module exists that does this. Specifically, the requirements are:

* Drupal 6 or 7 (7 preferred)
* Taxonomy items will be flat lists - not nested trees
* The initial items will be the default set
* Registered users can each change their default terms to suit their purposes - but the default set is untouched. Other users could have their own set. This would need to work similarly to internationalization (i18n).
* Duplicate customizations are allowable.
* Using (searching or displaying) duplicate customised terms will concatenate the result set of all the translated terms.

To try to give a simple example. Purely for illustration purposes, lets say the vocabulary is **Soldiers**.

The terms in the default set is:

```
Guard
Footman
Swordsman
Archer
Sergeant
Captain

```

and an orc user wants to reference the same terms with these customisations:

```
Peon     (Guard)
Grunt    (Footman)
Grunt    (Swordsman)
         (Archer)
         (Sergeant)
Chief    (Captain)

```

So when using the system the orc user has the following soldier list:

```
Peon
Grunt
Archer
Sergeant
Chief

```

Where 'Grunt' references both the Footman and Swordsman terms from the original. Archer and Sergeant use the defaults.

Hope this makes sense.

# Answer
> 1 votes
This sounds like a rather tricky to do.

i18n\_taxonomy.module needs to do a lot of hacking and overriding of the taxonomy.module behaviors to always display translated terms. I don't think something like this already exists as a ready to use module.

One option might be to do this using fake translations and building a custom UI which would allow users to create a new personal language and "translate" the terms. However, it won't be able to deal with the merging part. It's also rather hackish...

Another option might be to ditch taxonomy.module completely using either a simple list field (which supports using a callback function for the possible values, but only through the API, see list\_field\_info()) and then build a UI which allows users to override the default values (and store them somewhere) or maybe even provide custom field widgets and formatters. Depending on your exact requirements, it might be easier to re-implement the features from taxonomy.module you need rather than trying to bend it to your will.

# Answer
> 1 votes
Assuming your vocabulary only contains those 6 terms you could create a node with 6 custom fields (guard, footman, ..) and then have the user enter their own terms for it. Possibly prefill the forms with those terms.

---
Tags: taxonomy-terms
---


# Question
Title: Changing text "Create new account" in /user tab
Does anybody know how to change the tab text "Create new account" in /user - I am using Drupal 7.

Many thanks

# Answer
By writing a custom module that implements hook\_menu\_alter and alter the title of the menu. Something like below.

```
mymodule_menu_alter(&$items) {
  $items['user/register']['title'] = 'New Text';
}

```

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_menu\_alter/7
> 6 votes

---
Tags: 7, users
---


title: Theming CCK field

text:
# Question
Title: Theming CCK field
I want to alter CCK field in theme layer so I use Theme Developer to find candidate function for this:

template.php:

```
function omega_starterkit_email_formatter_contact($element) {
    firep($element, 'element');
    return $element;
}

```

firep gives me this output:

```
Array
(
    [#formatter] => contact
    [#node] => stdClass Object
        (
            [nid] => 15
            [type] => opiekun
            [language] =>
            [uid] => 0
            [status] => 1
            [created] => 1306400895
            [changed] => 1307955137
            [comment] => 0
            [promote] => 0
            [moderate] => 0
            [sticky] => 0
            [tnid] => 0
            [translate] => 0
            [vid] => 15
            [revision_uid] => 1
            [title] => Magna Volutpat
            [body] =>
            [teaser] =>
            [log] =>
            [revision_timestamp] => 1307955137
            [format] => 0
            [name] =>
            [picture] =>
            [data] =>
            [path] => opiekun/magna-volutpat
            [field_phone] => Array
                (
                    [0] => Array
                        (
                            [value] => vKaqmxdNJZAALXErcWBi2qkKcZZneTVXNjmye6LBoe6zccGDFj
                            [safe] => vKaqmxdNJZAALXErcWBi2qkKcZZneTVXNjmye6LBoe6zccGDFj
                        )

                )

            [field_email] => Array
                (
                    [0] => Array
                        (
                            [email] => email
                            [safe] => email
                        )

                )

            [taxonomy] => Array
                (
                )

            [referencing_node] => stdClass Object
                (
                    [nid] => 385
                    [type] => page
                    [language] => pl
                    [uid] => 0
                    [status] => 1
                    [created] => 1307101436
                    [changed] => 1307362258
                    [comment] => 0
                    [promote] => 0
                    [moderate] => 0
                    [sticky] => 0
                    [tnid] => 0
                    [translate] => 0
                    [vid] => 385
                    [revision_uid] => 1
                    [title] => Maszyny
                    [body] =>
                    [teaser] =>
                    [log] =>
                    [revision_timestamp] => 1307362258
                    [format] => 1
                    [name] =>
                    [picture] =>
                    [data] =>
                    [path] => maszyny
                    [field_opiekun] => Array
                        (
                            [0] => Array
                                (
                                    [nid] => 15
                                    [safe] => Array
                                        (
                                            [nid] => 15
                                            [title] => Magna Volutpat
                                            [status] => 1
                                        )

                                )

                        )

                    [field_photos] => Array
                        (
                            [0] =>
                        )

                    [taxonomy] => Array
                        (
                        )

                    [files] => Array
                        (
                        )

                    [build_mode] => 0
                    [readmore] =>
                    [content] => Array
                        (
                            [field_opiekun] => Array
                                (
                                    [#type_name] => page
                                    [#context] => full
                                    [#field_name] => field_opiekun
                                    [#post_render] => Array
                                        (
                                            [0] => content_field_wrapper_post_render
                                        )

                                    [#weight] => -4
                                    [field] => Array
                                        (
                                            [#description] =>
                                            [items] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [#formatter] => full
                                                            [#node] => stdClass Object
 *RECURSION*

```

Before this function I display link to e-mail contact form page.

All I want to do with this link is change label from 'Email Contact Form' to something different.

# Answer
> 4 votes
There are generally two ways of controlling the output of a field.

1. Create a field formatter in a module which you can then activate for the field of the type it's made for.
2. Overwrite the theming function that the field formatter uses to render the output.

It seems like you are trying to do #2, but what you have posted doesn't look like a theming function. Are you sure you have named it correctly, have you cleared cache? If you name your theme function correctly and clear the theme cache, it will always take precedence, if done in your site's theme.

# Answer
> 0 votes
Content Template or Custom Formatters

---
Tags: theming, entities
---


# Question
Title: How can I speed up the module registry approval proces on Drupal.org?
The module is done, the code and documentation meets the prescribed standards for Drupal projects, the sandbox project has been created and submitted for review. What more can be done to help speed the review process for a contributors first module?

I don't actually have a module in this position, but recently met a developer who was trying to get a module approved that integrated his new CAPTCHA service into Drupal. Hopefully someone has reviewed and approved it, but you can take a look at the application here to see how the approval process can stagnate.

# Answer
> 4 votes
The process can be very slow unfortunately. There probably isn't a complete answer, but I can give a few hints.

Try to find users which test and report that it works (as detailed as possible), developers to review it and report that too. There are many ways to do that, for example for developers:

* Ask in IRC (#drupal-contribute) (Remember to offer something in return, e.g. patch reviews). Do not ask multiple times and only when the channel is quiet.
* Review/test applications of other users and ask for a review of yours in return.
* If your module interacts with other modules, ask their maintainers to review the integration code. Again, you could help with the issue queue of these modules (review, write patches, answer support questions)

This has two advantages. a) It shows that your module works and users are interested in using it. b) It helps to keep it on top of the (very long) list of issues.

Also, try to make it as easy as possible to install and test your module. For example, if your module integrates with a third-party service/website, provide a test account for it or make it possible to register there for free (if it isn't anyway) and provide detailed installation instructions (for example in a README.txt or INSTALL.txt file).

# Answer
> 0 votes
Please don't go into #drupal-contribute and pester for reviews. It never works out well. There's a long line of people waiting, and a shorter line of people reviewing.

Thankfully though, there is a proposal to revamp the project application process. Hopefully that will be resolved soon.

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


title: Site really slow for registered users

text:
# Question
Title: Site really slow for registered users
When I look at the devel query logs of my website I see that views takes up most of the loading time. Anonymous loads of my page are much faster compared to registered loads but how come? Isn't views loaded the same way for every user?

# Answer
Views supports caching the query and the rendering.

If you have page caching enabled then it's obviously much faster and views isn't involved at all.

There is no silver bullet to improve performance, try to install xhprof to find out where your bottlenecks are.

Using a different cache backend like memcached can help a lot, for a start.
> 4 votes

---
Tags: views, 6
---


# Question
Title: How to create a "Link posting" system in Drupal 7
I'm new to drupal. What I want is to **share "links" of different sites - users can publish links**. Links can be a certain type of "content" - I've some knowledge of working with custom content types & "Views". I'm assuming Links should be a custom content type, users can add new links from Add Content \>\> Links

This "Link" content type should have only two fields:

1. Text to display for the link
2. URL

In front page, I want a block that will display most recent links: the first field (text to display for the link) - when clicked, viewer will be navigated to the 2nd field (URL)

Thanks in advance for helping!

# Answer
> 4 votes
Basically, you need a couple of modules to do that. You already mentioned Views to create the list of links.

To set up your content type, you will need the Link module which provides a link field. You can configure it to display two fields, for link title ("My cool site") and link url ("http://www.example.com"). I think that new content types contain a body text field by default, but you can remove that.

I also recommend Automatic Nodetitles in your case. In Drupal, a node is required to have a title, but you probably do not want to expose a title field to the user because the link field already contains a link title. Automatic Nodetitles allows you to hide the title field and populate it with another value, for instance the link title, the link url or even a combination of those two.

I hope that helps - if not, please clarify your question.

---
Tags: 7
---


title: Hit count/ number of page visits in D7

text:
# Question
Title: Hit count/ number of page visits in D7
How to implement a hit counter for all 'Article' type nodes? I want to display number of times (could be unique) a node was visited - perhaps within the teaser and at the bottom of the node.

# Answer
> 5 votes
In Drupal, you already have that module. You just need to activate Statistic module and set the rights permissions to anonymous users. And maybe you might modify your `node.tpl.php` to show count information.

Also, this module provides you blocks that show the most viewed nodes in the day, all the time or right now.

---
Tags: 7
---


# Question
Title: how do i store fields in one table via the install file?
I am new to d7 and I am writing an install script. This install script needs to create a content type (I've done that) and then create lots of fields that are used in this.

The problem I have found is that d7 automatically creates lots of tables for each field. Considering I will have something like 60+ fields per content type, this isn't very practical.

How can I code into my .install file a way of making all these fields be in a single table e.g. |ID|value1|value2|value3| instead of 3 tables for value1,2,3

Thank you.

# Answer
Short answer: You can't.

As consumer of the Field API you don't have any control on the SQL schema when using the default field storage. The Field API however, allow usage of different field storage on a per field basis. It seems that the Per-Bundle Storage module aims to provide the feature you want. But it has no release, only code in its repository. Another solution is to switch field storage for your content type to a separated MongoDB database.
> 1 votes

---
Tags: 7, entities, installation
---


# Question
Title: How to use multiple submit within a CTools Modal
I'm using a CTools modal to add a holiday. The topside of that form in the modal displays the already defined holidays with an "X" that will allow you to delete a holiday. I have created a submit button for each that is put in a table with this code (the rows are rendered in a table afterwards).

```
foreach ($locationVO->Holidays as $holiday) {
    $fid = 'delete' . $holiday['id'];
    $form['holidays'][$fid] =
            array(
                '#name' => 'delete_' . $holiday['id'],
                '#type' => 'image_button',
                '#src' => $crossimg,
                '#attributes' => array('class' => array('delete_holiday')),
                '#return_value' => $holiday['id']
    );
   $field = drupal_render($form['holidays'][$fid]);

   $rows[] = array($holiday['name'], ISOdate2DutchDate($holiday['from']), ISOdate2DutchDate($holiday['to']), $field);
  }

```

Everything is rendered ok, but if I try to delete a holiday, the triggering\_element and the clicked\_button arrays in form\_state still always refer to the main submit that I defined in the CTools form\_info array. I therefor cannot distinguish between the submits for adding and deleting.

What do I need to do to get my triggering\_element to correspond with the selected submit? I also tried specifying a separate '#submit' handler for the delete buttons, but that is never called either.

Other solutions are welcome as well, as long a I can do it without closing/leaving the modal (I already tried with a link to a separate delete handler which worked up until the referral back to the modal).

Thanks!

# Answer
Never figured out how to do this, but I worked around the problem by using CTools functionality. In a nutshell I used ctools\_ajax\_image\_button in the table, specified a specific callback for the url and then alter the table with ajax\_command\_remove, ajax\_command\_restripe and finally returning it with ajax\_render.

This is all based on the CTools AJAX example that deletes rows from a table.
> 0 votes

---
Tags: modal-dialogs, chaos-tool-suite, forms
---


title: How do I add an element to a fieldset?

text:
# Question
Title: How do I add an element to a fieldset?
When creating a webform in version 5.18 each element had an option to include it in a selected fieldset. Worked like a charm. Now, on version 6.22 I cannot find this option anywhere. I can't believe they've done away and my research only yields php code which user form creators are not going to use. Can someone please advise where to find or what to add to bring this feature back? One post I found elsewhere talks about an 'advanced' area but again, cannot find it anywhere. Suggestions please? Thank you.

# Answer
In fact in Drupal 6 there is no need to select the parent from the drop box anymore: You drag your field under your fieldset and push it to its right.

As result, you get this.
> 1 votes

---
Tags: forms, 6, webforms
---


# Question
Title: Contact Form with drop-down subject (bonus: auto-selected based on GET/POST)
I have a number of services on my site and I want them to all direct to the contact form. Now, this is where it gets tricky- I want the subject to be a dropdown selection of all services provided and, if possible \[bonus\], based on the link clicked (GET/POST).

**Alternatively:** I would also be open to a contact-form jquery popup modal box that I could tailor for specific services.

Any help is greatly appreciated and I thank you in advance.

# Answer
> 1 votes
You can try `hook_node_view()` to pre-select default value of webform component on the base of referer.

```
function yourmodule_node_view($node, $view_mode){
    if($node->nid == [nid of webform]){
            global $base_path;
            $referer = $_SERVER["HTTP_REFERER"];
            $start = strpos($referer, $base_path) + strlen($base_path);
            $ref_local_path = substr($referer, $start);
            switch($ref_local_path){
                    case 'service_1_path':
                            $node->content['webform']['#form']['submitted']['<component_name>']['#default_value'] = 'option_1';
                    break;
                    case 'service_2_path':
                            $node->content['webform']['#form']['submitted']['<component_name>']['#default_value'] = 'option_2';
                    break;
            }
    }
...

```

If you are looking to do it via JS/JQuery that is another solution.

---
Tags: 7, forms, javascript, webforms, emails
---


# Question
Title: Drupal on IIS 7: URL Rewrite vs. ISAPI Rewrite modules
I'm preparing to install Drupal 6 on an Win2k8 server. I'm still on the fence about using IIS 7 exclusively as the web server, or installing Apache and avoiding IIS 7 altogether. I work on a campus with a lot of different networks & system which mostly run on Windows servers, so I fear that not utilizing IIS 7 in some form may come back to bite me later on.

Anyway-one of the main issues I've seen from folks who've installed Drupal w/o Apache is in configuring clean URLs & URL rewriting. I'd like to ask if it is any easier setting up URL rewriting with the MS URL Rewrite vs. an ISAPI Rewrite module? Is there a major difference between the two modules other than that the full-feature ISAPI modules seem to cost money?

Thank you.

Jason

# Answer
This should help you out: Clean URLs with IIS

> The best method is Microsoft's URL Rewrite Module for IIS7, available via the Web Platform Installer on Windows Server 2008 and Vista. Download and documentation are also available on Microsoft's IIS.Net site. You can also use third party rewrite modules (see list above).
> 3 votes

---
Tags: iis
---


# Question
Title: How to remove the Day field from the Date drop down?
on this page http://dev.amnesty.io1developer.com/donate-now under the section of the Credit card,I want to remove from the date the Day field. It is a webform.How to achieve this? Thanks

# Answer
if there is no validation on the form you could hide it with CSS. Otherwise you can use a hook\_form\_alter
> 0 votes

---
Tags: webforms
---


# Question
Title: Can I use hooks in a template for views?
I'm still not sure how hooks work.

I want to join a table to one of my views, but I have no idea where I'm supposed to put the hook for that. Do I just stick it in the template for the view? Or where does it go?

# Answer
> 4 votes
The API reference at http://drupalcontrib.org/api/drupal has all of the Views hook in it: http://drupalcontrib.org/api/drupal/contributions--views--docs--docs.php/group/views\_hooks/6

That said, the views documentation is a little sparse. The best thing to do is look through the list of hooks, then search on the various hook names for examples.

I suspect you need to use hook\_views\_query\_alter but I don't think I have ever had to add a JOIN to a view before.

EDIT:

Notice another of your questions: Join a custom table on a View.

In your case, if you want to properly make a custom table Views aware, implementing hook\_views\_data is the correct solution. But you still need to do this in a custom module, and not in your theme files.

---
Tags: 6, hooks
---


title: Attach content to node

text:
# Question
Title: Attach content to node
I was wondering if its possible to setup a facility where I can attach content to existing content? Let me elaborate: I have my *Page* content type, but I want to give the content-editor the ability to add extra information which can be displayed in a separately styled `<div>`. (I do not want the editors playing around with the HTML.) This must be a *zero-or-one* relationship.

I'm thinking something like the nodereference\_url module, except that I want to limit the amount of node references to a maximum of one. Does anyone how this can be achieved?

# Answer
> 2 votes
This is actually pretty easy.

1. Edit your content type (or clone to a new type). Add in a noderefernce CCK field as needed. Configure it for not mandatory, but limited to one value.
2. Edit the fields for the type so that they are all hidden.
3. Add a preprocess\_node for your content type in template.php to read in the node relationship, theme the node, and then add it as a theme variable.
4. Create a node template for your type.
5. Edit the node template, to add in your div in the markup.
6. Print out this theme variable in the node template.

This should get you down the right path.

---
Tags: 6, nodes
---


title: HTML table in a render array?

text:
# Question
Title: HTML table in a render array?
I dislike the notion of using something like this since it may mean I have to commit my table data straight to HTML sooner than I want to:

```
$render_array = array(
    'maintable' => array(
        '#markup' = theme_table($table)
    ),
    ...
);

```

Do I have an option to pass the table data into the render array (as opposed to rendering it immediately to HTML), by chance?

# Answer
> 17 votes
```
$render_array['maintable'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

```

---
Tags: 7, theming
---


# Question
Title: How to find the user avatar filename in Drupal 7
In my custom module for Drupal 7 I've been using the following 2 SQL queries to find the user's avatar picture and the city (a custom text field):

```
function pref_block_view($block_name = '') {
  global $user;
  $viewer_id = $user->uid;

  if ($block_name == 'pref_main') {

    $result = db_query('select field_city_value from {field_data_field_city} where entity_id=:uid', array(':uid' => array($viewer_id)));
    $city   = $result->fetchField();

    $result = db_query('select filename from {file_managed} where uid=:uid', array(':uid' => array($viewer_id)));
    $avatar = $result->fetchField();

```

and at first this worked well (probably because each user hat just 1 picture - namely the avatar).

But then users attached pictures to blogs and books and now this query doesn't really work:

```
 # select * from drupal_file_managed where uid=1;
 fid  | uid |           filename           |                      uri                       |  filemime  | filesize | status | timestamp
------+-----+------------------------------+------------------------------------------------+------------+----------+--------+------------
  631 |   1 | 111.png                      | public://111_0.png                             | image/png  |   289191 |      1 | 1303376737
  843 |   1 | etud18.png                   | public://etud18.png                            | image/png  |   893838 |      1 | 1305905585
  527 |   1 | yaro-3.jpg                   | public://yaro-3.jpg                            | image/jpeg |    89814 |      1 | 1302367745
  529 |   1 | yaro-4.jpg                   | public://yaro-4_0.jpg                          | image/jpeg |   122129 |      1 | 1302367789
  638 |   1 | etud015.jpg                  | public://etud015_0.jpg                         | image/jpeg |   116956 |      1 | 1303459359
  835 |   1 | pref.jpg                     | public://pref_0.jpg                            | image/jpeg |    95079 |      1 | 1305838610

```

So I'm obviously using wrong query. Any help please?

# Answer
> 3 votes
Check the table "users", column "picture". Join that on the fid from the file\_managed table.

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


# Question
Title: ajax_command_invoke addClass changes lost after form validation
I am currently trying to build a form which has a series of select elements, each of which triggers display of a textarea specific to that select element which is initially hidden.

Currently the select element has a callback to a function which is using ajax\_command\_css (to toggle the view of the textbox) and also ajax\_command\_invoke to add a class to the textbox so that it is still shown after validation errors are triggered. Currently after a validation event, the classes added using this method are lost so the textboxes remain hidden.

Select and textareas are created like this:

```
$form['2og_select'] = array(
    '#prefix' => $blurb,
    '#title' => t('2OG'),
    '#type' => 'select',
    '#options' => array(
      t(' '),t('1'),t('2'),t('3'),t('4'),t('5'),
    ),
    '#ajax' => array(
      'callback' => 'show_comments_js',
      'event' => 'change',
      'effect' => 'fade',
      'progress' => array(
        'message' => '',
        'type' => 'throbber',
      ),
    ),
  );
  $form['2og_textarea'] = array(
    '#type' => 'textfield',
    '#maxlength' => 512,
    '#suffix' => ('<div style="clear:both;"></div>'),
    '#attributes' => array(
      'class' => array('comments'),
    ),
  );

```

Callback function looks like this:

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

  $commands = array();

  $triggerName = $form_state['triggering_element']['#name'];
  $triggerValue = $form_state['triggering_element']['#value'];

  $name_bits = explode('_',$triggerName);
  if ($triggerValue != '0') {
    $commands[] = ajax_command_css('#edit-' . $name_bits[0]  . '-textarea', array('display' => 'inline'));
    $commands[] = ajax_command_invoke('#edit-' . $name_bits[0]  . '-textarea', addClass, array('show-comments'));
  }
  else {
    $commands[] = ajax_command_css('#edit-' . $name_bits[0]  . '-textarea', array('display' => 'none'));
    $commands[] = ajax_command_invoke('#edit-' . $name_bits[0]  . '-textarea', removeClass, array('show-comments'));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

I have also noticed that the id of the form has '--2' appended to it after submitting, could this be related?

Would using an ajax validation tied to the submit button have the same effect?

# Answer
> 0 votes
What I did to get round this was to use the highly useful #states property in the Form API - set the textarea display to be dependent on the select box having a value other than 0 selected. Did the trick without too much hassle!

For an example of this go to

form\_example\_states\_form documentation

# Answer
> 1 votes
Yes, the IDs of an element change when it's being reloaded using AJAX. That's supposed to be a feature. :/ You might try using a class to target your textareas instead.

---
Tags: 7, ajax, forms
---


title: Join a custom table on a View

text:
# Question
Title: Join a custom table on a View
I need to join a custom table `custom_table` on a View `my_view`.

I have a module created called `join_table`

The `nid` is the referential id (the nid is what ties the two table to the view).

Then, I need to take the info the column `price` in `custom_table` and be able to display using my Views template.

I'm completely lost.

# Answer
> 5 votes
Example:

```
/**
 * Implements hook_views_api()
 * @file modulename.module
 */
function modulename_views_api() {
  return array('api' => 2);
}

/**
 * Implements hook_views_data()
 * @file modulename.views.inc
 */
function modulename_views_data() {
  $data['custom_table']['table']['join']['node'] = array(
    'left_field' => 'nid',
    'field' => 'nid',
  );

  $data['custom_table']['price'] = array(
    'title'  => 'Title',
    'help'   => 'Help',
    'group'  => t('Node'),
    'field'  => array('handler' => 'views_handler_field'),
    'sort'   => array('handler' => 'views_handler_sort'),
    'filter' => array('handler' => 'views_handler_filter_string'),
  );

  return $data;
}

```

Read more info in oficial manual Describing tables to Views

---
Tags: views, 6
---


# Question
Title: What is incorrect with this HOOK_node_presave method ?? Trying to modify a FAPI textfield
```
/*
 * Implements hook_node_presave()
 */

function custom_kca_node_presave($node) {
    drupal_set_message('DEBUG: PRESAVE Called');
    if ($node->type === 'product') {
        $node->field_product_short['und'][] = 'test';
    }
}

```

I created a custom textfield called *field\_product\_short* on the *product* Content Type.

A krumo check on $node after saving reveals $node-\>field\_product\_short to have the following:

```
field_product_short (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 1 element)
            value (String, 1 characters ) t | (Callback) t();

```

?!? I'm setting it to a string in my HOOK. Why is it setting it to a value only of 't' with a callback t(); method? Shouldn't it just be reading:

```
field_product_short (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 1 element)
            (String, 4 characters ) test

```

What am I doing wrong?

# Answer
Your structure is wrong, you are missing the 'value' part. Something like this should work:

```
$node->field_product_short['und'][0]['value'] = 'test';

```

I'd recommend to explicitly use \[0\] instead of \[\], the first always writes the first field value while the second appends a new one (which is 0 if it is the first). Within it are the actual values of the field, which is, in case of a text field the mentioned 'value'. A term refernence would be tid, a node reference nid and so on.

The reason you are getting 't' is because the field structure is now a string where Drupal expects an array. Example:

```
$string = 'abc';
echo $string['value'];

```

This prints 'a', because only integers are supported when accessing strings like this which means 'value' is casted to a 0 and the first character of the $string is 'a'. Welcome to the strange world of PHP.

And another hint. The callback stuff is there because there also exists a function 't'. krumo doesn't know if something is a callback or not (as this is not possible to know in PHP), it simply checks if a function with the same name exists.
> 4 votes

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


title: Database schema of comments

text:
# Question
Title: Database schema of comments
I would like to clarify the database table relationship between `comment` & `field_data_comment_body`.

Questions are:

1. Is `comment`'s body saved in `field_data_comment_body` table?
2. Is `comment`'s cid = `comment_body`'s entity\_id ?
3. Is there any table other than these 2 contributed to comments?

# Answer
1. Yes.
2. Combined with 'entity\_type' = 'comment', yes. An entity (comment, node, term, user, ..) is always identified by their entity\_type and entity\_id.
3. Not directly, in this case. There is also field\_revision\_comment\_body table, which is in this case not used because comments don't support revisions (but field always needs to create one because nothing stops you from adding that field to a node and create revisions of it). There are also the field\_config and field\_instance\_config tables which contain information about which field is attached to which entity type/bundle.
> 3 votes

---
Tags: 7, comments
---


# Question
Title: Prepare name and address for use with drupal_mail()
I'm having problems with certain characters when using the `drupal_mail()` function.

Here is the apache error.log entry for the issue:

> Ignoring invalid 'To:' recipient address '=?UTF-8?B?IsWgxZLFvcWhxZPFvsW4wqXCtcOAw4HDgsODw4TDhcOGw4fDiMOJw4rDi8OMw40=?= =?UTF-8?B?w47Dj8OQw5HDksOTw5TDlcOWw5jDmcOaw5vDnMOdw5/DoMOhw6LDo8Okw6XDpg==?= =?UTF-8?B?w6fDqMOpw6rDq8Osw63DrsOvw7DDscOyw7PDtMO1w7bDuMO5w7rDu8O8w73DvyI=?= =?UTF-8?B?IDxjaXRyaWNndXlAZ21haWwuY29tPg==?=' Transaction aborted: no recipients specified

For sake of example, what would be the simplest way to successfully send an email (In the RFC2822 format of "`User <user@example.com>`") to:

```
ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÍÎÏÐÑÒÓÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñóôõöøùúûýÿ <example@example.com>

```

Currently drupal\_mail() fails with:

> "Unable to send e-mail. Contact the site administrator if the problem persists."

Preferably, I would like to be able to keep these special characters intact.

Otherwise, could I use a project like Transliteration or Pathauto to convert or prepare the string? If so, which project and function should I use to prepare the "To" name?

Drupal Log Message:

# Answer
> 0 votes
All credit to @deceze

Original Solution

In short:

```
mb_internal_encoding('UTF-8');

$name  = '山本';
$email = 'yamamoto@example.com';
$addr  = mb_encode_mimeheader($name, 'UTF-8', 'Q') . " <$email>";

```

---
Tags: 7, emails
---