I have a twig macro for creating a combo box form element like this :
{% macro select(name, label, choices, help, value) %}
<div class="control-group">
<label class="control-label" for="{{ name }}">{{ label }}</label>
<div class="controls">
{% for choice in choices %}
{% if value is not empty and value == choice.id %}
<option value="{{ choice.id }}" selected="selected">{{ choice.code }} - {{ choice.name }}</option>
{% else %}
<option value="{{ choice.id }}">{{ choice.name }}</option>
{% endif %}
{% endfor %}
<p class="help-block">{{ help }}</p>
</div>
</div>
{% endmacro %}
As you can see, it's not very flexible because I can only use objects with id and name field as the option value and label. Before migrating to twig, I use this PHP function :
function form_select($name, $label, $choices, $keycol, $valcol, $value=null, $help=null)
{ ?>
<div class="control-group">
<label class="control-label" for="<?php echo $name; ?>"><?php echo $label; ?></label>
<div class="controls">
<select name="<?php echo $name; ?>" class="span7" id="<?php echo $name; ?>">
<?php foreach ($choices as $choice) : ?>
<option value="<?php echo $choice->$keycol; ?>" <?php if ($choice->$keycol == $value) echo "selected"; ?>>
<?php echo $choice->$valcol; ?>
</option>
<?php endforeach; ?>
</select>
<p class="help-block"><?php echo $help; ?></p>
</div>
</div>
<?php }
With this function I can send arbitrary objects to the function and use it as the option value and label by passing the field name to the function ($keycol
and $valcol
) and accessing them via PHP's variable variable name feature ($choice->$keycol
and $choice->$valcol
).
Is there anyway I can recreate this function as a twig macro?
The attribute function does this : http://twig.sensiolabs.org/doc/functions/attribute.html
{{ attribute(choice, valCol) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With