# Question
Title: Getting data from a form field using JavaScript in Drupal6
I have a form with two autocomplete fields: 'province' and 'city'.

When a province it's written I would like to get the input from that field in order to use it in a query for only showing cities relative to that province in the 'city' field.

Here is the code so far.

**Hook form:**

```
function location_form(&$form_state, $unused, $form_values) {
  $form = array();

  $form['state'] = array(
    '#type' => 'textfield',
    '#title' => 'Province',
    '#description' => 'Province',
    '#autocomplete_path' => 'admin/autocomplete/provinces',
  );

  $form['city'] = array (
    '#type' => 'textfield',
    '#title' => 'Cidade',
    '#description' => 'Cidade',
    '#autocomplete_path' => 'admin/autocomplete/cities'
  );

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

  return $form;
}

```

**Hook menu:**

```
function location_menu() {
 $items['admin/autocomplete/provinces'] = array (
    'title' => 'Provinces autocomplete',
    'description' => 'Provinces autocomplete',
    'page callback' => 'location_provinces_autocomplete',
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  $items['admin/autocomplete/cities'] = array(
    'title' => 'Cities autocomplete',
    'description' => 'Cities autocomplete',
    'page callback' => 'location_cities_autocomplete',
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

**Autocomplete functions:**

```
function location_provinces_autocomplete($input) {
  $items = array();

  $query = "SELECT name FROM location WHERE name LIKE '%s%%' AND level = 1";

  $result = db_query($query, $input);

  while ($row = db_fetch_object($result)) {
    $items[$row->name] = $row->name;
  }

  print drupal_to_js($items);

  exit;
}

function location_cities_autocomplete($input) {
  $items = array();

  $query = "SELECT name FROM location WHERE name LIKE '%s%%' AND level = 2";

  $result = db_query($query, $input);

  while ($row = db_fetch_object($result)) {
    $items[$row->name] = $row->name;
  }

  print drupal_to_js($items);

  exit;
}

```

Hopefully someone can point me out to an example on how to do this or something similar.

# Answer
> 4 votes
My answer is to override the Drupal Autocomplete's populatePopup method to pass in both the state input and the city input, and then account for it in your autocomplete function.

You can override the Drupal AC functions by simply adding the same function to your script.js

Place this at the bottom of your script.js file in your theme directory

```
Drupal.jsAC.prototype.populatePopup = function () {
  // Show popup
  if (this.popup) {
    $(this.popup).remove();
  }
  this.selected = false;
  this.popup = document.createElement('div');
  this.popup.id = 'autocomplete';
  this.popup.owner = this;
  $(this.popup).css({
    marginTop: this.input.offsetHeight +'px',
    width: (this.input.offsetWidth - 4) +'px',
    display: 'none'
  });
  $(this.input).before(this.popup);

  // Do search
  this.db.owner = this;
  if ($(this).parents("form").attr('id') == 'location-form' && this.input.id == 'city') {
    this.db.search($("#location-form input[name='state']").val() + "|" + this.input.value);
  } else {
    this.db.search(this.input.value);
  }
};

```

And change your city autocomplete function to this (and replace "AND state LIKE" with whatever relation your city has to your state):

```
<?php
function location_cities_autocomplete($input) {
  $items = array();

  $pieces = explode("|",$input);
  $province = $pieces[0];
  $city = $pieces[0];

  $query = "SELECT name FROM location WHERE name LIKE '%s%%' AND level = 2 AND state LIKE '%s%%'";

  $result = db_query($query, $city, $province);

  while ($row = db_fetch_object($result)) {
    $items[$row->name] = $row->name;
  }

  print drupal_to_js($items);

  exit;
}
?>

```

Make sure your clear your cache, and this seems like it would work with the code you provided.

---
Tags: 6, forms, javascript, ajax
---


# Question
Title: How to edit a custom region from an Omega subtheme in Drupal 7
I created a new region in my Omega subtheme called MYTHEME-MENU. I want this region to do the same thing as the normal menu region, but with adding some markup. What is the proper way of doing this (I don't want to add the markup in Omega's region-menu.tpl.php file)?

I see I have a template, process and preprocess directories along with an empty template.php file, but I'm not sure how to use these.

Essentially my MYTHEME-MENU region needs to spit out the following:

```
<div<?php print $attributes; ?>>
   <div<?php print $content_attributes; ?>>
