Hi,
I have a form for creating and editing a Product. My problem is to pass a database derived variable to the form and select element. When editing a product, the user can select from a dropdown list the number of sub-products displayed (this number comes from a count of sub-products from the repository and must be called with the product_id parameter). The form needs to receive the parameter with the number and build a select element based on it. Have any of you done something similar and can share an example?
Greetings and thank you for your help.
Hello and welcome to our forums!
Do you use laminas-form as stand-alone solution or in a laminas-mvc based application?
I use an application based on laminas-mvc.
Just add a call to your model in the form to get the array of options when you define the dropdown in the form.
That would not solve the task with the product_id
.
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:
If only the select element needs entries from a database then you can create a separate form element with the required dependencies.
Create the element:
class CountrySelectElement extends Laminas\Form\Element\Select
{
// …
public function init()
{
$this->setName('country_id');
$this->setLabel('Countries');
$this->setValueOptions($categories->fetchAllCountries());
// …
}
}
Create a factory for the element.
Register the new element:
retur…
1 Like