form-manager icon indicating copy to clipboard operation
form-manager copied to clipboard

FR: Please add {{id}} placeholder in template

Open Hubbitus opened this issue 5 years ago • 3 comments
trafficstars

Said I have form:

	$filterRealtyTypeTemplate = '<li>{{ input }}{{ label }}</li>';

	$form = F::form([
		'filter_realty_type' => F::radioGroup(
			[
				'residential'	=> F::radio('Residential real estate')->setTemplate($filterRealtyTypeTemplate)
				,'rural'	=> F::radio('Rural properties')->setTemplate($filterRealtyTypeTemplate)
				,'commercial'	=> F::radio('Commercial real estate')->setTemplate($filterRealtyTypeTemplate)
			]
		)
        )

And I would like access values residential, rural and so on in my template like:

$filterRealtyTypeTemplate = '<li><a href="#tab_realty_type_{{ id }}">{{ input }}{{ label }}</a></li>';

In my case for use with jQuery tabs plugin, but I think it would be helpfull in other cases too.

Change seams trivial like do in Input.php:

    public function __toString()
    {
        if ($this->label) {
            return strtr($this->template, [
                '{{ label }}' => (string) $this->label,
                '{{ input }}' => parent::__toString(),
                '{{ id }}' => $this->getAttribute('value') // !!!
            ]);
        }

        return parent::__toString();
    }

If you wish I could prepare PR.

P.S. Is it possible to provide the template for all radio objects once at radioGroup level?

Hubbitus avatar Apr 15 '20 00:04 Hubbitus

Hi. Thanks for your suggestion but I'm not convinced. This library does not pretend to provide a full template system, just the minimum required to render a form. But for more complex layout, you should implement it in your own templates. For example:

function renderRadio($input) {
    $value = $input->getAttribute('value');
    return "<li><a href=\"#tab_realty_type_{$value}\">{$input}</a></li>";
}

echo '<ul>';
foreach ($form->filter_realty_type as $input) {
    echo renderRadio($input);
}
echo '</ul>';

This is a better (and more performant) solution. Your suggestion is not valid because it is for your specific use case. Other users may want to get the real id (not the value), or any other different attribute.

oscarotero avatar Apr 15 '20 10:04 oscarotero

Sure, I can also build form without that library too ;)

There may be an even more flexible solution. What do you think about setTemplate method which will allow pass lambda for formatting?

Hubbitus avatar May 06 '20 19:05 Hubbitus

That's small enhancment which is not break anything, is not? Could you please add it?

Hubbitus avatar Jan 24 '21 12:01 Hubbitus