oscarotero / form-manager

PHP library to create and validate html forms
MIT License
153 stars 42 forks source link

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

Open Hubbitus opened 4 years ago

Hubbitus commented 4 years ago

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?

oscarotero commented 4 years ago

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.

Hubbitus commented 4 years ago

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 commented 3 years ago

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