<span class="nav-bg"></span>
    <?php if ($main_menu || $secondary_menu): ?>
    <nav class="navigation">
    <?php print theme('links__system_main_menu', array('links' => $main_menu,
       'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline',
       'clearfix',     'main-menu')), 'heading' => array('text' => t('Main
        menu'),'level' => 'h2','class' =>     array('element-invisible')))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu,
       'attributes' => array('id' => 'secondary-menu', 'class' => array('links',
       'inline', 'clearfix', 'secondary-menu')), 'heading' => array('text' =>
        t('Secondary menu'),'level' =>     'h2','class' => array('element-
        invisible')))); ?>
    </nav>
    <?php endif; ?>
    <?php print $content; ?>
    </div>
  </div>

```

# Answer
I'm trying to get a similar issue solved. In your case, I think you also need to have the region.tpl.php file in your custom templates folder also.
> 1 votes

# Answer
You don't need to create another region for that.

You just have to copy the Omega file omega/templates/region--menu.tpl.php to your subtheme's template folder: MYTHEME/templates/region--menu.tpl.php.

There you can make whatever changes you need.
> 2 votes

---
Tags: theming
---


title: problem with [$node->language][0]

text:
# Question
Title: problem with [$node->language][0]
I have a problem with this code in node.tpl.php

```
<?php if (isset($node->field_image[$node->language][0])): ?>
  <div class="image-block">
    <a href="<?php print $node_url ?>" title="<?php print $node->field_image[$node->language][0]['title'] ?>">
      <?php print theme(
        'image_style',
        array(
          'style_name' => 'teaser',
          'path' => $node->field_image[$node->language][0]['uri'],
          'alt' => $node->field_image[$node->language][0]['alt'],
          'title' => $node->field_image[$node->language][0]['title'],
          'attributes' => array(),
          'getsize' => false
        )
      );?>
    </a>
  </div>
<?php endif; ?>

```

I know above code work if language natural, but my website is bilingual. How can i solve this problem.

# Answer
You shouldn't be accessing the data directly. You should use field\_get\_items() instead. I also use a foreach below, as that makes your code more generally applicable. Limiting to a single image should happen at the field layer, not theme. If you really want to, you could $image = reset($images).

```
$images = field_get_items('node', $node, 'field_image');
foreach ($images as $image) {
  $image_render = theme('image_style', array(
    'style_name' => 'teaser',
    'path' => $image['uri'],
    'alt' => $image['alt'],
    'title' => $image['title'],
    'attributes' => array(),
    'getsize' => false)
  );

  $link = l($image_render, $node_url, array('title' => $image['title'], 'html' => TRUE));
  print '<div class = "image-block">' . $link . '</div>';
}

```
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Removing a field from the new content form
I have created a content type which consists of a title a .zip file and a screenshot using Drupal 7's site builder.

When a user adds an instance of this content type I would like for them to only have exposed fields for the .zip file and the title. I have a custom module that unzips the .zip file and does some analysis and I would like to extract the screenshot at this time.

Is there anyway that I can have the new content form of my content type not show the screenshot field?

# Answer
Three good options:

* Display Suite has a feature to hide fields from the form
* You can use hook\_form\_node\_form\_alter to remove the field

**Edit**: per Clive's suggestion, set \['#access'\] = FALSE instead of unset($form\['field\_zip\_file'\])

Create a new module, (create MY\_MODULE.info, MY\_MODULE.module), and add this to MY\_MODULE.module:

```
<?php

  function MY_MODULE_form_node_form_alter (&$form, &$form_state, $form_id) {
    if ($form['#node']->type == 'my_content_type') {
      if ($form['nid']['#value'] == '') {
        $form['field_zip_file']['#access'] = FALSE;
      }
    }
  }

```
* Use CSS to make it disappear:

Add this to your theme's CSS file:

```
body.page-node-add #edit-field-zip-file {
  display: none;
}

```
> 4 votes

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


title: Undefined offset, CCK field

text:
# Question
Title: Undefined offset, CCK field
I've been getting the following php notice:

Notice: Undefined offset: 9 in include() (line 89 of node--*name*.tpl.php).

Here's the code:

```
<?php
// loops through array to print out addendum pdf's.
for ($i = 0; $i < 10; $i++) {
  $variable2 = "../sites/default/files/" . $node->field_addendum['und'][$i]['filename'];
  $variable1 = $node->field_addendum['und'][$i]['filename'];
  if (isset($variable1)) {
    $result = $i + 1;
    echo "<a href='$variable2' target='_blank'>$result&nbsp&nbsp&nbsp</a>";}
  else {}
}
?>

```

The field\_addendum is a "file" field type from a custom content type. I understand why I'm getting the notice: if the node only has 3 addendums, once the loop gets to $node-\>field\_addendum\['und'\]\[3\]\['filename'\] and onwards, there is nothing in the array.

Is there a way to get the number of files without having to loop through the array first?

# Answer
There are a few different ways to do the loop, personally I'd use a `foreach` statement. You can also compress your code a fair bit and make use of some API calls:

```
$options = array('attributes' => array('target' => '_blank'));
foreach (field_get_items('node', $node, 'field_addendum') as $index => $file) {
  echo l(($index + 1) . '   ', file_create_url($file['uri']), $options);
}

```

You could also use `count($node->field_addendum['und'])` to get the number of elements in the array if you want, but I think the above is a bit simpler.

Reference for API functions:

* `field_get_items()`

> Returns the field items in the language they currently would be displayed.
* `l()`

> Formats an internal or external URL link as an HTML anchor tag.
* `file_create_url()`

> Create the download path to a file.
> 0 votes

# Answer
You can try to check if array element exist before assigment, and only if so, assign it, an this way avoid undefined offset:

```
  if (isset($node->field_addendum['und'][$i]['filename'])) {
     $variable1 = $node->field_addendum['und'][$i]['filename'];
    }

```
> 1 votes

---
Tags: 7
---


# Question
Title: Is there a suggested approach to altering the field schema for already populated fields?
I specifically wish to solve this problem http://drupal.org/node/1514826#comment-5866494.

Currently the fivestar module's field schema looks like this:

```
<?php
 function fivestar_field_schema() {
  return array(
    'columns' => array(
      'rating' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
        'sortable' => TRUE,
      ),
      'target' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
    ),
  );
}
?>

```

I would like to change it to:

```
<?php
 function fivestar_field_schema() {
  return array(
    'columns' => array(
      'rating' => array(
        'type' => 'float', // Change to float from int
        'unsigned' => TRUE,
        'not null' => FALSE,
        'sortable' => TRUE,
      ),
      'target' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
    ),
  );
}
?>

```

This would work for new Fivestar fields. However, those that contain data cannot be updated. Since the field storage can be in SQL or Mongo or Solr, I would like to create a generic update to this. However, the most commonly used sql storage does not allow column changes if it has data (see field\_sql\_storage\_field\_storage\_update\_field()).

Is there a suggested way out? Thanks.

# Answer
> 1 votes
I have no idea if this is a "suggested way out," I'm tending to think not, but, with your site offline, you should be able to use phpmyadmin and:

1. Add a field to the database table (your float field),
2. copy all of the data from the original column/field to this new one (something as simple as `UPDATE "tablename" SET "newfield" = "oldfield"` would probably do it),
3. drop the original integer field from the table,
4. rename the new field with the old field's name, and

then take drupal online with the new schema and code that is expecting a float in there instead of an integer.

You could also just rename instead of dropping the original field so you could quickly go back if this screwed up, but I would definitely back things up before trying this in any case :)

---
Tags: entities
---


# Question
Title: How to sync two different content types?
I'm going to build a website for a magazine.I have two different content types. In the first one, I will post the first page of magazine. But in the second one is for articles.
Now, my problem is:
I want to show just articles which are related to the issue which displayed on the top. I know how to show latest content \[for first content type which includes first page\], but i don't know how to show its articles under it. I guess,I would use views, but I don't know how.
to be more clear: I want something like this site.

# Answer
Assuming you have an Issue content type, and an Article content type

Install References and enable Node References. On the Article content type, Add a Node Reference field (could name it "issue") and restrict its options to nodes of type Issue.

Then create a View of Articles and add (under Advanced) a Contextual Filter of Content: Issue (and if you are using url aliases for the Issues, then provide the Contextual filter with a default value of Content ID from URL). Make it a Block display.

Then display the block on Nodes of type Issue, and it should work great for you.
> 3 votes

# Answer
A combination of Panels, Taxonomy and Views could be used for this site. You could use taxonomy terms to differentiate the issues. For e.g for Issue 1, you could enter the term "issue1", for Issue 2 you could use "issue2", etc. Then you could use views to filter content based on Taxonomy terms. This tutorial comes close to what you are trying to build.
> 1 votes

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


# Question
Title: Is it possible to set: "show block on specific pages" into "is only the listed pages", programmatically?
Is it possible to set: "show block on specific pages" into "is only the listed pages"?

I suppose that I should add a new item in this block info, but I don't know which one and can't find it in the api hook\_block\_info(); This block should be only visible in the page overview\_courses/course but is visible in every page except overview\_course/course

```
function menuNode_block_info() {
  $blocks['Course'] = array(
    'info' => t('Dit toont alle blocken weer'),
    'region' => 'sidebar_first',
    'weight' => 1,
    'status' => 1,
    'pages' => "overview_courses/course",
    'cache' => 'DRUPAL_NO_CACHE',
  );
  return $blocks;
}

```

Can someone help me? all help is welcome.

Kind regards

# Answer
You need to set, visibility =\> 'BLOCK\_VISIBILITY\_LISTED'

```
function menuNode_block_info() {
  $blocks['Course'] = array(
    'info' => t('Dit toont alle blocken weer'),
    'region' => 'sidebar_first',
    'weight' => 1,
    'status' => 1,
    'visibility' => 'BLOCK_VISIBILITY_LISTED',
    'pages' => "overview_courses/course",
    'cache' => 'DRUPAL_NO_CACHE',
  );
  return $blocks;
}

```
> 3 votes

---
Tags: blocks
---


# Question
Title: how to insert a block within a cck input form in Drupal 7?
I wanted to insert a block within the CCK input field in drupal 7. I have created a block which would display all the custom content types and the nodes created with those content type in tree structure and categories,sub categories from Magento. The tree value is dynamically populated every time.

I want to display this tree in the cck input form to enable the user to make the selection. I was trying to do this using ***hook\_theme*** in ***hook\_form\_FORM\_ID\_alter***. I used ***module\_invoke*** to insert the block module within the module template file. but its look like I cant insert the block within the template.

Could anyone tell me why I module\_invoke is not working and suggest me a way to insert this tree in the CCK input field. I want to get the value selected in this field and store for use in some other module.

# Answer
> 1 votes
So you're block is created and working? You just want to insert it as a field? You can do that using Display Suite, or if you want to insert it within a text field you could try Insert Block (still in dev)

I think Display Suite is the way to go, it is a very comprehensive module so it takes time to take it all in, but it provides very intuitive solutions for Drupal shortcomings, such as displaying a block as if it were a field.

---
Tags: 7, entities, blocks
---


title: variable_get/set not working right

text:
# Question
Title: variable_get/set not working right
I am using drupal 6. I have a variable in a function which I saved with variable\_set. I called variable\_get in a different function and it keeps giving me the default. Why wont it save the variable? I know that the variable has a value because its used in sql query.

here's my set:

```
    $staff_action = $_GET['staff_action'];
$first_name = $_GET['first_name'];
variable_set('first_name', $first_name);
$last_name = $_GET['last_name'];
variable_set('last_name', $last_name);
$email = $_GET['email'];
variable_set('email', $email);
drupal_set_message($email . " in first function");

```

here's my get in second function:

```
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
$email = variable_get('email', 'none found');
drupal_set_message($email . " in second function");

```

# Answer
> 1 votes
In your code where you are setting the value move the last line above variable\_set() function

Change this code:

```
 $staff_action = $_GET['staff_action'];
$first_name = $_GET['first_name'];
variable_set('first_name', $first_name);
$last_name = $_GET['last_name'];
variable_set('last_name', $last_name);
$email = $_GET['email'];
variable_set('email', $email);
drupal_set_message($email . " in first function");

```

To this:

```
 $staff_action = $_GET['staff_action'];
$first_name = $_GET['first_name'];
variable_set('first_name', $first_name);
$last_name = $_GET['last_name'];
variable_set('last_name', $last_name);
$email = $_GET['email'];
drupal_set_message($email . " in first function");
variable_set('email', $email);

```

Then it should work.

---
Tags: 6, configuration
---


# Question
Title: How do you get the last star to be only star shown in a rating?
The out of the box process with fivestar will show star 1,2,3,and 4 highlighted (it will show all stars up to the actual vote). I need stars except the actual vote to be the neutral or the unselected star.

Say for example, someone votes 4 out of 5. How do I show ONLY 4th star highlighted while all the others are either the neutral or unselected star?

EDIT: After reviewing fivestar.js, I believe the code that handles highlighting is the following;

```
$container.find('.star:lt(' + index + ')').addClass('on');
      $container.addClass('fivestar-widget-' + ($options.length));
      $container.find('a')
        .bind('click', $this, Drupal.behaviors.fivestar.rate)
        .bind('mouseover', $this, Drupal.behaviors.fivestar.hover);

      $container.bind('mouseover mouseout', $this, Drupal.behaviors.fivestar.hover);

      // Attach the new widget and hide the existing widget.
      $select.after($container).css('display', 'none');
    });
  },
  rate: function(event) {
    var $this = $(this);
    var $widget = event.data;
    var value = this.hash.replace('#', '');
    $('select', $widget).val(value).change();
    var $this_star = $this.closest('.star');
    $this_star.prevAll('.star').andSelf().addClass('on');
    $this_star.nextAll('.star').removeClass('on');
    event.preventDefault();
  },

