Retrieve rendered html for form fields in laminas inside of the Controller

183 Views Asked by At

I've tried rendering form fields in laminas within the same form class and also controller. I can fetch them within the view, but i need this html in the server side to process and return the html via ajax.

i also search on set template for each field, but no good resource found.

Within the form, I did: use Laminas\View\Renderer\PhpRenderer;

then in the construct: $this->renderer = new PhpRenderer();

and tried to return html:

$form = new ManageInquiry(); // this is my form class
var_dump($this->renderer->render($form->get($fieldName)));
exit;

this gives A plugin by the name "render" was not found in the plugin manager Laminas\Mvc\Controller\PluginManager

same tried with formElement, formRow but still no success.

also in controller:

$html .= $this->formElement($sampleFormBluePrint->get($fieldName));
// here also same error as above was when within the form

Could someone help with this to get rendered html within controller or same form? Or even a partial template for each field and then render it within the controller and return to view via ajax?

1

There are 1 best solutions below

0
mdthh On

I would suggest to cling to the MVC-concept and to not set view-logic within the controller. Also, view helpers like formElement, formRow only work in views and not in the controllers.

If you want to render a view, e.g. your form, without any layout around it, you could use the setTerminal-method:

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;

class BazBatController extends AbstractActionController
{
    public function doSomethingCrazyAction()
    {
        $form = new ManageInquiry();
        $view = new ViewModel([
            'form' => $form,
        ]);

        // Disable layouts; `MvcEvent` will use this View Model instead
        $view->setTerminal(true); // <-- This does the trick!

        return $view;
    }
}

And now in your view you can design your form and use all available view helpers. And only your view-template will be rendered if you call the doSomethingCrazyAction() via an AJAX-request! The layout-file layout.phtml will be ignored

More can be found in the official docs: https://docs.laminas.dev/laminas-view/quick-start/#dealing-with-layouts