# Question
Title: Search a content type fields based on user inputs
I am using Drupal 7. I need to create a search condition to generate a search result.I have a content type called "properties".It contains around 20 fields like Location,City,Availability,Property type,Category,Price,Nearby Landmarks,amenities etc...

I have a search form to search properties based on PropertyCategory PropertyType City Location Price Furnish etc...

But drupal generates separate tables for each field type.How can i retrieve data from all table based on any search condition?I have created a view based on this content type "properties".

Do we have any option to generate a single table for a content type? Could you please give me an idea. Please help me ,i am stuck on the way and can't move without any help.

Thanks in advance!

harikris.

# Answer
If you want result from a specific content type then user views with expose filter for search and filter it with the specific content type.
Why do you need single table for all the fields, Either you can use join to fetch data from all the table. You should not write custom code for this kind of functionality best option is to alter the search query or user views with expose filter to provide this functionality.
> 0 votes

---
Tags: search
---


title: Filter Views results by users mobile OS

text:
# Question
Title: Filter Views results by users mobile OS
I'm building a mobile website with Drupal 7 and I need to filter articles displayed using Views by visitors mobile OS. If visitor is using Android phone - I would like display only articles with "Android" tag, etc. Visitors with "other" mobile OS'es will get "no results" message. What is the best approach to accomplish this task?

# Answer
> 1 votes
I would take a look at the Context module with this add-on: Context Useragent

# Answer
> 0 votes
If you want to use Panels (or just Page Manager from ctools), you can use the Mobile Detect module if you also enable the Mobile Detect ctools sub-module.

Make your view over the content type. Then add a pane display, and add a filter for your device term. Add more panes as needed.

Use Page Manager to make a page. Make variants for each of the mobile devices that you need. Set the access options to whatever you need. Then set the selection rule to use the mobile detect device type. You will get a modal with a whole bunch of devices. Configure as needed. Then for the content, add the pane you created above. Add additional variants as needed.

Full disclosure: I am the author/maintainer for Mobile Detect, but this is one of the scenarios I envisioned when I made this module.

---
Tags: 7, views
---


# Question
Title: How to display related data along with node
I have a custom table that contains data related to certain nodes. I'm using EVA (Entity Views Attachment) to display some of this data along with the node, which works great.

However, I now want to display a single value from a related table when viewing a node.

I guess this could also be done using EVA, but creating a view to output a single value seems like the wrong approach(?)

In this case, the table does not contain entities. It is defined using hook\_schema(), and made available to views with hook\_views\_data () in Drupal 7.

Thanks for any thoughts on the best way to proceed.

# Answer
> 0 votes
there is surprisingly many ways to acheive it :) this is one that will require some work, but should be sane and scalable :

* in a hook\_node\_load, load the data and attach it to the $node ($node-\>my-data)
* \[optionally\] in hook\_preprocess\_node, create a variable for the template
* in your template file, show the value aproprietly

---
Tags: nodes
---


title: Media Browser doesn't show

text:
# Question
Title: Media Browser doesn't show
I've got the media module installed, but I'm not seeing the Media browser at all when I go to upload images.

Do I need to do something special to enable the media browser?

# Answer
try checking the "media library" in the settings of the field, as seen on the picture in the Quick Start Guide
> 1 votes

---
Tags: 7, media
---


# Question
Title: How to edit content of panels Custom text that was made reusable?
I'v created a Custom text element for page manager and made it reusable, and I'm not able to edit it now in Panels. Is it possible to edit such Panels elements after they were made reusable?

Thanks

# Answer
> 2 votes
If you go into the panels from the structure menu... you will see "Manage custom content" on the top right.

---
Tags: 7, panels
---


# Question
Title: How to have one node's access dependent on another node's access?
I've got two content types. One we'll call "company"; the other, we'll call "project". Companies can have projects, managed by a field in the project. Companies and projects can also have fields that determine their visibility; each of them can be marked "public" or "private". Node access rules are used to control access to the nodes, based on the value of that field. All of this is working fine.

What I'd like to do is make it so that, if a company is marked "private", all of its projects also become private, in the sense that people other than the company's owner get `access_denied` if they try to look them. However, if the company's access is returned to "public", the access rights of the projects are restored to whatever their own visibility setting specifies.

Here's what works for me at the moment. My concern is that it requires directly hacking the `node_access` table, which, aside from the fact that it works, bothers me...

Add two bits of code to the company's `_node_access_records()` handler:

* When the company's visibility changes from public to private, for each of the company's projects: blow away the entries for the project in the `node_access` table and insert a "only the author can access" right.
* When the company's visibility changes from private to public, for each of the company's projects: again blow away the entries for the project in `node_access`, but this time get the access rights for the project by calling its `node_access_records()` handler and insert the corresponding rights into `node_access` for that project.

Any other ideas out there, perhaps something that (in particular) avoids the direct hacking of `node_access`?

# Answer
Create a custom module.

Use hook\_node\_view to run some code whenever a project node is viewed.

In that custom hook, find the company nid by looking at the field of the current node.

Then use node\_load to get a node object of the company, check the company's access and then call drupal\_access\_denied if the current user does not have access to that company.
> 1 votes

---
Tags: 7, nodes, users
---


# Question
Title: How to troubleshoot general module issues?
My site has a somewhat complex setup, so I therefore have a good number of modules installed. As a result, sometimes different things will randomly stop working, and I am not sure what exactly the cause was. Posting in issue queues can only go so far, and I'd like to start learning how to troubleshoot these problems myself.

For instance, I'm currently using Entity Reference Prepopulate to help prepopulate fields in a "Review" entity type. I'm also using LoginToboggan to redirect users to a login page when they don't have permission to view the current field. Upon login, they are supposed to be redirected to the last page that they were on. So, with Prepopulate, the URL is something like http://www.gigindie.com/node/add/review?field\_review\_venue\_reference=235, but after logging in with the LoginToboggan login form, the user is redirected back to http://www.gigindie.com/node/add/review instead of http://www.gigindie.com/node/add/review?field\_review\_venue\_reference=235, which does not include the Prepopulate portion of the URL.

Obviously the above example is a specific use case, and help with that would be appreciated, but this question is a more general one. How do I go about figuring out why a module might not be working, and which other modules are conflicting with it, if any? Are there any tactics that would help specifically with troubleshooting module malfunctions?

# Answer
My first port of call is usually the reports in /admin/reports, in particular 'recent log entries' (use the filters) and 'status report'. Also the PHP error logs on the server can be useful.

Also, keep an eye on Javascript errors by using your web browser's javascript console/log, as you attempt to do the broken activity.
> 0 votes

---
Tags: 7
---


