I'm trying to add some additional data to dropdown options so I can use them in JavaScript. However, I can't seem to be able to use the $BasePrice or $Blah variables in the template. Anyone any tips?
The code I'm using is:
DropdownExtraDataField.php
<?php
class DropdownExtraDataField extends DropdownField {
/**
* @var boolean $extraData Associative or numeric array of extra data for all dropdown items,
* with array key as the submitted field value, and the array value as a
* extra data included in the interface element.
*/
protected $extraData;
/**
* @param string $title
* @param array $extraData
*/
public function setExtraData($name, $extraData) {
$this->extraData[$name] = $extraData;
return $this;
}
public function Field($properties = array()) {
$source = $this->getSource();
$options = array();
if($source) {
// SQLMap needs this to add an empty value to the options
if(is_object($source) && $this->emptyString) {
$options[] = new ArrayData(array(
'Value' => '',
'Title' => $this->emptyString,
));
}
foreach($source as $value => $title) {
$selected = false;
if($value === '' && ($this->value === '' || $this->value === null)) {
$selected = true;
} else {
// check against value, fallback to a type check comparison when !value
if($value) {
$selected = ($value == $this->value);
} else {
$selected = ($value === $this->value) || (((string) $value) === ((string) $this->value));
}
$this->isSelected = $selected;
}
$disabled = false;
if(in_array($value, $this->disabledItems) && $title != $this->emptyString ){
$disabled = 'disabled';
}
$extraDataValues = array();
foreach($this->extraData as $key => $v) {
$extraDataValues[$key] = $v[$value];
}
Debug::Show($extraDataValues);
$temp = array(
'Title' => $title,
'Value' => $value,
'Selected' => $selected,
'Disabled' => $disabled,
'Blah' => 'Test'
);
Debug::Show($temp);
$options[] = new ArrayData(array_merge(
$temp, $extraDataValues)
);
}
}
Debug::Show(print_r($options, true));
$properties = array_merge($properties, array('Options' => new ArrayList($options)));
return parent::Field($properties);
}
}
DropdownExtraDataField.ss
<select $AttributesHTML>
<% loop $Options %>
<option value="$Value.XML"<% if $Selected %> selected="selected"<% end_if %><% if $Disabled %> disabled="disabled"<% end_if %>>$Title.XML ! $BasePrice $Blah </option>
<% end_loop %>
</select>
Form:
public function Form() {
$fields = new FieldList(
DropdownField::create('ServiceType', 'Service Type'),
DropdownExtraDataField::create('PaperTypeID', 'Paper Type', PaperType::get()->map('ID', 'Name'))->setExtraData('BasePrice', PaperType::get()->map('ID', 'BasePrice'))
);
$actions = new FieldList(
FormAction::create("OrderForm")->setTitle("Submit")
);
$required = new RequiredFields('Name');
$form = new Form($this, 'OrderForm', $fields, $actions, $required);
return $form;
}