I did see some form classes which set form object properties in the buildForm()
method.
However, these property values are no longer available in submitForm()
.
Simplified/incomplete example:
class MyForm {
private $arg0;
public function buildForm($form, $form_state, $nid) {
$this->nid = $nid;
}
public function submitForm($form, $form_state) {
$nid = $this->nid; // $nid will be NULL.
}
}
Actually there are some callbacks where these property values are available. E.g. if you register a #process => [[$this, 'process']]
callback.
But it is not really surprising that the values are gone in some callbacks. ::buildForm()
is not a constructor.
In some other form classes, they use $form_state->set($key, $value)
to make data available to submitForm()
. This works, but it somehow seems ugly.
Another way would be to store these values in the $form
array as '#type' => 'value'
, or as #_my_data' => ...
. Again, I find this ugly.
Is there a more reliable way to initialize object properties on the form object based on url parameters? E.g. to have these parameters sent to the constructor?
Also, depending how I do this, do I need to worry that the data will be serialized?
(To me this seems like a flaw in the form API. But maybe I am missing something. I might open an issue on drupal.org, if the answer does not change my mind.)