laravel-form-builder icon indicating copy to clipboard operation
laravel-form-builder copied to clipboard

Custom label?

Open hopewise opened this issue 8 years ago • 6 comments

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?

hopewise avatar Nov 21 '16 11:11 hopewise

There are two ways to tackle this:

  1. just pass the label property to the field.
$this->add('name', 'text', [
  'label' => trans('first_name')
])
  1. 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'
    ]
  ]
];

kristijanhusak avatar Nov 23 '16 18:11 kristijanhusak

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'

CsFender avatar Apr 15 '19 21:04 CsFender

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.

rudiedirkx avatar Apr 15 '19 22:04 rudiedirkx

Or do you mean the <option> labels...? Those come from your db, not the translator.

rudiedirkx avatar Apr 15 '19 22:04 rudiedirkx

I mean to the "admin_user" text.

er

CsFender avatar Apr 16 '19 00:04 CsFender

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");
    },
]);

rudiedirkx avatar Apr 16 '19 13:04 rudiedirkx