官术网_书友最值得收藏!

Rendering forms

Staying on forms for just a bit longer, let's quickly learn how to render forms programmatically. Also, we have already seen how to map a form to a route definition so that the page being built contains the form when accessing the route path. However, there are times where we need to render a form programmatically, either inside a Controller or a block or wherever you want. We can do this using the FormBuilder service.

The form builder can be injected using the form_builder service key or used statically via the shorthand:

$builder = \Drupal::formBuilder();

Once we have it, we can build a form, like so:

$form = $builder->getForm('Drupal\hello_world\Form\SalutationConfigurationForm');

In the preceding code, $form will be a render array of the form that we can return, for example, inside a Controller. We'll talk more about render arrays a bit later on, and you'll understand how they get turned into actual form markup. However, for now, this is all you need to know about rendering forms programmatically--you get the form builder and request from it the form using the fully qualified name of the form class.

With this, we can close the parenthesis on forms.

主站蜘蛛池模板: 纳雍县| 根河市| 宾阳县| 海安县| 和平区| 建昌县| 泽库县| 宜州市| 长子县| 江口县| 霍林郭勒市| 台中市| 灵山县| 黔西| 晴隆县| 共和县| 海盐县| 天长市| 壤塘县| 玉田县| 宿州市| 广丰县| 上思县| 原平市| 岳西县| 凤山县| 黑水县| 宁乡县| 墨竹工卡县| 崇文区| 金湖县| 突泉县| 北票市| 军事| 奇台县| 江华| 大庆市| 赤峰市| 绥德县| 杭锦后旗| 三江|