Yii2: Illegal offset type - MongoDB

Created on 2 Jan 2015  Â·  7Comments  Â·  Source: yiisoft/yii2

I try to make dropdownlist with mongoDB :

field($model, 'parent')->dropDownList(
ArrayHelper::map(Category::find()->all(),'_id','name'),['prompt'=>'Select Category'])
?>

And get this error :
PHP Warning – yii\baseErrorException

Illegal offset type

Most helpful comment

If you're getting "Undefined property: MongoId::$id", try this:

<?= $form->field($model, 'parent')->dropDownList(
        ArrayHelper::map(
            Category::find()->all(),
            function ($model) {
                return $model->_id->{'$id'};
            },
            'name'
        ), ['prompt'=>'Select a Category']) ?>

The problem relies in the fact that the MongoId object names the id variable as "$id", and php treats $object->$id as if you were looking for a variable variable (I'm not making up this, check out http://php.net/manual/en/language.variables.variable.php), which roughly translates to $object->null (?) or whathever $id is holding at the moment. using $object->{'$string#withreserved!chars'} solves this issue.

Hope this helps, and maybe it should be addressed to avoid further confusion.

All 7 comments

try

ArrayHelper::map(Category::find()->all(),function ($model){return $model->_id->id;},'name'),['prompt'=>'Select Category'])

see: php.net/manual/ru/class.mongoid.php

0r use __toString

thank you, but with the first solution , I get this error : Undefined property: MongoId::$id

try

return (string) $model->_id; 
//return $model->_id->__toString();

If you're getting "Undefined property: MongoId::$id", try this:

<?= $form->field($model, 'parent')->dropDownList(
        ArrayHelper::map(
            Category::find()->all(),
            function ($model) {
                return $model->_id->{'$id'};
            },
            'name'
        ), ['prompt'=>'Select a Category']) ?>

The problem relies in the fact that the MongoId object names the id variable as "$id", and php treats $object->$id as if you were looking for a variable variable (I'm not making up this, check out http://php.net/manual/en/language.variables.variable.php), which roughly translates to $object->null (?) or whathever $id is holding at the moment. using $object->{'$string#withreserved!chars'} solves this issue.

Hope this helps, and maybe it should be addressed to avoid further confusion.

Thanks @lynicidn , you saved my hours.

Thanks!!!!!!!!!!! :+1:

Was this page helpful?
0 / 5 - 0 ratings