Tags/topics: 
1
Answers
Vote up!
0
Vote down!

Render field with custom formatter on attribute change

Hi,

The normal way to render a commerce field would be to use this:
print render($content['product:field_my_image']);

Now I need to render it with a different formatter than the default and from what I know I need to use the field_view_field way to do that?

So far I have manage to render it with this:

$display = array('type' => 'custom_formatters_my_formatter'); // Formatter
$product_id = $node->field_product['und'][0]['product_id']; // Product ID
$product = commerce_product_load($product_id); // Load the product
$output = field_view_field('commerce_product', $product, 'field_my_image', $display);
print render($output);

This works nice except I don't know how to get the current ID ( [0] ) from the product that is currently beeing viewed.

Anyone have any suggestion how to solve this?

Kind regards, Mats

Asked by: matsjacobsson
on February 18, 2015

1 Answer

Vote up!
0
Vote down!

So I eventually did manage to fix this, maybe someone will have any use for this.. I'm sure there is a better way to solve this.

In template.php:
// Remove SKU Label
function THEME_preprocess_commerce_product_sku(&$vars) {
$vars['label'] = FALSE;
}

In product template.tpl.php:
// Get sku:
$sku = trim(strip_tags(render($content['product:sku'])));

// Get default field, wont update on ajax call
$display = array('type' => 'custom_formatters_my_formatter'); // Formatter
$product = commerce_product_load_by_sku($sku); // Load it by SKU
$output = field_view_field('commerce_product', $product, 'field_my_image', $display);
?>

<?php
 
print render($output)
?>

(Render it inside a div wrapper)

Custom module:
// Fires on attribute change, replacing the content in ".my-ajax-div"
function HOOK_commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state) {
if (!empty($form_state['context'])) {
$display = array('type' => 'custom_formatters_my_formatter'); // Formatter
$product = $form_state['default_product']; // The product
$output = field_view_field('commerce_product', $product, 'field_my_image', $display);
$replacement = ".my-ajax-div";
$commands[] = ajax_command_replace($replacement, ''.render($output).'');
}
}

/M

Answer by: matsjacobsson
Posted: Feb 19, 2015