```

# Answer
fivestar.theme.inc on line 206

```
FROM: elseif ($rating >= $star_value) {

TO: elseif ($rating == $star_value) {

```
> 0 votes

# Answer
I haven't used Fivestar but if you use rate it has an option to show the users vote. Rate has a fivestar widget as well.
> 1 votes

---
Tags: 7, rating
---


title: Should I use a separate content type?

text:
# Question
Title: Should I use a separate content type?
In drupal 6 I have a content type with a lot of fields, voting, referenced nodes (as answers), etc. Now I would like to create a very similar content type - same behaviour and everything, there are only 2-3 fields that are different, but everything else is the same. Now comes the question: Should I create a separate content type, setup everything, use separate voting, etc? Or is there a way to somehow *'inherit'* everything and change only 2-3 fields that need to be changed?

# Answer
> 1 votes
If you are going to do this often, or expect changes that require these two types to be in sync in the future, you might investigate the http://drupal.org/project/features module, which packages stuff up like this. But, if it's a one off thing, I'd just go and create a new content type and reuse the existing fields plus the new/different ones in the second content type. If you don't want to type everything in again, you should be able to use the CCK export feature and then just change the name and type of the result and import it, which if all goes well, will create the second type for you identically to the first. Then just add the new/different fields manually.

---
Tags: 6, nodes
---


# Question
Title: Programmatically setting an image field from hook_node_insert (drupal 7)
I have a content type that has a file field (which accepts only .zip file) and a screenshot which is an image field and is not displayed on the content submission form. Instead I have a module that unzips the .zip file from hook\_node\_insert. At this point I would also like to set the screenshot to be a .png extracted from the .zip file. So far I have had no success and I always seem to get an error like this:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '463' for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created, changed, comment, promote, sticky, tnid, translate, uuid) VALUES (:db_insert_placeholder_0,

```

Since I was having trouble getting this to work, I tried what I thought might be simpler, I.E. trying to set the node to some image from the web using code like this:

```
  $image = file_get_contents('http://drupal.org/files/druplicon.large_.png');
  $file  = file_save_data($image, 'public://drupalicon.png',FILE_EXISTS_REPLACE);
  $node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;
  node_save($node);

```

but I always get the integrity constraint problem listed above. Could my problem be related to trying to do this from hook\_node\_insert?

# Answer
`node_save()` actually invokes `hook_node_insert()` so calling it from inside that hook probably isn't the best idea (I'm surprised you don't get out of memory errors doing that actually).

Instead you might want to use `hook_node_presave()`, which is called before the node and associated data is committed to the database:

```
function MYMODULE_node_presave($node) {
  $image = file_get_contents('http://drupal.org/files/druplicon.large_.png');
  $file  = file_save_data($image, 'public://drupalicon.png',FILE_EXISTS_REPLACE);
  $node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;
}

```

That way you won't have to call `node_save()` so you won't get the error, and the field data will save with the node as normal.

As `hook_node_presave()` is called for both inserts and updates, you might want to add a condition in there to check whether the node is new or not (checking `$node->nid` will probably suffice). Otherwise you'll end up doing this operation every time the new node is subsequently saved.
> 3 votes

---
Tags: 7, media
---


title: Get historical stock level in Ubercart

text:
# Question
Title: Get historical stock level in Ubercart
Is there a way to find out the stock level of an Ubercart product on a given date?

I can a) get the total number of items sold between a given date and today, and then b) subtract that number from the current stock level. That's not very useful, though, since the client will likely update the stock level in the interim.

If Ubercart logged changes in stock, something like this, then I think I'd be good to go:

```
| nid | stock_level | datestamp  |
----------------------------------
| 23  | 15          | 1303707600 |
| 23  | 25          | 1327471200 |

```

# Answer
Ubercart doesn't store that information by default, and there's no way to do it without patching the `uc_stock.module` file.

The reason is that the `uc_stock_set()` function updates the `uc_product_stock` database table, but doesn't invoke any hooks to allow other modules to act on that information.

If you create a patch that changes the `uc_stock_set()` function to this:

```
function uc_stock_set($sku, $qty) {
  db_query("UPDATE {uc_product_stock} SET stock = %d WHERE sku = '%s'", $qty, $sku);
  $stock = db_fetch_object(db_query("SELECT * FROM {uc_product_stock} WHERE sku = '%s'", $sku));
  module_invoke_all('uc_stock_set', $stock);
}

```

then you'll be able to write a custom module that implements the new `hook_uc_stock_set()` hook to save timestamp data to a custom table. That would look something like this:

```
function MYMODULE_uc_stock_set($stock) {
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $stock->sku, $stock->qty);
}

```

The uc\_stock module works with the sku rather than the node id so it would be best to store that in your custom table.

The other hook you'll need to implement is one already provided by the uc\_stock module, `hook_uc_stock_adjusted()`. Your module's implementation would look like this:

```
function MYMODULE_uc_stock_adjusted($sku, $prior_stock_level, $qty) {
  $stock_level = $prior_stock_level + $qty;
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $sku, $stock_level);
}

```
> 3 votes

---
Tags: 6, ubercart
---


# Question
Title: How do I set up both a landing page and front page?
Here's the behavior I'm trying to achieve.

If a user types in our domain name www.mysite.com, I want them to go to one page, describing our site. It can be called www.mysite.com/landing.

But if they hit the logo or the home button anywhere in the site, I want them to go a different page, the one defined in Configuration-\>Site Information. It is called www.mysite.com/phront.

Ideas?

# Answer
It’s as simple as sheena\_d already commented on your answer. Define `/landing` as your home page and link your logo and home button to `/phront`. Done!
> 1 votes

---
Tags: 7
---


# Question
Title: Correct way to link to views (to solve multi-domain problem)
I have one site (same codebase, same database) that uses two different domains to display two different themes, depending on the content. (This is achieved via the *Domain Access* module.)

I need to be able to link from one domain to a view on another domain without manually inserting the absolute URL, but I'm not sure how (or even if it's possible).\*

I can use `l()` to link to nodes without any problems. For example, if I'm on **first-domain.com** and I want to link to **second-domain.com/news-story**, I would do the following:

`<?php print l('News Story', 'node/2213'); ?>`

I don't know exactly how it works, but it realises that the news story isn't available on the first domain and automatically creates the absolute link to the second domain.

Creating a link to a view doesn't seem to be so easy. I've made sure the view's *Access restrictions* is set to *Domains* (and that only the one domain is selected) but the `l()` function doesn't seem to look this up.

For example, if I'm on **first-domain.com** and want to link to a list of all the news stories (which is created by a view) on **second-domain.com**, doing this:

`<?php print l('Latest News Stories', 'news-stories'); ?>`

Results in a link like this:

`first-domain.com/news-stories`

When I really want: `second-domain.com/news-stories`

Is there any way to solve this? Even if I could look up both domains that have been set via the *Domain Access* module would work, but I don't know how to do that either. (I've also thought about using Path Redirect, which is better than nothing, but not quite what I'm looking for.)

* Obviously it's possible to put in an absolute URL, but this is far from ideal as the site is currently being developed locally and will eventually be moved to a staging site, and then moved again to production once ready. Remembering to change the absolute links every time would be annoying at best.

# Answer
> 1 votes
Since you obviously are capable of PHP, the best way I can think of is to write a custom wrapper for `l()`, something like:

```
function ml($text, $path, int $domain = NULL, array $options = array()) {
  switch ($domain) {
    case 1:
      return l($text, 'http://first-domain.com/'.$path, $options);
      break;
    case 2:
      return l($text, 'http://second-domain.com/'.$path, $options);
      break;
    default:
      return l($text, $path, $options);
      break;
  }
}

```

That way, the absolute domains only have to be changed in this one central place with each staging step (domains may even be stored in settings.php).

---
Tags: views, navigation, domain-access
---


# Question
Title: System pager isn't showing for logged in users
I'm using Panels 7.x-3.2 on Drupal 7.12. I have the Panels Taxonomy term template enabled and for some reason, there's no pager being rendered below the content. You can manually append ?page=x to the URL and it works, but the pager isn't being shown.

It displays if I enable the Taxonomy Term View instead of the Panel, but I need to use Panels to handle term output in order to heavily customise the layout of terms under a specific vocabulary, so using Views for it isn't really an option.

Any ideas? I looked through the Panels settings both for the specific Panel page and the general ones, but there's no mention of pagers or pagination anywhere, so I'm completely stumped...!

**EDIT** turns out this isn't Panels related. D'oh. It appears to be strictly related to Taxonomy itself. I recall having this issue before, where a Taxonomy term page should have shown a pager but didn't until I overrode the output using Views' Taxonomy term page. Not sure what's causing this but I can't find any related issues for Drupal 7.x core, so maybe it's something to do with my theme (which is derived from Zen)?

**EDIT 2 (25-Apr-12)** after extensive scouring for the cause of this problem I have been able to narrow it down further, but not much. Here's what I know at this point:

* It's affecting system-generated (non-Views) Taxonomy term pages
* The pager is rendered to anonymous users; as soon as you log in, regardless of the account/roles/permissions, the pager disappears
* Pagination itself works; you can append the ?page= parameter to the URL and it will return the specified page of content
* Changing the theme to Bartik fixes the problem

Given that, you'd think my themes (I'm using a parent one and a child theme, both derived from Zen) doing some really weird stuff with page output, but there's absolutely nothing in them that could logically affect paging - especially not for logged in users. In fact, the only hooks they implement are:

* `template_preprocess_page()` (to add some page-specific JS and CSS)
* `hook_form_alter()` (to customise the search form)
* `hook_privatemsg_message_presave_alter()`
* `theme_breadcrumb()` (pretty much as written in Zen)
* `theme_menu_local_tasks()` (also pretty much as written in Zen, which in itself is almost like the original code for it - tweaks the HTML for tabs slightly)
* `theme_menu_local_task()` (again, just the Zen implementation)
* `template_preprocess_html()` (to add body classes)
* `template_process_page()` (very small if condition to specify if the page is a node or not)

Plus some other process\_ and preprocess\_ hook implementations to add some classes and tpl suggestions. There's absolutely no manipulation of any "pager" stuff anywhere, or nothing obvious anyway... so this has really stumped me, but it has to be *something* in my themes surely?

