0

This question is not similar to the regarded questions. This question meant by a weird result of a PHP anonymous function. The regarding of Yii here is just for showing the context in which the anonymous function has been involved.

I decided to use PHP anonymous function to format an attribute value in the DetailView Widget in Yii2 application as follows:

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'DatabaseID',           
            'Prod:ntext',
            'desc:ntext',
            [
                'label' => Yii::t('app','review'),
                'value' => function(){return 'hi';}, //Just for simplification the issue explanation. However, it is the actual code that generates the error.
            ],
        ],
]) ?>

I have got the following error which telling that the anonymous function does not return a string:

htmlspecialchars() expects parameter 1 to be string, object given

I wonder, why does the anonymous function return an object? As shown in the code sample, it should only return a simple string hi!

I have read the PHP documentation about Anonymous functions but I could not able to find anything regarding this issue.

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • similar question.......http://stackoverflow.com/questions/27787242/yii2-detailview-value-of-attribute-using-a-function – Jacob Sep 29 '16 at 03:18
  • This is a wrong way of setting value in `DetailView` widget. You passed function to `value`, but it never executes (`call_user_func` is never called unlike in `GridView`). As a result, you have this error. You can wrap it with `call_user_func` but that does not make sense. The correct way is to directly call methods of `$model` or some helper components. This is a wrong way of using anonymous functions. Please read [my answer](http://stackoverflow.com/a/28301600/4323648) to related question carefully. – arogachev Sep 30 '16 at 04:17
  • @arogachev Ok, it may not be the correct or the suitable way, but in some cases it should be the quicker one. In addition, this question mainly directed to the anonymous functions concept that I implemented it wrong when I thought it should work without `call_user_func`. So it is not a duplicate question. – SaidbakR Sep 30 '16 at 11:01

1 Answers1

0

The error is actually with the ntext format. Change to text or html and it fixes the problem. This an amazingly long standing bug!

Zaq
  • 1