title: Rendering a CCK Date field exaclty

text:
# Question
Title: Rendering a CCK Date field exaclty
I am having an interesting problem with some birthdate data in my profile nodes. I am using Drupal 6.

There are two people: Ann has the following UNIX timestamp value stored in the db: 353026800 Her profile page renders it as '1981. March 10'. When I edit the node I see also this value.

Bete has the timestamp in the db: 484696800 His profile page renders it as '1985. May 11' **but** when I open the node for edit then I see 1985. May 12.' in the date edit box.

The profiles are rendered in a custom tpl.php and the according piece is as follows:

```
format_date($p->field_szuldat[0]['value'], 'custom', 'Y. F. d.');

```

When I `dpm` the loaded node then I see that both fields have the same Europe/Budapest timezone. I see that Bete's birthdate is (not counting the days) is 1 hour before Ann's. But I see that Drupal somehow handles it and renders the values in the edit boxes properly. It might be related to DST because Bete was born in DST and Ann wasn't.

My question is: how could I make my template's date rendering also handle it properly?

I have read all the related comments to the topic, but they do not match my case because here an extra hour is being added to one of my dates.

UPDATE:

The field I am talking about is a "Datestamp" with the following configuration: "No timezone correction" is set, the granularity is only year-month-date.

# Answer
> 1 votes
Solution:

```
$birthdate_object = date_make_date(
   $p->field_szuldat[0]['value'],
   $p->field_szuldat[0]['timezone'],
   $p->field_szuldat[0]['date_type'],
   $granularity = array('year', 'month', 'day'));

$birthdate_formatted = date_format_date($birthdate_object, 'custom', 'Y. F j.');

```

This yields incorrect value in the DST period of the year (1 day difference), so very dangerous:

```
$wrong_birthdate = format_date($p->field_szuldat[0]['value'], 'custom', 'Y. F. d.');

```

---
Tags: datetime
---


title: Drupal Migration and 404 Errors

text:
# Question
Title: Drupal Migration and 404 Errors
I've set up a Drupal 7 site locally and have ftp'd the site over to my ISP's server which is a linux box running PHP and MySQL.

I've never successfully logged into the remote site before and I have locked myself out as I got the admin password wrong. When I go http://www.example.com/?q=user and click on request New Password then I get this error:

```
Not Found

The requested URL /user/password was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

```

One thing I've been confused about and that is the .htaccess file. I never had one locally on my Mac and I did not need it (I know it is hidden) - so I downloaded one and deployed it to the web site but then I got 500 errors, it made it worse.

I've since deleted that file and at least I get some content - but not very much - just the front page. I overrode the themes name in settings.php as I have user access errors when using a new template, if I get passed this bit I can probably fix that. I changed it back to one of the default themes and that allowed me to get some content and not the 'white screen of death'

Advice welcome!

# Answer
> 1 votes
**To get site working properly:** It seems like .htaccess issue. You do need the .htaccess file. It should be in the document root folder and secured so that any host account can read it. Out of the box Drupal has this file.

**To recover Drupal User=1 password:** If you are lucky, your ISP may have drush installed globally on this server. SSH to the server and try "drush uli" command. If not, you can try installing drush on your local machine - the pain will be well worth it if you plan to continue working on Drupal. You can use "drush uli" command on your local machine, login with the on-time login link given and change the admin password. They upload the database back to your ISP.

---
Tags: migrations
---


# Question
Title: SQL insert in taxonomy_index doesn't work
I used the following code, but it doesn't work, and I get no errors.

```
$query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
$query->values(array(
  'nid' => $node->nid,
  'tid' => 53,
  'sticky' => 0,
  'created' => time(),
));
$query->execute();

dvm($query);

if (!$query) {
  dvm($query);
}

```

The output of this code is the following.

```
$query = db_insert('taxonomy_index')
  ->fields(array('nid' => 27, 'tid' => 53, 'sticky' => 0, 'created' => time()))
  ->execute();

dvm($query);

if (!$query) {
  dvm($query);
}

```

This code doesn't output any error; `dvm($query)` outputs `'0'`.

```
$row = new stdClass();
$row->nid = 27;
$row->tid = 55;
$row->created = time();
drupal_write_record('taxonomy_index', $row);

```

This gives the same result of the previous code.

```
$arr[] = 55;

db_query('INSERT INTO {taxonomy_index} VALUES  (%d, %d, %d, %d)', 27, 55, 0, time());

```

It doesn't work; It outputs the following error message.

> Recoverable fatal error: Argument 2 passed to db\_query() must be of the type array, integer given, called in D:\OpenServer\domains\boobon\sites\all\modules\backup\_bike\backup\_bike.module on line 214 and defined в функции db\_query() (строка 2342 в файле D:\OpenServer\domains\boobon\includes\database\database.inc).

I have installed the Ubercart module.

# Answer
> 1 votes
I think in D7, you can not use db\_query() for insert operations - db\_query() can be used only for Select and you should use db\_insert() for insert operation.

For your 1st code bloc, perhaps the db\_insert() causes 1st row with blank values - since it expects fields and values for 1st row. The subsequent $query-\>values() adds a second row. This may explain the blank values in dvm().

# Answer
> 0 votes
Only thing I see here is that your db\_query has to give you an error, because it's not well set :

```
db_query(
   'INSERT INTO {taxonomy_index} VALUES (%a, %b, %c, %d)',
   array(
     '%a' => 27,
     '%b' => 55,
     '%c' => 0,
     '%d' => time()
   )
);

```

---
Tags: taxonomy-terms
---


# Question
Title: Does the tmp directory have to be shared between servers?
I am having a problem with multi file uploads and I suspect the issue lies in the fact the tmp directory is not not shared between servers.

Does it have to be shared between servers? I have 2 webheads (server boxes) and both have a local tmp directory (not shared between them).

# Answer
Yes, if you have multiple servers serving the same domain, then you need to ensure that the two Drupal server instances share the same filesystem. Best is to use NFS mount, so it is physically only one folder. You may get by with rsync in a cron depending on how the filesystem is used in your application.
> 1 votes

---
Tags: files
---


# Question
Title: Images not loading until the page is refreshed
The links are identical, the path is correct, the image is there,but i have to refresh the page for the image to show, i am suspecting the "itok" parameter might be causing the problem,. It was working fine at the beginning, at some point during the development i started having the problem.

Any help with be appreciated.

Thanks

# Answer
> -1 votes
Have you tried the Image Allow Insecure Derivatives module?

> Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.
>
> ### Details
>
> Drupal 7.20 comes with a security fix that changes all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)
>
> s an example, links that previously pointed to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png
>
> will now point to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD\_VaCaD
>
> For more information on the security improvement, visit the release notes.
>
> This is a fantastic security improvement, but in certain cases, has some ramifications. This module provides a configuration setting in order to toggle whether or not Drupal bypasses that token check.

---
Tags: ajax, media
---


# Question
Title: "languages" is not found in regional settings
I installed drupal commons 7.3.4,

I want to ADD an additional language. I try to follow this manual:

https://docs.acquia.com/articles/adding-another-language-your-drupal-7-site#language

```
go to Configuration > Regional and language > Languages

```

But there's no "Languages" section under "Regional settings"

I tried to enter the URL manually, but it brings me to "regional settings".

I enabled

* Locale
* content translation
* Entity Translation
* Variable admin
* Internationalization
* ...

i also flipped-flopped in the air, and prayed to budhha.

but there's no "Languages" in Regional settings.

What am I missing?

# Answer
> 0 votes
You're misreading the instructions (they're correct) and as a result, you're looking in the wrong place. It is not in "Regional settings".

Start by clicking on "Configuration" on the admin toolbar. Then scroll down the page until you see a box with the heading "Regional and language". Inside that box, *below* "Regional settings", you should see the link to "Languages"

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


title: References vs. Books

text:
# Question
Title: References vs. Books
If you were about to create a hierarchy of nodes that can have parents and children, which way would you go for? Using "References" module or the "Books" module that is included in the Drupal standard installation? And why please?

# Answer
For a strictly hierarchical organization (i.e. an inverted tree) I would use the core **Books** module. With a book, you get some "extras" to help you with maintenance and navigation. E.g. you get a drag and drop UI to help you re-organize the entire book (or parts of it), you get up/down/sideways navigation links automatically created and inserted, and you get meaningful breadcrumbs. You also get a "Create child node" link at the bottom of any node that is part of the book.

