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

Rendering forms

Staying on forms for just a bit longer, let's quickly learn how to render forms programmatically. 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 when 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.

主站蜘蛛池模板: 鹤庆县| 长泰县| 垫江县| 克拉玛依市| 汪清县| 通许县| 庐江县| 高邮市| 蒙城县| 康保县| 共和县| 贺州市| 寿光市| 浪卡子县| 什邡市| 来宾市| 溧水县| 兰州市| 桐城市| 格尔木市| 西畴县| 五大连池市| 五峰| 罗江县| 琼中| 双牌县| 浪卡子县| 廉江市| 永仁县| 吉林省| 都匀市| 高清| 邵阳市| 阳曲县| 佛山市| 科技| 宜宾县| 镇康县| 德令哈市| 克拉玛依市| 修武县|