Findmodel() With Dynamic Model Class

One thing I don’t understand:

Im my controller the is the findModel($id)-method. I wanted to customize it and pass the model class name as second parameter, but then Yii can’t find the class.

In OrderItemController:





namespace backend\controllers;


use Yii;

use common\models\Order;

use common\models\OrderItem;

use common\models\OrderItemSearch;


class OrderItemController extends Controller

{

    public function actionIndex($orderId)

    {

        $orderModel = $this->findModel($orderId, 'Order');

        

        $searchModel = new OrderItemSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $orderModel);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

            'orderModel' => $orderModel,

        ]);

    }


    protected function findModel($id, $modelName = 'OrderItem')

    {

        if (($model = $modelName::findOne($id)) !== null) {

            return $model;

        } else {

            throw new NotFoundHttpException('The requested page does not exist.');

        }

    }

}



Trying to call the index action: Class ‘Order’ not found.

It has something to do with namespaces. When I pass the $modelName as ‘common\models\Order’ it works. But I included all models corrctly in the top.

Can anybody tell me why?

(($model = $modelName::findOne($id)) !== null) 
``` its generate as string => 'OrderItem'::findOne...
so you must convert to object models
try 
protected function findModel($id,$models)
    {
        $modelx=Yii::createObject([
          'class' => "app\models\\".$models,
         ]);
        if (($model = $modelx::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
its work for me.