Attribute Labels for DynamicModel

I have the following controller action in which I am creating a dynamic model.

The idea is a simple view use to generate a report and I need to have 2 fields to allow the user to specify a Start and End date to base the report on.

public function actionIndex()
{
    //https://www.yiiframework.com/wiki/759/create-form-with-dynamicmodel
    $model = new \yii\base\DynamicModel([
        'StartDt', 'EndDt'
    ]);
    $model->addRule(['StartDt', 'EndDt'], 'required')
        // ->addRule(['StartDt', 'EndDt'], 'safe')
        ->addRule(['StartDt', 'EndDt'], 'date');

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        // echo $model->StartDt;
        GenBookingStats($model->StartDt, $model->EndDt);
    } else {
        $model->EndDt = date("Y-m-d");;
        return $this->render('index', ['model' => $model]);
    }
}

In a general sense, this work, but the labels remain StartDt and EndDt which is less than ideal. I know I can add ->label() to the view form fields, … but was wondering if there was a better approach.

Is there a simple way to set the Attribute Labels in the controller while I am creating the model?

Any advice on working with Dynamic Models? Should I be doing the reporting another way, is a Dynamic model the wrong choice here?

As always, thank you for taking the time to help!

hi,

there is a way to inject the Attribute labels into the ActiveField (if you use a ActiveForm to render Inputfields). But i think, you should either use ->label() or write a Model. Anyways, here the answer to your Question:

    $model = new \yii\base\DynamicModel([
        'StartDt', 'EndDt'
    ]);

    $model->addRule(['StartDt', 'EndDt'], 'required')
        // ->addRule(['StartDt', 'EndDt'], 'safe')
        ->addRule(['StartDt', 'EndDt'], 'date');

    \yii\base\Event::on(
    	\yii\widgets\ActiveField::class,
    	\yii\widgets\ActiveField::EVENT_INIT,
    	function ($event) {
    		switch ($event->sender->attribute) {
    			case 'StartDt':
    				$event->sender->parts['{label}'] = 'My StartDate Label';
    				break;
			case 'EndDt':
    				$event->sender->parts['{label}'] = 'My EndDate Label';
    				break;
    			default:
    				$event->sender->parts['{label}'] = null;
    		}
    	}
    );
1 Like

I agree with Henry.
I would write a Model class for the view form. It would be the simplest and the most straightforward solution.

1 Like

So I can still create Model Class for a Dynamic Model?

Thank you both. It took a bit of fiddling, but I created a Model and everything seems to be in order. I thought a model had to be tied to a table. This opens a lot of possibilities and makes my life much easier.

1 Like