Also note that in Drupal 7, any node content type may be included in the book (i.e. you're not restricted to the "Book page" content type. However, you can't include *non-node* entities such as taxonomy terms, files and users.

I would not use the **References** as it is more restricted than the **Entity reference** module.

And I would *only* use the **Entity reference** if I wanted to create a linked structure that is *not* hierarchical but some sort of directed graph, or I wanted to include non-node entities in this structure.

A typical use case for the **Entity reference** module would be the "Related issue", "References", "Referenced by" (directed graph); and "Parent issue", "Child issue" (hierarchical) links that are maintained in the new issue tracker system at the D7 version of Drupal.org.

To sum up. You get a lot of tools for maintaining the structure for free with the core **Books** module, but you're restricted to having a hierarchical structure made up if nodes.

With **Entity reference**, your structure can be made up from any entity type, and it can be a directed graph, but there is no tools to help you maintain the structure or to navigate it (beyond clicking on the links).
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Create a view to show nodes tagged with certain terms next to each other in comparison table
I have a content type called 'Product Feeds' that contains hundreds of nodes. These product feed nodes have fields attached; product name, product description, product price and also a taxonomy term field for the shop name.

I want a view that shows me all the terms from 'shop name' vocabulary along the top of a table then all the other attributes in rows so I have a comparison of prices, descriptions etc.

Can anyone offer any pointers in how to do this?

# Answer
> 1 votes
The way I would implement this in Views is to create a node (of type 'Products Feeds') for each product the way you suggest. Then I would add an additional field (`field_unique_product_code`) and make that field a taxonomy term (term reference) of a vocabulary named 'products'. That vocabulary would contain unique products codes for *all* the products your system will process. The shops need to use the *same* unique product code (or you need to translate shop-specific SKUs in the incoming products feeds to this unique product before saving the node). Note that while the product codes may be strings (e.g. `sony-kdl-46R473a`, each term gets an unique *numeric* id in the vocabulary (for instance, the term for this particular Sony tv model may have the numeric id '42'. Take a note of this number, because you're going to need it later.

Now, perform the following steps:

* Create and save a new View named 'Comparisons' and make it a view of type 'Products Feeds'. Press 'Save & exit' to save and exit.
* Go back and edit the View:

1. Make the format for the View 'Grid'.
    2. Click on Show: Content, and change the radio button from 'Content' to 'Fields'.
    3. Add the fields you want to display (shop name, price, description), rearrange the sequence and remove the display of labels.

If you look at the auto preview (bottom of page) at this point, you'll see that you have a nice grid display of the shop name, price and description, but for *all* the products, rather than for a single product.

To narrow down the display for a single product, you need to add a contextual filter.

* Expand the Advanced section (to the right in the Views UI), click on 'Add' next to Contextual Filters, and add the `field_unique_product_code` as a contextual filter.

Now, look up the numeric ids for your unique product codes. Let's say your database contains a product with product id 42. Type in '42' in the textfield with label 'Preview with contextual filters', and click 'Update preview'.

Now, the preview should be restricted to a comparison between the shops, restricted to a single product. Click 'Save' (top right) to save the View.

Now, you can produce comparions of specific products just by including their numeric product ids in the URL. For instance:

```
http://example.com/comparison/42

```

will produce the comparison grid for the product with numeric product id 42.

This should give you the *basic* functionality you're looking for. A lot of refinement is possible. For instance, if you want to use products names in the URL for contextual filtering, you need to create URL aliases for the numeric ids (you do this with *Administration » Configuration » Search and metadata » URL aliases*).

For more refinement, you can use templates to get a nicer layout of the table grid, and add a left column with labels.

(But if you need help with these refinements, ask separate questions after you've got the basic grid with the contextual filter working.)

---
Tags: views
---


# Question
Title: Hierarchical Select reset when I click add another item
I have a custom content type that has an unlimited field. This field is from field collection type and it contains a field that is from taxonomy type and with a hierarchical select widget. When I want add a node of that type and choose a value for hierarchical select field and then click add another item the value of the hierarchical select will reset. What is the problem?

# Answer
> 0 votes
Temporarily I fixed it by rearranging the hierarchical select field at top and add another item field(image field) at the bottom of that field.

You can rearrange the field under Mange Fields.

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


# Question
Title: Views : custom table with relationship is not queried
I use a custom table to store data on my nodes, and hook on `_views_data` to display or sort from this table.

Everything's going fine :

```
/**
* Implements hook_views_data()
*/
function MYMODULE_views_data() {

  $data['MYTABLE']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    )
  );
  $data['MYTABLE']['MYFIELD'] = array(
    'field' => array(
      'handler' => 'MYHANDLER',
    )
  );
}

class MYCLASS extends views_handler_field {
  function query() {
    // Add 2 columns I need to the query
    $this->view->query->add_field('MYTABLE', 'COLUMN1', 'ALIAS1');
    $this->view->query->add_field('MYTABLE', 'COLUMN2', 'ALIAS2');
  }

function render($values) {
    // WORKS FINE WITH NO RELATIONSHIP
    $dates = array($values->ALIAS1, $values->ALIAS2);
    ...
    return ..
  }
}

```

**My problem is : I can't get values when my table is called on a node-relationship relationship.**

I tried

```
function query() {
        if(isset($this->relationship) && !empty($this->relationship)) {
            $table = $this->view->relationship[$this->options['relationship']]->table_alias;
            $field = $this->view->relationship[$this->options['relationship']]->real_field;
            $this->view->query->add_field($table . '.' . $field, 'COLUMN1', 'ALIAS1');
            $this->view->query->add_field($table . '.' . $field, 'COLUMN2', 'ALIAS2');
        }
}

```

and

```
function query() {
if (!empty($this->relationship)) {
            $this->table = $this->query->ensure_table($this->table, $this->relationship);
        }

```

but in `render`, my `$values` is always empty when the relationship is set.

# Answer
Instead of adding the fields manually, you should populate the instance variable `additional_fields`. From the views documentation:

> **additional fields:** An array of fields that should be added to the query for some purpose. The array is in the form of: `array('identifier' => array('table' => tablename, 'field' => fieldname);`

Looking through some of the implementations out there indicates that your code should look something like this:

```
class MYCLASS extends views_handler_field {
  function construct() {
    parent::construct();

    $this->additional_fields['ALIAS1'] = array(
      'field' => 'COLUMN1',
      'table' => 'MYTABLE',
    );
    $this->additional_fields['ALIAS2'] = array(
      'field' => 'COLUMN2',
      'table' => 'MYTABLE',
    );
  }

  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  function render($values) {
    $alias1 = $this->get_value($values, 'ALIAS1');
    $alias2 = $this->get_value($values, 'ALIAS2');
    ...
  }
}

```
> 4 votes

---
Tags: 7, views
---


# Question
Title: How to create a view of unread comments on own nodes for the user's profile page?
I'd like to create a view for the user's profile page that displays all unread comments on the nodes he/she created. When I say 'unread', I mean that the page where the comment is situated (namely, the node's page) hasn't been visited by the user yet. In other words: when the user hasn't read a new comment, it will be displayed in the view; once the user has read it, it will disappear in the view.

I've already set up a view that simply displays all comments on the user's nodes, but I can't find an extra 'Filter criteria' or 'Relationship' that filters out the unread ones.

Can you help me?

---

**Edit:** I created a flag called 'Read' ('Reactie gelezen' in Dutch) with the Flag module and a rule 'Comment read' that automatically flags comments with 'Read' when they're viewed. I've also granted every user the permission to flag comments with the 'Read' flag (although they won't see the flag links above their comment of course).

My rule works perfectly and the flagging works manually too. The view however, doesn't work properly. These are my settings:

Both uid's were provided the default value 'User ID from URL'.

What did I do wrong?

# Answer
> 2 votes
The Flag module only keeps rows in the database for content where a flag is set. I.e. when something is **not** flagged, there will be no corresponding row in the database.

The problem is, that views will generate a query which looks something like this (for a user with `uid=12` and a flag with `fid=1`):

```
SELECT cid FROM comment AS c
INNER JOIN node AS n ON c.nid = n.nid
LEFT JOIN flagging AS f ON c.cid = f.entity_id AND f.fid = '1'
WHERE n.uid = '12' AND f.uid = '12'

```

However in order to select all comments for a given user excluding those which are **not** flagged, you need an SQL subquery:

```
SELECT cid FROM comment AS c
INNER JOIN node AS n ON c.nid = n.nid
WHERE n.uid = '12' AND c.cid NOT IN (
    SELECT f.entity_id FROM flagging AS f
    WHERE f.fid = '1' AND f.uid = '12'
)

```

AFAIK Views has no built-in support for subqueries. I therefore recommend you to reverse the logic and implement the following:

* Add a comment-flag `is_new`
* Whenever a new comment is posted, execute a rule which sets this flag on behalf of the content author.
* Whenever a node is viewed by its author, execute a rule which removes all `is_new`-flags on the associated comments (this is essentially the same rule you already have, except that you need to reverse the flagging-logic).
* Configure the view just as you did before but remove the `flagged=false` filter, instead configure the flag-relationship such that only flagged content is included.

---
Tags: 7, views, rules, comments, flags
---


# Question
Title: Let New Users Connect with Twitter OAuth only (not Facebook)
I would like to let new users register with a Twitter OAuth for new' signups' to my project so not really wishing for Facebook implementation as yet. There seems to be a range of subjects & options via Drupal.org etc, but I'm simply looking for a quick and easy 'out of the box' solution to getting this going without having to waste lots of time trying to figure out which route to go. I already have a Twitter account so just need a pointer to best 'free' option geared towards Twitter for signup purposes to my projects. Thanks.

# Answer
You can look into HybridAuth Social Login

> This module integrates HybridAuth library into Drupal and allows your users to login and register using:
>
> Facebook Twitter Google LinkedIn Foursquare Yahoo Windows Live MySpace AOL OpenID Github, LastFM, Vimeo, Disqus, Instagram, Viadeo, Identica, Tumblr, Goodreads, QQ, Sina, Murmur, Pixnet, Plurk, Skyrock, 500px, Vkontakte, Mail.ru, Yandex, Odnoklassniki, Twitch.tv, Steam and more

You can select which all social logins you want to enable. So if you are just looking for twitter you can enable that alone.
> 0 votes

---
Tags: users, social-network, authentication-authorization
---


title: How can I add text in my theme?

text:
# Question
Title: How can I add text in my theme?
Drupal is a complex CMS but all I need is simply a text on my page in the specific region of the page ( that will be rarely changed ) that can be changed by an admin.

Here's my theme mockup.

The text is going to be in the red square area as seen above. That text is going to be rarely changed. I was trying to do this with 'Basic page' content type block but It isn't showing me what I want it creates some text showing up

"No front page content has been created yet. **Add new content**"

and when I create new content It shows up **Read more** and then redirects me to node/1 URL If I click it.

There must be some other simpler way of doing this. I mean all I want is text that is editable by admin in control panel not some fancy blog posts. Also please notice that I am still learning Drupal and any answer would be great!

# Answer
> 0 votes
By Default Drupal front page shows the list of Contents you create, the number of contents you can list is controlled in **Site Configuration**. To answer you particular scenario would be too much of an answer here, I'd recommend you to read some Beginner Documents or watch some Videos in the net. Good place to Start is Drupal documentation

To displaying content in front page go-to `UR-URL/admin/config/system/site-information` and change the default front page to `node/1` (in your case). This will display static front-page when your created the Basic page.

Be aware this is not the best bet, so, I'd suggest you to explore Drupal bit more before actually starting the site building.

---
Tags: theming, nodes
---


# Question
Title: Facets: Show more and Show less functionality
I am interested in a "Show more" and "Show less" functionality in facets like on this page http://ethicshare.org/publications/ethics?sc=publications How can I do that?I am using search api. thanks

# Answer
> 0 votes
Answer:You can select the visible items of the facet on the facet display. E.g. you can select 3 items to be visible.If the facets items are more than 3,by default will appear a Show more/Show less functionality for the facet. Hope this is clear. thanks

---
Tags: search
---


title: Plugin to customize home page

text:
# Question
Title: Plugin to customize home page
i would like to know of there's a plugin to let an authentified user customize his home page by moving and adding predifined widgets like (agenda, events ..), using drag and drop like iGoogle.

i'm still drupal newbie, any advices are welcomed.

# Answer
The homebox module makes that reasonably easy to do, worth a look: https://drupal.org/project/homebox

Details from its project page:

> Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.
>
> Homebox is currently used on Drupal.org for the 'Your Dashboard' feature.
> 2 votes

---
Tags: 7
---


# Question
Title: Panels -> Add content in panels gives AJAX HTTP-error
When I'm trying to add Content to a panel page (just installed Panels), I get this error message:

```
An AJAX HTTP error occurred.
HTTP Result Code: 400
Debugging information follows.
Path: /panels/ajax/editor/select-content/panel_context%3Apage-panel%3Apage_panel_panel_context/middle
StatusText: Bad Request
ResponseText:
Runtime Error
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
Server Error in '/' Application.
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration>

```

Someone who has a clue? What can it be?

# Answer
This worked for me: https://drupal.org/node/1036202

Posted by Kye on February 11, 2013 at 11:45am I had the same problem today. Went through this and similar threads. We were hosting the site in IIS and the problem turned out to be URLScan, and colon in the URL plan. I had to do is exclude the colon rule and everything worked as expected.

C:\Windows\system32\inetsrv\urlscan\UrlScan.ini

; : ; Don't allow alternate stream access
> 2 votes

---
Tags: panels
---


# Question
Title: Changing the logic for an exposed taxonomy select in a view
So, I have a view of a content type, and this content type has three unique taxonomy terms it are: Alpha, Beta, and Both.

Currently, my view lists all nodes of this type, and I've added an exposed filter that lets the user select one and only one of the three terms above, like so:

Both -\> Show only content tagged Both

Alpha -\> Show only content tagged Alpha

Beta -\> Show only content tagged Beta

What I would now like to do is extend the behaviour of the filter so that the following happens:

Both -\> Show only content tagged Both

Alpha -\> Show only content tagged Alpha and Both

Beta -\> Show only content tagged Beta and Both

So as you can probably see, if something is Both, then it is also Alpha and Beta. Obviously the taxonomy terms themselves don't contain this semantic information.

I cannot use "All" to represent Both because then selecting Both -\> Alpha, Beta, Both.

So I'm thinking that somehow I could make Alpha and Beta a child term of Both, and Better Exposed Filters might allow this logic to work? Or will I need to use a hook - if so, which hook and any ideas about how I might approach it?

# Answer
You need to use hook\_views\_query\_alter(). And the logic would be as below.,

1. Both -\> Show only content tagged Both

When the user selects the Both, make no changes in the hook, just return the default result. So by this way the contents tagged under Both will be displayed.
2. Alpha -\> Show only content tagged Alpha and Both

Now use the alter hook, by default the query will have alpha's tid in it. Here you need to add the Both's tid to the query. So now the Alpha and the Both will be displayed.
3. Beta -\> Show only content tagged Beta and Both

Now use the alter hook, by default the query will have Beta's tid in it. Here you need to add the Both's tid to the query. So now the Beta and the Both will be displayed.

In simple term, just use the alter query and add the Both's tid to it. So that we will get the Both's content in all cases.
> 6 votes

# Answer
The Views PHP module could let you write your own logic for when the taxonomy term matches.
> 1 votes

# Answer
This is a great case for using grouped exposed filters! I don't have a D6 site handy to see if they are supported in views 6.x-3.x, but I'm *fairly* certain that they are available in D6.

Heres a screenshot example of how I've configured an exposed views grouped filter similarly to how you are describing.
> 0 votes

---
Tags: 6, views
---


title: Call custom form in a block

text:
# Question
Title: Call custom form in a block
I am trying to call a custom form in a block. The form is written in my custom module. I tried different ways to call the form, but not getting the form.

Here is the syntax, I last tried.

```
$form = drupal_get_form('my_custom_form');
print drupal_render($form);
//my_custom_form is my form_id

```

(or)

```
drupal_render(drupal_get_form('my_custom_form'));

```

Here is the link I found a similar question, but didn't get the correct solution for my question. Form within a block

# Answer
You should return your form using `drupal_get_form` in the content definition of your block. Drupal will do the rest.

For example like this:

```
function YOURMODULE_block_info()
{
    $blocks = array();

    $blocks['custom_block'] = array(
        'info' => t('Custom block example'),
        'title' => t('Custom block example'),
        'region' => 'content',
        'status' => 1,
    );

    return $blocks;
}

function YOURMODULE_block_view($delta = '')
{
    $block = array();

    switch ($delta) {
        case 'custom_block' :
            $block['content'] = YOURMODULE_block_content();
            break;
    }

    return $block;
}

function YOURMODULE_block_content()
{
    return drupal_get_form('my_custom_form');
}

function my_custom_form($form, &$form_state)
{
    // Build your form

    return $form
}

```
> 4 votes

---
Tags: 7, forms, blocks
---


# Question
Title: How add a views page url to the admin_menu?
I tried creating a view with a page display, giving it a normal menu item in navigation, the url admin/people/allusers (or any url like admin/content/listing), clearing the caches, but the admin menu does not pick up the page and put it in the drop downs.

How do I do this without having to use hook\_menu for each views page url I want in the admin menu bar?

# Answer
The link needs to get added to the Management menu to show up in admin\_menu.

You can add a admin menu link on: http://example.com/admin/structure/menu/manage/management

Or through the interface at : Structure-\>Menus-\>Management-\>Add Links
> 3 votes

# Answer
As mentioned by @ursula, you can add view with a page display link from Structure-\>Menus-\>Management-\>Add link (admin/structure/menu/manage/management) in admin menu.

Please see the image where I have added Archive View link under Reports menu. I have specified following 3 fields in the 'Add link' form,

Menu link title - Archive View
Path - Archive
Parent link - ----Report
> 3 votes

---
Tags: users
---


# Question
Title: Can I use custom name for theme directory?
I'm developing site using Drupal 7. I want to give a custom name for the themes directory. Is it possible with Drupal?

# Answer
> 1 votes
Renaming core directories is not possible without hacking Drupal's core. Hacking core is highly discouraged. Even if it will work, one module that will try to access directory directly may mess up your installation.

---
Tags: 7, theming, files
---


title: I cannot log into after migration

text:
# Question
Title: I cannot log into after migration
I've searched what feels like hundreds of solutions and implemented them all. I've also searched this website in order to find the same question, but I was unable to locate it.

I have a development site and a production site. To migrate between the two I use github push and pulls. This hasn't been an issue in the past, however, I have run into this problem multiple times. After a file migration Drupal no longer allows me to login. I attempt my login credentials and immediately receive an Access Denied page.

My site cookies are reading and writing no problem. I've located the cookie ID and found it's entry in the database. So the cookies seem to be working fine and the database entries are working somewhat fine.

The problem that I can see is that the database session records are not saving any user ids. When I manually change the user id in the db record to 1, for my IP, and then refresh the website, I'm logged in. Any ideas?

```
ini_set('session.cookie_domain', 'exampleorg');
ini_set('session.cookie_domain','www.example.org');
ini_set('session.auto_start', 0);

```

# Answer
> 6 votes
I also had the same problem, and it was related to `mod_rewrite`. I have enabled the `mod_rewrite` with the following command and the problem was fixed.

```
sudo a2enmod rewrite

```

# Answer
> 3 votes
FYI, your sites\default\settings.php file should contain a cookie with the same name as the path you are using so if your previous web server had a domain of www.boldlygowherenomanhasgonebefore.com and you moved your drupal to localhost, the cookie domain must reflect that change:

**WAS:** `$cookie_domain = '.boldlygowherenomanhasgonebefore.com';`
**CHANGE TO:** `$cookie_domain = '.localhost';`

# Answer
> 1 votes
Obviously not your solution but for anyone else coming here, I had a similar problem (unable to log in) but mine was a clean URLs issue solved as follows:

There was something going on with clean URLs, they were semi-working which is why I dismissed them as the problem, but it was.

I eventually had to edit the variables table in the DB (changing LONGBLOB to LONGTEXT so I could), switched off the clean URLs flag (set "1" to "0"), clear the caches to remove the cached version of variables.

And then things worked right.

---
Tags: users, migrations, 6
---


title: Reinstalling CKEditor module

text:
# Question
Title: Reinstalling CKEditor module
I installed the latest recommanded release of CKEditor, but when I tried to change content authoring I got an error saying it wasn't installed properly.

So I tried uninstalling it by doing:

* disable module ckeditor
* uninstall
* tried to look for the module in my project and delete there also (site/all/modules) but it isn't present

When I trie to reinstall (dev version) I get:

* Archivers can only operate on local files: temporary://update-cache-235f2e3c/ckeditor-7.x-1.x-dev.tar.gz not supported and then when I trie the same link a second time:
* CKEditor is already installed.

Also clearing the cache in development doesn't work. How can I properly delete and reinstall ckeditor?

# Answer
1. Disable the Module
2. Uninstall the Module
3. Delete the Module folder from sites/all/modules
4. Remove the CkEditor folder from site/all/libraries
5. Clear the Cache
6. Copy the CkEditor Module to site/all/modules folder
7. Copy the Downloaded CkEditor to sites/all/libraries folder
8. If in \*nix systems, check the folder permissions. (Most of the time this happens to be the issue)
9. Enable the Module as usual.

More info is given CkEditor docs
> 1 votes

---
Tags: 7, wysiwyg
---


title: Tree view of node under taxonomy

text:
# Question
Title: Tree view of node under taxonomy
Hi I am facing a serious problem to list all nodes/subterms under each terms. Let's say I have several terms.

```
Games
   -> Cricket
   -> Football
   -> Badminton
   -> Tennis
     -> Long Tennis
     -> Table Tennis
   -> Hocky

```

Here you can see Games is the top most categories and Cricket, Football etc are sub categories. Must note: Tennis has 2 sub categories.

Each last term has some contents. That means Football, Cricket all are have several contents. But Tennis don't have any content. Long Tennis and Table Tennis has contents.

My aim is to show all the 1st level categories (That means Cricket, Football, Badminton, Tennis, Hocky) and then show all content under taxonomy term tree.

Like this below:

```
Categories:
   -> Cricket
   -> Football
   -> Badminton
   -> Tennis
   -> Hocky

---

Football:
   How to play Football?
   Football ground measurement.
   What is Football

Badminton:
   How to play Badminton?
   Badminton ground measurement.
   What is Badminton

Tennis:
  Long Tennis:
      How to play Tennis?
      Tennis ground measurement.
      What is Tennis
  Table Tennis:
      How to play Table Tennis?
      Table Tennis ground measurement.
      What is Tennis

Hocky:
   How to play Hocky?
   Hocky ground measurement.
   What is Hocky

```

I tried with Taxonomy View but no success. Tried to create the taxonomy-term.tpl.php file but I failed to give the display. I have modified the code many times so I can not paste the code here.

I am using Drupal 7 and views 3.

Is there any solution to solve this? Can you suggest me how can I achieve this? I think I am running on some wrong way. Please help me and give some advice to solve the things.

Lots of thanks in advance.

# Answer
> 1 votes
This can be done with Views Tree module. Install the module and read the readme.txt file to implement the same. Do get back in case of any doubts.

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


# Question
Title: How to fetch submenu items for current page?
My site nav is all in a single menu: **main-menu**, eg:

* Home
* About
    + Director Name 1
    + Director Name 2
* Contact

My site navigation bar comprises two horizontal strips: the upper one lists all top-level pages (ie: Home, About, Contact, Services). The lower one should be populated with the revelant sub-menu items *for the current page*. So if you're on the Home page, the bar will be empty. If you're on the About page, the bar will contain links to each of the Directors pages.

My top menu is populated by the following, unchanged from the code in the default page.tpl.php:

```
<?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')))); ?>

```

To get the sub-menu items, however, I've had to add the following to my theme's template.php:

```
function mytheme_preprocess_page(&$vars){

    $vars['page_submenu'] = NULL;
    $main_menu_tree = menu_tree_page_data('main-menu', NULL, TRUE);
    foreach ($main_menu_tree as $menu_item) {
        if (count($menu_item['below']) > 0) {
            $submenu = $menu_item['below'];
        }
    }
    if ( !empty($submenu)){
        $vars['page_submenu'] = menu_tree_output($submenu);
    }
}

```

... basically, "get the main menu, find the menu item in it that has some "below" items, and return that "below" bit as a menu tree".

I can then just render that in the template:

```
print drupal_render($page_submenu);

```

This seems a bit kludgy. Returning only the submenu items for the current page would seem like a fairly common requirement - is there a better way to do it?

# Answer
You are right it's a pretty common requirement. If you are not afraid of slight performance hit, you may use Menu Block module. It is able to provide you with submenu relative to your current path:

> So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
>
> Pretty simple, eh?

Of course it is a pretty big module, and it puts additional block layout between your menu and your display, so if it is too much of a performance hit, you can try to borrow some of it's code - it's GPL after all.
> 1 votes

---
Tags: routes
---


# Question
Title: a lot of template (.tpl.php) files, is it good or not?
I have used about 110 template files (tpl.php) in my theme, will that slow my drupal site?

I mean:

> more template files == consume Server performance.

# Answer
Say you override the default page.tpl.php with your own in your theme folder, and compare this to the case of using the default. In both cases, **one** page.tpl.php is being evaluated during the page render process - either the default template or yours. Even if you do not override the template, Drupal must search the theme folder to check if an override exists. Of course, if you have a lot of complex logic in your override the page will render more slowly, but that is not due to the overriding itself.

Creating custom templates with hook\_theme might slow things down, though.

In general, caching will do more to speed up your site since it bypasses page rendering altogether.
> 5 votes

---
Tags: theming, files
---


# Question
Title: Add aditional field with title to every node
I am trying to add additional field to nodes. I could add the field but I can't find a way to add its title. I have implemented the hook\_node\_view . My code is

```
function cso_node_view($node, $view_mode, $langcode) {

  $node->content['my_additional_field'] = array(
      '#markup' => "additional field",
      '#title' => "additional title",
      '#weight' => 1000
    );
}

```

The title is not appearing where the node is being printed. How can I add the title for this additional field?

# Answer
As far as I know there's no generic `#title` property (it's certainly not mentioned in the render array docs); forms use them, but I don't think extends to any render array.

`#prefix` would be the way to go:

```
$content['my_additional_field'] = array(
  '#markup' => "additional field",
  '#prefix' => "<h3>Title</h3>",
  '#weight' => 1000
);

```
> 3 votes

---
Tags: nodes
---


title: Views tabs and argument

text:
# Question
Title: Views tabs and argument
I have a views with to page displays with following paths:

```
/question/%/popular (page, title - Popular)
/question/%/new (page_1, title - New)

```

The views has a contextual filter (argument) tid. I set the first page to be default tab (with parent menu item as Normal menu item in main menu), and the second one - a tab.

I expect at url /question/all to see a views display "page", with argument value "all", active Popular tab (with url /question/all) and also New tab (with url /question/all/new).

But I've got an error

```
Notice: Undefined index: localized_options in menu_navigation_links() (line 1861 of /var/www/notlookatme/data/www/qa.winfaq.info/includes/menu.inc).

```

And an item in main menu with url /question/%25

How can I fix it?

# Answer
> 3 votes
This could be caused by a bug in Drupal 7: Inaccessible menu items in navigation links cause "Notice: Undefined index: localized\_options". There is a patch available which has worked for some people.

---
Tags: routes, views
---


title: Can't add custom fields to Calendar

text:
# Question
Title: Can't add custom fields to Calendar
I've created a new content type event (With title, body and date), but I can't select the type when editing my calendar view (screenshot included).

How come I can only select comments and dates, ..?

edit: it's because I added a view from template (Comments). How do you change the type of this view from comments to content? Is that possible?

# Answer
You cannot change View types (i.e. Users to Content or Content to Comments etc.). You will have to start the view from scratch.
> 2 votes

---
Tags: views, datetime
---


# Question
Title: Moving a Drupal installation to a subdirectory
Ok, I've got a Drupal install with a lot of links inside various nodes. All of these links are relative.

The problem is that if they're going to say, an image or a pdf in the /sites/default/files directory, they stop working.

Let me give an example:

There is a link in a node like this:

```
/sites/default/files/image1.png

```

`www.livesite.com/sites/default/files/image1.png` works

`www.domain.com/devsite/sites/default/files/image1.png` does not work

How do I (easily) switch the links to work in such a way? Do I have to do an .htaccess edit, or is there something in the Drupal settings for this? This is for Drupal 7

# Answer
> 2 votes
You can use the module Pathologic that acts as a filter on your text formats (Full HTML, Filtered HTML) and basically rewrites URL's which are parts of fields depending the site configuration and Pathologic settings.

You can for example set **Processed URL format** to `Path relative to server root (/foo/bar)` and for the **All base paths for this site**, you fill in the different website URL's.

---
Tags: 7, files, navigation, migrations
---


# Question
Title: How to create a preconfigured block/view.
I am looking for a way to create a view/block that is styled with CSS by myself, that can have content uploaded by an administrator, that will automatically use the same styles.

So it is easy for the admin to add content repeatedly that will automatically through my preconfiguration layout with the CSS as I have styled it.

I thought maybe I could create a content type then run it through a view and place that view on the page that I need it. I this case it is an Image/Icon with a link and text description, so the admin can upload the content easily and it will layout as I have styled it without them needing to write any CSS.

Thanks

Ant:-)

# Answer
> 0 votes
Yes I could work with a specific content type and views. an alternative way is to create a module with a specific form to change the content block, and to add the content to the block API.

1 _ add your admin path

```
function my_module_menu() {
 $items['content_block'] = array(
  'menu_name' => 'main-menu',
  'type' => NORMAL_MENU_ITEM,
  'title' => 'My content block',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_module_form'),
  'access arguments' => array('admin_content_block'),
 );
 return $items;
}

```

2 _ Set your permission

```
function my_module_permission() {
 return array(
  'admin_content_block' => array(
      'title' => t('Can change content block'),
  ),

}

```

3 _ A form dedicated to your admin, allowing to change the content :

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

$form['block_content'] = array(
   '#type' => 'textarea',
   '#title' => t('Block Content'),
    '#default_value' => variable_get('my_module_block_content', ''),
);
$form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
);

return $form;
}

function my_module_form_submit($form, &$form_state) {
   variable_set('my_module_block_content', $form_state['values']['block_content']);
}

```

4 _ your block view

```
function my_module_block_info() {
$blocks['block_content'] = array(
  'info' => t('Block Content'),
);
return $blocks;
}

function my_module_block_view($delta = '') {
if ($delta == 'block_content') {
    $block['subject'] = t('Your block title');
    $block['content'] = variable_get('my_module_block_content', '');

    }
return $block;
 }

```

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


# Question
Title: Why disable non-core modules when doing a core update?
I have seem multiple update tutorials tell you to disable all non core modules before doing an update. What is the reason for this? I'm not real familiar with the update area of core but can't see any real good reason. Is there something major I am risking if I don't do this?

I can understand the reasoning if we are doing an update between major versions (6 -\> 7). But when doing a minor update (7.10 -\> 7.12) is where I have my question.

# Answer
> 3 votes
Contributed modules are not always robustly built and can fall victim to changes made in core. This is particularly an issue if the contributed module has not made proper use of Drupal's API or relies on a database structure in core that may change with the upgrade (even if it is just a minor update). It is therefore safest to disable all the contributed modules before updating in case one of the modules causes the site to fail on completion of the upgrade process. Admittedly this is rare, but it does happen. It happened to us once, but thankfully just on a dev version of a site.

# Answer
> 0 votes
When upgrading from 6 to 7, none of the modules should use *sessions* table (in \*hook\_boot\* or \*hook\_init\*), otherwise it generates the fatal error. If you have simple website, you can try to upgrade Drupal, but in case of any fatal errors, you should disable them.

Please see the common problem which happens when some people trying to upgrade with contrib modules:

Upgrade D6.20 to D7 fails with PDO Exception

---

Here is sample command to disable all non-core modules and themes:

```
echo 'UPDATE system SET status = 0 WHERE filename NOT LIKE "themes%" AND filename NOT LIKE "modules%";' | `drush sql-connect`

```

Also you may try to clear the caches:

```
echo "DELETE FROM cache`drush sql-connect`
echo "DELETE FROM cache_bootstrap" | `drush sql-connect`

```

And remove any included files from the settings.php file such as memcached, etc.

# Answer
> 0 votes
My suggestion is: don't. It's Drupal 6-era advice, and the world has changed since then.

In Drupal 7, many modules can't be disabled properly, or there is a danger of them not working properly when they are re-enabled. Any module that provides field / entity types is a suspect, Commerce for instance. This is why Drupal 8 has removed the concept of disabled modules completely.

(Of course, this only concerns point upgrades, not major version upgrades such as 6 -\> 7)

---
Tags: updating
---


title: How to use Rules with Profile2

text:
# Question
Title: How to use Rules with Profile2
I want to send an email to the site admin whenever a user changes any of their Profile fields.

The tokens Rules offers are Updated Profile and Unchanged Entity, however I can't seem to figure out how to show ONLY changed items.

When I use any of the Updated tokens it merely just outputs what is there, which isn't much use in this case.

Can anybody help?

# Answer
You may have to create a custom rule if the profile2 fields are not available individually.

This guide is a good example on how to make a custom events, conditions, and actions for rules.

If you have any questions about the guide feel free to ask.
> 1 votes

---
Tags: rules, users
---


# Question
Title: Order nodes based on entity reference filter
In my Drupal 7 website I have an *A* content type with an entity reference 'parent' field which I use to link to nodes of a *B* content type.

I have to implement a way to sort *A* nodes basing on their *B* parent.

Modules such as Nodeorder and Nodequeue (smartnodequeue) can achieve this with term references. Is there any way to sort them based on entity references without creating vocabularies and term reference fields? I would prefer a draggable solution.

# Answer
> 0 votes
Create a view that shows Content of type "A", add a relationship for Entity Reference: "B". Then add a sort criteria and sort by Content "A". Choose the relationship on the sort criteria as the relationship you made earlier. You can expose the sort order so it can be chosen to sort ascending or descending. This is not a draggable solution but it does allow you to sort by the referenced entity.

---
Tags: taxonomy-terms, views, nodes
---


# Question
Title: Show a term description when the search filter in a view is that term?
I have a content type that has several vocabularies. Nodes can have 0, 1, 2 or all 3 terms selected.

Ive added a field to the terms so they all have a description as well as their name.

Color (vocabulary)

-Red (term) --This has red items (term description)

-Blue (term) --This has blue items (term description)

-Green (term) --This has green items (term description)

Pattern (vocabulary)

-Stripy (term) --This has stripy items (term description)

-Spotted (term) --This has spotty items (term description)

-Pinstripe (term) --This has pinstriped items (term description)

I have a View of nodes of the content type. I'm using Better Exposed Filters so you can filter by the different terms. I need it so when you have selected a single term its description is shown at the top of the view.

So if you checked 'Red' and 'Stripy', or 'Blue' 'Spotted' and 'Pinstripe', then no description would be shown. But if you just checked 'Blue' then 'This has blue items' would be printed at the top of the view before the nodes tagged with 'Blue' were listed.

# Answer
> 2 votes
Create a template for the view.

Edit the view. Under "Advanced" find "Theme: Information". Click on it to find the names of the templates that are applied in your theme. I think "Display output" is what you want to use. It will show you the contents of the template.

In your custom theme, create a template with the same name as the template you copied. Paste in the contents of the template you copied.

Now you can use PHP to get the information you want (available variables are listed in the comments of the templates), manipulate it as needed, and add it to the `$header` or wherever you want it, without any PHP in the database.

# Answer
> 1 votes
I really don't know if this is the best way to solve this but what I would do in that case is:

* Add two fields to the view, one for each term description
* Hide them (exclude from display)
* Create a new custom field below them (so you could use the fields from (1) as "Replacement Patterns")
* Re-write the result of the custom field using PHP (Views PHP) checking whether both descriptions are empty or not, to decide when to show or not.

Hope it helps!

# Answer
> 0 votes
You might be looking for this:

https://drupal.org/project/taxonomy\_tooltip

Using you get description of vocabulary and term description on hovering wherever they appear in content.It automatically add CSS and some effects to term or vocabulary name and shows description of it on hover.

There are lot other options also available you might be interested in. related to tooltip like :

tooltip, field tooltip, views tooltip.

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


# Question
Title: how to put markup around indiviual radio buttons
Is it possible to set the markup (#prefix and #suffix) around individual radio buttons? I know that I can add these fields to the radio button group, but that would mean that I would be wrapping the entire group, which is not what I want to do.

# Answer
According to the Forms API matrix you can. See https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#radio Have you tried some code to see if it does what you are looking for?

You can set '#options' for the radios to be a variable:

```
$rads = array(
  0 => '<span>' . t('Yes') . '</span>',
  1 => '<span>' . t('No') . '</span>', );

$form['fldset8']['exp_radios'] = array(
 '#type' => 'radios',
 '#options' => $rads, );

```
> 2 votes

---
Tags: forms
---


title: Can you cache blocks per language?

text:
# Question
Title: Can you cache blocks per language?
I am working on a multilingual site right now, and am using the Internationalization suite of modules to build it out.

The site has some custom blocks in it that I would normally use `DRUPAL_CACHE_GLOBAL` in the `hook_block_info()` definition. However, some of these will have translatable strings in them, so I really need to cache them per-language.

Is this possible? Or, is my only real option to use `DRUPAL_CACHE_PER_PAGE`?

# Answer
Just use `DRUPAL_CACHE_GLOBAL`. On multilingual sites the users language is part of the (`cid`), i.e. the key used when storing/fetching entries to/from the block cache.

The function responsible for this behavior is drupal\_render\_cid\_parts which is called from \_block\_get\_cache\_id.

You can embed the following fragment into a custom PHP block in order to verify the mechanism:

```
$fakeblock = (object) array(
  'module' => 'some-module',
  'delta' => 'some-delta',
  'cache' => DRUPAL_CACHE_GLOBAL,
);
print _block_get_cache_id($fakeblock);

```

On a multilingual site, the fragment should print something like:

> some-module:some-delta:bartik:en
> 6 votes

---
Tags: blocks, i18n-l10n
---


# Question
Title: If I download a sub-theme do I install it under the main theme's directory?
For example, I found this theme, which says it requires the Nucleus Base theme.

Does that mean that I need to install it in the Nucleus Base theme directory?

# Answer
> 2 votes
Yes, you should install it under main themes directory i.e. `sites/all/themes`.

1. Download Nucleus Base theme and put it inside `sites/all/themes/` folder
2. Download TB Purity theme and put it inside `sites/all/themes/` folder.
3. Go to **Appearance** and enable TB Purity theme.

The concept of base theme is it provides code base to its sub-theme, so, you don't really need to enable Base theme, just keep it there for your Sub-theme to find the codes that it needs to run.

# Answer
> 2 votes
You install it as other themes that are not sub-themes of other themes, in its own directory of the theme directory.

You could install it in a sub-directory of the directory containing the theme from which the sub-theme depends, and Drupal would find it the same. The problem would be when you update the parent theme, as you would risk to lose the sub-theme's files.
It is like with modules: You don't install a module inside the directory containing another module, if not in the case both modules are part of the same project hosted on Drupal.org, and you get them in the same archive file.

# Answer
> 0 votes
It is still added to Drupal in the same way as other contributed themes are added, in the `sites/all/themes` folder.

The 'requires Nucleus Base Theme' just means that the nucleus base theme also has to be installed on the site.

---
Tags: theming
---


# Question
Title: Drupal site shows frontpage instead of added content
I'm restoring a client's site after they lost all information. After some trouble, we could restore their database, which now shows all tables. The problem is that, after uploading all files and connecting to the database, the page displays Drupal's default frontpage and says 'no content has been created yet'. The database contains all tables, and I'm assuming the connection is right; otherwise I'd get an error message.

Why aren't I seeing all info stored there?

# Answer
> 0 votes
You might have all of the tables, but you might not have all of the rows, perhaps. Two tables to look at: node and node\_revision. See of there are rows there.

---
Tags: 7
---


title: Add a translatabe text into panels

text:
# Question
Title: Add a translatabe text into panels
i want to add a translatable text into panels.So I enabled the php filter and add this snippet : Unfortunately it doesn't appear.What am I doing wrong? thanks

# Answer
> 1 votes
If using Drupal 6, ensure these edits are within the settings.php file, as this is where the translation will take effect.

If using Drupal 7, there are a few reasons why this may not work. Most usually, if the text you are translating contains anything that needs to be substituted (i.e. using %user:name etc.), then the text will be substituted before being passed to t(), and as such will not work! Also, the functionality of t() in Drupal 7 for attributes and variables is limited, so perhaps an additional module will be helpful.

For solutions using additional modules: Place the text in a basic page, you can then use Entity translation to handle the languages and translation. @pedrosp also suggests that "to avoid SEO duplicated content issues, install Rabbit hole module and use the redirect to your panel page for those nodes."

Also, i18n has some solutions to tranlsate text within panels. It may take some playing around with however, to match the intended functionality of your site.

Finally, @Letharion has shared before some custom code to "force" a title to become translatable, perhaps playing with this to focus instead on where you would like your translatable content would also help:

```
/**
 * Implements hook_panels_pane_content_alter().
 */
function HOOK_panels_pane_content_alter($content, $pane, $args, $context) {
  if ($content->title) {
    $content->title = t($content->title);
  }
  return $content;
}

```

Hope this is of some assistance!

---
Tags: panels
---


# Question
Title: Best way to use image styles with Media and WYSIWYG?
Up to now, I've been using the Insert + WYSIWYG + CKEditor to insert images with specific Image Styles in a wysiwyg interface. This works well, and it's very easy to select and apply image styles (including colorbox variants) using Insert.

I'm currently testing Media (7.2x) + WYSIWYG + CKEditor as an alternative, and want to make sure I understand how to best use image styles in this context.

Based on a great write-up here (http://www.58bits.com/blog/2013/03/06/how-to-add-captions-to-images-in-drupal), it looks like one way to use Image Styles with Media is to do something like this:

1. Create desired image styles to use in WYSIWYG editor
2. Add view mode(s) as needed to the Image file type
3. Set view mode(s) to use desired image styles under Manage File Display
4. Choose "Format" (view mode) when embedding Media

Ultimately, this is more powerful than Insert, since the view modes can manage more than just the image (i.e. other fields like title, alt, and more) but it's a little clunky. For one thing, you'd need to add a new view mode for each image style that you want to have access to when embedding (?)

My question: is this currently the best way to use image styles when embedding images using Media (7.2x) + WYSIWYG + CKEditor?

# Answer
> 0 votes
It completely depends on your requirement. If you are looking to apply particular styles through wysiwyg then view styles is definitely the right option.

If you need image style (height and width) to be chosen during wysiwyg then go for this option

a) Media + Wysiwyg -: https://drupal.org/comment/8009717#comment-8009717

b) Wysiwyg + Ckeditor -: https://drupal.org/node/1956778 (patch 37)

---
Tags: 7, wysiwyg, media
---


title: How can I edit my search box

text:
# Question
Title: How can I edit my search box
I want to customize my search box. I want it to auto complete as I type and not to be case sensitive. What should I do to achieve this?

# Answer
For the autocomplete search box, there is a fantastic module Search Autocomplete with a detailed installation guide, and also has functionality such as integrating Views and Transliteration modules (which will overcome special characters/capitilisation etc.)

There is also a Patch for an exposed filter that may be of some assistance (if you are using a custom search box that you have made) that will help with the "contains" or "contains any word" operator.
> 3 votes

---
Tags: search, ajax
---


title: How can I color my taxonomy term

text:
# Question
Title: How can I color my taxonomy term
How can I add color to my taxonomy terms. Example I have terms "Working" and "Under maintenance". I want to color them green and red respectively. How can I achieve this?

# Answer
I believe the best way would to be to use Views, as this allows a lot of flexibility and in-built functionality to customise a variety of attributes, especially using taxonomy terms. I would then follow this Solution which thoroughly explains how to style each row and the icons for each taxonomy term. Hope this helps.
> 1 votes

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


# Question
Title: Configuring Drupal with a dynamic IP address
I have now a problem with the multisite configuration of Drupal 7 installed on my linux machine.
I want this site to be accessible from outsite from my local machine. For this I have a domain name from no-ip, that redirects the requests to my machine, and a multisite Drupal 7 configuration.
When I check the configuration, I am facing the result below:

* I can access the non-drupal sites with no problem from the linux machine using the mydomain.no-ip.org address.
* I can access the drupal sites with no problem from the linux machine using the local network address (192.168.1....).
* I ****CAN'T**** correctly access the drupal sites (drupalsite1, drupalsite2) from the linux machine using the local network address.
This is the problem: I am redirected to the main drupal site, although I request the drupalsite1.

And, for information, I can't access the linux machine from my W7 other machine using the mydomain.no-ip.org address (I have the STB interface). All is right with local addresses.
It seems that Drupal doesn't recognize the specified drupal site I want to get, and then redirects me to the default main drupal site.
Has somebody any idea?
May I get any example of Drupal configuration working with a dynip or no-ip service?

I am quite newbie in D7.

Thanks in advance.

# Answer
> 3 votes
There's no need to use external DNS when working locally on a development box.

You can add the required mapping to your `/etc/hosts` file

e.g:

```
127.0.0.1 drupalsite1 drupalsite2 drupalsite3

```

Then you can access the site by visting, e.g `http://drupalsite1` in your browser

You could even use something like

```
127.0.0.1 drupalsite1.no-ip.org drupalsite2.no-ip.org

```

If you'd prefer.

The `/etc/hosts` file is checked prior to external DNS lookup and will override / take precedence over the latter. There's a similar file in Windows as well.

More info: http://en.wikipedia.org/wiki/Hosts\_(file)

---
Tags: uri
---


title: My Menu Will Only Semi Translate

text:
# Question
Title: My Menu Will Only Semi Translate
I have created a menu on my site and have used features to export it. The first 2 menu items are translating to different languages but the third is not.

The third word is Contact. I have gone to `/admin/config/regional/translate/translate` and searched for Contact. I get the following.

At the bottom of my features it has

```
  // Translatables
  // Included for use with string extractors like potx.
  t('Contact');

```

So we can see that is there OK. When looking at my menu at `/admin/structure/menu/manage/menu-example` it is all in English. If I go to `/fr/admin/structure/menu/manage/menu-example` Contact remains in English and the other words change.

Contact is a mailto:link if that makes any difference.

```
  $menu_links['menu-teleplan_contact:mailto:a@a.com'] = array(
    'menu_name' => 'menu-example',
    'link_path' => 'mailto:a@a.com',
    'router_path' => '',
    'link_title' => 'Contact',
    'options' => array(
      'attributes' => array(
        'title' => '',
      ),
      'identifier' => 'menu-example_contact:mailto:a@a.com',
    ),
    'module' => 'menu',
    'hidden' => 0,
    'external' => 1,
    'has_children' => 0,
    'expanded' => 0,
    'weight' => -48,
    'customized' => 1,
  );

```

Why is the word in my menu not translating?

# Answer
> 3 votes
I think you will find there is a conflict somewhere that is preventing the specific word (as it is a link) from being translated, and this submodule should overcome the conflict. I would utilise the "Menu Translation" submodule as it will specifically achieve what you are attempting above, and hopefully make it simpler! I would use the Translate and Localize Menus option (a detailed guide of how to do that is here)

If you are still stuck, and are using SuperFish for your menus (even though this is supported in i18n), there is a work around here and this may overcome the problem also.

Lastly, just in case, ensure you have this update, the most recent version, installed also.

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


# Question
Title: Why can I only view content published to current domain?
I'm using the Administration Views modules and Domain Access. When I'm logged in as the Administrator (user 1) I can view any content across all domains at /admin/content no matter what domain I'm on.

When I'm logged in as another role (Role X), who has permission to edit any content on any domain I can only see content published to the current domain. What permission or view setting or other setting do I need to apply to allow Role X to see content published on any domain no matter what domain they're on?

The only way Role X can see everything is if I give them the "Bypass content access control" permission, which I'd rather not.

# Answer
After researching the api and reading up on how the permissions work (here) it looks as if the Node Access module limits a user (who is not user 1) to only be able to see content of the domain of which they belong, regardless of their editing permissions. You could, however, play around with grants (specifically grant\_edit) to try and override the active domain. I would suggest some custom script to allow Role X grant\_edit, or bite the bullet and use the "Bypass content access control" permission.

I understand this probably isn't the answer you wanted, however hopefully it helps in some way!
> 0 votes

---
Tags: domain-access
---


# Question
Title: expose age range in views but DOB field is date
I want to expose an age range in a view (select registered users of age between 25-50) . I tried birthday module and also tried adding a Date of Birth field to user profile using Profile2 Module .

And I think Views Contextual Range Filter works with ranges (25--100) not with dates .

any ideas ? thanks

# Answer
Try using the Computed Field module (in beta in 7). You would simply add a new field, of say age, and of Computed type, (follow a walkthrough here) and then use a Filter in the View to select the range of ages that you require.

Hope this helps!
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to get absolute url with different domain language prefix
What is the best way to get absolute url with correct language prefix? The `url()` function accepts language parameter but it seems that it is not using it to generate the prefix - only to get translated alias. I don't care about aliases - I need correct domain prefix.

When I'm on `http://en.example.com/something` and use this code:

```
<?php
$all_languages = language_list();
url('something-else', array('language' => $all_languages['nl'], 'absolute' => true));
?>

```

I will get this: `http://en.example.com/something-else` (**en** prefix).

How can I get this: `http://nl.example.com/something-else` (**nl** prefix).

# Answer
> 0 votes
Apparently the `url()` function will create links like `http://nl.example.com/something-else` (note the **nb** prefix) BUT only for specific languages configuration. This will work correctly only if I set appropriate domain for each language here: `/admin/config/regional/language`.

By default the field *Path prefix language code* is set to language code (*nl* in this case) and *Language domain* is empty.

Now since I am using **DOMAIN** prefix for language selection, and not the **PATH** prefix, then for each language I should set language domain instead of path prefix.

For some weired reason Drupal insists on filling only one of those fields, but consequently fills *Path prefix language code* by default even if language detection is set to **domain**.

# Answer
> 0 votes
This was pulled from my theme file, but as long as you have access to $node and $language, it will do the trick:

```
<?php
    if (isset($node))
    {
?>
<div class="language-switcher">
        <?php
            $nodes = translation_path_get_translations("node/" . $node->nid);
            $path  = "";
            if ($language->language == "en")
            {
                if (array_key_exists("nl", $nodes))
                {
                    $path = drupal_get_path_alias($nodes["nl"], "nl");
                }
        ?>
        <a href="http://nl.example.com/<?php print $path; ?>">Change to NL</a>
        <?php
            }
            else
            {
                if (array_key_exists("en", $nodes))
                {
                    $path = drupal_get_path_alias($nodes["en"], "en");
                }
        ?>
        <a href="http://en.example.com/<?php print $path; ?>">Change to EN</a>
        <?php
            }
        ?>
</div>
<?php
    }
?>

```

The URL's are hard coded with the path information calculated.

# Answer
> 0 votes
I format my urls like this.

```
 $order_url = url('user/' . $params['order']->uid . '/orders/'. $params['order']->order_id, array(
'absolute' => TRUE,
'language' => (object)array(
  'language' => 'lang-key',
)
  ));

```

We can see this is reflected in the url function below.

```
$language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
$alias = drupal_get_path_alias($original_path, $language);
if ($alias != $original_path) {
  $path = $alias;
}

}

```

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


# Question
Title: Other users cannot view content published to front page
why can't other users view content posted by user? Where can I find this permission issue?

# Answer
Go to admin/people/permissions and ensure that "View published content" under the title "Node" is selected.

Also, if using OG go to admin/config/group/context and ensure that "Node" is enabled, and that if you have "Content" under admin/config/group/permissions that these permissions are also correctly selected.

Also ensure that the node you want all users to see has the two checkboxes *Published* and *Promoted to front page* checkbox ticked. You find these under "Publishing options" when you edit the node as the administrator.

The defaults for these are set per content type. If a user that is *not* the administrator is creating content, these must be set by default for the type. The built-in content type "Article" has these checked by default, so the user should create article of type "Article" (or another type that has these two boxes checked by default) for the article to be visible on the front page for non-admin users.
> 1 votes

---
Tags: views
---


# Question
Title: How do I send notifications for followers of a group when group content is updated?
I want to build such functionality that allow the user to follow the other users, and when the followed person is updating the information, the follower can get notified for what they are doing.

I think to build the specified functionality, I can use the Flag module, but for the notification, what kind of modules are good to work with?
I am confused. There are too many modules like notification, or messaging; even the NodeJs module can notify.

# Answer
> 0 votes
Its depend on how regular you want to notify the user. If you want actual real time notification then go for nodejs module. See the documentation and you will get better idea about it.

# Answer
> 0 votes
For my site, I simply use a Rule to decide when the event has occurred, have an action (referencing either the Flag or the OG for who to notify), and then send an email (pushes the messages to the cron and the emails get sent off to the users who are "subscribed")

It was a lightweight and easy way to do achieve something similar to what you have outlined.

---
Tags: 7, flags, notifications
---


# Question
Title: Create content in chinese language in drupal 7?
I want to create content in Chinese language manually in drupal 7 just by inserting translated text into body, without using any module like internationalization. Kindly suggest any solution ? Do I need to add language support for chines by using 'locale' module ?

# Answer
See how to install a language on Drupal.org. After installing and enabling Chinese as a language, you will be able to specify that a node is a Chinese language node when creating/editing it.

There is no risk of data corruption, but in order to avoid problems, **never change the default language** (as quoted from the documentation).
> 2 votes

---
Tags: nodes, i18n-l10n
---


# Question
Title: Advice on using Organic Groups for course management in an academic context
I am thinking about using Organic Groups for course management in an academic context.

Initially I was going to create an OG group per course e.g. Physics 101. However if the users change per semester this could become tricky to manage...

There are 2 options I can think of:

1. Create a new group each semester e.g “Physics 101 – Semester 1, 2013”
    * But would soon end up with 1000’s of groups.
2. Somehow archive the data, clear down the group and re-enrol the next class each semester
    * I'm unsure how we could effectively do the archival while keeping the data available, and it seems like it would become a convoluted process

I would love to know how other users of OG handle this type of problem?

Is there any online material that would help me learn how to use OG in this way?

Thanks for your help in advance!

Joe

# Answer
> 0 votes
I currently run a site where every 6-12 months users Groups (OG) will change. To help me, I use the Profile2 module, it makes dynamically changing user info such as OG memberships simple. If you're not already using it, have a read of the handbook.

The way I have solved the issue you have addressed is to have a spreadsheet of all the users who have changed groups, run a simple code on my spreadsheet to edit the "groups" column of the users to what they will now be, (you can simply cross reference another sheet, say the enrollment sheet for that class, and if the username or student ID appears there, put that class ID into the group column in the sheet), and when the spreadsheet is complete, simply export as a csv and then run an import through the Feeds module. This gives you the option to update the existing user information, and you have all of the old spreadsheets as an "archive". Alternatively, you could take a snapshot of the tables database, keep this in an archive, and run simple SQL Queries to update the groups of a user.

Let me know if you need more information, if you choose to approach it this way!

---
Tags: organic-groups
---


title: private messages and views

text:
# Question
Title: private messages and views
I find the perfect module to do what i want to do in **private messages** (put a "Send author a message" to open a contact between a user and an author)

Unfortunately, i didn't find a way to put that "Send author a message" when i use views module. I display my article by fields and i don't find that field. I'm just begin to discover Drupal 7 so i don't know if i do the right thing.

I searched on the module section in drupal.org and i saw that the only module available for views with private messages was for Drupal 6.

Maybe someone know if there is a solution to integrate private messages with views (i'd love to have the same behavior that flags has with views: add the flag with add field) I looked at "advanced section" and "add relationship" to see if i can find something to add like flag but i didn't find anything.

ps: sorry if i made many mistake in english.

Thanks, Arno

# Answer
That should be there. Make sure that you add a relationship to the user/author of the nodes that you are displaying, that might be the missing piece.

Note that this is the only available views integration as of now. Privatemsg and it's group of submodules rely heavily on dynamic queries and being able to alter them. That and the rather complex queries which can't be replaced by Views easily.
> 1 votes

# Answer
The URL for 'send author a message' is 'messages/new/\[target-user:uid\]'. Simply add it as a new custom views HTML field (replace \[target-user:uid\] with the UID of the target user, which you should fetch using a previous view field.

When you enter this URL in you browser, you get a nice screen which allows to send the user a private message:

The URL can also be used in a custom pane if you set a "send a message" button on the user's profile page, or anywhere else.
> 0 votes

---
Tags: 7, views, privatemsg
---


# Question
Title: On Cron run Open and save all Profile2 based user profiles
i have a RULES event on "Cron maintenance tasks are performed" and a action is attached to it "execute custom php code"

```
<?php
$old   = '1 day';
$old = strtotime("now - $old");
$query=db_select('profile','pf')
        ->condition('pf.created',$old, '<')
        ->fields('pf',array('uid','pid','created'));
$result=$query->execute();
foreach($result as $record){
$profile=profile2_load_by_user($record->uid);
profile2_save($profile);
}
?>

```

Error :

> Recoverable fatal error: Argument 1 passed to profile2\_save() must be an instance of Profile, array given, called in /home/test/public\_html/drupal\_sedco\_2/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code on line 9 and defined in profile2\_save() (line 292 of /home/test/public\_html/drupal\_sedco\_2/sites/all/modules/profile2/profile2.module).

Any clues . Thanks

# Answer
`profile2_load_by_user` returns either a single profile **or an array of profiles** keyed by profile type. `profile2_save` expects a single profile.

It looks like in your particular case array is returned, so you need to:

1. Test what you got from `profile2_load_by_user`
2. If it's a single profile, use `profile2_save` directly.
3. If it's an array, either select the array element you need, or `foreach` over that array, calling `profile2_save` on each element.
> 1 votes

---
Tags: users
---


# Question
Title: What does the 'master' option in the attachment view settings stand for?
I am using some attachment views to display the latest one of different content types in one view.

I was using the first (block) view as the parent view and was attaching the others to this view. This, in many cases ok. But now I ran into some styling issues, caused by the overly complicated markup.

So I decided to delete the block view, convert all the views to attachments and of the view attachments, and attach all of them to 'master'. I was hoping this would give me a homogeneous markup.

But now the block disappeared completely. It is not even visible in the blocks admin page.

So my question is, what does the 'master' in the attachment options stand for?

# Answer
> 1 votes
The master display is the default one created automatically for every view. It's not a block, so it won't show up in the list. For views, only their block displays show up in that list.

A quick trick to get access to the Master display: edit the view then without selecting any of the displays append "/default' to the URL and hit return.

# Answer
> 0 votes
@Alfred Armstrong has well explained what the 'master' attachment option stands for, which I understand directly answers your questions. However, for the problem you have outlined, as a temporary solution, to get it to display the Master, go to admin\>structure\>views\>settings, and click "Always show the master display".

Then simply create a new block view, copy the newly displayed info from the Master to this, and go back to admin\>structure\>views\>settings and turn off "Always show the master display" again.

Useful link

---
Tags: views
---


title: Content Types and drupal_get_form

text:
# Question
Title: Content Types and drupal_get_form
I've created a content type for authenticated users to use, to create and edit & delete their own of. I have set up the permissions and can get access as a authenticated user to the forms directly via node/add/story & node/19401/edit.

Now i want to use the form on another page, to be used in a block within a panel.

```
$form = drupal_get_form('story_node_form');
return drupal_render($form);

```

using drupal\_get\_form doesn't seem to work correctly is there another function I should be using to pull in the form?

\*UPDATE

I managed to get it to work using node\_add

```
include_once(drupal_get_path('module','node') . '/node.pages.inc' );
return drupal_render(node_add('story'));

```

is there any security issues with this method?

# Answer
This is no secure issues with this.

* Drupal 6 `return node_add('story')`
* Drupal 7 `return drupal_render(node_add('story'))`

> Returns a node submission form.

for more information checkout the node\_add() function
> 1 votes

# Answer
Actually what I need was to display a node addition form of any content type say 'page' on any custom callback, so that a user can use that form to submit and create a node. In order to get this thing working, we need to include node.pages.inc as this is required by a node form to get loaded successfully. Following code worked for me in drupal 6.

```
// required for Drupal 6

  module_load_include('inc', 'node', 'node.pages');

  // which nodeform you want

  $node_type = 'YOURNODETYPE';

  $form_id = $node_type . '_node_form';

  // maybe add current users info

  global $user;

  // create a blank node

  $node->uid = $user->uid;

  $node->name = (isset($user->name) ? $user->name : '');

  $node->type = $node_type;

  // Invoke hook_nodapi and hook_node

  node_object_prepare($node);

  // Or you can also use an exiting node, for example

  // $node = node_load(123);

  // and the display the form:

  $output = drupal_get_form($form_id, $node);

```
> 1 votes

# Answer
all you have to do something like that

```
  $node = new StdClass();
    $node->uid = $user->uid;
    $node->type = 'article';
    $node->language = '';
    node_object_prepare($node);
    $form = drupal_get_form('catering_information_node_form', $node);
    $output .= drupal_render($form);
    return output;

```
> 0 votes

---
Tags: forms, nodes
---


title: Hook form alter for select list

text:
# Question
Title: Hook form alter for select list
I tried to convert a text field filter for title into a select list filtered by content type using hook form alter:

```
function myhook_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form'){

      // load nodes filtered by content type - news
      $nodes = node_load_multiple(array(), array('type' => 'news'));

      // Build an array
      $dropdown_array = array('' => '--Any--');
      foreach ($nodes as $node) {
         $key = $node->title;
         $value = $node->title;

         $dropdown_array[$key] = $value;
      }

      // Alter form
      $form['title'] = array(
         '#type' => 'select',
         '#default_value' => '1',
         '#options' => $dropdown_array,
      );

   }//endif

}

```

The code above works well. Now I wonder is there a better, shorter, more efficient or proper API to implement ? I'm a newbie in drupal programming. Learning to code in a more drupal way. Please advise. Thanks.

# Answer
If you know that this list won't grow more than few dozens of nodes (you have to make some tests with more items) I'd just avoid loading complete nodes - it's unnecessary if you need only the title.
This call might become a significant database hit (=\> page will load slower and will slow down other visitors of the site) when you add more nodes to the site.
When you call `node_load()`, Drupal builds the complete node object, meaning it looks for all additional fields you added, settings and calls corresponding node hooks from other modules. Avoid calling it for small details whenever you can.

Here's what you could use instead:

```
function myhook_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form'){

      $nodes = db_select('node', 'n')
        ->fields('n', array('title'))
        ->condition('type', 'news')
        ->orderBy('n.title', 'ASC')
        ->execute();
      $dropdown_array = array('' => t('-- Any --'));
      foreach ($nodes as $node) {
        $dropdown_array[$node->title] = $node->title;
      }

      // Alter form
      $form['title'] = array(
         '#type' => 'select',
         '#default_value' => '1',
         '#options' => $dropdown_array,
      );

   }//endif

}

```

Check out also Chosen module for Drupal - it will allow you to have a much nicer select form element than the default one. It's pretty straightforward to install.
You can see a demo here.
> 5 votes

---
Tags: 7, forms
---


title: How to modify a form field?

text:
# Question
Title: How to modify a form field?
i want to modify a Select option field of webform with hook\_form\_FORM\_ID\_alter(), but when I do something like:

```
$form['submitted']['dia'] = array(
'#type' => 'select',
'#title' => 'Dia',
'#options' => $options_first,
'#default_value' => $selected,
'#ajax' => array(
  'callback' => 'ajax_example_dependent_dropdown_callback',
  'wrapper' => 'dropdown-second-replace',
),
);

```

all the other values are replaced and also the weight.

I only need to add `'options'`, `'default_value'`, and `'ajax'`. If I remove other properties like, 'type' the field is not displayed, and the other properties like weight is removed if I do what is in the code. How to modify these 3 attributes?

# Answer
When you are using this syntax:

```
$form['submitted']['dia'] = array(

```

you create a whole new array, with only the values you provided. Old array that was there is simply discarded. If you only want to add or modify `'options'`, `'default_value'`, and `'ajax'`, you need to access them directly:

```
$form['submitted']['dia']['options'] = $options_first;
$form['submitted']['dia']['default_value'] = $selected;
$form['submitted']['dia']['ajax'] = array(
  'callback' => 'ajax_example_dependent_dropdown_callback',
  'wrapper' => 'dropdown-second-replace',
);

```
> 0 votes

---
Tags: ajax, webforms, forms
---


# Question
Title: Admin Menu is messed up - Drupal 6 (Not cache related)
Here is a screenshot of the menu on our dev server, everything looks fine:

View it bigger here:https://i.stack.imgur.com/uVtpo.png

Here is a screenshot of the menu on production, not fine: View it bigger here: https://i.stack.imgur.com/PZqGh.png

I cleared the cache a couple of times, not sure why it all of a sudden started happening.

This site has also had issues where the main nav menu disappears from time to time. Clearing the cache restores it and it may not be related to this issue at all, but thought I would mention it.

Admin Menu module 6.x-1.5

# Answer
Under admin/settings/admin\_menu there is a feature to Wipe and Rebuild. That fixed the issue for me.

Very weird problem.
> 2 votes

---
Tags: 6
---


title: entity getPropertyInfo() not working

text:
# Question
Title: entity getPropertyInfo() not working
I am working with the entity\_metadata\_wrapper, and I found online this function to display all of the wrapper's properties.

```
$billing_profile = commerce_customer_profile_load($order->commerce_customer_billing['und'][0]['profile_id']);
$billingWrapper = entity_metadata_wrapper('commerce_customer', $billing_profile);
dpm($billingWrapper->getPropertyInfo());

```

However, it gives me an error.

> PHP Fatal error: Call to undefined method EntityValueWrapper::getPropertyInfo()

When I googled the function, it came up as EntityStructureWrapper::getPropertyInfo(), where I see that its not a function of `EntityValueWrapper`, but rather `EntityStructureWrapper`.

How do I create that class instead of using the code I found?

# Answer
> 1 votes
Commerce customer only defines a `commerce_customer_profile` entity type (not `commerce_customer`), so changing the second line to this should fix it:

```
$billingWrapper = entity_metadata_wrapper('commerce_customer_profile', $billing_profile);

```

---
Tags: commerce, entities
---


title: Setting an order as Completed

text:
# Question
Title: Setting an order as Completed
In code I am trying to mark an order as completed. I am doing this in `hook_commerce_payment_order_paid_in_full`

```
function my_module_commerce_payment_order_paid_in_full($transaction) {
  $orderid = $transaction->order_number;
  $order = commerce_order_load($orderid);
  commerce_order_status_update($order, 'completed');
}

```

However this does not seem to work. The state the call is at when going into this is `processing`

I also have the following 2 rules

```
{ "commerce_checkout_order_status_update" : {
    "LABEL" : "Update the order status on checkout completion",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "commerce_order", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce-order" ], "order_state" : "pending" } }
    ]
  }
}

```

And

```
{ "rules_update_the_order_status_on_checkout_completion_if_payment_" : {
    "LABEL" : "Update the order status on checkout completion (if payment complete)",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "1",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "commerce_payment", "commerce_order", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "IF" : [
      { "commerce_payment_order_balance_comparison" : { "commerce_order" : [ "commerce_order" ], "value" : "0" } }
    ],
    "DO" : [
      { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "completed" } }
    ]
  }
}

```

In short as soon as the balance is 0 I want the order to be complete.

# Answer
> 0 votes
In the end I created a new rule:

```
{ "rules_complete_order" : {
    "LABEL" : "Complete Order",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "commerce_payment", "commerce_order", "entity" ],
    "ON" : [ "commerce_payment_transaction_insert" ],
    "IF" : [
      { "commerce_payment_order_balance_comparison" : {
          "commerce_order" : [ "commerce-payment-transaction:order" ],
          "value" : "0"
        }
      }
    ],
    "DO" : [
      { "commerce_order_update_status" : {
          "commerce_order" : [ "commerce-payment-transaction:order" ],
          "order_status" : "completed"
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
If the problem is simply that orders are being marked "paid in full" while still in checkout and then having their statuses overridden when the checkout completion rules run, why don't you just add a condition to the default checkout completion rules to not change the order status if it's already completed?

---
Tags: 7, commerce
---


# Question
Title: Filtering nodes shown on taxonomy menu block
As in the picture, the taxonomy terms are showing count of nodes tagged with the term( using taxonomy\_menu module). That nodes are of type classified ads.

Is it possible to filter out expired ads ? I mean in the picture, the first menu item is "10th" with 24 nodes in it. But I want to filter out 5 nodes which have expired containing a hidden flag that it has expired. So that is should show as "10th(19)"

How can I do it?

Looks like in the file taxonomy\_menu.database.inc we have this function:

```
function _taxonomy_menu_term_count($tid) {
  $result = db_select('taxonomy_index', 'tn');
  $result->condition('tid', $tid);
  $result->join('node', 'n', 'n.nid = tn.nid AND n.status = 1');
  $result->addExpression('COUNT(n.nid)', 'term_count');
  $temp = $result->execute();
  $temp = $temp->fetchObject();
  return $temp->term_count;
}

```

Along with n.status I should add n.field\_expired check to exclude I think. I wouldn't mind to temporarily hack the code of Taxonomy Menu though.

# Answer
> 1 votes
Since you said you "would not mind temporarily touching the code" (I would highly advise not to touch and try to find alternative ways) here is my quick solution and also alternative ways of accomplishing it.

Assuming the field\_expired is a boolean field (single on/off check-box values 1/0) and you are not using revisioning.(see the three lines I added), also make sure you resave at least one node to recalculate.

```
function _taxonomy_menu_term_count($tid) {
  $result = db_select('taxonomy_index', 'tn');
  $result->condition('tid', $tid);
  $result->join('node', 'n', 'n.nid = tn.nid AND n.status = 1');

  $result->join('field_data_field_expired', 'fdfe', 'fdfe.entity_id = tn.nid');
  $result->condition('fdfe.field_expired_value', '1', '=');
  $result->condition('fdfe.entity_type', 'node', '=');

  $result->addExpression('COUNT(n.nid)', 'term_count');
  $temp = $result->execute();
  $temp = $temp->fetchObject();
  return $temp->term_count;
}

```

Another ways of patching it would be to add a module\_invoke\_all higher up the code to allow other modules to interact (hook into), or use "addTag" along your query and allow other modules to alter the query itself (the latest one would be recommended). Both this require you to write your own custom module.

# Answer
> 1 votes
I think the best solution here is going to be to not use the taxonomy\_menu module at all and write your own custom query to pull the terms with their counts out...

# Answer
> 0 votes
As a simple solution, why not set a Rule that when the content expires, it is either deleted, cached, or as a custom solution, the content is copied to another content type (say "Expired" for example) and then erased?

**EDIT:**

In order to keep the content "searchable" and viewable, create a Content Type called "Expired" (or whatever suits you) and put a View somewhere in your site that lists all of the content associated with this type. Then, do as suggested above with the Rule to copy the all the data out of the now hidden content, into a new piece of content of type "Expired". It is now searchable and viewable, you can even link the taxonomy terms if you wish via Views, and no need for custom code

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