# Question
Title: How to trigger JavaScript/jQuery on AJAX-enabled ImageField submit?
I'm trying to trigger a JavaScript event when an AJAX-enabled ImageField submit button is clicked.

I've tried variations on `delegate()`, `submit()`, and `click()`, but no joy.

This is something similar to what I'm trying:

```
$('#edit-field-image-und-0-upload-button').mousedown(function () {
  alert('hi');
});

```

I read the documentation I could find on Drupal's AJAX forms, but haven't found what I'm looking for yet.

# Answer
I agree with DeeZone that .click() should work.

Try putting that code in a `$(document).ready();`

Drupal ajaxifies it's stuff on document ready so your code might be executing BEFORE the form gets ajaxified by Drupal.

```
$(document).ready(function() {
  $('#edit-field-image-und-0-upload-button').click(function () {
  alert('hi');
  });
});

```
> 1 votes

# Answer
I'd check your selector #edit-field-image-und-0-upload-button to make sure it's valid, "und" seems kind of odd but I'm not sure. The event handler .click() should do the trick.
> 0 votes

---
Tags: 7, ajax, javascript, entities
---


title: Use images in pagination links

text:
# Question
Title: Use images in pagination links
I am using drupal 7 and i am trying to override the pager.inc function like this .

```
function bartik_pager_first($variables) {
  $text = '<img src="http://localhost/drupal/themes/bartik/logo.png"></img>';
  $element = $variables['element'];
//  $parameters = $variables['parameters'];
  global $pager_page_array;
  $output = '';

  // If we are anywhere but the first page
  if ($pager_page_array[$element] > 0) {
    $output = theme('pager_link', array('text' => $text, 'page_new' => pager_load_array(0, $element, $pager_page_array), 'element' => $element, 'parameters' => $parameters));
  }

  return $output;
}

```

As you can see i am just trying to print the image for the text "first". But its just displaying like

```
<img src="http://localhost/drupal/themes/bartik/logo.png"></img>

```

How do i tell drupal that display it as html image rather then just text.

# Answer
> 3 votes
You have to override theme\_pager\_link() as well. The last line calls the l() function and you have to force it to render html.

Another possibility is to use css to theme the links

# Answer
> 1 votes
CSS is the proper way. Imagine you have to change the way your pagers are shown. You don't want to edit PHP for this. CSS is for the presentation layer.

---
Tags: 7, paging
---


# Question
Title: Internationalization -- impact on other modules?
I installed the internationalization module because the site I'm developing is in a different language, but I can no longer index the site in Drupal's search engine, and Tagadelic isn't working either. I'm assuming all of these issues are somehow related but I'm actually not entirely sure... is there anything specific I need to do when I install the internationalization module to ensure other modules keep working are compatible with other languages?

# Answer
The i18n modules can have a huge effect on a site, as they integrate with a large number of modules. Many modules for example deal with taxonomy terms and displaying them, so they all need to be compatible with i18n.

The main problem is that many content elements (like menus, taxonomies, ..) are not designed to be translatable or even just language aware. So the i18n project needs to alter a lot of things and build data structures and API's on top of those provided by core.

Also, there have been a number of API changes unfortunately, so it's possible that the modules you mentioned have a broken i18n integration due to that.

You need to provide more details on what exactly isn't working to get more help than this. You can also try to check the issue queue of the broken modules to see if there already is an issue for this and if not, open one.
> 2 votes

# Answer
With i18n each module might have it's own sort of i18n config that you might have to set. Some modules you have add i18n settings via config variables in settings.php, some have settings that you have to set for each language that you have installed. Views you might have to include filters for language, or current user's selected language and what not, there can be a ton of configuration depending on what your requirements are. Check out the README of each module and more times than not if it's a widely used module it'll have some section telling you what to do when you're using i18n.

I wish there was a simple answer to this but as it stands it's just a case by case basis per module. The best thing you can do is include i18n from the very beginning when you start building your site, instead of building your site then enabling i18n later. I say this because now you have to deal with all of the configuration and optional development associated with i18n along with fixing errors and maintaining the site, which can be a hassle to juggle.
> 1 votes

---
Tags: 6, i18n-l10n, search
---


# Question
Title: Avoid a revision is automatically published
I currently have new revisions created whenever a page is edited, but I don't want it to be automatically published. Instead, I want to have to go into the revision tab and click revert for the latest revision. Is this incorporated in Drupal 7 or do I have to download a module?

# Answer
> 1 votes
Please have a look at Revisioning module, this is probably what you are looking for. There is simpler module Revision Moderation, but it has no D7 version

---
Tags: nodes
---


title: Custom theme for module?

text:
# Question
Title: Custom theme for module?
I am creating a new module in drupal 7 called coolmodule and I'm trying to figure out how to bind content to the file `sites/all/modules/coolmodule/coolmodule.tpl.php` file. Here's the block view code in my coolmodule.module;

```
function coolmodule_block_view($delta = '') {

    $block['subject'] = t('My Special Module');

    $block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

    return $block;
}

```

But for some reason, pages with this block does not render `sites/all/modules/coolmodule/coolmodule.tpl.php`. What am I doing wrong?

# Answer
> 5 votes
you are missing a hook\_theme() function

see you defined a theme for your block by using:

```
$block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

```

but you never told it how to relate your theme with the template file, this work is done in `hook_theme()` function.

```
function coolmodule_theme() {
    $items['coolmodule'] = array(
        'template' => 'coolmodule',   // here comes your template name
        'render element' => 'content'
    );

    return $items;
}

```

Don't forget to clear your cache

---
Tags: 7, blocks, theming
---


# Question
Title: How do I send an email to the administrator users when a specific link is clicked?
I'm working on a new site built with Drupal 6, and I have to program a specific action on the node pages.
I have a page that shows the product information for users. Following the information, I have a button labeled "order now"; when this button is clicked, two scenarios are possible:

1. if the user is not logged in, he is redirect to the login form
2. if the user is logged in, an e-mail is sent to the administrator with the current product information and the information of the user who clicked the button

# Answer
Rules Module can do this for you.
> 2 votes

# Answer
Check out the Drupal Commerce module, or simply try the Commerce Kickstart installation profile.

It is a complete commerce solution which is highly integrated with the Rules module, so you can easily define what you described in your question.
> 0 votes

# Answer
You can just use a submit callback for the button and check the current user with `global $user;`. Just add `$form['button']['#submit'] = array('mymodule_submit_callback');` to the button's array and use the callback to do your work.

```
function mymodule_submit_callback($form, &$form_state) {
  global $user;
  if ($user->uid == 0) {
    // Send the user to the login page if user is anonymous.
    drupal_goto('user');
  }
  else {
    drupal_mail(); // Send an email to the administrator.
  }
}

```

So, here you have access to the user that clicked the button as well as any form data in `$form_state['values']`. Check out the drupal\_mail API reference for information on how use this function to send mail.

Alternatively, if you want to just provide a link you could also just use a menu callback.

```
function mymodule_menu() {
  $items['path/to/callback/%user'] = array(
    'title' => t('Send mail'),
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_mail_callback',
    'page arguments' => array(3),
  );
  return $items;
}

function mymodule_mail_callback($user) {
  // Check if this is an anonymous user and redirect if necessary.
  if ($user->uid == 0) {
    drupal_goto('user');
  }
  else {
    drupal_mail(); // Etc.
  }
}

```

Then, the link on the node form can be done like this

```
function mymodule_form_alter($form, &$form_state, $form_id) {
  // Ensure this is the form you want with a conditional.
  global $user;
  // Add your "Order now" link to the form, linking to your menu callback.
  $form['mail_link'] = array('#value' => l(t('Order now'), 'path/to/callback/' . $user->uid));
  return $form;
}

```

Alternatively, you could disclude the user ID from the menu callback path and just get the `global $user` variable from within the menu callback itself.
> 0 votes

---
Tags: 7, emails
---


title: Additional Query String in a Node Url

text:
# Question
Title: Additional Query String in a Node Url
I'm not sure if this is possible in drupal 7, but I think I may have seen something like this happen before. Let's say i added a content and you can see it at the url `http://mysite.com/my-article`. In the content area, I'm displaying a block that's made by a custom module. Right now, I have no problems going to a url like `http://mysite.com/my-article?var1=hello`, and then having my module responsible for creating the block to print `$_GET['var1']`.

However, the only change I would like to make is to have friendly urls. I would prefer the url to be `http://mysite.com/my-article/hello`, then I would output the same content in my module block. Is this easily do-able?

# Answer
> 2 votes
All is right what you are doing.

You cannot pass additional parts randomly with URL without adding them to menu registry and associating with callback.

Drupal uses `$_GET['q']` for default URL path and makes it SEO friendly. `$_GET['q']` can contain 9 parts in total in Drupal 7 (7 parts in Drupal 6). Each part can be accessed via `arg(n)` function.

---
Tags: 7, uri
---


# Question
Title: hide if on front page and on taxonomy pages
i wondering how i can hide $title if its on the front page and on taxonomy pages, I only want it to show on nodes.

here my code, I dont know if im close or not =)

```
function bartik_process_html($variables){
    if(!drupal_is_taxonomy()){
    $variables['title']['class'][] = 'element invisible';
    }
    elseif(!drupal_is_front_page()){
    $variables['title']['class'][] = 'element invisible';
    }
    else{

    }
}

```

# Answer
> 1 votes
Just a few notes from what you have so far:

* I agree with Dave Hall, create a subtheme instead of hacking on Bartik in core
* Your logic is backwards, you would be looking for `if (drupal_is_front_page()) {...` instead of `if (!drupal_is_front_page()) {...`
* There is no function `drupal_is_taxonomy()` (unless you created it)
* The core style is `element-invisible` instead of two separate classes `element invisible` (again unless you created these classes separately)

A really easy way to remove these titles is to create simple template files and remove the code that prints the title. For instance, using the code from Bartik's page.tpl.php, copy all the code and create 2 files: page--front.tpl.php and page--taxonomy--term.tpl.php. Inside those files you can remove

```
<?php print render($title_prefix); ?>
<?php if ($title): ?>
   <h1 class="title" id="page-title">
      <?php print $title; ?>
   </h1>
<?php endif; ?>
<?php print render($title_suffix); ?>

```

Save the files to your theme, and clear the cache.

# Answer
> 2 votes
Try something like this:

```
<?php
   function hook_preprocess_page(&$variables) {
       if (drupal_is_front_page() || drupal_is_taxonomy()) {
           $variables['title'] = NULL;
       }
   }

```

Change hook to the name of your theme. Based on your example, it looks like you're hacking core which isn't good. Create a subtheme and implement your custom themeing there.

# Answer
> 1 votes
You can also do it using CSS using classes on the body tag like this :

```
.front .title {
    display: none;
}

```

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


# Question
Title: How to set up Drupal 7 on Apache/2 without .htaccess files ?
I would like to improve Drupal 7 and overall server performance by setting apache/2 without .htaccess files. How to configure apache/2 httpd.conf to achieve this?

# Answer
> 8 votes
You should be able to take the contents of the .htaccess file, and place them in your httpd.conf. Exactly where depends on how you have your site running in Apache.

If you are using a virtual host, you would place everything inside a `<Directory>` section that matches your `DocumentRoot`, inside your `<VirtualHost>` section for the site.

If you aren't using a virtual host, then everything would (probably) still go in a `<Directory>` section that matches your `DocumentRoot`, but I can't remember the last time I didn't use a virtual host, even for servers with a single website on them.

You may get better answers over on ServerFault, as this isn't totally Drupal specific.

# Answer
> 2 votes
In a directory section that refers to your Drupal installation, you can do the following:

```
<Directory ...>
AllowOverride None
...paste contents of Drupal .htaccess here...
</Directory>

```

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


# Question
Title: Award user points for selecting an avatar?
I'd like to award my happy little users when they select an avatar.

Anyone know of a module that melds User Points and Avatar Selection?

Both modules are awesome, but I can't find a way to combine them into thanks-for-making-your-profile-pretty goodness.

# Answer
I don't think there already exists a module for this.

What you need to do is implement hook\_user\_update() and check if the user now has a picture assigned but didn't before. If so, use userpoints\_userpointsapi() to grant the user the number of points you want.

Something like this:

```
<?php
function yourmodule_user_update(&$edit, $account, $category) {
  if (!empty($edit['picture'] && empty($account->picture)) {
    $params = array(
      'uid' => $account->uid,
      'points' => 10,
      // You probably want to provide additional arguments,
      // refer to the API documentation.
    );
    userpoints_userpointsapi($params);
  }
}
?>

```
> 3 votes

---
Tags: userpoints, media
---


# Question
Title: load a node content into a lightbox2 (without headers and footer and other blocks)
is it possible to load a node (from an id) into a lightbox 2 without having to load all the additional blocks ? just what the node has to display

I want to make some popups on some links to allow some nodes to be shown inside.. no submission will be made in this case (comments are disabled)

another cool thing will be including webforms in a lightbox.. Again no headers..but I believe that that's more complicated because it's form submission... so ajax in required

# Answer
> 5 votes
There are many ways to do this, and this gets asked a lot, please have a look at my answer in this question.

Look at this doc page from the Lightbox2 documentation.

Right now though I highly recommend using the Modal Frame API and Automodal for things like this.

\** Drupal 7 update

The colorbox module doesn't offer out of the box support for nodes yet (they are working on a patch for this), but in the meantime you can use this approach. You can also use the Shadowbox module, have a look at this and this issue.

# Answer
> 1 votes
I know in D6 if you linked to http://your/target/url #content-inner then it would only display that div in the Lightbox!

Example:

```
<a class="lightbox-processed" rel="lightmodal[search|width:400px; height:470px; scrolling:none;]" href="/request-callback #content-inner">

```

Obviously use Firebug or the like to find out which div ID you want to display and replace #content-inner with that (making sure to include the space between the URL and the div ID) :-)

Hope this helps!

---
Tags: nodes, ajax, webforms, forms, javascript
---


# Question
Title: EntityFieldQuery and how to use aggregate functions SUM, ARG and MAX
I have entity type payment and need count all payments (calculate based on field\_total), if its hard to undersand, I show it on example:

Payment A - $10 Payment B - $20 Payment C - $30

And I need query that SUM all values. In my example it will be $60.

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node', '=')
                    ->entityCondition('bundle', 'payment')
                    ->execute();

```

What is best method to solve this problem? I could select all nids and load it. But this is not very good if I have thousands nodes, or Iam wrong?

Thank you for advice.

# Answer
> 6 votes
EntityFieldQuery does not support Aggregations/Expressions.

You have three options, basically:

* Load all nodes, make the summary in PHP. As you already said, not a good idea if you expected thousands or even just hundreds of payments.
* Write an SQL query, which should be rather simple since your field is probably only attached to the relevant bundle so you only need to query a single table and get the SUM() of the field value of all values. To be sure, you could also join the node table and add a condition on the node type. Although not nice, doing this is IMHO fine for custom code, where you know that the field will always be in the database. If you want to support different field storage implementations like MongoDB, not so much...
* Lastly, a bit more work, you could maintain a global summary that you update every time a payment is created/updated by implementing a corresponding node/field hook (like hook\_field\_insert(), as you can see this is what taxonomy.module does...). This would probably be a good idea if you expected that you need the summary frequently. Also, while it might be tempting to use variable\_get()/set to maintain a single value, that's not a good idea as it results in cache clears every time a variable is written.

# Answer
> 5 votes
To expand on Berdir's answer, EntityFieldQuery is *not* an SQL query builder. Sure, core contains an SQL implementation because core happens to ship with a Field SQL storage module. As such, only a very limited set of functionality is provided. In other words, how do you run AVG on the score of your YouTube videos (which could be a field just fine).

---
Tags: database, entities
---


# Question
Title: creating custom panes for field data in drupal 7
I need to port a panel feature from drupal 6 to drupal 7. I am able to get all the panel fields that come from views and blocks. Only thing i am not able to get is the fields that are coming from the content types.

Editing the panel shows "This pane's content type is either missing or has been deleted. This pane will not render." in the pane. The code generating this pane is

```
$pane->css = array();
  $pane->extras = array();
  $pane->position = 2;
  $display->content['new-4'] = $pane;
  $display->panels['top'][2] = 'new-4';
  $pane = new stdClass;
  $pane->pid = 'new-5';
  $pane->panel = 'top_left';
  $pane->type = 'content_field';
  $pane->subtype = '<field name>';
  $pane->shown = TRUE;
  $pane->access = array();
  $pane->configuration = array(
    'label' => 'inline',
    'formatter' => 'default',
    'context' => 'argument_nid_1',
    'override_title' => 0,
    'override_title_text' => '',
  );

```

The content\_field type requires a plugin content\_field.inc which was present in cck module in drupal6 as 'cck/includes/panels/content\_types/content\_field.inc'. How do i port this thing in drupal 7. There should be something equivalent to content\_field.inc in drupal7 also.

Can someone lemme know how to get over this issue?

Thanks

# Answer
> 1 votes
Got his one. We need to replace content\_fields with entity\_+fields in drupal 7 as the content types are entity type in drupal 7 now.

Thanks

---
Tags: entities
---


# Question
Title: db_query(); -- list of files attached to a node?
I have a `DRUPAL_BOOTSTRAP_DATABASE` .php -script that loads info based on the `nid` it gets via POST request.

I need to list files attached to the requested node, and I know how to do this in D6, but after spending 30min trying to understand the new table structure of Drupal 7, I cannot fathom how to pull the `fid` (or any other file info related to the node) via a `db_query();`

I've been trying to read Devel query log to get a hang of how Drupal handles this to no avail. Any insight into my problem would be greatly appreciated. :)

# Answer
Here's the final solution to pull the data from {file\_managed} and another field to be returned as json based on GET parameter nid.

```
<?php
  // only take action on GET parameters
  if ( !empty($_GET) ) {

    // escape and map GET parameters
    $post = array_map('mysql_escape_string', $_GET);
    $nid  = $post['nid'];

    // we have a numerical nid
    if ( is_numeric($nid) && !empty($nid) ) {
        // switch to drupal root, as relative to our module path
        chdir('../../../../../../');
        // define root dir
        define('DRUPAL_ROOT', getcwd());

        // load drupal db layer
        require_once './includes/bootstrap.inc';
        drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

        // regardless of is audio data found, we return the edit path of the node
        $temp = new stdClass();
        $temp->path = "node/$nid/edit/";
        $temp->nid  = $nid;

        // grab audio urls and slot states
        $params = array(':nid' => $nid);
        $sql    = "SELECT      f.filename,
                               f.uri,
                               fss.field_slot_state_value state
                    FROM       field_revision_field_related_audio AS fra
                    INNER JOIN field_revision_field_audio_file AS faf
                            ON faf.entity_id = fra.field_related_audio_value
                    INNER JOIN file_managed f
                            ON faf.field_audio_file_fid = f.fid
                    INNER JOIN field_revision_field_slot_state fss
                            ON fss.entity_id = fra.entity_id
                    JOIN       node n
                            ON (fra.revision_id = n.vid AND fss.revision_id = n.vid)
                    WHERE      n.nid = :nid
                    AND        fra.entity_type = 'node'";

        $results = db_query($sql, $params);

        // if we have results, display them in json format
        if (!empty($results)) {
          $i = 0;

          foreach ($results AS $result) {
            // add the state just once, as it's the same for each file
            if ( $i == 0 ) {
                  $temp->state = $result->state;
            }

            // add all audios related to production
            $temp->audio->{$i++} = $result->uri;
          }
        }

        // encode to json and spit out
        $json = json_encode($temp);
        print $json;
      }
    }

?>

```
> 0 votes

# Answer
replace uppercase by your data:

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$sql = 'SELECT f.* FROM {field_data_field_YOURFIELDFILENAME} ff INNER JOIN {file_managed} f ON ff.field_file_fid=f.fid WHERE ff.entity_type = :etype AND entity_id=:nid';
$result = db_query($sql, array(':etype'=>'node', ':nid' => YOURNID));

foreach($result as $row) {
  print_r($row);
}

```

Create custom function for processing uri: public://FILENAME.EXT and getting right path from this.
> 1 votes

---
Tags: database, files
---


# Question
Title: what about multiple files and their archives in sites/default/files/[css] and /[js]?
/sites/default/files/css & /sites/default/files/js my drupal sites above folders are filled with numbers of css and js files respectively and also with their archives. What are these meant to? and what they have effect on the performance of my site?