Also, just to clarify, it's definitely not a case of CSS interference as the markup doesn't even make it into the output - it's completely absent. Argh!

# Answer
> 2 votes
Finally figured out the problem with some help from a friend. It was being caused by a conflicting pager in a custom made View that rendered the current user's picture in a block on every page. It's only set to display when the user is logged in, hence why the problem was non-existent for anonymous users.

Changing the pager settings for the view from "Full, display 10 items" to "Display all items" has fixed the problem (presumably since there's only a maximum of 1 user picture to output in the View, Views dictated that there was only 1 page and that interfered with the other pager).

I suppose another solution, although not necessary in this case, would be to change the View's Pager ID.

In hindsight the solution is pretty obvious, because I have known about the Pager ID setting for a long time, and even knew what it did - but hopefully this will come in useful for anyone else with a complex site layout running into the same problem. :)

---
Tags: 7, paging
---


# Question
Title: How to include a rule variable (text) in "Set a data value" direct input mode
Originally posted this in the Rules issue queue ( http://drupal.org/node/1547160 ) but then saw how few posts from the last 2 weeks had any replies. Scary!

When setting a data value (text) I am unable to include a rule variable (also text) in direct input mode. I was originally trying to do this to build up a large string from fields while looping through a list of nodes. For the sake of understandability I've reduced this to the simplest possible case. The rule export is below and requires Devel module.

Note: I can perform direct assignment of one variable to another using data selection. (Unfortunately that does not satisfy my use case.) It's just direct input mode where I'm failing.

Please can someone tell me whether I should be able to do this and, if so, what I'm doing wrong?

```
{ "rules_example_text_inclusion" : {
    "LABEL" : "Example text inclusion",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "devel" ],
    "ON" : [ "node_view" ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "*This is the value of text_variable_1*" },
          "PROVIDE" : { "variable_added" : { "text_variable_1" : "Text variable 1" } }
        }
      },
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "*This is the initial value of text variable 2*"
          },
          "PROVIDE" : { "variable_added" : { "text_variable_2" : "Text variable 2" } }
        }
      },
      { "data_set" : {
          "data" : [ "text-variable-2" ],
          "value" : "Overwriting the value of text_variable_2:\r\n[text-variable-1]\r\n[text_variable_1]\r\n"
        }
      },
      { "devel_debug" : { "value" : [ "text-variable-2" ] } }
    ]
  }
}

```

# Answer
Okay, the answer is: What I was doing wrong was trying to use a feature that did not exist! However, milesw posted a patch on my d.o issue ( http://drupal.org/node/1547160 ) that totally worked for me (woo!) and that I hope will work for you too if you're looking for the same feature.

Edit: If you are looking for this feature please could you try milesw's patch and feed back on it.
> 2 votes

---
Tags: 7, rules
---


title: Change script in preprocess

text:
# Question
Title: Change script in preprocess
> **Possible Duplicate:**
> How do I update jQuery to the latest version I can download?

I need to upgrade jQuery from 1.5 to 1.7 in Drupal 7.

In Drupal 6 I could implement a `hook_preprocess_html()` function and alter the `$variables['scripts']` to do this; but after inspecting `$variables` in Drupal 7, I can see there is no index called `'scripts'`.

How can I do the same thing in Drupal 7?

# Answer
> 0 votes
If you want to do it use hook\_js\_alter. But unless you really know what you're doing, consider using jquery update.

# Answer
> 1 votes
It's not a good Idea to change manually the jQuery lib of drupal , because It can cause lot of bugs , instead of this use jquery update module

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


# Question
Title: Use a class on a DIV on specific content with Omega
I'm using Drupal 7 and my theme is Omega. I have got a class "`mask`" and its CSS code is like so:

```
.mask {
    background:url("../img/header_mask.png") repeat-x scroll 0 0 transparent;
    height:200px;
    position:absolute;
    top:0;
    width:100%!important;
    z-index:101
}

```

I'm creating a class on Omega theme options to show content top, but my div shows on every page. So, I want show this class only on node pages.

```
This is my node.tpl.php:
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print $user_picture; ?>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

  <div class="content"<?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);
    ?>
  </div>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>

</div>

```

Where should I add my "`mask`" class in this code?

# Answer
> 0 votes
You don't mention if it's a particular node TYPE that you're after. If it is, then please clarify that. You also don't say what the `.mask` div actually contains, so I'm going to assume it contains nothing and the content is the background image. If this is the case then you can just put `<div class="mask"></div>` anywhere. The `position: absolute` should mean that it won't dislodge any other content anyway.

I'm also not sure why you need `!important` after `width`. If this class is something you're declaring then it shouldn't get overriden unless YOU want it to. If you're worried about it then I'd namespace the class instead (ie `.mytheme-mask`).

**EDIT**

Put it anywhere, but write it like this:

```
<?php if (!drupal_is_front_page() && !$teaser) { ?>
  <div class="mask"></div>
<?php };?>

```

This means that if the page is a content page (not the front page) and not a teaser then place your div in the node.

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


# Question
Title: Allow another role to edit only parts of any node
I have nodes with a "topic" field that is a taxonomy reference. Nodes are submitted by users and users can only edit their own nodes.

How can I allow a "moderator" role to be able to edit the topic fields for any nodes but not any other fields on those nodes?

# Answer
The Field Permissions module will allow you to do exactly this.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 5 votes

---
Tags: 7, users
---


title: Suggest linking of content types

text:
# Question
Title: Suggest linking of content types
I have two OG groups - Organizations and E-hoods. and group content types - goals and ideas. I would like users to have a suggest feature which enables people to basically link groups and group content. Also the linking should be moderated.

Is there a module that does this ? or if anyone can give me a direction to work on, I can work on it too. I'm using Drupal 7 and have a limited knowledge on drupal.

Thanks!

# Answer
You should take a look at References for the linking part, and also Workbench for the moderation part, and lastly Field Permissions to give users access to do the linking.

* Create a Node reference field on one content type, to link the child node to the parent (or vice-versa)
* Use Field Permissions to grant everyone access to enter/edit the field
* Use Workbench to force changes into a new revision which need to be approved.
> 0 votes

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


# Question
Title: How to debug #states mecanism - trying to get #states to work with inner fieldsets & webform
I have a relatively simple webform, with 2 fieldsets and a few other fields. The fields aformentionned have #states actions configured and behaving proper like in a regular form.

It is in the fieldset shown below I have a problem. THe fieldset should be collapsed (via #states) and there is nothing I can do to make it so.

The offending fieldset has #states defined in the bottom form\_alter, I outlined the error location in caps:

```
// Implements hook_form_alter()
function formHelper_form_alter(&$form, $form_state, $form_id)  {
switch ($form_id)  {

        case 'webform_client_form_1':

           // Set fieldsets as collapsible
          $form['submitted']['inscription']['#collapsible'] = true;
          $form['submitted']['inscription']['#collapsed'] = true;

          $form['submitted']['inscription']['enfant_1']['#collapsible'] = true;
          $form['submitted']['inscription']['enfant_1']['#collapsed'] = false;

          $form['submitted']['inscription']['enfant_2']['#collapsible'] = true;
          $form['submitted']['inscription']['enfant_2']['#collapsed'] = true;

            //vardump of fieldset
           dpm($form['submitted']);

           // Show datepicker for child one if inscription is part time
           $form['submitted']['inscription']['enfant_1']['jrs_semaine']['#states'] = array(
              'visible' => array(   // action to take.
                ':input[name="submitted[inscription][enfant_1][horaire]"]' =>
                  array('value' => 't_partiel'),
              ),
           );
           // Show datepicker for child two if inscription is part time
           $form['submitted']['inscription']['enfant_2']['jrs_semaine2']['#states'] = array(
              'visible' => array(   // action to take.
                ':input[name="submitted[inscription][enfant_2][horaire_2]"]' =>
                  array('value' => 't_partiel'),
              ),
           );
            // THIS IS THE FIELDSETY THST DOES NOT WORK:
           // set state on second fieldset to be visible only when two is seiected.
           $form['submitted']['inscription']['enfant_2']['#states'] = array(
              'expand' => array(   // action to take.
                ':input[name="submitted[inscription][enfant_1][horaire]"]' =>
               array('value' => 't_partiel'),
              ),
           );
          break;
 }
}

```

Now, in the drupal docs (example module) there is a fieldset shown with working code using as the state to change, and it seems in the docs fieldsets are clearly supported, alas not the one in my webform.

I am using the same condition that is working on the other field so I assume the problem is not with the selector. In light of this fact, I have no clue of what even to really look for but I really want to figure it out.

Is anyone familiar enough with #states to tell me how I could debug the js in this case?

I know it is in /misc/states.js, I just don't know what to look for in states.js, or even if this is what is preventing the fieldset from collapsing.

**update:** Reposted the full hook\_form\_alter function as per request.

# Answer
Can you add the full code for both form items?

If the element needs to be collapsed at start-up you need to add '#collapsed' =\> TRUE,

It also looks like there's an error in you're selector as pointed out in comments
> 1 votes

---
Tags: forms, webforms
---


# Question
Title: How do you create a block that contains fields from the User Profile?
I tried using the method described in one of the answers here: How to put user profile in a block

I created a block and used the following PHP code as a test; `<?php render(user_view($account)); ?>`

It didnt work. So the question remains, How can you create a block and call user profile fields into it using PHP?

# Answer
`render()` only returns the string, it doesn't print it to the output. This code should work:

```
<?php print render(user_view($account)); ?>

```

Assuming of course that you have loaded the `$account` object. If not you probably want to use something like:

```
global $user;
$account = user_load($user->uid);

```

As an aside, using the PHP filter is considered bad practice (it uses `eval()` which is an inherent security risk).

The best way to get what you're looking for is to write a small custom module that implements `hook_block_info()` and `hook_block_view()`:

```
function MYMODULE_block_info() {
  return array(
    'user_profile' => array(
      'info' => 'User Profile Block',
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

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

  if ($delta == 'user_profile') {
    global $user;
    $account = user_load($user->uid);
    $block['subject'] = 'User Profile';
    $block['content'] = user_view($account);
  }

  return $block;
}

```

If your new to writing modules the best resource I know of is the Module developer's guide, and in particular the Creating Drupal 7.x modules sub-section; it will walk you through all of the steps necessary to get your module up and running.

**UPDATE**

Just to address your second comment...

I think the easiest way to get only certain fields to display would be to install the Entity View Modes module. Then you can create a custom view mode for the user entity (called `block_profile` or something), and in the "Manage Fields" admin page for users assign only the fields you want to be displayed to that new view mode.

Then you can pass the new view mode to the `user_view()` function:

```
$block['content'] = user_view($account, 'block_profile');

```

And voila, your block will contain only the fields that you've added to the new view mode through the admin UI.

If Entity View Modes is causing you issues you can just uninstall it, and add the new view mode yourself using `hook_entity_info_alter()` (again in your new custom module):

```
function MYMODULE_entity_info_alter(&$info) {
  $info['user']['view modes']['profile_block'] = array(
    'label' => t('Profile Block'),
    'custom settings' => TRUE
  );
}

```
> 5 votes

# Answer
You can print the user profile using:

```
<?php print render($user_profile); ?>

```

You can get specific user information by

```
<?php print render($user_profile['user_picture']); ?>
<?php print render($user_profile['summary']); ?>

```
> 0 votes

---
Tags: 7, blocks, users
---


title: How to hide blocks based on menu_name

text:
# Question
Title: How to hide blocks based on menu_name
I've a site with a main menu, and submenus as block. If I'm on node "50" I want to hide every submenu, except the submenu with the link to node "50".

**Question**: How can I hide a block based on it's variable menu\_name (I think it is this variable) without javascript.

Here's a wireframe, so you can get an overview.

# Answer
> 0 votes
I use Menu Block for this purpose. You can specify which levels of which menu you want to show, and the blocks display conditionally depending on the current active trail.

---
Tags: 7, nodes, routes
---


# Question
Title: How can I create a "related content" view but display it as a page with an url alias?
I have created a "related content" view but display it as a page instead of what would more traditionally be a block.

Let's say I have three content types, event, photo and speaker. Each photo and speaker node have an entity reference to an event node.

Photo ----\> EVENT \<---- Speaker

When I view an event node, I would like to have a link to a page that displays all of the photos that reference that event and a similar link/page to display all speakers that reference the event. I have created a view page for each of the subordinate content types (photo/speaker) that takes an event nid as an argument and displays all the nodes that reference that parent node, but there are a number of issues related to the url of these view pages which follow the structure /node/%/photos.

Aesthetically these url's are not ideal. I would prefer to have the url contain the url alias of the event node. For example /event1/photos and event2/photos etc. would all be pointing to the same view but passing the bid of the event as the argument to the view.

I am also open to the possibility that I am going about this in the wrong way so any advice would be appreciated.

# Answer
> 2 votes
You could create two new views for this. For example:

1. Create a new page view and name it something like `Event_Photos`.
2. Set the path to be something like \`event/photos/%'.
3. Add an argument of type `Content:nid`.
4. Setup a relationship using the field that references the photos from the event content-type.
5. Add a filter using the above relationship of type `Content:Type` = photo.
6. You will also need to use the relationship for all your fields.
7. In your first view, rewrite the output for the photo link to `event/photos/nid`.
8. Create a second view for your other content type and follow the above steps.

It would also be possible to use a url in the form `your-event-title/photos`. Then you would have to change the path to `%/photos` and use a argument like `Content:Title` instead.

# Answer
> 1 votes
Mark!

Saw your tweet and thought I could lend a hand:

For #1, I've used arg() many times to construct a URL of this type. This works even when the current page is an aliased page. So node/21, aliased as marks/awesome/page, will return 21 when you use arg(1). I know this is true in D6, I'm assuming it's true in D7.

For #2, you could use PHP to handle processing of the argument. Assuming you use the URL alias for the event node as the first part of your "photos" page. You could use PHP to process the argument by running a simple query to return the node id for that alias.

Hope this helps!

# Answer
> 1 votes
You can try Relation

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.

The Learn Relation module screencast

# Answer
> 1 votes
It turns out the answer is simple (as it often is). The Sub-Pathauto module solves this exact problem. No configuration required. After installing and enabling the modules, my links that I pass through l() that were rendered as node/55/photos now are displayed as event1alias/photos.

---
Tags: 7, views, entities
---


# Question
Title: Why do my breadcrumbs see double? and How can I control them? A double question?
I have a taxonomy menu that invokes a Panel variant linked to a view that uses the taxonomy term. The display works fine, but I get a breadcrumb trail that repeats the menu path twice. I cannot find a setting in the menu, panel or view that offers control of the breadcrumbs, in fact, since this is my first time dealing with breadcrumbs, I discovered I cannot find what controls them at all. How do I configure breadcrumbs?

# Answer
I had similar problem and find out that theme I was using had breadcrumb override function in template.php which was messing with results.
> 3 votes

---
Tags: views, panels, breadcrumbs
---


# Question
Title: How to add sub title name in the header using pixture reloaded sub theme of drupal 7.x?
I need to add sub title name(with different font) next line of the "site name" in the header. Am using pixture-reloaded sub theme. could anybody, please help me out, where should i change and what piece of code i should add to diplay it out.

for example: site name: Drupal Answers next line of the site name, i need one more line to display : Welcome to out job portal.

How can i alter my coding. Please help me out.thanks

# Answer
The "sub title name" you are referring to is called the "Site Slogan" in Drupal. In Drupal 7, you can add or edit your site slogan on the Site Information page (/admin/config/system/site-information).

Then, on the Pixture Reloaded settings page, just make sure that the "Site Slogan" checkbox under "Toggle Display" is checked. You don't need any custom code.
> 2 votes

---
Tags: theming
---


# Question
Title: How to read the session cookie with javascript?
I'm trying to detect with javascript if a user is logged in. For some reason the drupal session cookie is not showing up when I use

```
alert(document.cookie);

```

It does show "Drupal.tableDrag.showWeight=0" and "has\_js=1" cookie.

When I use a cookie tool I see that the SESS... cookie is set.

**Update:**

I'm trying to fix a browser caching issue: Varnish sets a "cache-control max-age" header of 30 minutes which causes the browser to cache the page. When a user logs in and then clicks on a link that's already been cached in the browser it will appear to the user that they have been logged out again.

If I could read the Drupal session cookie from Javascript to see if a user is logged in I could then reload that page.

# Answer
If your theme is somewhat standard, you should be able to look to see if the body has a class of "logged-in" or "not-logged-in" and key off of that. Eg,

```
if ($('body').hasClass('not-logged-in')) {
  // do whatever you want for anon users
} else {
  // do whatever you want for logged in users
}

```

or if all in jQuery:

```
$('body').hasClass('not-logged-in').doWhatEverHere();

```

EDIT ADDITION DUE TO COMMENTS :)

It appears that drupal uses httpOnly with its cookie:

https://www.owasp.org/index.php/HTTPOnly

so you won't be able to access it from the client. So..... given that, you might want to investigate setting your own cookie upon login and deleting it on logout and looking for that, but suggesting that makes me make Bill the Cat noises :)
> 2 votes

---
Tags: 7, javascript, sessions, cookies
---


# Question
Title: Modal Popup in IE submit button does not work
We are using the Ctools modal popup for registration. In every other browser, this works.

In IE8 and IE9, after filling out the popup form, when a user presses "Create Account", the form disappears, and then pops back with all the fields empty. In other browsers, it reroutes to the registration page.

I tried debugging in F12 developer tools but I'm not sure where to look.

# Answer
Have a look at http://drupal.org/node/1549934 for a potential fix.
> 1 votes

---
Tags: users, javascript
---


# Question
Title: Import files into a file field in Drupal 7
I have a content type that accepts a PDF document as a file attachment. I have a bunch of entries that currently have no attachment, but I have the files for each entry and need to associate the files with each of their respective entries.

Currently, all of those files are stored in public://publications, so they're already in the public file path where they should be, I just need to "hook them up".

Rather than hack this with Ruby which I would normally do, I'd like to kick the bad habit and use the Drupal API. I've looked at the following articles:

..but haven't been able to really wrap my head around it.

Curious if others have dealt with this situation and what they've done to address it. Thanks.

**UPDATE**

I've got the files copying as they should be. However, I'm not encountering an error, and the error happens during the `node_save` call.

Here is the error:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
    [:db_insert_placeholder_0] => 0
    [:db_insert_placeholder_1] => 1
    [:db_insert_placeholder_2] => 1330491978
)
 in drupal_write_record() (line 6975 of /var/www/website/drupal-7.4/includes/common.inc).

```

And here is the code.

```
$node = node_load($bib_value->nid);

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);

// THIS IS A PROBLEM LINE
$node->field_publication_attachment[LANGUAGE_NONE] = $file;

node_save($node);

```

If I comment out the line labeled `THIS IS A PROBLEM LINE` then no error occurs, but that obviously isn't desirable because that means it's completing but without attaching my file to the node! Help!

**SOLUTION**

```
$node = node_load($bib_value->nid);

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);

$node->field_publication_attachment[LANGUAGE_NONE][] = (array)$file;

node_save($node);

```

Needed to set `display` and `description` on `$file` as well as cast `$file` as an array when adding it to the attachment field. All worked smoothly after that.

# Answer
> 5 votes
I am currently working on the exact same thing, except using photos. If you click my profile name, you will see a series of questions related to learning how to do what you are asking to do.

I was able to easily accomplish the code to loop through all the files in my folder and add them to my nodes.

```
$file = new stdClass();
$file->filename = basename($local_path);
$file->filepath = $local_path;
$file->uri = $local_path;
$file->filemime = $mime;
$file->filesize = filesize($local_path);

// Set this at the very beginning to correspond to USER you want posting items.
$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$images[] = array(
'fid' => $file->fid,
'alt' => $page_data['title'],
'title' => $page_data['title']
);

```

# Answer
> 5 votes
Another way of doing it:

```
$entity = entity_load($id);
$data = file_get_contents($localpath);
$destination = file_create_filename(basename($localpath), file_default_scheme() . '://yourdir/' );
$file = file_save_data($data, $destination);
$entity->field_attachment[LANGUAGE_NONE][] = (array)$file;
$entity->save();

```

---
Tags: 7, files, importing-exporting
---


# Question
Title: How to get php error logging working properly in a production site
OK, I'm clearly missing something about how error logging is supposed to work. This is a D7 production site, so my goal is to get errors written into a log file, but not show up on the screen. I've added the following to the end of my site's settings.php file:

```
error_reporting(E_ALL); // just to get going; I'll scale this back later
ini_set('display_errors', 0); // don't display errors on the screen
ini_set('log_errors', 1); // log errors...
ini_set('error_log', 'syslog'); // ...in the syslog (I'm running this on Fedora 15,
                                // so I think this should work (although I'd happy to
                                // have the logging happen somewhere else

```

My reading of all the docs makes me think that this should work, but when I put the following into a module file as a way of forcing some errors:

```
$x = 1 / 0;
$foo = $bar + $baz;

```

I still get the divide-by-zero warning and the undefined variable notices coming up on the screen via drupal\_set\_message, and comparable messages in watchdog. If I instead do `error_reporting(0)`, I get nothing on the screen, and nothing in watchdog. In no case do I see any messages showing up anywhere in /var/log.

I'm clearly doing something wrong, no? Can anyone see what it is?

# Answer
Just to be sure that you are in the right path...

PHP.net says that:

> Note:
>
> Although display\_errors may be set at runtime (with ini\_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

Also check http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors and http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log
> 2 votes

---
Tags: configuration
---


# Question
Title: Saving user specific customization settings
My module prints entries from the database,
I use Pager and -\>limit to choose the number of records to show per each page,
instead of hardcoding limit, I'd like user to decide, between e.g. 10,20,50,100 entries per page.

I've got form with select, and the question is - how I can save and pass user defined value to -\>limit.

1. use database - it works, but I'd like to avoid creating extra entry to database concerning such a silly setting like number of records per page
2. variable\_set - if I'll set variable e.g. number\_of\_rows, change in the limit made by one user will affect rest of the users - not acceptable

maybe there's some solution concerning cookies/sessions?

# Answer
> 0 votes
The `$_SESSION` variable is definitely the right place to store this data, e.g. in your form's submit handler you would do something as simple as this:

```
$_SESSION['MYMODULE_num_per_page'] = $form_state['values']['num_per_page'];

```

And when you're actually defining the form element:

```
$default = 10;
$current = isset($_SESSION['MYMODULE_num_per_page']) ? $_SESSION['MYMODULE_num_per_page'] : $default;

$form['num_per_page'] = array(
  '#type' => 'select',
  '#title' => 'Number per page',
  '#options' => drupal_map_assoc(array(10, 20, 50, 100)),
  '#default_value' => $current
);

// Build up the query and add $current to the ->limit() call on the query object

```

# Answer
> 1 votes
The best place maybe the drupal user object's data array for tiny amounts of information, like preferences on a per user basis.

```
$user->data

```

I'm trying to solve this myself but these links seems useful:

---
Tags: users
---


title: Adding classes to menu items

text:
# Question
Title: Adding classes to menu items
Hi I am developing a custom module for menus and I want to add active class to menu items based on the current path. For this I have tried `theme_menu_link()` but this function only provides the mlid(menu link ID) of the original links and not all the menu items. But I need the mlid of all individual menu links.

Is there any alternate hook for this functionality, or any other way to do this?

# Answer
> 2 votes
have a look at `l()` function in `includes/common.inc`:

```
...
if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
    (empty($options['language']) || $options['language']->language == $language_url->language)) {
  $options['attributes']['class'][] = 'active';
}
...

```

# Answer
> 1 votes
Here is my jQuery solution, the advantage is you dont need to add a menu/alter hook.

```
$(document).ready(function() {
    var pathname = window.location.href;
        $('a').each(function() {
            var cur_a_url = $(this).attr('href');
            if(cur_a_url == pathname) {
                $(this).addClass('active');
            }
        });
});

```

But THIS is the perfect Drupal way.

---
Tags: 7, routes
---


# Question
Title: redirecting legacy URLs to corresponding drupal path
I'm planning to migrate the content from my existing legacy system to drupal. In process there are a lot of static pages, nodes and taxonomy terms which have hyperlink references to the legacy URLs that cannot be replaced with current URLs due to their sheer magnitude and for which redirects cannot be set manually (i'm using path\_redirect module to handle redirects, atleast I intend to).

So my idea of implementing this by redirecting my legacy URLs in my *.htaccess* to handle them in a custom module where the drupal URL is deduced based on the URL and its params and redirect them. Also add an entry for them with HTTP 301 in `path_redirect` table so that next request I could check for the entry before proceeding to programmatically determine the node/page URL again. I skimmed the module code which seemed to use `hook_init` to work the redirections and it seemed feasible in theory, though i'm not sure of the results in practice.

Hence I wish to know if this idea is sensible or if it has some flaws as I'm not an expert in the areas of URL rewriting or SEO. Also I'd request anyone with practical experience on the same to know of any challenges involved in this.This served as a reference before I decided to post my query.

# Answer
I've just done a transition like you mentioned and the domain names changed. I didn't want the old urls hitting my drupal server so I setup a 2nd site just for redirects. At first I had a simple php redirect script that would map old urls to Drupal urls. The mapping came off the "migrate\_map" tables that the migrate module generated.

Then someone on the team was concerned about the immediate SEO impact and preferred to keep the old site content available at the old domain name. So I copied the new Drupal site to a 2nd hosting account.

I added a "custom404" module which uses hook\_init() to read the URI, detect a pattern, find the unique key in the uri, then lookup the Drupal nid using the migrate\_map table and then use drupal\_goto() to do a 301 to Drupal URI.

On that Drupal site I show a "website has moved" message with a link to the same URI on the new domain. Pretty soon I'll change my script to just 301 redirect to the new domain directly.

I was initially toying with the idea of using a lower bootstrap level (to have faster redirects) but ran into issues with database connections. Got some great help here about that.
> 2 votes

# Answer
This is quite a specific example, but hopefully it helps.

I moved a site to Drupal that had legacy 'item' (node) URLs that could be any of the following:

* cgi-bin/item.cgi?id=12345
* cgi-bin/item.cgi?id=12345&d=1&h=2
* item/12345
* item/12345/1/2

To preserve these URLs, the site alias on the imported node was set to item/12345 and the code below was added to the vhost.conf to handle the redirection

```
RewriteCond %{QUERY_STRING} id=([0-9]+)(.*)
RewriteRule ^cgi-bin/item.cgi /item/%1? [L,R]
RewriteRule ^item/([0-9]+)/.+ /item/$1 [L,R]

```

I've quite a bit of experience migrating sites to Drupal and between Drupal versions, keeping an eye on the SEO impact. It might be that you don't have to redirect all URLs. Since the publishing titles I have worked with have inbound links almost entirely at nodes or the homepage, I have only preserved their URLs. I've totally changed structural pages addresses and not only avoided a drop in SEO traffic, but have seen positive changes in that area.

I'd suggest you look in Google web master tools to see which pages your inbound links come to and make sure you accommodate those pages in your solution. You could also check in Google analytics to see if a substantial amount of traffic comes to you from specific sites.
> 1 votes

---
Tags: path-aliases, redirection, migrations
---


# Question
Title: how to apply single page checkout using drupal ubercart
I am using Drupal6 with ubercart.I want to apply single page checkout instead of multi step checkout. When I checked the ubercart features it provide the one page checkout in features lint but I am not getting idea how to use this feature.Is there any module for it?

I have a package functionality in my site.There are three package silver,gold and standard.I want user can choose only one package at a time and user should be not able to add more package in cart if the package is already in cart and if user has already that package?

Please help waiting for the response.

Thanks in advance.

# Answer
Yo cant make it single page. Mandatory steps are,

1. Add product to cart
2. Go to checkout page
3. Payment

You can combine the steps 3 by adding Shipping and billing address using Ubercart Checkout Tweaks module, which helps to

**Assume billing and delivery addresses will be the same**

> In many stores, orders are delivered to the billing address more times than not. Enabling this option in the checkout settings will default the "same address" checkbox at checkout, making the checkout page seem shorter and less intimidating.

For limit the products that added to cart you can use `hook_add_to_cart`

```
Parameters:
$nid - the node ID of the product
$qty - the quantity being added
$data - the data array, including attributes and model number adjustments

```
> 1 votes

---
Tags: ubercart, 7
---


title: D7 Views 3 Blog Archive Block

text:
# Question
Title: D7 Views 3 Blog Archive Block
I need to build a "blog archives" block with Views 3. I've seen (and am currently using) the solution at Archive block for nodes using Views, but this method doesn't allow specific enough paths.

Following the linked method, the summary output relies on the selected context filter. For example, if you use **Content: Created Year+Month**, your links turn out like **base\_path/YYYYMM** \- no separation between month and year. Likewise, if you use the **Content: Created Year** or **Content: Created Date** contextual filters you get a string output... not that great for organization.

Is it possible to generate a link path like **base\_path/YYYY/MM** instead of a mixed string? I have attempted to create this solution using aggregation, count and grouped Views fields with no luck.

# Answer
You'd have to create 2 views, one which takes Year argument with path `base_path/yyyy` and another that takes 2 arguments with path `base_path/yyyy/mm`

And you have to create a custom module which defines a `hook_block_info` and `hook_block_view`. This block will basically read your node table for blog type posts, and build links to the 2 views you created above, structured in Year \> Month hierarchy. I'm not sure if there's an easier way to achieve this.
> 2 votes

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


title: Theming forms : what am I doing wrong?

text:
# Question
Title: Theming forms : what am I doing wrong?
I've got a simple form which I would like to run through a theme function of mine. What I do is that I've got a form builder function where I define the form. I've then used hook\_theme() to define which theme function Drupal should use to theme the form.

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_form' => array(
      'render element' => 'form',
    ),
  );
}

