community-forum icon indicating copy to clipboard operation
community-forum copied to clipboard

[Feature Request]Allow automatically translating field labels instead of requiring a "label" property for each

Open pekka opened this issue 2 years ago • 1 comments

When defining fields/columns in a CrudController, the usual way to give the field a translated label is:

 CRUD::field('fieldname')->label(trans('my.dictionary.field_fieldname'));

this is arguably a redundancy, because your dictionary entries will usually coincide exactly with the field name, and an option to automate it away it could be useful.

So for example

 CRUD::field('fieldname1');

would automatically be assigned

 trans('<custom prefix>.<model name>.field_<fieldname1>')

(As an option, of course, not by default, to make it non-breaking and of course not everyone needs this!)

As a proof of concept, I created a Trait that does this, below 👇

You would call its assignLabelsFromTranslation() method eg in setupCreateOperation() after defining the fields:

   CRUD::field('fieldname1');
   CRUD::field('fieldname2');
    
    $this->assignLabelsFromTranslation("models.mymodel.field_");

it automatically walks through each field and assigns the translated values to each label:

  trans('models.mymodel.field_fieldname1')
  trans('models.mymodel.field_fieldname2')

I'm sure this is way too hacky to make it into the core - I'm new and don't really know what I'm doing! But a feature along these lines, more nicely implemented, could be a small useful improvement, and should be non-breaking.

trait assignLabelsFromTranslation
{

    /**
     * Automatically override all column labels with a translation.
     *
     * @param  string  $translation_prefix A prefix to use for the trans() lookup call.
     * 
     */
    public function assignLabelsFromTranslation($translation_prefix = null)
    {
        $columnsArray = $this->crud->getOperationSetting('fields');
    
        foreach ($columnsArray as $index => $column)
         {
          
            if (!$column['name'])
             continue;
            
            $translation = trans($translation_prefix.$column['name']);

            $columnsArray[$index]['label'] = $translation;

         }

        $this->crud->setOperationSetting('fields', $columnsArray);
    }

}

pekka avatar Jan 22 '23 13:01 pekka