This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

FeliX
FeliX

HI, All. As i see in doc, i can setup default value for field in yaml file.

fields:
    minute_interval:
    label: Time of receipt
    type: number
    comment: time of receipt
    default: 20

But how i can change default value when i show form ?

FeliX
FeliX

After i write this post i find solution :)

So i do it in model constructor, and read value from settings

public function __construct(array $attributes = array())
{
    $settings = Settings::instance();
    $this->setRawAttributes(['time_period' => $settings->time_period], true);
    parent::__construct($attributes);
}
daftspunky
daftspunky

This could also work:

public function getTimePeriodAttribute()
{
    return Settings::get('time_period');
}
KurtJensen
KurtJensen

These both work but there is still one with daftspunk's solution. Problem is that, it overrides values that were actually set by users when the record is opened for editing. I only want for creating new records, not editing existing. For clarification daftspunks solution above is added to the model file. The function is named "get" + field_name (in CamelCase) + "Attribute()" Don't know the magic behind it but it does work. Thanks daftspunk.

FeliX solution works just like I need it to but it seems a little less elegant.

Last updated

Kirill Artemenko
Kirill Artemenko

KurtJensen said:

These both work but there is still one with daftspunk's solution. Problem is that, it overrides values that were actually set by users when the record is opened for editing.

Just check it before return:

public function getTimePeriodAttribute()
{
    return $this->time_period ?: Settings::get('time_period');
}

or use Settings only when creating:

public function getTimePeriodAttribute()
{
    return $this->exists ? $this->time_period : Settings::get('time_period');
}

for simple value, use $attributes:

public $attributes = [
    'time_period' => 20,
];

Last updated

Mohsin
Mohsin

Alternatively you can do use formExtendFields to override it and it will go into your controller than the model. I used this code for a plugin you can do something like this.

    public function formExtendFields($host, $fields)
    {

      foreach ($fields as $field) {
          if($field -> fieldName == 'name' && !$field -> value)
              $field -> value = ucfirst(BackendAuth::getUser()->login);

          if($field -> fieldName == 'email' && !$field -> value)
              $field -> value = BackendAuth::getUser()->email;

      }
    }

Last updated

maxDubovsky
maxDubovsky

How to do the same with relation_form, where has many relation and pivot data used. How to specify the pivot special defaults? For example: put +1 day to the datapicker on relation when created, but value can be changed there by admin if he needs it.

maxDubovsky
maxDubovsky

maxDubovsky said:

How to do the same with relation_form, where has many relation and pivot data used. How to specify the pivot special defaults? For example: put +1 day to the datapicker on relation when created, but value can be changed there by admin if he needs it.

Sorry for not trying before, solution is very simple, inside an extend pivot class it is possible to set defaults for pivot data.

jfo
jfo

Using this approach get+FieldName+Attribute how can I make this field a sortable column when displaying it on a list?

For example I have this calculated age field on my user model:

public function getAgeAttribute()
{
    return $this->birth->age;
}

Clicking this column on the list to sort by it throws an exception:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'age' in 'order clause' (SQL: select ...

Of course I could set sortable to false to prevent the exception, but I really need to be able to sort by age. Is there a way to sort by a custom column?

wilirius15434
wilirius15434

For anyone who is looking for details on the getXAttribute or setYAttribute methods, please see Laravel's documentation on Accessor's and Mutators.

behiry
behiry

to get attribute value if it empty only, use this:

public function getFieldAttribute() { return $this->exists ? $this->attributes['field'] : 3; }

tony8938
tony8938

You can also set the default value using a partial. Specify the field in the .yaml file to use a partial but leave off the label and comment otherwise they get duplicated.

    'test' => [
                'type' => 'partial',
                'path' => '$/author/plugin/controllers/something/_test.htm',
            ],

Then in the partial, set up the field type, label and any comment and calculate the value in a similar way to the posts above, first checking if it is already set.

<?php
/**
 * $value - default value set in .yaml file
 * $model - model for field
 * $field - configured class object Backend\Classes\FormField
 */
$field->type = 'switch';
$field->comment = 'My comment';
$field->label = 'Test Mode';
$myDefault = 1;  //Calculate this how you wish
$field->value = is_null($field->value)? $myDefault : $field->value ;
?>
<?= $this->formRenderField('test') ?>
tech.computeraid55120
tech.computeraid55120

Dear friends, the partial didn't work for me but the model's extendFormFields did. Its like 2 issues happening at the same time. Basis the set permission, the model needs to 'retweet' the BackendAuth::getUser()->id and we need to reset readOnly='1' or '0' instead of 'true' or 'false' while changing the drop down attributes.

Here's my code in the model doing this perfectly basis the set permission -

public function formExtendFields($form) { if (!$this->user->hasAnyAccess(['daf.erp.manage_employee_tickets'])) { $form->addFields([ 'backenduser_id' => [ 'label' => 'daf.erp::lang.ticket.backenduser', 'emptyOption' => '-- Select --', 'showSearch' => 'false', 'span' => 'auto', 'required' => '1', 'readOnly' => '1', 'default' => BackendAuth::getUser()->id, 'type' => 'dropdown' ], ]); }else { $form->addFields([ 'backenduser_id' => [ 'label' => 'daf.erp::lang.ticket.backenduser', 'emptyOption' => '-- Select --', 'showSearch' => 'true', 'span' => 'auto', 'required' => '1', 'readOnly' => '0', 'default' => BackendAuth::getUser()->id, 'type' => 'dropdown' ], ]); } }

Not sure of the reason why the BackendAuth returns null and why readOnly = 'true' or 'false' doesn't work but the string '1' and '0' do.

JanBo
JanBo

And what about this solution ?

fields:
    minute_interval:
    label: Time of receipt
    type: number
    comment: time of receipt
    defaultFrom: minuteIntervalDefault

Then, in your model :

public function getMinuteIntervalDefaultAttribute()
    {
        return "my other value here, or function, etc...";
    }

By the way, you also can use this solution to give a default value to dropdown fields.

1-14 of 14

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.