```

Drupal does invoke the theme function. However, I've got a call to drupal\_render($variables\['form'\]) to actually render the form in my theme function. What happens then is that Drupal seems to go into a loop as this call results in mymodule\_theme to be called again (and again, and again...).

```
function theme_mymodule_form($variables){

  // Add custom text on top.
  $output = '<span>' . t('Table description goes here') . '</span>';
  $output .= drupal_render($variables['form']);

  // Return output.
  return $output;

}

```

When I do a dump of $variables passed to my theme function, I see that #theme is set to 'mymodule\_theme'. Should I at this point change it to 'form', and not 'mymodule\_form' as I'd just like to render the form as a plain form? How should I really render the $variables'\[form'\] in my theme function to make it appear as a plain old form? Should I rather use theme('form', $variables\['form'\]) for that?

As far as I understand, drupal\_render($variables\['form'\]) takes care of rendering the form and all its children, as opposed to to theme('form', $variables\['form'\]) which only renders the immediate form and not children.

I'd be really happy if someone have the time to enlighten me on this :-)

# Answer
> 1 votes
In Drupal 7 you need to use `drupal_render_children()` instead of `drupal_render()` for the `$form`. Otherwise, if the form has the `#theme` property set you will get an infinite loop (as your theme function will invoke the form builder to run your theme function again, and the cycle will continue).

