This may already be possible but if so I can't work it out.

On my product I have a length attribute with some pre defined values, but I also want the option for the customer to chose there own length, so there would be an option of per meter.

I have created a custom line item which includes a field in which they can enter there own length value but I only want to display this field if the per meter attribute is selected. Is this possible?

Comments

marcus178’s picture

Ok found a way of doing it, think it could be better but it works.

Firstly I hide the customisable field and wrap it in a div.

functionmy_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
	$form["line_item_fields"]["field_product_length"]['#prefix'] = '<div id="custom-length">';
	$form["line_item_fields"]["field_product_length"]['#suffix'] = '</div>';
	$form["line_item_fields"]["field_product_length"]['#attributes'] = array('style' => 'display:none;');
}

Then detecting when the attribute is changed can be done through the following commerce hook

function my_module_commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state) {
	$lid = $form['attributes']['field_length']['#value'];
	if ($lid == '110') {
		$commands[] = ajax_command_invoke('#custom-length .form-wrapper', 'fadeIn');
	} else {
		$commands[] = ajax_command_invoke('#custom-length .form-wrapper', 'hide');
	}
}

I would have hoped there was a better to target the element that needs to be shown and hidden but every time I change the attribute the id changes which is why I've wrapped it in a div.

nvahalik’s picture

Component: Miscellaneous » Code
Issue summary: View changes
Status: Active » Closed (works as designed)

Use the Select or Other module to accomplish this. Here is an example.