0

In a model, I have two fields that are arrays of values, those are imploded inside a model on beforeSave() and saved into database as strings (this is working fine).

Now, I need to know, how can I retrieve these two fields back into an array on afterFind() so the fields can be populated inside a form.

I should probably note that every form operation is done via RESTful API, and frontend is in AngularJS.

    public $array_1 = [];
    public $array_2 = [];

    public function beforeSave($insert)
        {
            $this->array_1 = implode(',', $this->array_1);
            $this->array_2 = implode(',', $this->array_2);
        }

When I want to do an explode by the same principle, I get error that argument 2 in explode is expecting string and get's an array. I'm assuming that it's because of the array parameters declaration at the top of the file.

I'm total Yii2 newbie, so please be gentle. :)

3
  • display code where you use explode function. Commented Feb 9, 2017 at 11:45
  • Maybe your array_1 is already array when finding. Commented Feb 9, 2017 at 11:48
  • Yasin Patel , thas is exactly what I need, because when I reverse above function and use these fields in afterFind, I'm manipulating same parameters and it doesn't work. Maybe my question is not formulated right, I tried my best to explain. Commented Feb 9, 2017 at 11:51

2 Answers 2

2

Concerning your piece of code, I suggest doing the following staff.

Using afterFind() and beforeSave()

//public $array_1 = []; ( those are redundant )
//public $array_2 = []; ( those are redundant )
public function afterFind()
{
  $this->array_1 = explode(',', $this->array_1);
  $this->array_2 = explode(',', $this->array_2);
}

Sometimes I do as follows:

For example, instead of array_1, array_2 I have one "column", which I like to be able to get as array or raw value (from DB)

public function getColumnArray()
{
  return explode(',', $this->column)
}

public function setColumnArray($value)
{
  $this->column = implode(',', $value);
}

So when I write $model->columnArray, it will give me array value of $model->column. And if I want raw string, then just $model->column


I hope these are what you need

Sign up to request clarification or add additional context in comments.

3 Comments

I understand that, but If I do it this way, I get an error "explode() expects parameter 2 to be string, array given".
@TenderloinSky, oh I get it. See my updated answer please
greatly appreciated!
0

A simple is manage you data using afterFind (in model) .. so each time you retrieve a model you can perform wath you need

public function afterFind()
{
  $this->performYourManiplation();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.