2019-11-18 05:58:33 +01:00
|
|
|
---
|
2014-10-19 10:32:34 +02:00
|
|
|
title: How to Create Lightweight Form
|
2019-11-18 05:58:33 +01:00
|
|
|
summary: Create a simple search form with Silverstripe CMS
|
|
|
|
iconBrand: wpforms
|
|
|
|
---
|
2014-10-19 10:32:34 +02:00
|
|
|
|
|
|
|
# How to Create Lightweight Form
|
|
|
|
|
2017-07-03 03:22:12 +02:00
|
|
|
Out of the box, SilverStripe provides a robust and reusable set of HTML markup for [FormField](api:SilverStripe\Forms\FormField), however this can
|
2014-10-19 10:32:34 +02:00
|
|
|
sometimes produce markup which is unnecessarily bloated.
|
|
|
|
|
2017-07-03 03:22:12 +02:00
|
|
|
For example, a basic search form. We want to use the [Form](api:SilverStripe\Forms\Form) API to handle the form but we may want to provide a
|
2014-10-19 10:32:34 +02:00
|
|
|
totally custom template to meet our needs. To do this, we'll provide the class with a unique template through
|
|
|
|
`setTemplate`.
|
|
|
|
|
2018-06-25 00:39:53 +02:00
|
|
|
**app/code/Page.php**
|
2014-10-19 10:32:34 +02:00
|
|
|
|
2017-08-03 02:51:32 +02:00
|
|
|
|
|
|
|
```php
|
2017-10-27 04:38:27 +02:00
|
|
|
public function SearchForm()
|
|
|
|
{
|
|
|
|
$fields = new FieldList(
|
|
|
|
TextField::create('q')
|
|
|
|
);
|
2017-08-07 05:11:17 +02:00
|
|
|
|
2017-10-27 04:38:27 +02:00
|
|
|
$actions = new FieldList(
|
|
|
|
FormAction::create('doSearch', 'Search')
|
|
|
|
);
|
2017-08-07 05:11:17 +02:00
|
|
|
|
2017-10-27 04:38:27 +02:00
|
|
|
$form = new Form($this, 'SearchForm', $fields, $actions);
|
|
|
|
$form->setTemplate('SearchForm');
|
2017-08-07 05:11:17 +02:00
|
|
|
|
2017-10-27 04:38:27 +02:00
|
|
|
return $form;
|
|
|
|
}
|
2017-08-03 02:51:32 +02:00
|
|
|
```
|
2014-10-19 10:32:34 +02:00
|
|
|
|
2018-06-25 00:39:53 +02:00
|
|
|
**app/templates/Includes/SearchForm.ss**
|
2014-10-19 10:32:34 +02:00
|
|
|
|
2017-08-03 02:51:32 +02:00
|
|
|
|
|
|
|
```ss
|
2017-10-27 04:38:27 +02:00
|
|
|
<form $FormAttributes>
|
|
|
|
<fieldset>
|
|
|
|
$Fields.dataFieldByName(q)
|
|
|
|
</fieldset>
|
|
|
|
|
|
|
|
<div class="Actions">
|
|
|
|
<% loop $Actions %>$Field<% end_loop %>
|
|
|
|
</div>
|
|
|
|
</form>
|
2017-08-03 02:51:32 +02:00
|
|
|
```
|
2014-10-19 10:32:34 +02:00
|
|
|
|
|
|
|
`SearchForm.ss` will be executed within the scope of the `Form` object so has access to any of the methods and
|
2017-07-03 03:22:12 +02:00
|
|
|
properties on [Form](api:SilverStripe\Forms\Form) such as `$Fields` and `$Actions`.
|
2014-10-19 10:32:34 +02:00
|
|
|
|
2019-11-18 05:58:33 +01:00
|
|
|
[notice]
|
2014-10-19 10:32:34 +02:00
|
|
|
To understand more about Scope or the syntax for custom templates, read the [Templates](../../templates) guide.
|
2019-11-18 05:58:33 +01:00
|
|
|
[/notice]
|
2014-10-19 10:32:34 +02:00
|
|
|
|
|
|
|
|