---
Tags: forms
---


title: Drag and drop builder

text:
# Question
Title: Drag and drop builder
This site comes with a nice drag and drop builder for webform. What modules are required to create a builder like this?

# Answer
The main module to accomplish this is the Form Builder module, which integrates with Webform. Acquia also uses a similar-but-different module for Drupal Gardens.
> 1 votes

---
Tags: webforms
---


title: Custom query in Views?

text:
# Question
Title: Custom query in Views?
At some point I found the need to modify an SQL query generated by Views, in the end I overrode `views_pre_execute` and changed the query for that specific view.

This feels like an ugly hack to me and I wonder if there is a more elegant and maintainable way to do that. Ideal would be a way that would allow me to directly modify the query from the Views UI.

# Answer
> 25 votes
You can also use `hook_views_query_alter()` to alter the query before it's run. I think this is similar to `hook_views_pre_execute`, but makes it easier to modify the query. You basically get access to each part of the query through a keyed array. I haven't found much official documentation, but there's a pretty good example of it at https://www.appnovation.com/blog/using-hook-views-query-alter. This is also the approach I had to use to fix a date bug in the Calendar module.

# Answer
> 4 votes
In general this depends on your use case.

If you want to have a field/filter/argument which should behave in a certain way, it is recommended to write a handler for it. See advanced help of views for more information.