One thing i know when i explore my css in fireug, most of contents are refferd from these and even repeating and over-rided contents also appear. How i can overcome this problem so no css over-ride? following is the image of css ove-riden, their actual path is sites/all/theme/themename/css but here these are from sites/default/files/css

# Answer
> 6 votes
The files are created when you enable 'Aggregate and compress CSS files.' and 'Aggregate JavaScript files.' The do have a positive effect on the performance since the browser has to do fewer http requests.

The overrides are normal as well, and they also happen when aggregation is turned off. Avoiding those means you probably have to re-write most of the css from core.

---
Tags: theming, files
---


# Question
Title: How can I access the virtual machine filesystem from within Windows?
I've recently tried to get used with Oracle VirtualBox Manager and the QuickStart 1.0 VM machine: http://drupal.org/project/quickstart. I've installed it on

Everything looks fine and great but the only big issue is I cannot access the files from outside (Windows 7). I need to have a way to control the Drupal installs (backup them, commit/checkout with the linux server etc). How do I?

I heard there is a solution to install samba but this only works if you have a real linux installation on your computer.

# Answer
> 1 votes
Create shared folders from Virtual Box Manager. For each drive you will have to create a shared folder. These shared folder will appear in guest OS as network file-systems.

As Ubuntu (Linux) is underlying in QuickStart.

Mounting temporarily need to fire this command from terminal:

```
sudo mount.vboxsf [share_name] [directory - mount point e.g. /mnt/share/]

```

OR

```
sudo mount -t vboxsf [share_name] [directory - mount point e.g. /mnt/share/]

```

Mounting permanently using fstab (/etc/fstab)
Make sure to install samba first (in ubuntu it should be already installed or do it `sudo apt-get install samba`, it needs internet connection)

Now edit your fstab file and add an entry in the last

```
\\vboxsvr\[share_name] [directory - mount point e.g. /mnt/share/] vboxsf rw,gid=100,uid=1000,auto 0 0

```

# Answer
> 1 votes
I recommend WinSCP for more advanced usage. Expandrive is also useful for mounting SFTP directories as Windows network drives.

---
Tags: installation
---


# Question
Title: Creating an email newsletter using simplenews
I need to create an email newsletter template using simplenews. Can anyone point me to a simple, clear tutorial on how to do so?

# Answer
I found this links useful

Designing a HTML newsletter for Drupal

http://drupalsteve.com/node/30

---

Drupal & Simplenews

http://www.slideshare.net/desk02/dug-simplenews-6192093

---

Email Newsletters and the Simplenews Module http://www.group42.ca/email\_newsletters\_and\_the\_simplenews\_module

---

and probably

Newsletter subscription management in Drupal with E-mail Marketing Framework

http://www.drupalcoder.com/blog/newsletter-subscription-management-in-drupal-with-e-mail-marketing-framework
> 3 votes

# Answer
I had posted a similar question for D7 here How to theme simplenews newsletters in D7?

and ran across the D6 version here: http://drupal.org/node/197057
> 1 votes

---
Tags: 6, theming, emails
---


# Question
Title: dl.example.com/file1.zip instead of example.com/sites/default/files/file1.zip
How can I convert address of uploaded files from *example.com/sites/default/files/file1.zip* to *dl.example.com/file1.zip*?

Is there a module for this purpose? If not what's the solution?

# Answer
In my opinion if you can create a subdomain dl.example.com then you can also redirect all requests to default/files subfolder using symbolic link in /home/domains/dl.example.com/ linking to /home/domains/example.com/sites/default/files/ depending on your .htaccess or httpd.conf setup.

Please note I don't think this is a Drupal-specific question, I am not an expert on this and you'd better asked on https://serverfault.com/

I think using this method will be faster then creating a custom module to do this for you because the method I explained doesn't even require loading Drupal for the request handling.
> 3 votes

---
Tags: 7, files, uri
---


# Question
Title: Database Connection error by giving specific IP address
I have created database and user and give all the privileges to the user. When I give the IP as database host, it will show the following errors. Giving database host as localhost it will work fine.

I am using phpmyadmin 3.3.2...

The error message is given below.

> Failed to connect to your MySQL database server. MySQL reports the following message: Can't connect to MySQL server on '192.168.85.10' (111)

# Answer
Definitely MySQL remote access would be blocked.

You can edit MySQL conf to enable it.
Loginto your remote db server and edit main configuration file.

vim /etc/my.cnf (in case of Linux)

Comment out `skip-networking` by adding `#` before it, should be located under `[mysqld]` and update `bind-address` for the desired IP you are using as connection host.

```
[mysqld]
...
...
bind-address = 192.168.85.10
#skip-networking

```
> 1 votes

---
Tags: users, database, installation
---


# Question
Title: Creating a block that lists various posts for various categories
I need to achieve something like this:

This is a block on a page. Stuff like U.S., Politics, World etc. are the categories (created by adding a custom vocabulary) and the sub-links are articles under those categories. I'm using Drupal 7.8 and have the Views module installed.

Maybe I could write some PHP code and save as a block and then add that to a region. If so, which functions would I need?

# Answer
Views are you friend. A View can also generate a Block. The sub-links are categories ordered by publishing date? Fairly easy.
> 1 votes

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


# Question
Title: I need a solution to in-depth scan into Drupal git repositories to find useful code snippets
I'm looking to find out the best solutions to in-depth search into git repositories for code snippets: inside Drupal custom modules, revisions, contribs, themes, profiles.

As far as I know, Drupal no longer uses CVS/SVM but switched to git instead.

I am working on a Windows machine, but I commit/checkout to linux server using tortoiseSVN.

There is an old nice tutorial movie by Jonathan Lambert about how to search into SVN on GotDrupal.com on how to search into http://www.searchdrupal.org/ but searchdrupal.org no longer exists.

I need to know how you guys are building up modules using other people's snippets and how do you find it. Any solution is precious to me

# Answer
drupalcontrib.org is a nice place to find functions used within contributed modules as well as the core Drupal API. It has helped me out in the past
> 2 votes

---
Tags: version-control
---


# Question
Title: Services: which hook to use for altering node field values before calling the node retrieve service?
I have a custom formatter for a field http://drupal.org/project/custom\_formatters but this seems to be ignored during node retrieve.

I also tried altering field value during hook\_node\_view, but no luck.

Do you have any tips on which hook node could I use to change the display of a field before retrieve?

# Answer
Actually I think it's only hook\_node\_load() that can be use. As I understand Services module send just data and doesn't do any HTML render of the node and the hook\_node\_view is actually done only for it : change the HTML render.
> 1 votes

---
Tags: 7, hooks, services
---


title: How to create dynamic link in views?

text:
# Question
Title: How to create dynamic link in views?
I am using views and I want to put a dynamic link in the header. The link is http://www.example.com/node/add/album/31 The number 31 varies depending which node it is viewing so I want it to change to whatever node id it is viewing. I'm not a coder so can anyone give me code?

# Answer
you can add a "global text area" field to the "header" of the view. Then add the link HTML in there:

```
<a href="node/add/album/%1">add</a>

```

The %1 will take the the first argument from the URL
> 1 votes

# Answer
you need to make a menu item with the name 'node/add/album/%'

```
function YOURMODULENAME_menu() {

    $items['node/add/album/%'] = array(
        'page callback' => 'YOURMODULENAME_YOURFUNCTNAME',
        'page arguments' => array(3),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

```

Then you need the function and you would print the title as well as the your view in this callback function

```
function YOURMODULENAME_YOURFUNCTNAME()
{
    $nid = arg(3);
    $node = node_load($nid);
    $title = $node->title;

    $content = '<p><a href="node/add/album/'.$nid.'">'.$title.'</a></p>';
    $content.= views_embed_view('YOURVIEWNAME', 'default');
    return $content;
}

```

There can be many solutions to it, the code is untested, let me know if there is any issue in it. Firdous
> 0 votes

---
Tags: views, nodes
---


title: Pass JSON array to drupal function

text:
# Question
Title: Pass JSON array to drupal function
I have a JSON array, and I want to pass it to drupal function to work with the data. what are the possible ways to do that?

any code sample would help

# Answer
The function drupal\_json\_decode() (D7 only) can convert a json string to the corresponding php data structure.

In Drupal 6, you can directly use the PHP function json\_decode(), just remember that you need PHP 5.2+ for that.

As I almost assumed, the part you're having problem with is not converting the JSON string to a PHP structure you can work with, but sending that from the client side to the server, so that you can access it with PHP (Try to provide more information what exactly you want to do when asking questions and you'll get better answers).

drupal\_json\_decode() is, in fact, just the very last step in the whole process. You obviously can't access that function (or anything else that is PHP) directly from jQuery, so you need to send it with jQuery.post() to the server, where it can be processed.

To be able to do that, you first need to define a endpoint where the data can be sent to by implementing hook\_menu(), for example your\_module/endpoint. In the page callback that you defined there, you can read the sent data in from php://input, for example with `$json = file_get_contents("php://input");`. Then, you can use the mentioned function to parse $json.
> 5 votes

---
Tags: javascript
---


# Question
Title: How activate Privatemsg Module to all users?
I just enabled the Privatemsg Module in my Drupal 6. I would like to enable this module to all users, who join in the website. But the registered users cannot see the **"Write new message and Messages"** link.

Why the Privatemsg is not active in users section ?

# Answer
You should change permissions for the *Privatemsg* module for *authenticated users* or whatever role you want in the permissions page(*admin/user/permissions*)

See http://drupal.org/getting-started/6/admin/user/permissions
> 1 votes

# Answer
In case you're talking about the local task in the user profile, that is meant for administrative purpose only (read all private messages permission).

The Privatemsg pages reside below /messages, a link to that page should have been added to the Navigation menu.

Privatemsg 6.x-2.x does allow to move it to the user profile by setting the url prefix in the settings to "user/%user/something".
> 0 votes

---
Tags: 6, privatemsg
---


title: Grouping users help

text:
# Question
Title: Grouping users help
I'm building an application where a group of users interact with customers...however for each user in a group he/she has his own customers. I also need the ability to having 1 user with his/her own customer...meaning this user is not a part of any group. Should I use Organic group for this or would vanilla drupal work just fine (with taxonomy and roles?). Thank you.

