laravel-form-builder
laravel-form-builder copied to clipboard
Custom label?
As I've read the docs, its seems that the label is the same as the filed name, with Capital starting letter, however, in some cases, we might need to customize the label, ex: translation.
How would we achieve this?
There are two ways to tackle this:
- just pass the
label
property to the field.
$this->add('name', 'text', [
'label' => trans('first_name')
])
- Add
language_name
to the form class, and it will search for translation in there automatically. Just make sure the field name exists in the translations to be properly translated. If it's not found, it defaults to ucfirst() field name.
class MyForm extends Form {
protected $languageName = 'translations.forms.my_form' // lang/en/translations.php. content below
public function buildForm()
{
$this->add('name', 'text');
}
}
// lang/en/translations.php
return [
'forms' => [
'my_form' => [
'name' => 'First name'
]
]
];
Hi!
I tried this setting, but it doesn't work on 'Entity' labels. :( Can you check this please? Thanks a lot!
$languageName = 'translations.forms.my_form'
Works fine for me. All field types use the same label mechanism (FormField::setupLabel()
), so every field type should work. Debug setupLabel()
or FormHelper::formatLabel()
to find out why it's not working.
Or do you mean the <option>
labels...? Those come from your db, not the translator.
I mean to the "admin_user" text.
Right, that's the <option>
(if not multiple) I was talking about. That's not translated. You have to do that manually by making the entity option property
a callback, which returns a single entity's label:
$this->add('permissions', 'entity', [
'class' => Permission::class,
'property' => function(Permission $permission) {
return trans("foo.bar.$permission->trans_key");
},
]);