1

I want to add a Preview button in Commerce Product Add form. Before adding product, user can see Preview of Product same as Product Display/Detail page.

I am using Rules to create Product Display after saving Product.

I have added below code in form_alter hook but :

//Add Preview

function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'commerce_product_ui_product_form') {
       $form['actions']['preview'] = array(
          '#type' => 'submit',
          '#value' => t('Preview'),
          '#weight' => 10,
          '#submit' => array('product_preview'),
        );

        // Some special stuff when previewing a node.
        if (isset($form_state['node_preview'])) {
          $form['#prefix'] = $form_state['node_preview'];
          $node->in_preview = TRUE;
        }
        else {
          unset($node->in_preview);
        }
  }
}

function product_preview($form, &$form_state, $node) {
  module_load_include('inc', 'node', 'node.pages');
  $node = new stdClass();
  $node->field_product['und'][0]['product_id'] = $productId;
  $node->title = 'test';
  $node->uid = 2;
  $node->type = 'commerceproduct';
  $node->in_preview = TRUE;
  $form_state['node'] = $node;

  node_form_build_preview($form, $form_state);
}

Above code displays preview for edit but problem is in node object i am getting $node->field_product['und'][0]['product_id'] value not whole Product object. So any updated value of product form fields won't be reflected in preview.

I am not sure how to build whole product object within node object.

Can anyone tell me what is missing here ?

1 Answer 1

0

You can try rendering the product entity and attaching it to the form.

To render the product entity (see entity_view):

// Extract the referenced product from the node.
$node_wrapper = entity_metadata_wrapper('node', $node);
$product = $node_wrapper->field_product->value();

$product_view_mode = 'full'; // Set the view mode you want to use to display this product.

// This will return a render array.
$rendered_product = entity_view('commerce_product', array($product->product_id => $product), $product_view_mode);

Finally, alter the form so that it also contains the rendered product.

// Now add the markup to the form.
$form['product_preview'] = array(
  '#markup' => render($rendered_product);
);
1
  • I have created node-type.tpl.php which is not rendering using above code. It is loading default node.tpl.php.
    – Adoshi
    Commented Sep 16, 2014 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.