# Answer
> 3 votes
I think Users can also be Organic Groups in Drupal 7, as everything related to OG are just fields now which can be attached to anything. So that might be something you could try.

Not sure what kind of communications you have in mind, but if it is meant to be private, maybe a combination of User Relationships and Privatemsg could get you started. Those modules can be integrated so that only related users can send each other private messages.

---
Tags: 7, organic-groups
---


# Question
Title: A way to determine where a URL is being generated?
I'm a drupal noob, and one of the most frustrating things for me is finding where a specific page is being generated from. The fact that it could be a block, or created via a module, or through a view, I so far can not figure out how I can easily determine where the page is being created.

Is there an easy way of finding the 'culprit' that is generating any given url?

For example: www.example.com/catalog/something

How can I quickly tell what is generating /catalog/something?

# Answer
> 2 votes
In Drupal 6 many different things use the PathAuto module to quickly create URL Aliases for your content.

Automatic generation of aliases, the code that controls the administration and application of patterns, the database schema definitions & more can be found within the module.

To answer your original question, it depends on what is creating that alias, a node or view or taxonomy page or whatever, but more times than not pathauto will be involved.

To see the automatic alias settings go to : admin/build/path/pathauto

# Answer
> 0 votes
Every path in drupal has a registered "system path" that is defined in the menu system. You can get that path at runtime with arg().

---
Tags: 6
---


# Question
Title: Develop a module that adds a new content type with custom fields
How do I start to develop a Drupal 7 module that adds a new content type with some custom fields, so it generates all the output I want?

# Answer
Although its possible to do programatically, your easiest bet would be to use features.

This is how you would do it:

1. Manually create your content type
2. Manually add fields
3. Create a new feature and export the content type (and its fields)
4. Done!

Now if you install this feature is a fresh Drupal installation that content type and fields will be automatically added.
> 3 votes

---
Tags: nodes, entities
---


# Question
Title: presave like option for adding vocabulary and terms similar to one provided by hook_nodeapi
I'm a Drupal newbie and trying to customize the 'Add Vocabulary' and 'Add Term' provided by taxonomy using a module named Domain Taxonomy.

To customize it as per my own requirement I'm gonna have to insert the domain specific data when the term is saved without messing up over the existing code provided by domain taxonomy rather wish to override it.

I'm looking for a hook similar to hook\_nodeapi where in '$op == presave' after validations and before saving node it can be customized with user added data.

To my understanding hook\_nodeapi doesn't apply for stuff like taxonomy or user profile. Does something similar exist for taxonomy that i could put to use here. Kindly let me know if my understanding is flawed and provide valueable comments/feedbacks and possible solution.

# Answer
> 1 votes
You can add a validation function to the form in hook\_form\_alter(). If you give your module a high weight, that validation function will be added last to the validation functions array and thus be executed last. The validation function can call form\_get\_errors to check whether errors occurred. If no errors occurred, you can be pretty sure that the vocabulary or term will be saved to the database, making it something like `hook_nodeapi($op = presave')`.

Note that you cannot use hook\_form\_FORM\_ID\_alter(), because these hooks are executed before hook\_form\_alter(). Also, I found no easy way to react on the installation of other modules.

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


# Question
Title: Is there a git repository for Drupal releases only?
Having cloned drupal from the git repository using

```
git clone --branch 7.x http://git.drupal.org/project/drupal.git

```

I noticed that I'm actually running 7.9-dev when what I want to be running is the most recent stable. Is there a git repository or branch that I can pull from to run the most recent stable release? I've seen references to git.drupal.org/project-stable/drupal.git around the net, but that doesn't seem to be a valid repository anymore.

# Answer
> 6 votes
Drupal releases are marked with a corresponding "tag" within the repository. When you clone a git repository, you get all the tags and branches along with it. Running the following command from within the repository will checkout the version 7.8 tag:

```
git checkout 7.8

```

To list the available tags, type `git tag`. To list all available branches, type `git branch -a`.

---
Tags: version-control
---


# Question
Title: Redirecting to external validation page using oauth with drupal_http_request()
I'm working on a module to integrate with the Piryx API, and per the OAuth documentation, I should be redirected to an external page where the user can allow access to my application. The problem is that I'm using drupal\_http\_request():

```
$response = drupal_http_request($url, $headers, 'GET', $data);

```

to get the data, and the page markup is returned in $response\['data'\] instead of redirecting me to the external page (if I put the URL in my browser, it brings up the page fine). Is there something I can do to redirect to the external URL so the user can allow access, or do I just somehow need to use the markup to display it in my site?

Thanks.

# Answer
> 2 votes
In the case the request is redirect to a different URL, `$response->code` is 301, and `$response->redirect_url` is the redirection URL. If the request is redirect, you can call `drupal_http_request()` using `$response->redirect_url` as new URL.

See aggregator\_aggregator\_fetch() as example of Drupal function that verifies the request is being redirected.

```
  // Process HTTP response code.
  switch ($result->code) {
    case 304:
      break;
    case 301:
      $feed->url = $result->redirect_url;
      // Do not break here.
    case 200:
    case 302:
    case 307:
      if (!isset($result->data)) {
        $result->data = '';
      }
      if (!isset($result->headers)) {
        $result->headers = array();
      }
      $feed->source_string = $result->data;
      $feed->http_headers = $result->headers;
      break;
    default:
      watchdog('aggregator', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $feed->title, '%error' => $result->code . ' ' . $result->error), WATCHDOG_WARNING);
      drupal_set_message(t('The feed from %site seems to be broken, because of error "%error".', array('%site' => $feed->title, '%error' => $result->code . ' ' . $result->error)));
  }

```

If you want to redirect the users to `$result->redirect_url`, and not requesting that URL with `drupal_http_request()`, you use the following code.

```
drupal_goto($response->redirect_url, array('absolute' => TRUE));

```

---
Tags: authentication-authorization
---


# Question
Title: How can I add CSS classes to poll questions?
I want to add some color and formatting to the polls at my site poll but the problem is that it seems Drupal is not adding any special IDs or classes for this poll.

Then how can I target the poll questions? I want to make their font larger with some background etc. I don't want to change the theme files.

# Answer
CSS Selectors can do that. You can target HTML that have no Classes or IDs http://www.w3.org/TR/CSS2/selector.html, http://css.maxdesign.com.au/selectutorial/selectors\_descendant.htm, http://css.maxdesign.com.au/selectutorial/selectors\_child.htm
> 2 votes

---
Tags: 6, theming, polls
---


# Question
Title: Redirect according to views filter input
I have a view with two filters (country and city) on node (country) page. What I want is redirect to another node page according to user input (filter country). So if user viewing page node/uk and chooses USA in country filter and New York in city filter, drupal must redirect to page node/usa showing results for New York. View is using AJAX. Tried using drupal\_goto in views exposed form submit but this produces error `Drupal.Views.Ajax.handleErrors is not a function` in ajax\_view.js. Help me please.

# Answer
> 1 votes
You can do it using hook\_form\_alter() on the exposed filter form.
It is very well explained in this post.
A drupal\_goto() depending on the input entered should work.

---
Tags: views
---


title: Get post information in drupal function

text:
# Question
Title: Get post information in drupal function
I posted JSON array from my script using `jQuery.post` , to get the posted data in my drupal module function I am using

```
$json = file_get_contents("php://input");

```

but is there a better way or a 'drupal-way' to get posted data in a drupal function?

# Answer
Assuming that you're using Drupal 7, take a look at the module Content as JSON. This should take care of the details and put you within the realm of the "drupal-way". There's also the Services module which might be overkill for what you're doing.

If you stick with file\_get\_contents then don't forget json\_decode:

```
$received = file_get_contents("drupal://input"); // Use inputstream module.
$received = json_decode($received, TRUE);

```

Then you can play around as much as you'd like with the $received value.

Additionally, the inputstream module is invaluable in letting you get to the input stream more than once (if you try using php://input more than once, the second time, and those following, will return NULL).
> 2 votes

---
Tags: 7, javascript
---


title: views output file alterations

text:
# Question
Title: views output file alterations
I am using d7 and views.

I've created a view tpl file specific to my view using the the file name of: `views-view-fields--cameras.tpl.php`

```
<?php

foreach ($fields as $id => $field): ?>
<?php
$output = '';
$output .=  $field->label_html;
$output .= '<table width=100% border=1>';
if($field->label_html == 'camera_brand_star:')
{
$output .= $field->wrapper_prefix;
$output .= '<tr><td>hello</td></tr>';
$output .= $field->wrapper_suffix;
}
else if($field->label_html == 'camera_price_star')
{
$output .= $field->wrapper_prefix;
$output .= '<tr><td>'.$field->content.'</td></tr>';
$output .= $field->wrapper_suffix;
}
else if($field->label_html == 'brand:')
{
$output .= $field->wrapper_prefix;
$output .= '<tr><td>'.$field->content.'</td></tr>';
$output .= $field->wrapper_suffix;
}

else
{
$output .= $field->wrapper_prefix;
//$output .= '<tr><td>'.$field->content.'</td></tr>';
$output .= $field->wrapper_suffix;
}
$output .= '</table>';
echo $output;
//echo $field->label_html;
?>
<?php endforeach; ?>

```

The if conditions are not working at all as its not printing any content. Only it prints the output of `$output .= $field->label_html;` What am I doing wrong?

# Answer
Please provide the markup that's currently produced by this code. The PHP logic looks fine but it's not cleat if `$field->label_html` has a value that will trigger and of the if statements. As a bare minimum you should be getting:

```
<table width=100% border=1>
</table>

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Adding metadata to a node through a module
I am developing a module that sync selected nodes with an outside site (another API on the web). I need to add some meta-data to each node:

* Last sync time (timestamp) - Not editable through UI
* Outside API ID for this item - Not editable through UI
* Sync enabled for this node (yes/no) - Editable through UI

Should I have my module create a new table through the Drupal Database API to store this data, or should I use the Field API?

# Answer
> 3 votes
Your requirement seems pretty straight forward. If you want to save some time, I would suggest that you use the Field API. To make those fields non-editable by users and administrators, all you need to do is implement a hook\_form\_alter and hide the form elements. You can also implement hook\_form\_FORM\_ID\_alter, which I find more efficient.

Example. Hide the author field:

`$form['author']['#access'] = FALSE;`

---
Tags: 7, nodes
---


# Question
Title: Make field content as exposed filter dropdown
I have a field in my node like brand, where in admin enters the brand name and creates the node. I want to make a exposed filter out of this as a dropdown with all the data entered by the admin. How do i do it ?

# Answer
> 1 votes
your question isn't 100% clear but it sounds like you want to display the nodes in a view and want to filter them with an exposed "brand" dropdown? I also assume your "brand" field is a term reference to a vocabulary.

Create a view for the nodes and add a filter for "Content: Has taxonomy term" and select your "brand" vocabulary, "dropdown" as the filter type and "expose this filter".

---
Tags: 7, views
---


# Question
Title: How can I programmatically validate that an user has uploaded an image in CCK?
I have an image field defined using CCK. I need to detect or validate that the image has been uploaded. Is it possible?

Thanks to all.

# Answer
> 1 votes
You may have to use hook\_form\_FORM\_ID\_alter().Define your own module and in your module try the following code

```
function yourModuleName_FORM_ID_alter(&$form, &$form_state) {
  $form['#validate'][] = 'yourModuleName_FORM_ID_validate';
}

//your validation function
function yourModuleName_FORM_ID_validate($form, &$form_state) {
  if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name']['machine_name_of_the_cck_field'])) {
    // File uploaded
  }
  else {
    //File not uploaded
  }
}

