Pull Ubercart Product Options onto Page Using Computed Field


This is just a little tip that came up because I was working on a shop that has a large number of product options in a select list and we want those to be more scannable and searchable in plain text columns as a field. In order to get this into a field you can use the Computed Field module which will let you enter PHP code and execute and output it. It has some advantages over enabling the PHP filter

  1. You don’t have to actually enable the PHP filter, which cuts down on the risk
  2. The resulting field won’t be editable by just anyone, but only people who have rights to manage content types
  3. full CCK integration
  4. Options for storing in DB or not, so you can effectively cache the computed value, which in the case we’ll look at here, has a bit of overhead.

One thing to keep in mind: if you do store the value in the database, I believe this will not update until you save the node. I’m not sure if there’s a refresh mechanism or not.

This is pretty simple – just enable the Computed Field module and create a new field on your content type and make it a Computed Field type.

Then in the computed field, you just add your PHP to grab what you need. In our case, we want to grab the attribute options that are specific to the actual node that we’re looking at.

Obviously, this is hardcoded for Attribute 1.

$result = db_query("select ao.name from
{uc_product_options} as po, {uc_attribute_options} as ao
where ao.aid='1' AND ao.oid=po.oid AND nid='%d'
order by `name`", $node->nid);

$items = array();
while ($row = db_fetch_object($result)) {
$items[] = check_plain($row->name);
if (empty($items))
$node_field[0]['value'] = '';
$num_options = count($items);
$leftside = '';
$rightside = '';
$colsize = intval($num_options/2);

for ($i=0; $i<$colsize; $i++) {
$leftside .= '<li>' . $items[$i] . '</li>';
$leftside = '<ul class="left half">'. $leftside . '</ul>';
for ($i=$colsize; $i<$num_options; $i++) {
$rightside .= '<li>' . $items[$i] . '</li>';
$rightside = (empty($rightside)) ? '' : '<ul class="right half">'. $rightside . '</ul>';
$items = array();
$node_field[0]['value'] = $leftside . $rightside;

And then to output it, in the Display field,

$display = $node_field_item['value'];

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>