If you want to change some parts of the query you can also use hook\_views\_query\_alter(). The bad thing about `hook_views_query_alter()` is that you can't really reuse the code there.

This is the example code shown from the documentation. It gives an example of what the hook can do.

```
function mymodule_views_query_alter(&$view, &$query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->name == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}

```

# Answer
> 3 votes
I have used the `hook_views_query_alter()` to alter a views mysql query. The following example is tested under Drupal 7 with `7.x-3.0`, it adds a custom `ORDER BY` clause to the query:

```
 function MYTHEME_views_query_alter(&$view, &$query) {
   // check so it's the correct view
   if($view->name == 'product_view') {
     // set a custom 'ORDER BY' clause in the query
     $query->orderby[0] = array(
       'field' => 'SUBSTR(taxonomy_term_data_name,3,4)',
       'direction' => 'ASC'
     );
     $query->orderby[1] = array(
       'field' => 'SUBSTR(taxonomy_term_data_name,1,2)',
       'direction' => 'ASC'
     );
   }
 }

```

# Answer
> 1 votes
I don't know if you can directly change the sql, but you could write your own field handler and craft your own query.

---
Tags: views, database
---


# Question
Title: How to make custom content type as product in ubercart drupal 7?
I want to make custom content types as ubercart products in drupal 7

# Answer
> 8 votes
1. Go to http://mysite.com/admin/store/products/classes
2. Enter the machine name of your content type in the 'Class ID' text field.
3. Enter a human-readable name for your new product class (and optional description)
4. Click save

Ubercart will now register the content type with the machine name that you added in the above steps as a product. Next time you add/edit content of that type you will see all of the Ubercart fields in the edit form.

---
Tags: ubercart, commerce
---


title: show related taxonomy blocks

text:
# Question
Title: show related taxonomy blocks
I wanted to show related taxonomy content in my page and I found this:

http://www.metachunk.com/blog/adding-related-content-view-drupal-7

and it worked perfectly. I wanted to know how it worked basically i.e the 5th step i.e

> Configuration on this filter: -\> When the filter value is NOT in the URL: -\> Provide default value -\> Type: Taxonomy Term ID from URL -\> under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." -\> now check the boxes of the taxonomies you want involved here

He says get Taxonomy term ID from URL and then says Load default filter from node page, that's good for related taxonomy blocks.

Basically what is it doing here ?? Is is trying to tell to block here that get the term ID from the given URL page's term ID selected?

# Answer
It basically means that when you include the view as block on a node page, it will get the term id from the page's taxonomy terms (magically) even though the term id is not really on the page's URL path.

I agree that the description for that option is really confusing.
> 0 votes

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


# Question
Title: Drupal 7 form, query DB and results display
I'm still somewhat new to Drupal but have a lot of experience programming in PHP. I'm looking for a list of modules in Drupal. I need to do this common list of tasks that are very typical of DB interaction:

1. Present a form to a user.
2. Do a query (select or insert) to one or many tables in a database in a custom DB or the one Drupal uses/
3. Present results in table form.

Please help me out thanks. Could anybody can give a sample examples.

# Answer
This is what you need. Take a look into the Examples for Developers module. And Views of course. No need for handcrafted SQL.
> 2 votes

---
Tags: 7
---


# Question
Title: Drush pm-download removing the destination folder
I'm creating a system to easily create new Drupal sites, using drush. When I'm creating a new site, I just point the path where drush should create it and run `drush pm-download drupal-7.12 --destination=/var/www --drupal-project-rename=test11` (example) on it. I saw that drush deletes the folder and then creates it again. Most of the time I still need the files that are in the folder (e.g. 404.html, 403.html etc)
There's any way I could use pm-download without deleting the current files in the folder?
Thanks
-- Info:

Drush version: 5

# Answer
> 1 votes
This sort of request is best made in the issue queue, since what you are requesting is a change in behavior in Drush. The default behavior for pm-download is to always provide a clean unaltered copy of the module; I for one would be reluctant to alter this behavior, but I could potentially get behind a new option that introduced 'merge' behavior.

A better option, I think, would be for you to download Drupal to a temporary folder, and do the merge yourself in your script as a secondary step.

---
Tags: drush
---


# Question
Title: How do I set the page title from view result (same as the view result)
I have set up a View that shows a random page from the site filtered according to node types and uses the `Global : Random (asc)` sort criteria. It displays only one result per page and a fresh page is shown every time the page is refreshed.

I want to set the view's page title to be same as the node displayed. I am doing this using javascript right now, but would prefer a PHP alternative that I could either use in the template or the views setting directly.

Setting the page title using javascript isn't SEO friendly.

I am using the latest version of Drupal 6 with the latest stable release of Views 3.

The results of `print_r($view->result, true)` (as requested) are :

```
Array
(
    [0] => stdClass Object
        (
            [_random] => 0.00171253550957193
            [radioactivity_node_1_s_energy] => 3
            [node_title] => <Title of the node being displayed>
            [nid] => 393
        )

)

```

# Answer
> 1 votes
Inside a views template, you could call `drupal_set_title()` with whatever you want out of the `$view->result` array. You can put a `drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>');` or its equivalent in there to see what you have to work with.