```

# Answer
> 1 votes
Even easier, you can do it with Rules on condition "Field xx has changed".

# Answer
> 1 votes
You can just set the CCK image field as a required field and the form won't validate unless the user uploads an image.

---
Tags: 6, entities
---


title: Trying to create a node_type in DP 7

text:
# Question
Title: Trying to create a node_type in DP 7
I'm trying to create a simple node\_type in drupal 7 based on the core blog module.

This is my hook\_install:

```
function node_link_install() {
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['node_link']);
}

```

and this is then the hook\_info in my node\_link.module file:

```
function node_link_node_info() {
  return array(
    'node_link' => array(
      'name' => t('Node Link'),
      'base' => 'node_link',
      'description' => t('Just playing around'),
    )
  );
}

```

and here is my hook\_uninstall:

```
function node_link_uninstall() {
  $result = db_query("SELECT n.nid FROM {node} n WHERE n.type = :type", array(':type' => 'node_link'));

  $nids = array();

  foreach ($result as $item) {
    array_push($nids, $item->nid);
  }

  if (count($nids)) {
    node_delete_multiple($nids);
  }

  drupal_uninstall_schema('node_link');
}

```

when I try to install the above module I get:

> ```
> Notice: Undefined index: node_link in node_link_install() (line 10 of
>
> ```
>
> drupal/sites/all/modules/custom/node\_link/node\_link.install). Notice: Trying to get property of non-object in node\_add\_body\_field() (line 555 of drupal/modules/node/node.module). Notice: Trying to get property of non-object in node\_add\_body\_field() (line 568 of drupal/modules/node/node.module). FieldException: Attempt to create an instance of field body without a bundle. in field\_create\_instance() (line 460 of drupal/modules/field/field.crud.inc).

Several things are puzzling me here:

1) why does this work for the blog module but not my module?

2) when I uninstall this module, the entry in the system table is not deleted

what am I missing?

# Answer
The error is complaining that it can't save the body field because you haven't specified the bundle of the object. But more importantly I think you want to look into the Entity API rather than creating a 'node\_type'.

In drupal there are nodes and there are types of nodes called content types. To make it more abstract, nodes are entities of type 'node'. Each content type is a 'bundle' of that entity type. Many things in drupal are entities, from users to comments to taxonomies.

If all you want to do is create a content type programatically, I think examples might have one. Otherwise just create the content type through configuration.
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: update order status after order creation
i try to update status like this

```
function module_order($op, &$arg1, $arg2) {
  switch ($op) {
      case 'update':
      $money = 'Cash';
      if (isset($arg1->custompane) && $arg1->custompane == $money) $arg1->order_status = 'completed';
      break;
    }
}

```

It does not work.

What do I do wrong?

# Answer
> 0 votes
Indeed `order_save()` should be used after modifying the order.

# Answer
> 1 votes
Use conditional actions to achieve this. Conditional actions are part of Ubercart.

---
Tags: 6, ubercart
---


# Question
Title: When using hook_FORMID_form_alter(), how does one use validation to prevent form submission?
Here is the code I have, and while the errors do print to screen, the form will submit anyway. How do I prevent the form from finishing submitting?

```
function my_module_my_form_form_alter(&$form, &$form_state) {
    // calls a function during validation
    $form['#validate'][] = 'my_module_validate_address_check';
}

function my_module_validate_address_check(&$form, &$form_state){
    if($form_state['values']['panes']['delivery']['delivery_postal_code'] != 91006){
         drupal_set_message(t('Wrong Zip'), 'error');
        $return = FALSE;
    }

}

```

# Answer
> 4 votes
Use `form_error($form['delivery_postal_code'], $message)` instead of calling `drupal_set_message()`.

OR try

form\_set\_error('delivery\_postal\_code', $message);

---
Tags: 6, forms, hooks
---


# Question
Title: Where did date-time "add [custom] format" go in Drupal 7?
In D6 this was located in, `Site Configuration >> date & time >> formats >> add format` Where is this in D7?

I found this Drupal.SE question: Date value to different date format explaining the code to create a custom format, but it doesn't say in which file to make the change.

# Answer
> 3 votes
Configuration -\> Regional & Language -\> Date and time -\> Formats -\> Add format.

You end up at `/admin/config/regional/date-time/formats/add`.

---
Tags: 7, datetime
---


# Question
Title: Get the user location during registeration process
I am developing a drupal site along with the mobile application. I want to store the latitude , longitude of the user who registers in my site... I can see there are many location based modules available but i want to use the one which affers the map ui on the registeration form and the user types in its address and through reverse geocoding i could fetch the latitude and longitude of that place.

Basically i need location module during registeration form Thanks

# Answer
> 0 votes
In Drupal 6, the obvious answer would be use the Location and Gmaps or OpenLayers module. I've used it on many many sites and it generally works well. Another very good alternative in Drupal 6 that I just found now is HTML5 user geolocation, that looks awesome and its what drupal.org uses!

However if I was using Drupal 7, I would definitely use the Geolocation Field module. I've tried it out and its really awesome and easy for users.

---
Tags: users, google-maps, location
---


title: How do I output one node as XML

text:
# Question
Title: How do I output one node as XML
I am creating a page flip for a drupal site using pdf\_to\_imagefield module to export PDf to JPG and then I need to have the list of JPG files as XML to use them in Dynaimc page flip.

The PDF and all JPOG files for each PDF page are stored in the same node of a certaine content type. How do I output this node as XML where I can control XML tags??

I have tried to create node-content-type.tpl.php but it comes as HTML.

# Answer
I would recommend that you use views as your source for the list of jpegs to output your XML file from. Using Views for example, I was able to make list of event images and make a custom XML file used to display the images in the Cub3r Flash plugin (I thought it was a bad idea but the client really wanted a Flash slideshow). I used the Views Bonus Pack export module, that gave me a style 'XML file'. I had only the image field, that was set to output the full image URL, the label I set it to was used as the custom tag. I then did an override of the XML template that came with the module and customized it to my needs (adding config parameters to cub3r).

Hopefully this will help you out. I also saw that the export module now has a fork that uses the batch API. Make sure you also checkout the Views data source module.
> 4 votes

# Answer
You can make a hook\_menu entry for your XML URL w/ a callback function.

The callback function can do a

```
drupal_set_header("Content-Type: text/xml; charset=utf-8");

// stuff to make the xml;

print $xml;

exit;

```

You can also do it with views, but I forget the steps to do this. There are a bunch of tutorials on the net, though, that outline this method, and likely some questions/answers on the main SO site.
> 3 votes

# Answer
I have solved it by creating a module, which generates an xml-file when you update your node. I used `hook_update` to hook into the update progress, check if the images have been updated and create / update the config.xml which I store in the directory of the images. this way you dont need to generate the xml file each time a user views the node.

You have to create a template for generating the xml-files, passing your image-datasetting the configurations and than save the themed content into the config.xml.

hope I could help
> 2 votes

---
Tags: nodes, 6
---


title: Creating a complex home page layout

text:
# Question
Title: Creating a complex home page layout
I was wondering about what might be the best approach to creating a complicated home-page layout along the lines of http://www.time.com/time/

I am attempting to do so. Here is how I'm approaching it:

* I'm using views primarily and defining tons of custom regions (I was hoping that there might be a better way)
* I have created a custom vocabulary called "Channels". I am using this for NewsFeed, U.S., Politics and so on. Articles are placed into one of these channels
* I have modified the "Article" content type and added a field for Channel. Also, I have added checkboxes to mark an article as "Editor's Pick", "Must Read" and "Featured Article". I am then using this as a filter in Views. That was the best way I could think of for categorizing the articles on the numerous boxes on the home page.
* Additionally, I'm marking articles with the "headline" tag so that they show up in the "Headlines" box on the upper right corner of the http://www.time.com/time/ home page.
* Images are scaled based on where I will be using them. (I'm using Drupal's in built functionality to scale images)

This is how far I've gotten. Since I've just started using Drupal, I was wondering if there might be a better way to do things. Appreciate any inputs.

# Answer
Views, Panels are your friend.

https://drupal.org/project/panels

You can also go with Omega Context and Delta

https://drupal.org/project/omega

https://drupal.org/project/context

https://drupal.org/project/delta

There are many ways to Rome....
> 7 votes

# Answer
Tutorials on Panels:

http://www.youtube.com/watch?v=v6zMcfTxkhc

http://nodeone.se/blogg/learn-page-manager-screencast-series-summed-up

The nodeone.se link will go more in depth, so I suggest starting with the YouTube link. The YouTube tutorial is D6, but it is the same in D7. NodeOne.se has Tons of tutorials that have helped me.
> 3 votes

# Answer
I prefer using templates, custom regions, and context or just regular Drupal blocks.
> 2 votes

---
Tags: 7, theming
---


title: Returns a list of nodes as XML?

text:
# Question
Title: Returns a list of nodes as XML?
I'm trying to do something like this with Drupal 7.

I need to generate either an XML file or a number of xml files based on the sub-parts of the over-all "Navigation" menu.

I have multiple "Portals", each with a list of pages... I need to generate an XML file for each portal, and be able to customize the hell out of it.

I've been trying Views... with XML Sitemap, feeds, etc... I just can't seem to get anything workable.

# Answer
> 2 votes
Will Views RSS do what you want? It typically throws articles/nodes out as RSS(XML), and you can modify it to produced more structured output if you wish.

---
Tags: 7, importing-exporting, navigation
---


# Question
Title: How can I get user_save() to update the nid instead of creating a vid?
I updated a node at hook\_user\_update() with this node object:

```
$node = new stdClass();
$node->nid = $f_node->nid;  // Updating
$node->title = 'TestT';
$node->type = 'employees';
$node->status = 1;        // Published?
$node->promote = 0;       // Display on front page?
$node->sticky = 0;        // Display top of page?
$node->field_employee_first_name['und'][0]['value'] = 'TestF';
$node->field_employee_last_name['und'][0]['value'] = 'TestL';
$node->field_employee_email['und'][0]['value'] = 'example@example.com';
node_save($node);

```

It executes without error but only my `node_revisions` (vid?) table is updated. The `node` table is untouched.

Am I missing something in the object that is keeping it from updating the node (nid) table?

# Answer
Instead of creating a new object, you should simply update the node object you already seem to have (or load it first with node\_load()), update it's properies and then save it.

Trying to save a node object that doesn't have all properties set will result in loosing those that aren't set and other issues like the one you're experiencing.
> 2 votes

---
Tags: nodes
---


# Question
Title: How to prevent drupal 7 from saving a node
I have a dummy form that will act as a main switchboard for all my content types. For example:

My starting point in the form fill up process starts with the 'Enter basic categories' node type where user specifies the categories in a taxonomy hierarchy:

Classifieds
-Autos
-Aston Martin
-Computers
-Desktop
-Laptop
-Jobs
A user then selects any of the terms and the page now redirects to the appropriate content type form, e.g. computers\_node\_form

The thing is that Drupal saves this Enter Basic Categories Node Form data that I no longer needed.

Is there a way to cancel or prevent Drupal 7 to save the first content type before the redirect? Any suggestions?

# Answer
So basically, you don't want a form for content entry, but you want a form to streamline the user navigation - right?

You can probably alter the node form (implementing hook\_node\_submit for instance) to stop it from saving data, but I recommend against it. The essence of a node is that it is site content, so it doesn't make sense to have a node form that doesn't save a node to the database.

You can build a custom form that does exactly what you want it to do by implementing hook\_menu (to choose the url for your form) and a custom form generating function. See form\_example.module for examples of custom forms.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: How to convert a block with views content into code?
I'm running into limitations of views. For example, I would like to add additional logic and formatting to a view shown in a block. Is there a good way of taking the existing SQL and formatting from the view to create a custom module?

**For example:** I want to show a table with taxonomy terms, including their hierarchy. Parent terms will have links to one one, children terms will have links to a different view. For children terms I want to show the number of nodes with that term, the number of comments, etc. This can currently not be done using views or would be rather complex to setup.

Rather than starting from scratch writing a module is there a good way to use a similar view and reuse the query and the formatting?

# Answer
You could also use something like this:

```
$view = views_get_view('view_name');
$view->set_display('block_display_name');
$view->set_arguments(array($arg1, $arg2)); //only if you need arguments
$view->execute();
foreach($view->result as $res) {
  // extra stuff here
}

```
> 4 votes

# Answer
Have you considered using a template file such as views-view-unformatted.tpl.php and do the login in there or possibly use a preprocess function?
> 2 votes

# Answer
You can create a small module implementing hook\_block() to create a block and as Stefan said you can then load and manipulate the view, and then call new views with arguments inside.

You create a first view that list the terms and a second that list the content based on the term.

```
function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
  switch($op) {
    case 'list':
      $blocks = array();
      $blocks['myblock'] = array(
        'info' => 'My block administrative title',
        // other options
      );
      return $blocks;
    break;
    case 'view':
      $view = views_get_view('my_view_name'); // view id
      $view->set_display('block_1'); // select display name
      $view->set_arguments(array($arg1, $arg2)); // used to pass arguments to the view
      $view->execute(); // execute the view
      foreach($view->result as $res) { // you go through each of the view result (default to 10)
        // print your term, and load the second view and pass the term as argument, then execute the view.
      }
      return array(
        'subject' => 'Block title', // Block title
        'content' => $content // Your block content.
      );
    break;
  }
}

