Laminas Form and Element Select with parameter from database

A form can be created by passing config to a factory. This is based on laminas-servicemanager’s build method.

Short example that illustrates the usage for your case:

Controller

class ExampleController extends Laminas\Mvc\Controller\AbstractActionController
{
    private Laminas\Form\FormElementManager $formElementManager;

    // …

    public function indexAction()
    {
        // Fetch product ID from request or query string or …
        $productId = '…';

        $form = $this->formElementManager->build(
            ExampleForm::class,
            [
                'product_id' => $productId,
            ]
        );
    }
}

Factory for Form

class ExampleFormFactory implements Laminas\ServiceManager\Factory\FactoryInterface
{
    public function __invoke(
        Interop\Container\ContainerInterface $container,
        $requestedName,
        array $options = null
    ) {
        $form = new ExampleForm();
        if (is_array($options)) {
            $form->setOptions($options);
        }

        return $form;
    }
}

Form

class ExampleForm extends Laminas\Form\Form
{
    public function init(): void
    {
        $productId = $this->getOption('product_id');
        if ($productId !== null) {
            $this->add(
                [
                    'type'    => SubProductElement::class,
                    'options' => [
                        'product_id' => $productId,
                    ],
                ]
            );
        }
    }
}

The list of sub-products should be created as a separate element and the option product_id can be used there.

See also:

1 Like