-3

I've a created a custom form in custom module. I have couple fields in the form that can be reused to other form. Also as per the coding standards, the function should not be more than 150 lines. So I tried to split the form into multiple (2) functions. But that didn't work. (the second form didn't render into the first form) Here is what I tried

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['some_element'] = [
       '#type' => 'textfield',
    ];
    ..
    ..
    if ($some_condition_exists) {
    //include second form here.
    $this->secondForm($param);
    }
    return $form;
    }

  public function secondForm($param) {
       $form['some_element'] = [
       '#type' => 'textfield',
       '#default_value' => $param
    ];
    return $form;
 }

Do I really need to put this form into another Form file and call \Drupal::formBuilder()->getForm('Drupal\module\Form\xxxForm'); ?

1
  • 2
    The only reason you want to add this complexity is from a coding standard guideline? Is there a functional reason for this need?
    – Kevin
    Oct 31 '20 at 18:28
6

You just seem to be getting confused with the form build concept and PHP logic - what you need to do is add to the existing form array ($form in buildForm), not create a second separate form/array.

With that in mind, this:

$this->secondForm($param);

Doesn't do anything. You're not merging the return value back into $form, and you're not passing $form to secondForm, so that line and the lines in secondForm are basically a no-op.

There a bunch of different ways PHP will let you do what you need to, probably the simplest would be to pass the $form:

public function secondForm($param, array &$form) {
  $form['some_element'] = [
    '#type' => 'textfield',
    '#default_value' => $param
  ];
}

And then

$this->secondForm($param, $form);

As an aside, it might be wise to rename secondForm to something like addAdditionalElements, just to avoid future confusion.

1
  • I usually have to build multistep ajax forms with lots of lines and I find splitting up a lot of related code into their own functions and passing $form by reference as answered here really helps me handle it all and I find it easier to go back to and read. Nov 1 '20 at 9:24
0

Without any details about what "it's not working" means, and if this is your real code, you call $this->secondForm() which returns something, but you don't set it to a variable.

If you update that line to something like $form = $this->secondForm();, this should technically work.

2
  • That will replace any of the current values in $form ... $form += $this->secondForm(); would do it though
    – Clive
    Oct 31 '20 at 19:45
  • 2
    The code shown from the OP doesn't use what secondForm() is returning. That's what doesn't work.
    – apaderno
    Oct 31 '20 at 21:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.