```

Hope it will help!
> 2 votes

---
Tags: 7
---


# Question
Title: Hide/disable EDIT & DELETE links in menu-customize form
How to hide/disable EDIT & DELETE links in menu-customize form.

www.yoursite.com/admin/build/menu-customize/primary-links

I think that those links bring more potential problems than benefits. It would be great if anyone knew how to disable them per role but a global disable is fine too. I'm using Drupal 6.

p.s. I still want user to have permission to rearrange menu items ordering.

Thanks for the help.

# Answer
You can create a small custom module and implement hook\_form\_FORM\_ID\_alter(). Below is a quick example for Drupal 6:

**.module file**

```
<?php
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function YOURMODULE_form_menu_overview_form_alter(&$form, &$form_state) {
  GLOBAL $user;

  // Check if user has a certain role or not and menu is primary links
  // Change ROLEID to the role id you want operations hidden from
  if (!array_key_exists(ROLEID, $user->roles) && arg(3) == 'primary-links') {

    // Hide edit/delete menu operations
    foreach ($form as $key => $ele) {
      if (substr($key, 0, 5) == 'mlid:') {
        unset($form[$key]['operations']);
      }
    }

  }
}

```

Change `YOURMODULE` to the name of the module you are creating. For assistance creating custom modules, see the Module developer's guide.

To work in Drupal 7, I *believe* all you would need to do is change `arg(3)` to `arg(4)` due to the path changes.
> 3 votes

---
Tags: 6, routes, navigation
---


# Question
Title: How do I trigger an AJAX submit button on page load?
I am attempting to trigger a form (to get live data) on a page load. So far, I have this code I have found from bits and pieces and digging around the net, but unfortunately not a lot of people actually appear to have needed to do this.

```
jQuery(document).ready(function($) {
  var element_settings = {};
  var element = {};
  element_settings.progress = { 'type' : 'throbber' };
  element_settings.submit = { js: true };
  var ajax = new Drupal.ajax($('#edit-ratessubmit'), element, element_settings);
  element.form.clk = element;

  ajax.form.ajaxSubmit(ajax.options);
});

```

This currently complains that element\_settings doesn't contain a URL, but when it does contain a URL, I get some random "b is undefined" error.

# Answer
This was a simple case of targeting the correct element using the code below.

```
$(document).ready(function() {
    $('#edit-submit').trigger('click');
}

```
> -2 votes

---
Tags: ajax, forms
---


title: Changing Menu Path to node/edit

text:
# Question
Title: Changing Menu Path to node/edit
Is it posible to make a copy of primary menu with changed paths?

For example instead of node/56, I need to rewrite the path to node/56/edit. The purpose of this is to have the new menu in my Admin Panel, so the site administrator can click on a link to go directly to node edit page.

# Answer
> 1 votes
You can do it easily with the "views" module by using the node edit link available as field. If you don't really need to keep the menu hierarchy, creating view would be the easiest solution.

# Answer
> 2 votes
Ok, I've got it. I'm using:

I then made a new view with these settings (called primary\_link\_in\_admin):

* **Filter** \- Menu: Menu name = primary-links (or whatever you need)
* **Sort criteria** \- Menu: Weight asc
* **Fields** \-
    + Menu: Link path - **Exclude from display**
    + Menu: Link title - **with overridden values** \- Output this field as a link → Link path: \[link\_path\]/edit

So I have my Primary Menu in the admin section of the site and a site administrator is able to click on any menu link and goes directly to node/edit on that node. In that way I have very clean Admin section of my Drupal site....(perfect for small - brochure type sites)

That's why I love Drupal and it's community :)

# Answer
> 1 votes
Use menu clone, then manually change paths for cloned menu.

---
Tags: 6, routes
---


# Question
Title: Using the Profile2 module, how to access contextual information to place a views block on profile page?
I'm trying to add a list of author's content to a profile2 page. The profile page is separate from the user account page so I can't use get UID from URL option.

# Answer
> 1 votes
Using the View Default Argument From Context Module I added this code to it.

```
function views_arg_context_profile2_view($entity, $view_mode, $langcode) {
  context_set('user', 'uid', $entity->uid);
  context_set('profile', 'pid', $entity->pid);
}

```

Now there is an option in Views Default Argument to pull the ID from context and I place either user or profile in the appropriate text field and it works fine.

# Answer
> 0 votes
You could try this module: http://drupal.org/project/eva. It sounds like using tokens you could probably achieve what you are needing.

I think you could also use page manager/panels to override the profile page and load a context with the author id and pass the context to a view content pane. This probably has a little more overhead and learning curve involved if you are not familiar with panels.

# Answer
> 0 votes
If you're on the profile2 page or have access to the `$profile2` object, you can access it's owner by looking at `$profile2->uid`

---
Tags: views, users
---


# Question
Title: How do I show the last created node in a block, without using Views?
How do I show the last created node in a block, without using the Views module?

# Answer
The recommended way would be to create a custom module that will find/load the node and display in a block. Assuming Drupal 6 from your previous questions.

In your custom module:

```
<?php
/**
 * Implementation of hook_block()
 */
function YOURMODULE_block($op='list', $delta=0, $edit=array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Last Node Created');
      return $blocks;

    case 'view':
      // Get the last created node
      $nid = db_result(db_query('SELECT MAX(nid) AS nid FROM {node}'));
      $node = node_load($nid);

      // Add subject/content to block
      $blocks['subject'] = t('Last Node Created');
      $blocks['content'] = theme('YOURMODULE_node_last', $node);
      return $blocks;
  }
}

/**
 * Implementation of hook_theme()
 */
function YOURMODULE_theme() {
  return array(
    'YOURMODULE_node_last' => array(
      'arguments' => array('node' => NULL),
    ),
  );
}

/**
 * Create the HTML output for last created node
 *
 * @param $node
 * Node object for last created node
 */
function theme_YOURMODULE_node_last($node) {
  // Insert theming code here...
}

