This component class can be subclassed to create components that can be used as form fields.
The component is very simple to use. It introduces two component properties called name and value, which contains the name and the value from the form field.
When rendering your component, you should base all field names on the name property.
Below is a simple component which mimics a normal text field:
class TextComponent extends FieldComponent { public function renderContent() { echo '<input type="text" name="'.$this->name.'" value="'.$this->value.'">'; } }
FieldComponent components can receive three events:
Event | |
---|---|
setvalue | Called if a value is attached to the field from javascript. The value is passed as the first parameter after the event itself. |
reset | Called if the field should reset, for example on form reset |
validate | Called when the field is validated on form submit. To prevent submit, you must set an error on the form field using the setError function from Platform |
For our simple field above a handler for these events could look like this:
addPlatformComponentHandlerFunction('textcomponent', function(item) { item.on('setvalue', function(event, value) { item.find('input').val(value); }); item.on('reset', function() { item.find('input').val(''); }); item.on('validate', function() { if (item.find('input').val() == 'banana') item.triggerError('You are not allowed to write \'banana\' in this field!'); }); });
In order to add the component to the form, you need to use the ComponentField form field. This field is created as a normal form field, and then you add the component with the attachComponent function, like this:
$textcomponent = new TextComponent(); $componentfield = new ComponentField('Label for field', 'field_name'); $componentfield->attachComponent($textcomponent); // $componentfield can now be added to a form
For convenience the form also have an addComponent-function that does exactly the same as above in one line:
$textcomponent = new TextComponent(); $form->addComponent('Label for field', 'field_name', $textcomponent);
It is also possible to perform backend field validation inside the component. The FieldComponent class has a parse()
function which can be overwritten, and functions exactly like the similar-named function in Field. FieldComponent also has the triggerError function to raise an error.
So backend validation for the component above could look like:
function parse($value) : bool { if ($value == 'cherry') { $this->triggerError('You are not allowed to write \'cherry\' in this field!'); return false; } $this->value = $value; return true; }