Wednesday, 2 October 2013

Yii - updating a model and using the model to echo data in the view

Yii - updating a model and using the model to echo data in the view

I have the following code for updating a Yii model:
public function actionSettings($id) {
if (!isset($_POST['save_hostname']) && isset($_POST['Camera']) &&
isset($_POST['Camera']['hostname'])) {
$_POST['Camera']['hostname'] = '';
}
$model = $this->loadModel($id);
$model->setScenario('frontend');
$this->performAjaxValidation($model);
if (isset($_POST['Camera'])) {
$model->attributes = $_POST['Camera'];
unset($model->api_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Camera settings has
been saved!");
} else {
Yii::app()->user->setFlash('error', "Unable to save camera
settings!");
}
}
$this->render('settings', array(
'model' => $model,
));
}
This works fine, except in my model I have code like this:
<h1>Settings For: <?php echo CHtml::encode($model->name); ?></h1>
The problem is that, even when the user input fails validation, the h1 tag
is having bad input echoed out into it. If the input fails the validation,
the h1 attribute should stay the same.
I can 'reset' the $model variable to what is in the database before the
view is returned, but this then means I don't get any error feedback /
validation failed messages.
Is my only option to have 2 models, one used for handling the form and the
other for sending data to the page? Or does someone have a more elegant
solution?

No comments:

Post a Comment