```

For more information on creating custom modules, see the Module developer's guide.
> 4 votes

---
Tags: nodes
---


# Question
Title: Variable available everywhere in template?
I'm developing my first website with Drupal. So far it's going well but I have a few details I haven't figured out.

I want to load a random variable on each page load, in order to load a different color scheme each time.

My template is called 'fest' so I put this in my template.php:

```
$color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
$variables['color'] = $color;

```

If I put it in `fest_preprocess_html` the color var can be accessed in html.tpl.php but not in page.tpl.php. I want that variable available in node, page, html, everywhere. Putting this code in plain function `fest_preprocess` didn't work either. What am I doing wrong?

--EDIT Check @Berdir's answer, which led me to resolve this issue. This is the code I used after all:

```
function mytemplate_get_color() {
    static $color = NULL;

    if (!$color) {

        $colors = Array('red', 'blue', 'magenta', 'green');
        $rand_key = array_rand($colors, 1);
        $color = $colors[$rand_key];
    }

    return $color;
}

```

# Answer
$variables are unique for each template. So if you implement hook\_preprocess\_html() and add something, then it is only available for html.tpl.php and nothing else.

I think the easiest way to achieve your goal is to create a new function in your template.php which sets the random color them the first time you access it and the returns the them on following calls. Then you can simply call that function from any template you want and it will return the same value on the same request. Such a function would look like this:

```
function yourtheme_get_color() {
  static $color = NULL;

  if (!$color) {
    // First call, define $colors here and then set $color.
    $color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
  }
  return $color;
}

```
> 5 votes

# Answer
You need to put your code in fest\_preprocess\_page. The last part of the function name ('page' in this case) indicates the template name for which you're proprocessing variables.

```
function fest_preprocess_page(&$variables) {
  $color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
  $variables['color'] = $color;
}

```

Make sure to clear the cache after adding a preprocess function.
> 3 votes

---
Tags: theming
---


title: Database schema for image field

text:
# Question
Title: Database schema for image field
I have a module which behaves much like question and answers. Each question needs to have a help image. So far, I have written the schema as this:

```
function mymodule_schema() {
  $schema(mymodule_questions) = array(
      'description' => 'Stores questions for my module',
      'fields' => array(
          'qid' => array(
            'type' => 'serial',
              'not null' => TRUE,
              'description' => 'Primary Key: Question ID.'
          ),
          'prompt' => array(
             'type' => 'text',
              'not null' => TRUE,
              'size' => 'normal',
              'description' => 'Question prompt',
              'length' => '1000'
          ),
          'option_type' => array(
              'type' => 'varchar',
              'not null' => TRUE,
              'description' => 'Option Type',
              'length' => '255'
          ),
          /* Image field schema goes here */
      ),
  );
}
?>

```

Now, I want to add an image field, i.e. a field where admins can upload images to be shown with each question. What should be the schema for this field? Should I use the Field API in the schema (is that possible?)? If yes, how?

Thanks.

Kaustav Das Modak

# Answer
> 1 votes
To be able to integrate with field API, you would need to declare your custom data thing as a fieldable entity. This is possibly, but it is quite a bit of work and then you'll have to add the field in a install hook.

What you can do as well is simply add a single 'fid' integer column to your table, add a form element of #type 'managed\_file' to your form, which will automatically save the file for you and create an entry in the file\_managed table. You can then simply reference the fid (file id) of that object. Also note that you need to call `file_usage_add()` so that the managed file knows that it is in use. When your object is deleted, use `file_usage_delete()` then the file will automatically be removed.

This is exactly what is done in Drupal 7 for profile pictures, have a look at user\_save() for an example.

---
Tags: entities, media, database
---


# Question
Title: LDAP Authentication + Drupal Registrations possible issue
I wish to have a site that allows for both LDAP authentication and plain old Drupal authentication (Drupal users without LDAP accounts). LDAP accounts will be employees, while Drupal accounts will just be all other types of users.

I foresee a problem with this in the future: What if a new employee is hired and the username (which is mandated by business rules) is already taken by an existing user. For example, a user "Jason Smith" created an account `jasons`. A new employee "Jason Sutherland" is then hired and an LDAP account is created for him `jasons`. Using the LDAP module http://drupal.org/project/ldap, the employee `jasons` would essentially be locked out of our Drupal site. And no, we cannot ask the user to change their username.

What are my options here? I first thought of forcing LDAP accounts to login by their email, disallowing any users from registering with the suffix `@company.org`. Since this should be unique, this could potentially solve the issue. Is this a viable solution? How could I do something like this? Would this require hacking the LDAP module a bit? Do I have other options?

# Answer
> 0 votes
If anyone is interested, here are some methods of resolving this:

1. You can do a force creation of all ldap users before putting your application into production. **Edit** I've written a module for this: http://drupal.org/sandbox/mrryanjohnston/1308882
2. You can require everyone to authenticate with their email addresses. This, too, requires a few modules and a little bit of figuring out, but it can work. This module is the result of some of those efforts: http://drupal.org/sandbox/branana/1300714

---
Tags: users, authentication-authorization
---


# Question
Title: How do we stop the heartbeat module from recording node update activity for certain specific content types we have created?
How do we stop the heartbeat module from recording node update activity for certain specific content types we have created?

We created a content type that collects voting information. When a user votes, a new node is created or an existing node is updated for this content type.

The heartbeat module seems to be recording this event and creating a new activity. In Drupal Commons this activity is displayed in a block called the "Recent Activity" block. We would like to avoid having this update to our "voting" content type from being recorded as an activity, and being shown in the "recent activity" block.

How would we do this?

# Answer
> 1 votes
seems like you use D6 since you mentioned Commons. I've only used Heartbeat in D7. Click on the "heartbeat streams" settings and you have an option for "Choose message types you want to deny from display". There you can select the ones you do NOT want to record. Repeat that for each of the streams.

Also, checkout the "heartbeat templates" for "add\_node" and "edit\_node", there is an option "Disable the message - Defines whether this message template is disabled from logging and viewing."

---
Tags: blocks
---


# Question
Title: how do I organize the input fields in fieldset?
I have a node form in Drupal 7, in order to simplify it for the user I want to break it up into sections using the vertical tabs feature.

Using hook\_form\_FORMID\_alter() I can move the fields with difficulty.tha following is my code.:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {
    $form['cpmonth'] = array(
      '#type' => 'fieldset',
      '#title' => t('test'),
      '#weight' => 5,
      '#collapsible' => TRUE,
    );
$form['cpmonth']['field-14sq']=array();
$form['cpmonth']['field-510sq']=array();

  }

}

```

"field-14sq" and "field-510sq" are my input text fields. Do you have any idea?

# Answer
> 6 votes
If I understand correctly you want to move existing form elements into the fieldset you created. Try this, I'm assuming the fields you want to move are `$form['field-14sq']` and `$form['field-510sq']`

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {
    $form['cpmonth'] = array(
      '#type' => 'fieldset',
      '#title' => t('test'),
      '#weight' => 5,
      '#collapsible' => TRUE,
    );
    $form['cpmonth']['field-14sq'] = $form['field-14sq'];
    unset($form['field-14sq']);
    $form['cpmonth']['field-510sq'] = $form['field-510sq'];
    unset($form['field-510sq']);
  }
}

```

If you have custom submit and validation functions this shouldn't affect them, since fields in fieldsets still come back in the root level of `$form_state['values']` .

# Answer
> 2 votes
what about using the Field Group module Start with creating the node that has the field groups attached to it. Then the each Field Appears like a very cool edit in place feature. It's a cool way of looking at that problem.

# Answer
> 1 votes
i would print each input individually with something like :

```
print drupal_render ($form['cpmonth']['field-14sq'])

```

This way you have lot of flexibility and then can organize your form the way you want.

Although make sure to also print the form ID and tokens to be able to validate the form using that techinc.

```
print drupal_render($form['form_id']);
print drupal_render($form['form_build_id']);
print drupal_render($user_edit['form_token']);

```

---
Tags: 7
---


# Question
Title: How to display the same views exposed form block twice?
I'm trying to display the same views exposed from block twice. Once in the left nav and once in content top. With multi block I can clone the block and I am able to display both. However, I would like the left nav form to have less exposed filters.

The problem is that in `hook_form_alter()` and `hook_preprocess_views_exposed_from()` there are no unique identifiers that I can check to alter the form. It runs through the hooks twice but I cannot seem to know if I am dealing with the left nav form or the content top form.

Does anyone have any insight into this?

I tried the code below which works for views 2 and was going to create my own block and render the form. But I cannot get the code to work for views 3.

```
$view = views_get_view('brands');
$view->set_display('page_2');
$view->init_handlers();

$form_state = array(
  'view' => $view,
  'display' => $view->display_handler->display,
  'method' => 'get',
  'rerender' => TRUE,
  'no_redirect' => TRUE,
);

$output = drupal_build_form('views_exposed_form', $form_state);
$blocks['content'] = $output;

```

Am I looking in the wrong direction?

# Answer
This code worked for me. I'm using Views 6 Alpha 4.

```
$view = views_get_view('your_view');
$view->set_display('the_display_you_want_that_have_a_exposed_block');
$view->init_handlers();
$exposed_form = $view->display_handler->get_plugin('exposed_form');
print $exposed_form->render_exposed_form(true);

```
> 3 votes

# Answer
1\> Can't you add one more display of the same view and override filters for that display? If I get your question correctly then that should do it, you want 2 diff versions of exposed filters in block from a view.

Suggestion for multi block problem:

2\> I would rather use context module - http://drupal.org/project/context to deal with multiple same blocks on the same page and other block visibility issues. This prolly won't solve the current problem at hand but is a better practice going fwd compared to multi block and block clone strategies.
> 2 votes

# Answer
I use some different code to create a block with a views form in (for a different reason, to display the form as a page callback, but it should still work).

```
 $module = 'views';
 $delta = '-exp-my_block_id';
 $block = (object) module_invoke($module, 'block', 'view', $delta);
 $block->module = $module;
 $block->delta = $delta;
 return theme('block', $block);

