The Form Lifecycle


Introduction

To better understand how to manipulate forms it's helpful to understand their lifecycle.

In general forms go through a build and make process before they can provide a response.

For this article let's take a look at what's involved with a very common use case:

public function create(ExampleFormBuilder $builder)
{
    return $builder->render();    
}

The above controller method injects the form builder and returns a form response via the render method.

Build

The first method that is called is build. This step is solely responsible for converting the form component definitions like model, fields, and sections into their respective classes and collections.

The form builder first guesses defaults and then uses a builder pattern (similar to a factory) to build the various classes and set them on the form object within the builder.

Make

After the form has been built the form calls it's make method. This method also first calls post internally which runs validation and saves the model entry when this form builder is used to handle POST requests.

If the form is handling a POST request then the response will generally be set then as a form redirect. However if after posting itself the form has not had a response set on it the make method will set a view response for rendering the form.

Render

Lastly the render method will run one last check to assure a form response has been set before returning the form's response.

Chain of Command

When calling the render method the make method is called first. When the make method is called the build method is called first. This way all you need to do by default is return $builder->render().

Manual Control

You can execute forms manually too:

public function create(ExampleFormBuilder $builder)
{
    $builder->make($this->request->get('id'));

    if ($builder->hasFormErrors()) {
        // Do something here.
    }

    return $builder->getFormResponse();    
}

In this example we make the form (which runs build internally first) and then check if it has any validation errors. Then we return whatever response the form has generated.


No Comments


Leave a Comment