You may create your own fields based on the abstract fields included in the package.
Field class must extend Yiisoft\Form\Field\Base\BaseField
or one of his children and implement necessary abstract
methods.
Full list of available base classes with their hierarchy is available here.
You can use feature traits for your field class.
Adds methods for using form model.
Adds methods for setting and generating custom field content.
Adds methods for setting valid and invalid CSS classes.
To apply common field configuration when field is created through a field factory, class must implement
ValidationClassInterface
.
Adds methods for using placeholder. Could be applied to children of InputField
only.
To apply common field configuration when field is created through a field factory, class must implement
PlaceholderInterface
.
Adds method to set option of enrichment field from form model rules.
To apply common field configuration when field is created through a field factory class must implement
EnrichFromValidationRulesInterface
.
Base configuration of field is set via fieldConfigs
parameter of a field factory. For example:
'fieldConfigs' => [
MyCustomField::class => [
'containerTag()' => ['div'],
'containerAttributes()' => [['class' => 'main-wrapper']],
'inputAttributes()' => [['data-type' => 'input-text']],
'customMethod()' => [true],
],
],
Detailed information about configuration of fields can be seen here.
Field class:
use Yiisoft\Form\Field\Base\InputField;
use Yiisoft\Html\Html;
final class SuffixInput extends InputField
{
private ?string $suffix = null;
public function suffix(?string $suffix): self
{
$new = clone $this;
$new->suffix = $suffix;
return $new;
}
protected function generateInput(): string
{
$input = Html::textInput(
$this->getInputName(),
(string) $this->getFormAttributeValue(),
$this->getInputAttributes()
)->render();
if ($this->suffix === null) {
$html = $input;
} else {
$html = '<div class="input-group">' . "\n";
$html .= $input . "\n";
$html .= '<span class="input-group-text">' . Html::encode($this->suffix) . '</span>' . "\n";
$html .= '</div>';
}
return $html;
}
}
Usage is the following:
echo \Yiisoft\Form\YiisoftFormModel\Field::input(SuffixInput::class, $procentForm, 'value')->suffix('%');
Result will be:
<div>
<label for="procentform-value">Value</label>
<div class="input-group">
<input type="text" id="procentform-value" name="ProcentForm[value]" value>
<span class="input-group-text">%</span>
</div>
</div>