```
> 0 votes

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


# Question
Title: Drupal Views: How to remove 1 item if it matches the Node TItle
I'm trying to remove one item from a block view if the CCK node title of that item matches the node title of the page it is appearing on. Can someone tell me how I would achieve this? Thank you!

# Answer
> 1 votes
It's better and easier to match by Node ID. To do that, add a "Node: NID" argument (or a 'contextual filter' in newer Views versions) to your view, set it to "Provide default argument", choose "Node ID from URL" as default argument type and check the "Exclude the argument" box. That should do the trick.

---
Tags: views
---


title: What does vid mean

text:
# Question
Title: What does vid mean
I have designed a view and I see this query in the preview section:

```
SELECT node.nid AS nid,
       node_data_field_crm_history_brokerid.field_crm_history_brokerid_value AS node_data_field_crm_history_brokerid_field_crm_history_brokerid_value,
       node.language AS node_language,
       node.type AS node_type,
       node.vid AS node_vid,
       node_data_field_crm_history_brokerid.field_crm_history_caseid_value AS node_data_field_crm_history_brokerid_field_crm_history_caseid_value,
       node_data_field_crm_history_brokerid.field_crm_history_dateadded_value AS node_data_field_crm_history_brokerid_field_crm_history_dateadded_value,
       node_data_field_crm_history_brokerid.field_crm_history_entrydesc_value AS node_data_field_crm_history_brokerid_field_crm_history_entrydesc_value
FROM node node
LEFT JOIN content_type_crm_history node_data_field_crm_history_brokerid ON node.vid = node_data_field_crm_history_brokerid.vid
WHERE node.type in ('crm_history')

```

What does `vid` mean here?

Actually I need this because when I try to insert a simple rule to insert a row in the crm\_history using this query:

```
$result = db_query("INSERT INTO {content_type_crm_history} (vid, nid, field_crm_history_caseid_value, field_crm_history_brokerid_value, field_crm_history_dateadded_value, field_crm_history_entrydesc_value) VALUES (" . $node->nid . ", " . $node->vid . ", " . $caseid . ", " . $brokerid . ", " . $dateadded . ", '" . t($entrydesc) . "')");

```

It does populate the database table but it doesn't show in the view. It shows only the view when I add via the create content page.

# Answer
Unfortunately, vid can mean multiple things. That's not ideal, but I have not seen it causing problems (other than mild confusion now and then).

In the context of nodes, it means 'version id'. For every node in the node table, Drupal can save multiple versions in the node\_revisions table. The version id is the unique identifier in the node\_revisions table. (This is the vid you see in your query.)

In the context of taxonomy, vid means 'vocabulary id'. A vocabulary is a collection of related terms. Every vocabulary has a unique id.

In the context of the Views module, vid means 'view id'.

On a different note, you should not be adding nodes to the database with custom queries. The better method is to create a node object and let drupal write it to the database using `node_save()`.
> 27 votes

# Answer
From the Drupal node object reference page, node-\>vid is the revision id of the current version of the node.

Node content isn't stored directly in the node table but in the node\_revisions table. There's a good explanation of the table structures on this page.
> 5 votes

# Answer
`vid` is the revision id. In Drupal, every node can have multiple revisions. If you aren't using revisions, then the `nid` (node ID) will equal the `vid`.
> 2 votes

---
Tags: views, database
---


# Question
Title: Multi site installation with cPanel showing Warning: symlink() [function.symlink]: File exists in
I want create multi site with drupal 7.I just started with below link http://drupal.org/node/960934 After setup show an warining

Warning: symlink() \[function.symlink\]: File exists in /home/ioss/mydomain/index.php on line 5

The PHP Code is symlik is given below

symlink( '/home/ioss/ashokks/', '/home/ioss/ashokks/test1/' );

in the above code snip drupal installed under the directory "ashokks" and test1 is the multi-site subdomain.

Thanks in advance

# Answer
I fixed the issue, now. Previously, I created an invalid folder name for multi site under the site folder in drupal.

### Wrong

* /home/ioss/ashokks/drupal/site/test1
* /home/ioss/ashokks/drupal/site/test2

### Right

* /home/ioss/ashokks/drupal/site/test1.ashokks.com
* /home/ioss/ashokks/drupal/site/test2.ashokks.com

I hope it is useful for who wants to create a multi site.

This link helped me to resolve this issue.
> 1 votes

# Answer
(1) You need to ensure if test1 does not exists there as directory to sub-domain. You will have to remove it and symbolic link will replace it and will point to main site directory.

Or alternatively....

(2) You can edit your sub-domain settings (from sub-domain manager in C Panel) and replace the file system path to `/home/ioss/ashokks/` so that subdomain can point directly on main site without involving symbolic link as `Options FollowSymLinks` can be disabled in some server configurations.
> 0 votes

---
Tags: multi-sites, installation
---


title: Multisite and symlinks doesn't work

text:
# Question
Title: Multisite and symlinks doesn't work
I just tried to implement Drupal Multi site installation with the link 2 Minute Multisite With cPanel. We found **Warning: symlink() \[function.symlink\]: File exists in /home/ioss/ashokks/sites/test1/index.php on line 5**. We are trying to installing the below domain http://test1.ashokks.com/index.php, i have already setup Drupal 7 in ashokks.com, and we add sub domain test1. We want a Multi drupal site **test1**, with the sub domain of ashokks.com

Thanks in advance

# Answer
> 1 votes
I fixed it by changing the folder name **test1** in sites to **test1.ashokks.com**, following what reported in this question.

---
Tags: 7, multi-sites
---


# Question
Title: Create a custom template for displaying a custom content type - and Views in Drupal 7
I'm creating custom templates for my Drupal 7 site. There is a custom **content type** called `flowers`.

1. Which **template** file (`.tpl.php`) should I put under `templates` directory of my theme's folder for displaying a single `flower-type` node?
2. Can I use the `Views` module to create different views *(i.e displaying picture of a flower in a view & displaying species of the flower in another view)* for displaying **only a single** `flower-type` node? So far I can create pages that displays *list* of flower-type nodes. I want to display *just a single* (perhaps providing it's node-id) `flower-type` node. How do I do that?

2.1. For displaying different types of views to display a single flower-type node, which **template files** (`.tpl.php`) should I edit?

Thanks in advance for caring :)

# Answer
Create node--flowers.tpl.php, put the default code from modules/node/node.tpl.php, and edit it.
> 4 votes

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


title: Software testing and regression testing

text:
# Question
Title: Software testing and regression testing
My company has taken maintenance of a Drupal website where there are some modules that have been specifically developed for this site.

I have to answer to a question that most software do: how can we do "software testing" and "regression testing" with Drupal?

# Answer
Drupal 7 comes with a Testing module, and for Drupal 6 you can download http://drupal.org/project/simpletest.

It doesn't do anything automatically (how could it..) but it allows you to write automated tests that test the functionality of your custom modules.

I wrote a blog post about this a while ago: Writing automated tests for Drupal 7. Even though the title says Drupal 7, most of it applies to Drupal 6 too. See Simpletest documentation on drupal.org for more information.
> 3 votes

# Answer
* Using tools like Selenium, you can automate testing of the website. This is not Drupal a specific solution and can be used with any web stack.
* Drupal 6 and 7 have their own testing framework called SimpleTest which can be used to perform functional testing and unit tests (with some caveats, because Drupal itself isn't suited for unit testing). This solution is tied to Drupal and requires a good understanding if Drupal as a developpement platform.
> 3 votes

# Answer
I am sorry, but I think your question is a little too broad to answer.

It sounds like you need to maintain a site, and the site has custom modules that it uses.

It also sounds like maybe you are interested in knowing how to go about testing new changes you intend to make for the site.

If all of this is true then I think you need to learn Drupal first.

This page should get you started: http://drupal.org/documentation/develop

You may also want to look at the Devel module: http://drupal.org/project/devel

If you have a little more specific details let us know so we can help you out.
> 0 votes

---
Tags: testing
---


title: Module that adds a script to the header

text:
# Question
Title: Module that adds a script to the header
How can I allow my module (created with Features) to add a new script to the head?

The script should be in the correspoinding module directory.

# Answer
You can add a script using `drupal_add_js` and to have it added on every page, you can call it in `hook_init`.

Module directory path can be resolved by `drupal_get_path('module', 'module_name')`

```
module_init() {
  drupal_add_js(drupal_get_path('module', 'module_name')."/js/myscript.js");
}

```
> 1 votes

---
Tags: 7, features
---


title: How do I lock a field on Node Edit?

text:
# Question
Title: How do I lock a field on Node Edit?
I want to create a node field that is only editable upon node creation. Once the node has been created, the field of that node will no longer be editable.

# Answer
If you are ready for the *do it in code* road, you can implement `hook_field_access()`, something like

```
function MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  if ($op == 'edit' && $entity_type == 'node' && $field['field_name'] == 'field_of_interest') {
    // The nid property of a new node is empty
    return empty($entity->nid);
  }
}

```
> 3 votes

# Answer
Here you go: the Field Permissions module, which (as stated on its project page) "*... allows site administrators to set field-level permissions to edit, view and create fields on any entity.*"
> 4 votes

---
Tags: 7, entities
---


# Question
Title: Display content type in custom display format
I created an content type of name "profile", where it has fields **Profile Name**, **Image** , **message** , **body**.

It displays in this format attached image\_1

Now how can we arrange or make change in custom format like below image image\_2 how can we displayed to end user

# Answer
> 4 votes
you can use `node--NAMECONTENTTYPE.tpl.php` in your directory template. Please see this documentation and comments about templates in Drupal 6 http://drupal.org/node/17565, this will give you a guidance to recognize some few differences with Drupal 7.

to be more detailed, you can copy/paste to your theme directory the file node.tpl.php (located in `modules > node` or already located inside your theme directory) and rename it according your content type. for example, if the Content Type is `Article` the name will be `node--article.tpl.php`

already inside in `node--article.tpl.php` you can see the variable `$content` or you can use `$node`. `$content` (or `$node`) variable is carrying the content of your node. you can use `print_r($content);` to see the list of the fields that you can use to your node (or if you use Devel module, is best use `dsm($content);`)

**see this example:**

I have a field called `field_demotext1`, then this is the way that I can use to call their respective value inside any custom html zone of my node layout:

```
echo $content['field_demotext1']['#items'][0]['value'];

```

here is the example of zone in the `node--article.tpl.php` where you can use a custom html:

```
  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      //print render($content); comment to hide all content
      echo $content['field_demotext1']['#items'][0]['value']; //will only show field_demotext1 value
    ?>
  </div>

```

---
Tags: 7, users, entities
---