Skip to content

Can't use related model as attribute #12

@olegkrivtsov

Description

@olegkrivtsov

Hi, I'm trying to use your EditableColumn, but with related model's attribute:

[
      'class' => EditableColumn::class,
      'attribute' => 'image.alt',
      'url' => ['update-related-alt'],
],

Currently your code doesn't allow such use.

I fixed this as follows:

Method run():

public function run()
    {
        $model = $this->findModelOrCreate();
        $attribute = $this->getModelAttribute();

        if ($this->preProcess && is_callable($this->preProcess, true)) {
            call_user_func($this->preProcess, $model);
        }

        $model->setScenario($this->scenario);
        $value = Yii::$app->request->post('value');
        
        $attributeParts = explode('.', $attribute);
        
        $relatedModel = $model;
        foreach ($attributeParts as $attributePart) {
            $relatedModel = $relatedModel->$attributePart;
        }
        
        $relatedModel = $value;
        
        if ($model->validate([$attribute])) {
            return $model->save(false);
        } else {
            throw new BadRequestHttpException($model->getFirstError($attribute));
        }
    }

And the method getModelAttribute():

    private function getModelAttribute()
    {
        $attribute = Yii::$app->request->post('name');

        /*if (strpos($attribute, '.')) {
            $attributeParts = explode('.', $attribute);
            $attribute = array_pop($attributeParts);
        }*/

        if ($attribute === null) {
            throw new BadRequestHttpException('Attribute cannot be empty.');
        }

        return $attribute;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions