Vlastní formulářový prvek

Pokud se chcete vyhnout manuálnímu vykreslování formulářů a zároveň vložit do formuláře vlastní html kód, je řešením vlastní formulářový prvek.

<?php

declare(strict_types=1);

namespace App\Model;

use Nette;
use Nette\Utils\Html;

class CustomFormControl extends Nette\Forms\Controls\BaseControl
{

    /** @var string */
    public $text;

    public function __construct(string|Html $text){
        parent::__construct();
        $this->text = $text;
    }

    function getControl(){
        return $this->text;
    }


}
<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;
use Nette\Application\UI\Form;
use App\Model\CustomFormControl;


final class PrvekPresenter extends Nette\Application\UI\Presenter
{

    protected function createComponentTestForm()
    {
        $form = new Form;

        $form->addText('inputNad','Input nad:');

        $form['vlastniPrvek'] = new CustomFormControl('<i>Do textu můžete vložit html přímo</i>');

        $form->addSubmit('odeslat', 'Odeslat');

        return $form;

    }

}

Pokud chcete vyplnit i label, nastavte property caption, která je v Nette\Forms\Con­trols\BaseCon­trol

<?php

declare(strict_types=1);

namespace App\Model;

use Nette;
use Nette\Utils\Html;


class CustomFormControl extends Nette\Forms\Controls\BaseControl
{

    /** @var string */
    public $text;

    public function __construct(string|Html $caption, string|Html $text){
        parent::__construct();
        $this->caption = $caption;
        $this->text = $text;
    }

    function getControl(){
        return $this->text;
    }

}
<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;
use Nette\Application\UI\Form;
use App\Model\CustomFormControl;

final class PrvekPresenter extends Nette\Application\UI\Presenter
{

    protected function createComponentTestForm()
    {
        $form = new Form;

        $form->addText('inputNad','Input nad:');

        $form['vlastniPrvek'] = new CustomFormControl('pokud chcete vložit html do caption (label), musíte použít Nette\Utils\Html::el()', 'text');

        $form->addSubmit('odeslat', 'Odeslat');

        return $form;

    }

}