In most cases, you can use a factory to prepare the element. But you are right, your example is the standard procedure in many applications where the value options are set and the specifications for the input filter are defined.
The goal for the next major version, or perhaps even sooner, is to find ways to simplify the process without having to extend the standard form elements.
Some additional background/explanation: The way to extend the standard form elements was originally intended to be. Therefore it is very easy in the current versions because in a form the form element manager is used. The form element manager can fetch form elements, fieldsets and forms without registration!
Fetch a Custom Element without Registration
The form element manager allows fetching custom elements without prior registration with the manager.
The following example creates a custom element:
final class ExampleElement extends Laminas\Form\Element
{
// …
}
The form element manager can create these custom elements by the related class name:
I created a trait that i can use in my Form that works, but is kind of clunky in that I have to surround the addition of the input filter with setUseInputFilterDefaults.
The alternative would be to make another function for the replacement of getInputSpecification(), and call that in the Form’s getInputFilterSpecification(), but I wanted it all-in-one like the inheritance way provided.
Use the translation at the view layer, as it already exists. No need to create a separate element for this usage.
This trait is not required and is a typical example of incorrect usage: methods are being called that do not exist or are defined as abstract methods.
(How this might look differently in the future is currently speculation, so I would not rewrite anything at this point.)
Correct these are defined in the Form class but your trait can be used everywhere:
(new class() {
use PeriodRangeT;
public function __construct()
{
$this->addPeriodRangeInput();
}
});
And this is the typical example of incorrect usage. You assume that it is used in the Form class of laminas-form, but this is not specified anywhere. Therefore you must define abstract methods:
trait PeriodRangeT
{
abstract public function add($elementOrFieldset, array $flags = []);
abstract public function setUseInputFilterDefaults(bool $useInputFilterDefaults);
abstract public function getInputFilter(): InputFilterInterface;
// …
}