0
votes

I have a form, where users pick some options, and I would like to insert into DB an additional, concatenated field, based on user inputs. I need to do it on SCENARIO_CREATE (and update). E.g.:

type: A
size: 100
color: black

concatenated: A100black

I've tried it this way:

Model:

class Xyz extends BaseXyz {

    const SCENARIO_CREATE = 'create';

    public function rules() {
        ...
        ['concatenated', 'generateConcatenated', 'on' => self::SCENARIO_CREATE],

    ...

    public function generateConcatenated() {
        return $this->type . $this->size . $this->color;
    }

Controller:

class XyzController extends base\XyzController {

    public function actionCreate() {
        $model = new Xyz;
        $model->scenario = Xyz::SCENARIO_CREATE;
        ...

I've tried with 'filter' also in rules, but no success. Maybe my approach is totally wrong, and it can't be done in rules? Please point me in the right direction. Many thanks!

1
You have two options: 1st solution You can create hidden field for concatenated column in form and concatenate data from inputs type, size, color using javascript on change event (and maybe other js events) of those three inputs and set value of concatenated hidden field. 2nd solution You can create method in your model which concatenates values of fields and put its result into concatenated field. - aslawin

1 Answers

0
votes

rules are for checking attribute validation but you can do it in rule too:

public function generateConcatenated($attribute,$param) {
    $this->concatenated = $this->type . $this->size . $this->color;
}

I think best logistic way to achieve this is to remove attribute from rules and overriding beforeSave() in your model:

public function beforeSave($insert)
{
    $this->concatenated = $this->type . $this->size . $this->color;
    return parent::beforeSave($insert);
}

you should consider that yii have default insert scenario for new record and update for existing record.