In Style Settings, just click on Theme Information, and choose one, I'd suggest modifying the Style Output one because you could also change `$title` in there as well.

ADDITIONS DUE TO COMMENTS:

No, views will not set this for you, I thought that's what you were asking.

In your views template for the view in question, you need to dig into your row result to get the value you want and then call `drupal_set_title()` with that. Calling it with a null value only returns the existing title, if any.

For example, if you put the print\_r() of your result in there, you will see what values you have to work with, and then you use them with this to set the title.

Let's say you have something like this:

```
[0] => stdClass Object
    (
        [node_title] => Sirens
        [nid] => 240
        [_random] => 0.000554758124570137
    )

```

which is the view result from a view I just put together that randomly returns node titles, you would do something like this in your template:

```
$title=check_plain($view->result[0]->node_title);
drupal_set_title($title);

```

You could also put this in a pre\_render() hook like so:

```
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name==NAMEOFYOURVIEW) { // && $view->current_display == 'page' if needed
    $title=check_plain($view->result[0]->node_title);
    drupal_set_title($title);
  }

}

```

But either way, since I don't know exactly what your view row looks like, I can't tell you precisely what `$view->result[0]......` you need.

Also, all of this is assuming your theme behaves nicely with the $head\_title variable as well.

---
Tags: views, 6
---


# Question
Title: jQuery code is loading content in an unpredictable way
I've got a view of teasers; each teaser has 3 clickable `<a>` elements:

* "morelink" toggles an extra row in a table.
* "noderef" loads the referenced node into a div.
* "ajaxview" sends the node id as an argument to ajax load a view into a `<div>`. This view contains a view of teasers which in turn each have 3 clickable `<a>` elements thus creating a nested view of teasers which in turn each have 3 clickable `<a>` elements.

This is the JavaScript code.

```
Drupal.behaviors.morelink = function(context) {
  $("a.morelink").click(function (e) {
    e.preventDefault();
    $('.xtrarow').eq( $('a.morelink').index( $(this) ) ).toggle();
  });
}

Drupal.behaviors.ajaxview = function(context) {

    $("a.ajaxclick").click(function(){
    var nid = $(".mynid").eq($('a.ajaxclick').index( $(this) )).val();
    $('.container').eq($('a.ajaxclick').index( $(this) )).load(Drupal.settings.basePath + 'myajax/' + nid);
    return false;
});
}

Drupal.behaviors.noderef = function(context) {

    $("a.nrefclick").click(function(e){
      e.preventDefault();
    var nref = $(".mynref").eq($('a.nrefclick').index( $(this) )).val();
    $('.container').eq($('a.nrefclick').index( $(this) )).load('node/' + nref );
    return false;
});
}

```

This is the HTML code.

```
<input type="hidden" class="mynref" value=<?php print $node->field_noderef[0]['nid']; ?> />
<a class="nrefclick" href = "<?php print url('node/' . $node->field_noderef[0]['nid']); ?>">
<img src="http://mysite/smallpinkarrowback.png" ALT="Back"></a>

<a class="morelink" href = "<?php print url('node/' . $node->nid); ?>">
<img src="http://mysite/smallyellowarrowdowninfo.png" ALT="Forward"></a>

<a class="ajaxclick" href="<?php print url('myajax/' . $node->nid); ?>">
<img src="http://mysite/smallpinkarrowforward.png" ALT="Forward"></a>

```

The behavior is erratic: The "morelink" works consistently and is fine; the ajaxview works intermittently, and seems to load ok for the first few clicks, but once you've clicked a few, the JavaScript stops working.

Can anyone spot the problem?

# Answer
Here's what worked in the end;

```
Drupal.behaviors.ajaxview = function(context) {
  $('a.ajaxclick:not(.ajaxview-processed)', context)
  .addClass('ajaxview-processed').each(function() {
    $(this).click(function(e){
        e.preventDefault();
      $index = $('a.ajaxclick').index($(this));
      var nid = $(".mynid").eq($index).val();
      var toLoad = Drupal.settings.basePath + 'myajax/' + nid;
        xhr = $.ajax({
        url: toLoad,
        success: function(data) {
          $('#content').html($('.audioforumtable', data));
          Drupal.attachBehaviors(context);
        }
      });
    });
  });

 $('a.nrefclick:not(.ajaxview-processed)', context)
  .addClass('ajaxview-processed').each(function() {
    $(this).click(function(e){
        e.preventDefault();
      $index = $('a.nrefclick').index($(this));
      var nref = $(".mynref").eq($index).val();
      var toLoad = Drupal.settings.basePath + 'node/' + nref;
        xhr = $.ajax({
        url: toLoad,
        success: function(data) {
          $('#content').html($('.audioforumtable', data));
          Drupal.attachBehaviors(context);
        }
      });
    });
 });
}

```

I changed the container to content because it worked better for what I need but the problem seems likely to have been the lack of the Drupal.attachBehaviors(context) . Thanks to Baysaa for steering me in the right direction! I will vote your answer up when I have enough reputation points.
> 3 votes

# Answer
I can't tell the immediate problem, but one thing I notice is you're not using the `context` variable in your behaviors. Try the code below see if it makes any difference.

The classes are to prevent the behavior getting attached to an element already processed by the behavior.

```
Drupal.behaviors.morelink = function(context) {
  $("a.morelink:not(.morelink-procd)", context)
    .addClass("morelink-procd")
    .each(function(i){
      $(this).click(function(e) {
        e.preventDefault();
        $('.xtrarow').eq($('a.morelink').index($(this))).toggle();
      });
    }
  );
}

Drupal.behaviors.ajaxview = function(context) {
  $("a.ajaxclick:not(.ajaxclick-procd)", context)
    .addClass("ajaxclick-procd")
    .each(function(i) {
      $(this).click(function(e){
        e.preventDefault();
        $index = $('a.ajaxclick').index($(this));
        var nid = $(".mynid").eq($index).val();
        $(".container").eq($index).load(Drupal.settings.basePath + 'myajax/' + nid);
        return false;
      });
    }
  );
}

Drupal.behaviors.noderef = function(context) {
  $("a.nrefclick:not(.nrefclick-procd)")
    .addClass("nrefclick-procd")
    .each(function(i){
      $(this).click(function(e) {
        $index = $('a.nrefclick').index($(this));
        e.preventDefault();
        var nref = $(".mynref").eq($index).val();
        $('.container').eq($index).load('node/' + nref );
        return false;
      });
    }
  );
}

```

**EDIT:** Reverted the `$.each()` indexing as it may not be appropriate for this occasion.
> 2 votes

---
Tags: views, ajax, javascript
---


title: can't query numeric field

text:
# Question
Title: can't query numeric field
I can't seem to query on a field of type "numeric".

From hook\_schema:

```
'id' => array(
  'description' => "ID",
  'type' => 'numeric',
  'unsigned' => TRUE,
  'precision' => 20,
  'scale' => 0,
  'not null' => TRUE,
  'default' => 0,
),

```

if I do something simple like the following code, I don't get anything.

```
$query = db_select('tablename', 't')
  ->fields('t', array('nid'))
  ->condition('id', $id, '=');

```

However, if I execute the following query on PHPMyAdmin, I get a row.

```
SELECT * FROM `tablename` WHERE id = 195755377227337728;

```

I did try to type cast the id with `(int) $id`, but that didn't work either.

Do you have any thought?

# Answer
Two things that might be causing the problem:

1. You need to execute the query: $result = $query-\>execute();
2. The id you gave is HUGE, and I don't know if it would ever work. Drupal comes with the nid column set to a length of 10. Even if you've accounted for that, the max INT column size in MySQL is 4294967295 and your ID is 195755377227337728. Theoretically you could use BIG INT instead of INT. See: MySQL column type sizes

Also, try this Static Query instead of db\_select():

```
$result = db_query("SELECT nid FROM {table} WHERE nid = :nid", array(':nid' => $nid,));

```
> 2 votes

---
Tags: database
---


title: Set link location on logo only

text:
# Question
Title: Set link location on logo only
I want the logo on my site to go somewhere other than the home page, but I can't seem to figure out where to change that.

I'd appreciate any help you can give

# Answer
The answer to your question very much depends on your how your theme is built and what you want to accomplish. If you want just to link the site logo to another location, I would suggest you to find a corresponding piece of code in page.tpl.php of your theme and replace it with correct link.

If you want to give your site administrators ability to change that link to whatever they want, then I would do this this way:

1. Create a module that adds a page to admin menu of drupal (using hook\_menu).
2. On that page render a form with one input field. When the form is loaded extract previously saved value using variable\_get function.
3. On form submit save the form value using variable\_set function
4. In your hook\_preprocess\_page extract value using variable\_get, compose correct link and pass it to the template
5. In your page.tpl.php just render it in the proper place
> 2 votes

---
Tags: uri
---


# Question
Title: Upgrade Drupal 6 to 7 using Drush 5 in Windows
Drush 4 has a site-upgrade command for major version upgrades.

Looking at Drush documentation pages, and it looks like the command is not a feature in Drush 5. Is there a replacement or was it removed? I'm using the windows version of drush 5.

# Answer
That functionality is now available as a separate module: Drush Site Upgrade

> The new home for site-upgrade drush command, which streamlines the major version upgrade process for Drupal.

There's also some reassurance that this will work with the latest version of Drush:

> **IMPORTANT**: Drush Sup 7.x-2.x requires Drush 5 or later.
> 3 votes

---
Tags: drush
---