# Question
Title: Browscap doesn't seem to hide blocks on google chrome for android
I have a website where I write some web development articles in it, in the blog page, I have set a slideshow with Views because the most of the slideshow modules are useless (it's my personal opinion, I was needing that the slideshow shows the image the title of the article with its caption, there were no slideshow modules that can do that), I used a forked version of Responsly slideshow (it's not the big deal but I liked it because it's really simple), unfortunatelly the slideshow looks pretty bad on mobile devices, I used Browscap to hide the slideshow on mobile devices and works great, but, Browscap doesn't seem to hide blocks on google chrome for android, I still don't have time to work on the slideshow, so, is there something I can do to solve this problem??

NOTE: I don't know the version of google chrome for android that I'm using, my cellphone is a galaxy S (international version) with cyanogenmod 9, I am not sure if it's a bug or if it's my phone.

# Answer
> 1 votes
Using Browsecap (AKA 'user agent sniffing') will always be error prone, because there are so many different browsers, all with different user agents.

Instead, consider implementing a responsive design, using CSS3 media queries, to hide certain elements based on screen width.

---
Tags: blocks, javascript, theming
---


# Question
Title: Caching - techniques? suggestions? best practices?
I have a website that will be using three (3) views slideshows on the landing page/front page. What are the best ways to set this up site to be able to load efficiently? Should I start with a Pressflow site? Install and enable specific modules to improve performance? Use Boost? Are most of the caching modules and techniques related only to logged in users? Do I have to own my own server to do this well? I am assuming that because there are so many slideshow instances loading at the same time that this will be a severe performance hit at loading.

# Answer
In general, I'd recommend using boost if you don't have access to the command line of a server. Boost creates a static HTML copy of the file inside a cache directory within your Drupal file structure. It updates cached pages only when content changes. It is used in conjuntion with the performance enhancement features of Drupal such as CSS and JQuery compression found under `/admin/settings/performance`.

If you have command line access I'd reccomend APC and memcache/memcached. This takes a little more effort to set up, but is well worth it IMO. There are plenty or resources on Drupal.org to help you to set up memcached.

You can also set basic caching on individual views as shown here:

You'll see the option for caching 7th from the bottom. There is also a similar option in panels if you use them.

These caching options are designed for end-users really, not specifically logged in users. Indeed you may want caching disabled for logged in users if they are administrators and/or are making changes to the site.
> 3 votes

# Answer
Picking a caching strategy before you have even built the site is really getting ahead of yourself. Ideally, you should get your site running as well as possible without caching, and then use advanced caching strategies to get extra performance.

Build the site, then optimize Apache, PHP, and MySQL for the memory footprint you are seeing. This will likely mean getting APC up and running, as well as interpreting mysqltuner results.

Getting a good baseline for Apache, PHP, and MySQL can do wonders for performance w/o even needing to play with caching. This is really important, because no matter what you do, you will have cache misses / clears, and you want the site to be acceptable under these circumstances.

Then profile your site, and see what your performance problems are. Then address them one by one so you can figure out if you are actually solving a problem, or just bandaiding it.

Don't underestimate the standard caching used by core Drupal and modules that utilize Drupal cache. Go through all of the setting pages and learn what they can do.

Additional strategies could involve Boost, Varnish, Memcache, or other additional modules. But, there is no solution that fits all scenarios. You need to profile and be able to measure whether you are making forward or sideways progress.

To address specific questions.

Pressflow can make a difference. But the changes to session handling can be problematic, and the the way it handles PHP error reporting can take a little getting used to. I typically start with Pressflow, so I am not fixing quirks after the fact (though some of my clients don't have problems when I develop against standard Drupal and then they deploy Pressflow).

You don't necessarily need your own server, but you should really have a VPS with true root. Preferable, you want one from a place where you can scale memory/CPU easily and on-demand. If you have true root you can think about if PostgreSQL or Zend Server CE makes sense.

Most Drupal-based caching strategies only take effect with anonymous users. This is why a properly tuned instance is so important.
> 3 votes

# Answer
Most of the other answers are about general caching strategies, not tailored to your situation.

3 slideshows loading on one page will probably cause a slow-to-load page, but not because of anything at the server end - generating the HTML and Javascript will take hardly any time at all, but it will take a long time for the user to download all the images used in three slideshows.

The problem here is the users's internet connection.

You can improve the user experience by using a slideshow script that progressively loads up slideshow images just before they are needed rather than before the slideshow starts. So choose your javascript slideshow carefully.

BTW having 3 slideshows on one page will probably result in a pretty horrible design. Talk to your designer about that...
> 3 votes

---
Tags: views, 7, performance, caching, javascript
---


title: Use CDN version of Video.js

text:
# Question
Title: Use CDN version of Video.js
Until the Video JS Drupal project supports the CDN version, how can we go about overriding the default URL in a custom theme? It looks like there is a plan to include it in the future but not yet implemented.

# Answer
> 0 votes
You can use the following code in a module, or a theme.

```
function mymodule_js_alter(&$javascript) {
  if (isset($javascript[$path])) {
    $javascript[$path]['data'] = 'absolute URL to the file';
    $javascript[$path]['type'] = external;
  }
}

```

Replace `$path` with the correct value. Normally `$path` is build from the path where the module is installed with `drupal_get_path('module, $module) . '/' $filename`.

---
Tags: 7, files, cdn
---


# Question
Title: Easiest way to post videos directly to S3?
I am working on a video sharing site and I plan to use the Video module. Amazon S3 is also being used as the file system. The problem is how to override/extend it so the video file skips the intermediate step of uploading to the server and directly upload to S3 using a separate POST request?

# Answer
If you're using Drupal 7, take a look at these two projects:

Both of these let you store file uploads on S3 instead of the local filesystem.
> 0 votes

---
Tags: 7, files
---


# Question
Title: Delete Custom Content Type Content with Custom Fields
I want to delete the content of a custom content type, which has thousand of nodes. The problem is that I can delete the references from the node database table, but the issue in this solution is that the content still remains in the custom field types database table, and when I want to recreate some data, it gives me the error of duplicate data.

Is there a solution to delete custom content type nodes with there related custom field types?

I am using Drupal 7.

# Answer
> 0 votes
Below is the code which can be posted in any file and then executed. It will remove all the nodes of the specific content type.

```
// Retrieve all nids for your custom content type.
$result = db_query("SELECT nid FROM {node} WHERE type = :node_type", array(":node_type" => "<YOUR_CONTENT_TYPE>"))->fetchAll();

// Delete all nodes.
 foreach($result as $node) {
  node_delete($node->nid);
 }

```

# Answer
> 0 votes
You could use `node_delete` or `node_delete_multiple` to do this:

```
// Retrieve all nids for your custom content type.
$result = db_query("SELECT nid FROM {node} WHERE type = :node_type", array(":node_type" => "<YOUR_CONTENT_TYPE>"))
  ->fetchAll();

// Delete all nodes.
foreach($result as $nid) {
  node_delete($nid);
}

// You should also be able to use node_delete_multiple().
// node_delete_multiple($result);

```

---
Tags: entities, nodes
---


title: Filter nodes based on active context

text:
# Question
Title: Filter nodes based on active context
Is it possible to filter nodes based on whether a certain context (defined by context module) is active? I can't find a way to do this. I'm using Drupal 6 and context 6.x-3.0.

Let's say we have a certain menu path that activates a context. In this context I have a view and I need to filter nodes that belong to the context (that is they belong to the menu, that activates the context).

# Answer
> 1 votes
Making context aware Views is not something you can easily do with Context module. That is I'm sure it would be possible, but it would require a lot of work.

Panels is designed to accomplish such tasks, with it's tight integration to views, it can pass arguments to views that you can use to determine what to display.

# Answer
> 0 votes
Views default argument from Context is a project that might help you out. (I've not used it yet, just remembered seeing it a while back.)

It looks like you'll need to write a small module with a bit of glue code. See these configuration notes in the issue queue for the module: http://drupal.org/node/774966

---
Tags: 6
---


# Question
Title: why does hook_menu produce a menu that belongs to the system module?
In my project we implement a little menu that provides information about the module. This snippet lives in `drutexml.module`.

```
function drutexml_menu() {
  $items['drutexml'] = array(
    'title' => 'LaTeX filter implemented via LaTeXML',
    'page callback' => 'drutexml_information',
    'access callback' => TRUE,
  );
  return $items;
}

```

Actually this is a bit silly, and I want to turn it back off inside the installation profile. But as it turns out...

```
SELECT link_path, module FROM menu_links WHERE link_path = "drutexml";

+-----------+--------+
| link_path | module |
+-----------+--------+
| drutexml  | system |
+-----------+--------+

```

and then in `menu.inc`, where `menu_link_delete` is implemented, we see this bit of logic on line 2997:

```
if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) { ...

```

In other words, I can only delete non-"system" links. That's fine with me! Or it would be, if my link was stored with the name of the module where `hook_menu` is implemented in the first place.

What's going on here? Why is this said to be a "system" link?

# Answer
> 1 votes
The only way to remove a menu item defined from a module in `hook_menu()` is, apart from removing its definition from the module's `hook_menu()`, removing it with hook\_menu\_alter().

```
function mymodule_menu_alter(&$items) {
  unset($items['drutexml']);
}

```

Menu items that are part of a menu, including the ones defined with `hook_menu()`, are saved in the menu\_links table. Those defined in `hook_menu()` are saved setting the "module" field to "system" to distinguish them from other links directly added from a module.

---
Tags: 7, routes, hooks
---


# Question
Title: Custom view single content wrapper css style
My custom view which shows only two rows of data looks like this

* content1
* content2

but I want to display them side by side like this content1 content2

to do this I have to apply float left and width 50% to the content wrapper css class or id but the problem it has a long **views-row views-row-1 views-row-odd views-row-first** css class how do I modify this class ?

```
<div class="view-content">
    <div class="views-row views-row-1 views-row-odd views-row-first">
    </div>

    <div class="views-row views-row-2 views-row-even views-row-last">
    </div>
</div>

```

Result I need is

```
<div class="view-content">
    <div class="customeview">
    </div>

    <div class="customeview">
    </div>
</div>

```

# Answer
> 0 votes
You can reduce the standard markup with these options in views:

# Answer
> 0 votes
Additionally to Volker's answer, I'd like to precise that these available options in Views 3 were previously in a contributed module called Semantic Views. This module has been integrated into Drupal 7, but not all of its features, so it is not totally obsolete for Drupal 7 (see this thread for more info).

---
Tags: views, theming
---


# Question
Title: Add a role to a user during MailChimp subscription
I'm sorry, I'm a beginner in Drupal 7, and I don't really understand the roles behaviors. I arrive in a website which is already done, and I have to add a functionality : a newsletter for another entreprise but on that website.

So I used Mailchimp to create a list, and the subscription is possible on the website. But I don't really understand how to send a mass contact to these people because they're not put in a specific role.

So my question is, how can I put people who subscribe to this newsletter in a specific role (Which I already created) ?

I'm sorry, maybe this is a bit difficult to understand, and there can be a lot of mistakes in my message because I'm French.

I read some of the answers in that website and I looked for some others on the internet, but really, it's extremly complicated, I don't even know where to put those php codes I found.

Thank you really much for reading it, if you can help me, I would really be pleased !

# Answer
> 0 votes
Try using rules you can add a condition and put action to it. condition -\> when to activate your rule: when a person subscribes action-\> add user role. Hope this solves your problem

---
Tags: users, emails
---


# Question
Title: Allow user to pick a number with each taxonomy term
Example: I have several vocabularies each one representing animals: First vocab: Dogs (child terms are breeds) Second vocab: Cats (child terms are breeds)

So user for example has 6 golden retrievers, and he picks the term "Golden retriever". Now he should be able to pick how many he has, so i need a number to pick next to each term.

Is this possible ?

# Answer
> 1 votes
Typical Field Collection case.

Have fun !

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


# Question
Title: Displaying dynamic image when image field is empty
I need to implement the following functionality in Drupal 7

I'm implementing a view to display a list of spare parts . A spare part has a category(oil pump, engine, etc...) assigned.

When the image of the spare part is empty , need to show the image of the category.

Appreciate your help on this.

# Answer
> 1 votes
In your view, set first a field to show the image of the term. **hide it.** Now set the field image of your node, and "rewrite result if field is empty" with the **token** of your first field.

Have fun.

---
Tags: views, media
---


# Question
Title: Ajax Submit Forgot Password Form Loaded in Front Page
Firstly, I altered the Forgot Password Form in my template.php and added the #ajax property:

```
// Ajaxifying the form

    $form['actions']['submit']['#ajax'] = array(
      'callback' => 'themename_user_pass_form_ajax_callback',
      'wrapper' => 'user-pass',
      'method' => 'replace',
      'effect' => 'fade',
    );

```

Then I created the ajax callback function:

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

  module_load_include('inc', 'user', 'user.pages');
  return $form;

}

```

**The form works fine in /user/password page and the ajax works too.**

I want the form to appear in the front page, So in my page--front.tpl.php I added the following:

```
<?php
      module_load_include('inc', 'user', 'user.pages');
      $user_pass = drupal_get_form('user_pass');
      print drupal_render($user_pass);
 ?>

```

The form appears and when submitting returns with js alert

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /system/ajax StatusText: Internal Server Error ResponseText: Memory used at: devel\_boot()=3.43 MB, devel\_shutdown()=32.2 MB, PHP peak=32.25 MB.

*Note: The ResponseText is from devel.*

In my php\_error log file I found this:

> PHP Fatal error: Call to undefined function user\_pass\_validate() in /www/drupal/includes/form.inc on line 1464

The `user_pass_validate()` is not declared maybe `module_load_include('inc', 'user', 'user.pages');` is not working with the ajax call?

# Answer
> 1 votes
`module_load_include()` works slightly differently from your example. The first argument is the file extension, the second is the module name, and the third is the file name minus the extension.

This should work:

```
module_load_include('inc', 'user', 'user.pages');

```

---
Tags: theming, ajax, forms
---


# Question
Title: I need help implementing an ajax block to prevent it from being cached by Boost module
I have a website fully cached through boost module with a region where a block is displayed. In this block content is shown via views and the display order in the view is set to random. So far so good. This works fine when logged in. But for guest users only the first block content that hits the cache is shown.

I found a snippet on drupalgroups that should do the trick, an "ajaxified block".

This is the snippet for blocka.php

```
<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$block = module_invoke('statistics', 'block', 'view', 0);
print $block['content'];
?>

```

And this should go in a block:

```
<div id="info">
</div>
<script>
$('#info').load('/blocka.php');
</script>

```

To test this I created the "ablock.php" and put it in the root directory and also made a block with the code.

Firebug tells me that the block is there, but it doesn't show any statistic.

1. How can i debug this to find out, if the blocka.php is loaded?
2. How do i have to customize this line for my needs? In fact, i do not understand this line...

$block = module\_invoke('statistics', 'block', 'view', 0);

Thanks for any advice.

# Answer
Without comment to the overall approach, but rather to "I do not understand this line," module\_invoke() invokes a hook in a specific module with any arguments passed. The snippet you found is for Drupal 6, so that's the major part of the issue here.

```
$block = module_invoke('statistics', 'block', 'view', 0);

```

invokes `statistics_block('view', 0)` which means to view the `0`th block of the statistics module, and

```
print $block['content'];

```

prints out its contents (so they get loaded into your `#info` div later on via ajax).

But, there is no hook\_block in Drupal 7, it's now hook\_block\_view (and hook\_block\_info) so you need something along the lines of...

```
$block = module_invoke('statistics', 'block_view', 0);

```

instead to accomplish what you are looking to do.

More information on all of this can be found here:

http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook\_block\_view/7

http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook\_block\_info/7

Now, if what you are wanting to do is put the contents of a View in this block, you could do something like this one-liner instead of the module\_invoke/print above:

```
print views_embed_view('NAME_OF_THE_VIEW');

```

with more information on `views_embed_view` here:

http://api.drupal.org/api/views/views.module/function/views\_embed\_view/7
> 1 votes

# Answer
Use Ajax Blocks to make the block in question load via Ajax.
> 1 votes

---
Tags: 7, ajax, theming, caching
---


title: Document has expired

text:
# Question
Title: Document has expired
I created my own module and it has a form that is created using the Form API. The problem is that when a user clicks on a link on the form after hitting the submit button, and goes to the link, and then hits the BACK button on their browser, then the user gets a message of "Document expired. The document is no longer available".

How can I make it so that the user can hit their BACK button and be taken back to the form?

# Answer
I didn't really solve the issue technically, but I used a workaround and made my links use "target=\_blank" to force open in a new tab/window. This prevents the user from hitting the BACK button. It's not a clean solution, but will suffice. :(
> 0 votes

# Answer
A better solution might be to add a link on the page that the user sees after the form, that takes them back to the form. You might need to put back in some session values. If the form was already submitted, you'll want to decide whether to load their submission or take them to a blank, new form.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to display custom content when viewing node?
I am using the Biblio module and I like the display mode (e.g. full, teaser). I would like to tack on custom text and information when a user views the content below the display. How do I append my own custom text in the current display? When I go to "Manage Display", the custom fields are not shown. It might be hard coded in the module. What Drupal API call should I be looking for? Or better yet, I am perfectly willing to write my own module. I just do not know where to start in adding my own additions to an existing display.

An example is the comment module. When someone leaves a comment, then you can see the comment someone has written that is tied to the specific node and/or content type. I am *not* talking about creating a user input form or input HTML field.

# Answer
> 0 votes
I resolved it by using hook\_node\_view() to append to the $node-\>content object.

---
Tags: 7
---


# Question
Title: Computed code db query issue -- working in PHPmyadmin but not field
On my site, I have venues, and reviews of the venues, related with an entity reference field. I'm creating a computed field to store the UID of the first person to create a review for each venue. To do so I've written the below query. Now, it works fine when I enter the simplified sql directly into PHPmyadmin, and substitute $entity-\>nid with an actual nid, but for some reason it just will not work when I add it into the computed code field, with the added `db_query` and `fetch` portions. Any ideas?

```
if (!$entity->nid) node_save($entity);

$entity_field[0]['value'] =
db_query (
    SELECT entity_id
    FROM (
        db_query (
            SELECT *
            FROM field_data_field_review_venue_reference AS ReviewRow
            WHERE field_review_venue_reference_target_id = $entity->nid
        )->fetchrow()
    ) AS uid
    LIMIT 1
)->fetchfield();

```

# Answer
What you wrote is not PHP code, which is what a computed field is expecting.
I would rather use the following code.

```
$entity_field[0]['value'] = db_query("SELECT entity_id FROM {field_data_field_review_venue_reference} vr WHERE vr.field_review_venue_reference_target_id = :id", array(':id' => $entity->nid))
  ->fetchField();

```
> 1 votes

---
Tags: database, entities
---


# Question
Title: theme_preprocess_node not working inside of a view
I'm trying to add a variable to the $classes array on a node, but it's not adding it while the node is in a view.

```
function MY_MODULE_preprocess_node(&$vars, $hook) {
  // Add the terms to the body classes for my_node_type'.

  if ($node = menu_get_object()) {
    if ($node->type == 'my_node_type') {

  // Return an array of taxonomy term ID's.
  $termids = field_get_items('node', $node, 'my_field_name');

  // Load all the terms to get the name and vocab.
  foreach ($termids as $termid) {
    $terms[] = taxonomy_term_load($termid['tid']);
  }

  // Assign the taxonomy values.
  foreach ($terms as $term) {
    $class = strtolower(drupal_clean_css_identifier($term->name));
    $vocabulary = drupal_clean_css_identifier($term->vocabulary_machine_name);
    $vars['classes_array'][] = $class;
   }
  }
 }
}

```

I added a

```
<?php dpm($classes); ?>

```

on my node.tpl.php I'm able to see the particular field being added to the classes array in my `<div class="my_field_name">`. But when it's in a view, the class isn't applied which makes me think that the preprocess\_node isn't being called properly. Any suggestions for what I should do or anything I'm missing that's preventing the hook\_preprocess\_node from being called properly? I've tried placing it into my theme's template.php instead of in the custom module I'm using but neither work.

**ANSWER NINJA EDIT** (can't post one for another 8 hours)

I was able to finally get it to call the classes properly. Appears that these conditions were not being met in the view:

```
if ($node = menu_get_object()) {
    if ($node->type == 'my_node_type') {

```

so I removed that line and instead replaced it with

```
$node = $vars['node'];

```

Removed the code from my custom module and placed it in my custom theme's template.php o the function now looks like this

```
function MY_THEME_preprocess_node(&$vars, $hook) {
  // Add the terms to the body classes for MY_NODE_TYPE'.
  $node = $vars['node'];

  // Return an array of taxonomy term ID's.
  $termids = field_get_items('node', $node, 'MY_FIELD_NAME');

  // Load all the terms to get the name and vocab.
  foreach ($termids as $termid) {
    $terms[] = taxonomy_term_load($termid['tid']);
  }

  // Assign the taxonomy values.
  foreach ($terms as $term) {
    $class = strtolower(drupal_clean_css_identifier($term->name));
    $vocabulary = drupal_clean_css_identifier($term->vocabulary_machine_name);
    $vars['classes_array'][] = $class;
 }
}

```

# Answer
> 1 votes
`$node = menu_get_object()` works only when the page you are seeing has a URL that is similar to node/12, or node/12/view. When you are watching a view, its URL is probably different.

That code is also not necessary, as template\_preprocess\_node() already initializes `$variables['node']` with the node object.

```
$variables['node'] = $variables['elements']['#node'];
$node = $variables['node'];

```

If you want to check if the node is being viewed in its own page, you can use the following code.

```
if ($variables['page']) {
  // The node is shown in its own page.
}
else {
  // The node is shown together other nodes.
}

```

`$variable['page']` is a variable set by `template_preprocess_node()`.

As side note, this is the code used by views\_plugin\_row\_node\_view::render() to render a node.

```
function render($row) {
  if (isset($this->nodes[$row->{$this->field_alias}])) {
    $node = $this->nodes[$row->{$this->field_alias}];
    $node->view = $this->view;
    $build = node_view($node, $this->options['view_mode']);

    return drupal_render($build);
  }
}

```

node\_view() is the function that calls the `theme_node()` theme function, causing preprocess/process functions to be called.

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


title: TinyMCE strips out audio tag

text:
# Question
Title: TinyMCE strips out audio tag
I'm using TinyMCE and I'm using the Full HTML format which shouldn't strip any tags. I copy another web page with an html5 audio tag in it and paste it into the editor. I can see the html5 audio player there, but when I save, it is stripped out.

I tried again and this time brought up the raw html editor and directly put the audio tag into the html. When I click Update, the audio tag is stripped out.

Here is my Full HTML text format config:

# Answer
> 1 votes
You need to deselect "Verify HTML" in the configuration page for the input format using Wysiwyg. Those settings are available in admin/config/content/wysiwyg.

Once I disabled that option, I tried with the following HTML, and it worked.

```
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mp3">
  Your browser does not support the audio tag.
</audio>

```

With that option enabled, this is what I get right after entering the HTML with the HTML button.

---
Tags: 7, wysiwyg
---


# Question
Title: Modifying contextual filters to display user name
I have a view that takes one contextual filter for a UID. I would like to make the title of the page include the user name? My closest bet it the "Override title" option under "When the filter value is in the URL or a default is provided". However, it appears that the only tokens available there are for the plain filter values, but I need the user name (as opposed to the UID). Is there a way to do this?

# Answer
> 1 votes
It appears that `%1` does actually return the title.

---
Tags: views
---


# Question
Title: Private files aren't blocking direct access to image files
I'm currently very confused by how private files work:

* I have a content type that has an image field and a file field. Both are set up to use private file access for their contents.
* Node access on the content type is working correctly.
* A user who does not have access to the node cannot get to the contents of the file field -- they get an access\_denied page when they try to load the URL of the file.
* However, they DO have access to the image file, via the image's url (/system/files/...): hitting the image URL in a browser brings it right up.

Are there any insights out there about why the image file is leaking through, and what I can do to stop it? I've explored hook\_file\_download and hook\_file\_download\_access, and have been putting watchdog statements throughout the image and files modules trying to track this down, but to no avail. Thanks!

# Answer
There are three implementations of hook\_file\_download(), in Drupal:

The first two implementations always check the user has access to the entity to which the file is associated; the third one doesn't check that, but it only checks the directory containing the file is the one used for the user profile's pictures.

```
function user_file_download($uri) {
  if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
    $info = image_get_info($uri);
    return array('Content-Type' => $info['mime_type']);
  }
}

```

If there isn't any other module implementing `hook_file_download()`, I would expect the users to be able to access the files through http://example.com/system/files when the URI points to the same directory containing the images used for the user accounts.
> 2 votes

---
Tags: 7, nodes, users, files
---


# Question
Title: How do I show nodes that share the same referenced node as the node page Im on?
Im on d7. I have two content types; Topics and Groups. There are 10 groups and when a user submits a topic, they choose a group to put it into. I use entity reference to connect the two content types. There is a ER field on the Topic content type where a user can choose up to 2 Groups for the topic to be in. On the Topic node page I need a block that shows all the other topics that are in the same Group.

**What Ive tried:**

I have a views block set up that shows the Groups content type. There is a ***Entity Reference: Referencing entity*** relationship and a ***Content: Nid*** contextual filter that uses the relationship.

I have just one field of ***Content:Title*** that is also using the relationship.

The only thing that is showing is the one same Topic who's node page im on (and there are more topics in the same group that should be showing).

Please help me figure this out. Thanks.

**Edit:**

Here is the way I have the view set up.

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_group_node']['id'] = 'reverse_field_group_node';
$handler->display->display_options['relationships']['reverse_field_group_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_group_node']['field'] = 'reverse_field_group_node';
$handler->display->display_options['relationships']['reverse_field_group_node']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'reverse_field_group_node';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'reverse_field_group_node';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] =
array(
'group' => 'group',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;

```

An example of what is happening is if there is 2 topics in a group, it will show the same topic that the node page is, two times.

# Answer
> 0 votes
Make sure that you set `Provide default value` in your contextual filter`(nid)` and set it

```
Content ID from URL

```

Also check *Require this relationship* in your entity relationship.

its works fine for me.

# Answer
> 0 votes
After playing with it over and over, the only way to accomplish what I needed was to use views field view. Using this way seem incredibly hackish so if anyone has a better way, please let me know.

---
Tags: views, entities
---


title: Why doesn't my code send emails?

text:
# Question
Title: Why doesn't my code send emails?
I am using the following code to send emails, but it doesn't work. What is wrong with it?

```
function yukerja_view_contact_import_form_submit($form, &$form_state){
  global $user;
  $c_user = user_load_by_name($user->name);
  $uid = $c_user->uid;
  $profile = profile2_load_by_user($uid, 'recruiter');
  $field = $profile->field_recruiter_company;
  $tid = $field['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  $company = $term->name;
  $query = db_select('import_contact');
  $query->fields('import_contact', array('name', 'email', 'company', 'operator_insert', 'status', 'matches'))
    ->condition('company', $company,'=')
    ->orderBy('name', 'ASC');
  $table = $query->execute();
  $a;
  $b;
  $email_user = array();
  foreach ($table as $key => $values) {
    $email_user[$key + 1] = array(
      'name' => $values->name,
      'email' => $values->email,
      'company' => $values->company,
      'operator_insert' => $values->operator_insert,
      'matches' => $values->matches,
    );
  }

  $params = array();
  foreach ($form_state['values']['table_user'] as $key => $value) {
    if(!$value == 0) {
      $email = $email_user[$key]['email'];
      $params = array(
        'name'            => $email_user[$key]['name'],
        'email'           => $email,
        'company'         => $email_user[$key]['company'],
        'operator_insert' => $email_user[$key]['operator_insert'],
        'matches'         => $email_user[$key]['matches'],
        'link_jobklik'    => 'http://dev.yukerja.gotpantheon.com',
        'subject'         => 'Invitation',
        'body'            => 'body tes',
        'from'            => 'as'
      );

      $module = 'yukerja_view_contact';
      $key = 'key';
      $language = language_default();
      $from = $params['operator_insert'] . "@jobklik.com";
      $send = FALSE;
      $message = drupal_mail($module, $key, $email, $language, $params, $from, $send);

      $message['subject'] = $params['subject'];
      $message['body'] = array();
      $message['body'][] = "Invitation";
      $message['body'][] = $params['link_jobklik'];

      // Retrieve the responsible implementation for this message.
      $system = drupal_mail_system($module, $key);

      // Format the message body.
      $message = $system->format($message);

      // Send e-mail.
      $message['result'] = $system->mail($message);
      // drupal_mail('yukerja_view_contact', 'invitation', $email, language_default(), $params, $params['from'], TRUE);

    }
  }
}

```

# Answer
I think your code is good enough to send email, but you need SMTP server to send the mail (which you has not specified), in case you have a mail server , the easy solution is install SMTP module which needs the SMTP server address and your are good to send email.

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

---
Tags: emails
---


# Question
Title: Responsive Layout of multi-page website in Adaptive Theme
I've read the book 'responsive web design' by Ethan Marcotte over the week & gone through the documentation on Adaptive Theme website, however, I'm confused about how to take responsive theming forward in Adaptive Theme when I have multiple web pages with their own CSS files.

From the documentation on Adaptive Theming, we have to split the CSS for each layout into its individual file (`responsive.smartphone.landscape.css`; `responsive.desktop.css`). Does that mean, we would have the full site CSS in one file for responsive.desktop.css? (! surely thats not right).

The way we have done thus far (in its current form, website is not responsive) is that there are small CSS files for each different regions/ areas of the page. In addition to this, we have custom modules with their own CSS files. How would we go about taking this mass of CSS files & distributing the code into responsive files in Adaptive Theme?

# Answer
Few days ago we(team) finished responsive-design site, what we done is simply write your desctop css in your css files like(blocks.css, field.css, node.css, etc..) and for ipad/smartphone version we used another css styles for portait and landscape versions like this:

```
ipad-landscape.css
ipad-portrait.css
ipad.css
smartphone-landscape.css
smartphone-portaint.css
smartphone.css

```

And int `html.tpl.php`

```
<!--[if !IE]>-->
  <link media="only screen and (max-width : 480px)"  href="/sites/all/themes/acro/css/layouts/responsive/smartphone.css" rel="stylesheet" type="text/css">
  <link media="only screen and (min-width : 321px) and (max-width : 480px)"  href="/sites/all/themes/acro/css/layouts/responsive/smartphone-landscape.css" rel="stylesheet" type="text/css">
  <link media="only screen and (max-width : 320px)"  href="/sites/all/themes/acro/css/layouts/responsive/smartphone-portrait.css" rel="stylesheet" type="text/css">

  <link media="only screen and (min-width : 481px) and (max-width : 1024px)" href="/sites/all/themes/acro/css/layouts/responsive/ipad.css" rel="stylesheet" type="text/css">
  <link media="all and (min-width: 769px) and (max-width: 1024px), all and (min-device-width:768px) and (max-device-width:1024px) and (orientation:landscape)" href="/sites/all/themes/acro/css/layouts/responsive/ipad-landscape.css" rel="stylesheet" type="text/css">
  <link media="all and (min-width: 481px) and (max-width: 768px), all and (min-width: 481px) and (max-width: 768px) and (orientation: portrait)" href="/sites/all/themes/acro/css/layouts/responsive/ipad-portrait.css" rel="stylesheet" type="text/css">
  <!--<![endif]-->

```

for specific pages we wrote css in this files.

*Update* Also we use sass and compass for css styles.
> 1 votes

# Answer
The more recent methods concerning responsive design is "mobile first". It's more time consuming to theme a desktop site and then bring it down it pieces to a mobile version, but some of this goes into the initial architecting as well. But, this is another topic.

You should keep your CSS as generic as possible at first, then drill down to specific items when you need to. Something you might want to look into is using a CSS preprocessor like LESS or SASS. On our projects (generally using LESS), we make CSS files for different regions of the site. Header, content, sidebar, footer, mobile, etc. and then compile them all into a few CSS files. In this screenshot, you can see the different sections broken up and they're all compiled into the global.css (the others are direct).
> 2 votes

# Answer
I use these css-files (e.g. responsive.smartphone.css) for the device-specific styles only, everything that applies for all devices goes into a "basics.css" or however you want to name it. The module-specific css stays where it belongs and in the css-file for a device-size are only the overrides of that...

I often work along the "desktop first" line and add the styles for the smaller devices afterwards. And if you have a complex layout, then the specific stylesheet can grow accordingly.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Programmatically assign a node to an organic group
How can I programmatically assign a node to an organic group?

I have tried the followings and non of them worked (assuming $target\_group is the group ID that I want the $node to be assigned to):

```
$node->og_groups = array($target_group => $target_group);
node_save($node);

```

,

```
$group = node_load($target_group);
$node->og_groups[0] = $target_group;
$node->og_groups_names[0] = $group->title;

```

What is the proper way to do this?

# Answer
> 2 votes
Assuming Drupal 7, you want to use the og\_group function in the API

```
/**
 * Set an association (e.g. subscribe) an entity to a group.
 *
 * @param $gid
 *   The group ID.
 * @param $values
 *   Array with the information to pass along, until it is processed in
 *   og_entity_presave(). Keys are:
 *   - "entity type": Optional; The entity type (e.g. "node" or "user").
 *     Defaults to 'user'
 *   - "entity" :Optional; The entity to set the association. Defaults to the
 *     current user if the $entity_type property is set to 'user'.
 *   - "state": Optional; The state of the association. Can be:
 *     - OG_STATE_ACTIVE
 *     - OG_STATE_PENDING
 *     - OG_STATE_BLOCKED
 *   - "save": Optional; TRUE if fields value should be saved. Defaults to TRUE.
 *   - "force reload": Optional; Determine if og_load_entity() should be used on
 *     the passed entity. This can be used when you pass an entity that has been
 *     saved yet to the database, but you want to assign it groups. Defaults to TRUE.
 *     // TODO: Adds docs on rest of keys.
 *
 * @return
 *   The entity with the fields updated.
 */
function og_group($gid, $values = array()) { ...

```

For your code, this would look like:

```
$values = array('entity type' => 'node', 'entity' => $node, 'state' => OG_STATE_ACTIVE);
og_group($target_group, $values);
node_save($node);

```

# Answer
> 1 votes
For Drupal 6, you can simple assign values to node object:

```
$gnode = node_load($gid);
$node = node_laod($nid);

$node->og_initial_groups[0][$gid];
$node->og_groups[0] = $gid;
$node->og_public = 0;
$node->og_groups_names[0] = $gnode->title;

```

In some cases the audience relationship doesn't store correctly if this is the case for you; you can insert a row to the og\_ancestry while saving the node.

```
if($node = node_submit($node)) {
  $node = node_save($node);
  $sql = "INSERT INTO {og_ancestry} (nid, group_nid) VALUES (%d, %d)";
  db_query($sql, $node->nid, $gnode->nid);
}

```

You are done. Check in node object.

---
Tags: nodes, organic-groups
---


title: Using Carousel without module

text:
# Question
Title: Using Carousel without module
I want to use jCarousel plugin or similar. But I do not want to use the module.

Add content will form part of and the carousel will add pictures. How can I do? Does anyone have an idea?

# Answer
You can do this on the theme level.

Your obviously going to want to setup the content using the CMS so will take the form of nodes.

You can then use a process function to determine what content type you are on for applying your script, for example...

```
function YOURTHEME_preprocess_node($variables) {
   if ($SOME_NODE) {
      // Add JS plugin...
   }
}

```

You can then create template files for node or specific fields in that node with markup that the plugin can manipulate.

```
node--[CONTENT_TYPE].tpl.php

```

To be honest, take Clives advice, use the modules, thats what makes Drupal what it is.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Embed rate number up down widget in panel node
I am using rate module and the number up down widget, and in the settings for this module I had set it to appear at the top of content. It was appearing fine. However, now I am using a panel for this node and the widget no longer appears as expected. I need to embed it into my panel. How would I go about this? I have done a few searchs and found rate\_embed, but I am not having any luck getting this to work. I have tried the following. My rate widget is called 'points', and its settings are at /admin/structure/rate/:

function:

```
<?php rate_embed(&$node, $machine_name, $mode = RATE_FULL); ?>

```

What I tried:

```
<?php print rate_embed($node, 'points', $mode = RATE_FULL); ?>
<?php echo rate_embed($node, 'points', $mode = RATE_FULL); ?>

```

this was giving an error that rate\_embed was acting on a non-object.

# Answer
You can try the following code.

```
 $up_down = rate_generate_widget('1', 'node', {current node id}, RATE_FULL, TRUE, FALSE, NULL);
 print render($up_down);

```
> 3 votes

---
Tags: rating
---


title: db_select() returns an array

text:
# Question
Title: db_select() returns an array
I have just started using Drupal 7 and `db_select()`.

if I have a result from `db_select()` (e.g. `$result = $query->execute()`, why can I only loop through this result once?

It appears as if there is a cursor that is not reset following a foreach loop.

So I tried to find a function that would convert this result into a multi dimensional array (e.g. `$result = $result->fetchAllAssoc()`) but I have found nothing.

Instead, at the moment I have to loop through the result to create an array of row objects to use later through the code (if i need to loop through it more than once)

```
/* this returns an array of row objects that you can use like any other array but seems as though there should be an API function to do this for me as part of the database class ? */

$array = array();
foreach($result as $row) {
  $array[] = $row;
}

```

Surely there must be an API function to do this already.

# Answer
I don't have a Drupal 7 dev environment handy to try this on, but I think you are looking for fetchAllAssoc(), as you mentioned. This page has some query examples that are helpful.

When you call `fetchAllAssoc()`, you need to specify a field name as the primary key of the array, like:

```
 $result->fetchAllAssoc($field);

```

It also appears that fetchAll() will work (but apparently it is not the recommended solution).
> 10 votes

# Answer
Yes there is an issue with fetchAll() or fetchAssoc() you havent use either of it just writing execute() will give u only one result that will be something like below

```
[dbh] => DatabaseConnection_mysql Object
    (
        [shutdownRegistered:protected] =>
        [target:protected] => default
        [key:protected] => default
        [logger:protected] =>
        [transactionLayers:protected] => Array
            (
            )

        [driverClasses:protected] => Array
            (
                [SelectQuery] => SelectQuery
                [UpdateQuery] => UpdateQuery
                [InsertQuery] => InsertQuery_mysql
            )

        [statementClass:protected] => DatabaseStatementBase
        [transactionSupport:protected] => 1
        [transactionalDDLSupport:protected] =>
        [temporaryNameIndex:protected] √ 0
        [connectionOptions:protected] => Array
            (
                [database] => pcl
                [username] => inhouse
                [password] => abcd!234
                [host] => localhost
                [port] =>
                [driver] => mysql
                [prefix] => Array
                    (
                        [default] =>
                    )

            )

        [schema:protected] =>
        [prefixes:protected] => Array
            (
                [default] =>
            )

        [prefixSearch:protected] => Array
            (
                [0] => {
                [1] => }
            )

        [prefixReplace:protected] => Array
            (
                [0] =>
                [1] =>
            )

    )

    [queryString] => SELECT u.uid AS uid, u.name AS name
      FROM profile p
      INNER JOIN users_roles ur ON p.uid = ur.uid
      INNER JOIN field_data_field_client fcl ON p.pid = fcl.entity_id
      INNER JOIN field_data_field_category fca ON p.pid = fca.entity_id
      INNER JOIN users u ON p.uid= u.uid
      WHERE  (ur.rid = :db_condition_placeholder_0) AND (fca.field_category_tid = :db_condition_placeholder_1) AND (fca.bundle = :db_condition_placeholder_2) AND (fcl.field_client_tid = :db_condition_placeholder_3)
      GROUP BY ur.uid
    )

```

So the solution is to use either `fetchAll()`, or `fetchAssoc()` in case you want a `key => value` pair array.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Rules send email containing tokens from submitted node displays token for empty field
I have a rule that sends the contents of a node to an email address on save, I am including the contents of the mail with tokens. However, if the field is blank then instead of not showing, the token itself shows in the email. Is there any way to prevent this from happening, or include all the fields in one token?

# Answer
> 1 votes
you may use **PhP** in your send mail rule action to check if your field is empty.

Be careful it's a bit tricky because token is not actually *empty* when the field is empty, it's just not computed, as you saw when you tested.

Unfortunately, the token will be rendered, if field not empty, whatever you put around it in PhP, even ' or ".

So, it's not really clean, but the way I see it is **explode** and then check whatever you want (for my part I use here only the first part, "\[node") :

```
<?php
// Explode your token (or your value, you don't know yet)
$a = explode(':',"[node:body]");

// Check if first part is [node
if($a[0] != '[node') { ?>

[node:body]

//Don't forget to close the if() statement
<? } ?>

```

Not very good if you have to check this on many fields, NOT CLEAN at all in fact, but working :D

---
Tags: 6, rules, tokens
---


# Question
Title: What are the options for an e-card wizard module?
I am looking at creating an e-card wizard and would like to know if there are any modules that exist which would help with this. A link should be added to a node and then the user should be able to create an e-card using information from this node. They need to be able to select a theme/image for the card, add a caption, add their email and the recipients email and then send it. Options to then share this with Facebook or Twitter etc should then be available.

Anyone done anything similar before?

# Answer
Take a look at ecards module

As mentioned in the page, you can see a demo on http://www.mahlove.com/friendship-day/friendship-day-ecards/160
> 1 votes

---
Tags: 7
---


title: add custom design to Views Row

text:
# Question
Title: add custom design to Views Row
i need to add custom css id/class to views row after row first. example:

in default i see this :

```
<div class="views-row views-row-1 views-row-odd views-row-first"></div>

<div class="views-row views-row-2 views-row-even"></div>

<div class="views-row views-row-3 views-row-odd views-row-last"></div>

```

Now, I need change this to:

```
<div class="views-row views-row-1 views-row-odd views-row-first"></div>

<div id="leftCol" class="views-row views-row-2 views-row-even"></div>

<div id="leftCol" class="views-row views-row-3 views-row-odd views-row-last"></div>

```

Actually i need to print result like this:

```
 <div>views-row-first</div> <-- example: 100% width

 <div>views-row-even</div> <-- example: 50% width + <div> views-row-last</div> <-- example: 50% width

```

With this i combination of one and two columns. 100% width and one column for first row And at the bottom 2\*50% and two column for other(even/odd/last). How to?

**NOTE:** i work with content-node / unforrmatted list.

# Answer
Why dont you just add the 100% to `views-row-1` and width: 50% to `views-row`? I believe that you do it like this:

```
.views-row {
  width: 50%;
  //other css
}

.views-row-1 {
  width: 100%;
}

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: populating field A with content of field B
I have a content type with several fields, e.g. phone1 and phone2.

I would like to populate another type of field, "table\_field", with values from the first two automatically, on creation of an instance of this content type.

What would be the best way? Can I utilize tokens to do this? Thanks for your time, I appreciate it. This is my first project. Huge learning curve, and am enjoying it.

# Answer
> 4 votes
In Drupal 6 you could use Computed Field for that, but unfortunately it's not completely ready for Drupal 7 yet.

You could also create a custom module in which you implement hook\_node\_presave to set the value of 'field A' based on the value of 'field B'. When you choose this method, you may also want to implement hook\_form\_alter to hide field A from the node form.

# Answer
> 3 votes
Now computed field has Drupal 7 version, I compare it with dynamic field and I it's it's better. Check out this post: Calculate Field Values Using Computed Field in Drupal 7.

And here's an example of using hook\_node\_presave:

```
function MODULE_NAME_node_presave($node){
  if ($node->type === 'NODE_TYPE'){
    $node->FIELD_COMPUTED['und'][0]['value'] =
    $node->FIELD_COMPUTED_A['und'][0]['value'] +
    $node->FIELD_COMPUTED_B['und'][0]['value'];
  }
}

```

---
Tags: tokens
---


# Question
Title: What is the difference between panel and blog in Drupal?
I am trying to find content holder for my site home page and came across the concept of panels. But I didn't found anything for user permission in panels.

Can anyone help me understanding the difference between panel and blog around user permission?

# Answer
Panle can load many things and you can set permission of each block or something that panel is loading. SO its would be better if you use panels and filter with roles that you want. You need to clearly define the question !!
> 0 votes

# Answer
Panel is a type of node that can use pre-defined templates for layout and CSS. A panel can contains multiple references to node.

A Blog Page is an other type of node. You can add content HTML in this type of node, with a title and a teaser. If you want to style the content, you should make CSS ans HTML.

Panel is simplest but louder. For the security, they are both Node ...

A Block is a zone that can contain different kinds of content; text, (part of ) menu, ...

Here is a little presentation about block and panel on slideshare
> 0 votes

---
Tags: 7, users
---


# Question
Title: why my code is not work on block body drupal
```
function confirm_form($form, &$form_state) {
  global $user;
  $c_user=user_load_by_mail($user->mail);
  $query = db_select('import_contact');
  $query->fields('import_contact', array('name', 'email', 'company', 'operator_insert', 'status', 'matches'))
    ->condition('email', $c_user->mail,'=')
    ->condition('status', 'pending', '=');

  $bolean = $query->execute();
  $data = $bolean->fetchAssoc();
  $check = $bolean->rowCount();

  if(!$check = 0) {
    $data = $bolean->fetchAssoc();
    $nama = $data['name'];
    $company = $data['company'];
  }

  echo "you have been invited by " . $company ".to join.";

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

```

# Answer
The most evident errors are:

* confirm\_form() is a Drupal function; you cannot define a function with that name.
* There isn't any reason to use `user_load_by_mail($user->mail)` when you need only `$user->mail`, and you can use `$user->mail` directly, which is what your code is already doing.
* `!$check = 0` is assigning `0` to `$check` and then checking `$check` is not zero. What you want is `!check`.
* A form builder should never use `echo`. `echo "you have been invited by " . $company ".to join.";` contains an error, as you moved the concatenation operator inside the string to the right, and PHP is complaining about that.
> 2 votes

---
Tags: forms, blocks
---


# Question
Title: After forced login, return to first entered login
I have situation where i redirect user programatically on condition. After condition is met:

```
drupal_goto('http://www.mydomain.com/user/login');

```

But what it does, it forgets path that was initially entered by user.

Is there a way to redirect user to login (programatically), but to remember url ? (as it works when you try to login to admin area).

BTW, i have Login Tobbogan also installed. (Drupal 7)

Thanks!

# Answer
> 1 votes
I take you want to redirect the user from the login page to the page where you are checking the condition. If this is the case, the code you should use is the following one.

```
drupal_goto('user/login', array('query' => array('destination' => $GET['q'])));

```

Otherwise, if you want to redirect the users to the destination set from other modules, when there is one, or the current page, then the code should be similar to the following one.

```
drupal_goto('user/login', array('query' => drupal_get_destination()));

```

Remember that the first two parameters accepted from `drupal_goto()` are the same parameters accepted from url().

# Answer
> 1 votes
I believe the correct way to do this is:

```
drupal_goto('user/login', array('query' => drupal_get_destination()));

```

The documentation for drupal\_get\_destination() states:

> Prepares a 'destination' URL query parameter for use with drupal\_goto().
>
> Used to direct the user back to the referring page after completing a form. By default the current URL is returned. If a destination exists in the previous request, that destination is returned. As such, a destination can persist across multiple pages.

Update: You could try putting the URL in directly:

```
$path = 'path-to-redirect-to'; // or $GET['q']
drupal_goto('user/login', 'query' => array('destination' => $path)));

```

---
Tags: users
---


# Question
Title: How do I create a Rule "When role is removed, send email to the user"?
I am trying to create a rule that sends an email to the user when a role has been removed from their account. I can't seem to find a rule reaction under User "When role is removed". How do I create a rule to do this?

# Answer
It has to be triggered when a particular role ("subscriber") has been removed. So we can use 2 conditions **User has role(s)**, to check if he had the role *before the edit*, and that he doesn't have it *after the edit* :

1st condition : selector "account\_unchanged", check the role "subscriber" (here test)

2nd condition : selector "account", check the same role, and **negate**.
> 8 votes

---
Tags: rules, users
---


# Question
Title: Page not found without record about page
Is there a way to find the source of an error that I have on my production site during the last few days? In reports/dblog I see an error "Page not found" but there is no any information about what page, source, time of this error.

**EDIT** I looked in phpmyadmin and saw the source of the problem. The error appears when user reposts node in livejournal. I don't know is it a big problem for website or not (I mean problems with perfomance or search engines). Does anyone know the answer on this last question?

# Answer
> 0 votes
Is it something you're experiencing personally or are you just looking at the logs?

If you're just looking at the logs, it's usually a spammer/bot/crawler that's triggering the response. There are some security modules you can install that gives you a little more insight into those kinds of things (such as the IP address that triggered it), but I can only think of the D6 ones right now.

# Answer
> 0 votes
The problem was in open graph meta property="og:url" with token \[site:url\]. In practice it was looking like example.com/ and as there is no page on my site with url example.com/ (there is example.com without slash) drupal recorded it as an error 404 when people came from other sites where the link was posted

---
Tags: 7
---


title: synchronization on 2 ubercart instances

text:
# Question
Title: synchronization on 2 ubercart instances
Because of problems with multi-currency ubecart, I am thinking about creating 2 identical e-shops for 2 countries with different currencies. One important thing worries me - stock levels. Is there any way to synchronize stock levels data between multiple drupal/ubercart installations? Thank you very much.

# Answer
Yes in the stock module is a function for set stock level and you also need a custom xml-rpc client/server functions for both instances.
> 2 votes

---
Tags: ubercart
---


title: Dealing with MySQL database quotas

text:
# Question
Title: Dealing with MySQL database quotas
I have my Drupal site hosted at a society that gave me a 400M database quota. After 4 weeks of production, it has reached 100M. I predict that after a year, it will reach the limit.

Is any way to reduce the database size, so I don't have problems with my quota?

# Answer
You could just shrink the database by optimizing every MyISAM you have

You can use to monitor how much space you database is taking up (in MB):

```
SELECT
    IFNULL(dbtb,'Total') tablename,
    (datsize+ndxsize)/power(1024,pw) table_size
FROM
(
    SELECT CONCAT(table_schema,'.',table_name) dbtb,
    data_length datsize,index_length ndxsize
    FROM information_schema.tables
    WHERE table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) A,(SELECT 2 pw) B
GROUP BY dbtb WITH ROLLUP;

```

This will add up all used data and index space.

I have other queries for measuring the amount of used space for MyISAM and InnoDB

If there is significant difference between in these queries' output and what your OS says you are using, try shrinking each individual table as follows:

```
SELECT CONCAT('OPTIMIZE TABLE ',dbtb,';') OptimizeCommand
FROM
(
    SELECT CONCAT(table_schema,'.',table_name) dbtb
    FROM information_schema.tables
    WHERE table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) A;

```

Export the output of this query to a SQL text file and run it:

```
SQLFILE=/tmp/OptimizeSQLScript.sql
SQLCMD="SELECT CONCAT('OPTIMIZE TABLE ',dbtb,';') FROM ("
SQLCMD="${SQLCMD} SELECT CONCAT(table_schema,'.',table_name) dbtb "
SQLCMD="${SQLCMD} FROM information_schema.tables WHERE table_schema NOT IN "
SQLCMD="${SQLCMD} ('information_schema','mysql','performance_schema')) A"
mysql -u... -p... -ANe"${SQLCMD}" > ${SQLFILE}
mysql -u... -p... < ${SQLFILE}

```

An even faster way without fancy parsing would be to mysqldump the entire dataset and reload it

```
mysqldump -u... -p... --all-databases --routines --triggers > mydata.sql
mysql -u... -p... < mydata.sql

```

Give it a Try !!!
> 2 votes

---
Tags: database
---


# Question
Title: Jump Menu Style Dropdown To External Links
I'm attempting to create a jump menu of links to external websites, and I would like to be able to order the links within this menu differently depending on the organic group of the current user attempting to access it. So far I've tried to accomplish this using views with nodequeue, and have come somewhat close, but its beginning to feel like a dead end.. Does any module(or combination of modules exist) which would allow me to accomplish this without having to write my own? Ideally each will be able to reorder the links according to their personal preference and override the default ordering of links. but that is not essential at this point

# Answer
> 0 votes
you could create a node type link and a Views jump menu that loads said node types.

---
Tags: views, 7, routes, users
---


title: How can I restore removed menu items?

text:
# Question
Title: How can I restore removed menu items?
I create a menu "XXXX" move "Create content" and all of it's children to "XXXX" then remove XXXX menu. now I miss "Create content", how can I restore them?

# Answer
> 2 votes
You can execute the following query.

```
if ($mlid = db_query("SELECT mlid from {menu_links} WHERE link_path = :path AND menu_name NOT LIKE :menu", array(':path' => 'node/add', ':menu' => db_like('shortcut-set-') . '%'))->fetchField()) {
  db_update('menu_links')
    ->fields(array('menu_name' => 'navigation', 'plid' => 0))
    ->condition('mlid', $mlid)
    ->execute();
  db_update('menu_links')
    ->fields(array('menu_name' => 'navigation', 'plid' => $mlid))
    ->condition('link_path', db_like('node/add/') . '%', 'LIKE')
    ->condition('menu_name', db_like('shortcut-set-') . '%', 'NOT LIKE')
    ->execute();
}
else {
  // There isn't any row for node/add.
}

```

What the code does is the following.

* It finds the database row where the link path is node/add, and where the menu name doesn't start with shortcut-set-, which is the menu name used from the Shortcut module for its shortcut sets; as the default shortcut set used from that module contains a link that points to node/add, the code exclude that link. If there are other rows that would point to node/add, you need to edit the first query to exclude them.
* For the row found from the first query, it changes the menu name to navigation, and plid (the parent link ID) to 0.
* For any row whose link path matches the SQL regular expression node/add/%, it sets plid to the mlid previously found.

In the code I used `db_like()`, even in this case was not strictly necessary. The purpose of `db_like()` is escaping any character that for the SQL regular expressions has a specific meaning. Suppose that I would change the code to find any database row whose link path is node/%, where % is the character that is really present in the link path; without `db_like()`, the query would find any row where the link path starts with node/, which would include more rows than the ones where the link path is node/%.

As the code is using two update queries, it should use transactions. In that way, if the second query would fail, the database would be left in a consistent state, which means that the rows for node/add, and node/add/\[content type\] will be part of the same menu. If the first query is executed, and the second one fails, you would have node/add that is part of a menu, while any node/add/\[content type\] link would be part of a different menu (or some of the node/add/\[content type\] links will be part of a menu, and other node/add/\[content type\] links will part of another menu).

```
if ($mlid = db_query("SELECT mlid from {menu_links} WHERE link_path = :path AND menu_name NOT LIKE :menu", array(':path' => 'node/add', ':menu' => db_like('shortcut-set-') . '%'))->fetchField()) {
  $transaction = db_transaction();
  try {
    db_update('menu_links')
      ->fields(array('menu_name' => 'navigation', 'plid' => 0))
      ->condition('mlid', $mlid)
      ->execute();
    db_update('menu_links')
      ->fields(array('menu_name' => 'navigation', 'plid' => $mlid))
      ->condition('link_path', db_like('node/add/') . '%', 'LIKE')
      ->condition('menu_name', db_like('shortcut-set-') . '%', 'NOT LIKE')
      ->execute();
  }
  catch(Exception $e) {
    // One of the queries failed; rollback the database to the previous status.
    $transaction->rollback();
  }
}
else {
  // There isn't any row for node/add.
}

```

PS: As the only way to find the menu item is too look for its link path, there could be more than one row using that link path. It is important the code excludes those rows that are not the correct one, and that is what my code does when it excludes the rows there the menu name starts with shortcut-set-. Unfortunately, it is not possible to write code that generic enough to work in any condition.

---
Tags: 7, routes
---


# Question
Title: What is the first function read by Drupal in a custom module?
I've got a custom module working fine in Drupal 7.

In some pages, I have parameters in the URL that I'd like to get in order to perform certain actions.

For example, if a=logout or a=forgot\_password or a=subscribe.

I'd like to know which function, in the mymodule.module file, is called first so I can check whether there's a special parameter and perform certain actions accordingly ?

Thanks in advance!

# Answer
> 8 votes
The first hook invoked is hook\_boot(), if the Drupal variable page\_cache\_invoke\_hooks is `TRUE`, otherwise is hook\_language\_init() (followed by hook\_init()).

I am assuming the module is not implementing alternative versions of bootstrap functions; in that case, the version of `cache_get()` implemented by the module is called first.

About `hook_boot()` keep in mind that:

* `hook_boot()` is invoked too early, when Drupal has not completed its bootstrap. This means that the only loaded modules are the ones implementing `hook_boot()`. Even in this case, your module can use function implemented from modules implementing `hook_boot()`, and already loaded from Drupal, which uses the following code.

```
foreach (module_list(FALSE, TRUE) as $module) {
  drupal_load('module', $module);
  module_invoke($module, $hook);
}

```

If your module is aaaa.module, and it tries to call `zzzz_create_object()` (where zzzz.module implements `hook_boot()`) from `aaaa_boot()`, `aaaa_boot()` will cause an error message about a not existing function.
* When `hook_boot()` is invoked, Drupal has not yet initialized its database, its Drupal variables (only when `$conf['page_cache_without_database']` is `TRUE`), and its session.

As consequence, the functions `hook_boot()` can call are restricted. For sure, the functions the hook can call are the ones that are part of bootstrap.inc, and all the PHP functions (with some restrictions too).

### References

---
Tags: bootstrapping
---


# Question
Title: Only require comment approval when an image is attached
I am working on a project that allows user commenting without administrator approval if they post only text; however, if the user decides to attach an image to their comment, the comment should require approval first before being published. What is the best way to approach this?

# Answer
I got this working using the Mollom module.

In Mollom's configuration, you can enable spam filtering and set up your own blacklist terms for the spam filter. I created blacklist terms for **\<img** and **"media-image"** (TinyMCE's encoded image class). Then I told Mollom to "Retain the post for manual moderation" if it gets detected as spam.
> 0 votes

# Answer
You can create a module to do this by using the hook\_comment\_presave hook. If your module name is playx, then try this code:

```
function playx_comment_presave($comment) {
  if(strstr($comment->comment_body[$comment->language][0]['value'], '<img')){
   $comment->status = 0;
 }

```
> 0 votes

---
Tags: comments
---


# Question
Title: How can I pass $title a node variable to html.tpl.php?
I'm looking to use the variable $title in my html.tpl.php file. How can I do this?

I would like to just write a bit of php like so:

```
<?php print $title ?>

```

So is a preprocess function needed? TPLNAME\_preprocess\_html() { ??? something like that?

I would like to reference this question here which got me thinking, what is the proper way?

Helpful Question That I Saw

# Answer
```
// template.php
function THEMENAME_preprocess_html(&$vars) {
  $vars['title'] = 'my title';
}

// html.tpl.php
echo $title;

```

http://drupal.org/node/223430
> 8 votes

# Answer
If you are wanting $title to be the node title of the current page (if it is a node page), which you mentioned in a comment above, you can do this in your theme's template.php:

```
/**
 * Override or insert variables into the html templates.
 */
function THEMENAME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['title'] = check_plain($node->title);
  }
}

```
> 6 votes

---
Tags: theming
---


# Question
Title: Taxonomy Term Page is showing the same body for all nodes
I'm converting my old site to drupal and updating my Teaser view mode so that the nodes appear as I want them on the Taxonomy Term page.

http://dev.inadaydevelopment.com/tags/ipad

The problem is that the Body field for all of the nodes is showing up with the same text. The nodes do not have the same body text, so I have no idea how or why all of these Teasers are showing the same body text.

Any idea?

# Answer
Found the problem. Some poorly written jQuery was dynamically swapping out the body tags. Blerg.
> 0 votes

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


title: Deleting nodes makes orphan records

text:
# Question
Title: Deleting nodes makes orphan records
I have a content type "event" which has an image field.
I tried to deleted the nodes, but I got the repeated errors when deleted the nodes.

> > Warning: array\_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 178 of D:\xampp\htdocs\mysite\includes\entity.inc).

I did not use any hook to delete nodes. I just deleted the nodes from the page "admin/content" by selecting "Delete selected nodes" in the UPDATE OPTIONS.

I checked the node related tables including field tables and I found that they were deleted as expected. When I tried to query the file tables, I found that some records were not deleted and the files in the file directory were not deleted too.

**BEFORE DELETE**

```
mysql> select * from file_usage where id = 41 order by fid;
+--+--+--+--+--+--+--+--+--+--+--+--+--++
| fid | module      | type | id | count |
+--+--+--+--+--+--+--+--+--+--+--+--+--++
| 30  | file        | node | 41 | 1     |
| 31  | file        | node | 41 | 1     |
| 32  | file        | node | 41 | 1     |
| 172 | file        | node | 41 | 1     |
+--+--+--+--+--+--+--+--+--+--+--+--+--++

mysql> select fid, filename, uri from file_managed where fid in (30,31,32,172);
+-----+------------------------------------+-----------------------------------------------+
| fid    | filename                        | uri                                           |
+-----+------------------------------------+-----------------------------------------------+
|    30  | Festival.jpg                    | public://Festival_0.jpg                       |
|    31  | Festival.jpg                    | public://Festival_1.jpg                       |
|    32  | Festival.jpg                    | public://Festival_2.jpg                       |
|    172 | Festival_465x350.jpg            | public://Festival_465x350_0.jpg               |
+-----+------------------------------------+-----------------------------------------------+

```

**AFTER DELETE**

```
mysql> select count(*) from node where type = 'event';
+----------+
| count(*) |
+----------+
| 0        |
+----------+

mysql> select * from file_usage where id = 41 order by fid;
+--+--+--+--+--+
| fid | module | type | id | count |
+--+--+--+--+--+
| 30 | file | node | 41 | 1 |
| 31 | file | node | 41 | 1 |
| 32 | file | node | 41 | 1 |
+--+--+--+--+--+

mysql> select fid, filename, uri from file_managed where fid in (30,31,32);
+-----+---------------------+-------------------------------+
| fid    | filename         | uri                           |
+-----+---------------------+-------------------------------+
|    30  | Festival.jpg     | public://Festival_0.jpg       |
|    31  | Festival.jpg     | public://Festival_1.jpg       |
|    32  | Festival.jpg     | public://Festival_2.jpg       |
+-----+------------------------------------+----------------+

```

They became orphan. What could that be why they are not deleted as expected?
Is there any fix for this? My Drupal version is 7.15.

# Answer
> 1 votes
Incidentally, I got this error yesterday ;-) And after a bit of searching and looking into the documentation, I found that the cause was the functions which loads entities in Drupal and with the name like `something_load`(e.g. `node_load()`). I was using `node_load()` function to load the node and then delete it using node\_delete\_multiple().

This error was caused because, I was passing array as an argument to `node_load()`, by something like `user_load(array("...`; which is not the right way to do it.
The argument to `anything_load()` function **must** be a single id. So, you can search for the `_load` functions which uses array as an argument in your code.

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


title: Theming a custom form

text:
# Question
Title: Theming a custom form
I have themed Drupal7 forms, cannot do the same with 6 ...

I have:

```
function _my_form() {
    $output="";
    $form=drupal_get_form("my_form");
    $output=theme("my_form",
        array(
            "element"=>array(
                "my_form"=>$form
            )
        )
    );

    return $output;

}

function MYMODULE_theme()
{
    $themes = array(
        'MY_form' => array(
            'template'=>'my_form',
            'variables' => array('element' => NULL)
        )
    );
    return $themes;
}

```

If i do a var\_dump($element\["my\_form"\]) in my\_form.tpl.php i only get a superlong string with the html form already rendered, while i expected to have an array with all the single form fields... what am i doing wrong?

# Answer
i think you should return a render array in your theme function
`array('render element' => 'form')`
> 0 votes

# Answer
Try this

```
   function _my_form() {
     return drupal_get_form("my_form");
    }

   function MYMODULE_theme()
    {
    $themes = array(
      'my_form' => array(
        'render element' => 'form',
        'template' => 'templates/my-form',
      )
    );
    return $themes;
   }

```
> 0 votes

---
Tags: 6, forms, theming
---


# Question
Title: Modifying CSS class of Menu Block links?
The Menu Block offers several hooks to override the markup it generates:

```
#theme:
  menu_link__menu_block__1
  menu_link__menu_block__main_menu
  menu_link__menu_block
  menu_link__main_menu
  menu_link

```

However, the variables don't seem to be passed by ref, and if I don't return any string, the links render out null. So, what should I do if I want to just append a custom class to the links and then render them just the default way?

I tried something like in template.php:

```
function MYTHEME_menu_link__menu_block($variables){
  $variables['element']['#attributes']['class'][] = 'my-class';
  return theme('menu_link__menu_block', $variables['element']['#original_link']);
}

```

but it causes fatal error.

Any help please?

# Answer
> 0 votes
You would need to copy the whole function. There is a good example on the theme\_menu\_link() page.

You could also check out the Menu attributes module which allows you to add classes to individual menu items.

# Answer
> 0 votes
If you need to add class to the anchor link then use this module. menu\_attributes

If you need to add class in li then use theme\_menu\_link

```
function YOURTHEME_menu_link__main_menu($variables){}

```

If you need to add class in ul then use theme\_menu\_tree/

```
function YOURTHEME_menu_tree__main_menu($variables){}

```

---
Tags: theming, navigation, blocks
---


title: Get path of Page Manager page

text:
# Question
Title: Get path of Page Manager page
Basically I have created a page and it shows up fine.

When I do a `arg` or `current_path` on that page it shows as a 404 path, not the one defined in the page.

```
current_path() => error-404
$_GET[q] => error-404
arg() => array(0 => error-404)

```

Is there a function that returns the path/URL that is set in the Page?

# Answer
Node that `current_path()` returns the URL path of the current page, not the URL. So on the `http://www.example.com/latest-deals` page it will return just `latest-deals`.

If you need to convert that to an actual URL, use `url(current_path())`, which will return `/latest-deals`. Or `url(current_path(), array('absolute' => TRUE))` if you need the absolute URL.
> 0 votes

# Answer
`current_path()` will return the path of the panel page.

The problem I was having was that we are using panels layouts for 404 pages as well. I had a missing file in the theme layer that was generating a 404 error and that was getting picked up and overriding current path for the page.
> 0 votes

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


# Question
Title: Render comment parts individually with Panels/Page manager?
Is there any way to create panels template for comments (comments attached to node). So far I've only found that "Node comments" thing under the node tab (Variants -\> content) which outputs default comments and Mini panels block which renders only one comment from random node.

I'm trying replace forum node template with panels and render node and comments with same layout.

Thanks.

# Answer
There's no out of the box solution for doing this today.

If you look at a file like `ctools/plugins/content_types/node_context/node_links.inc` you'll see how it's done for nodes and their links. The other files in the same directory do the same but to different pieces of nodes. For historic reasons, there's a lot of `Node` specific content in there.

Today it should be possible to generalize the same approach onto all entities, but as far as I know, that hasn't happened anywhere.
> 0 votes

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


# Question
Title: file or image migrate from drupal 6 to drupal 7 using Migrate D2D module?
I am using migrate\_d2d module to migrate my Drupal 6 website to Drupal 7, I succeed to transfer every thing except for images.

I read the new documentation sever times and I managed to migrate the files into the file\_managed but I cant link them with the nodes any hints or examples will be greatly appreciated

# Answer
In your migrate register function define the files table migration.

```
/**
 * Migrate files table
 */
// The description and the migration machine name are also required arguments,
// which will be unique for each migration you register.
$file_arguments = $common_arguments + array(
  'description' => t('Migration of files from Drupal 6'),
  'machine_name' => 'Files',
  'source_dir' => '/var/www/drupal6/files/xxxx/',
);

// We just use the migrate_d2d D6 migration class as-is.
Migration::registerMigration('DrupalFile6Migration', $file_arguments['machine_name'],
$file_arguments);

```

Then in your node migration class set the files migration as the source.

```
// Map the image field to the new image field, base this on the Files migration
// to map the files to the imported files table.
$this->addFieldMapping('field_image', 'field_image')
  ->sourceMigration('Files');
$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');

```

Hope that helps
> 4 votes

# Answer
Migrating images and files are similar. Check this: Migrate Contents from Drupal 6 to Drupal 7 Using Migrate 2

Here's the pieces of code for images and files migration. You can put it in your migration class and remember to change the database name, field names, urls to yours.

```
<?php
// Add other source fields which may be populated in prepareRow()
$source_fields = array(
  'image_filename' => t('img_filename'),
  'attachments_filename' => t('attachments_filename'),
  'attachments_filepath' => t('attachments_filepath'),
  'attachments_description' => t('attachments_description'),
);

// Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query, $source_fields);

$this->addFieldMapping('field_image', 'image_filename');
$this->addFieldMapping('field_image:source_dir')->defaultValue('http://DOMAINNAME.COM/sites/default/files/THE_DIR_YOU_PUT_IMAGES');

$this->addFieldMapping('field_attachments', 'field_attachments');
$this->addFieldMapping('field_attachments:source_dir', 'field_attachments_filepath');
$this->addFieldMapping('field_attachments:description', 'field_attachments_description');

public function prepareRow($current_row) {
  // Set image data for the image fields.
  $query = db_select(SOURCE_DATABASE . '.content_type_NAME', 'i')
  ->condition('i.vid', $current_row->vid, '=');
  $query->join(SOURCE_DATABASE . '.files', 'f', 'i.field_image_fid = f.fid');
  $query->addField('f', 'filename');
  $result = $query->execute();

  foreach ($result as $row) {
    $image = array(
      'filename' => $row->filename,
    );
    $current_row->image_filename = $image['filename'];
  }

  // Set file data for the attachment file fields.
  $query = db_select(SOURCE_DATABASE . '.content_field_attachment', 'a')
    ->fields('a', array('field_attachment_data'))
    ->condition('a.vid', $current_row->vid, '=');
  $query->join(SOURCE_DATABASE . '.files', 'f', 'a.field_attachment_fid = f.fid');
  $query->addField('f', 'filename');
  $query->addField('f', 'filepath');
  $query->orderBy('a.field_attachment_fid', 'ASC');
  $result = $query->execute();

  foreach ($result as $row) {
    $field_data = unserialize($row->field_attachment_data);
    $field = array(
      'filename' => $row->filename,
      'filepath' => str_replace($row->filename, '', $row->filepath),
      'description' => $field_data['description'],
    );
    $current_row->attachments_filename[] = $field['filename'];
    $current_row->attachments_filepath[] = 'http://DOMAINNAME.COM/' . $field['filepath'];
    $current_row->attachments_description[] = $field['description'];
  }
}
?>

```
> 3 votes

---
Tags: media, migrations
---