formbuilder and scenarios

Hello,

I’m trying to get a form to show different options depending on scenario. I would like this to be all in one file. Right now I am doing this :

default form view - views/someform.php


return array(

    'type' => 'form',

    'elements' => array(

	

    ),

    'buttons' => array(

	'submit' => array(

	    'type' => 'submit',

	    'label' => Yii::t('admin', 'Create'),

	),

    ),

);

Same form but in an ‘edit’ type action - SomeController.php


$someModel = new SomeForm;

$form = new CForm('application.views.someform', $someModel);

$form->setButtons(array(

'submit' => array(

	'type' => 'submit',

	'label' => Yii::t('admin', 'Update'),

)));

I wanted to know if there was a way of changing the button text, form action, etc … through scenarios, something like :

controller:


$someModel = new SomeForm('update');

$form = new CForm('application.views.someform', $someModel);



form builder view config


if ($scenario == 'update'){$label = Yii::t('admin', 'Create');}

else {$label = Yii::t('admin', 'Create');}


'buttons' => array(

	'submit' => array(

	    'type' => 'submit',

	    'label' => $label,

	),

    ),

Thanks !

You don’t need scenarios in this scenario (pun intended).

You can just ask the model if it’s new or not:


<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

If you use Gii to generate CRUD, you get code like that.

The update and create view files both use _form.php:


<h3>Create Something</h3>

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>


<h3>Update Something<?php echo $model->id; ?></h3>

<?php echo $this->renderPartial('_form', array('model'=>$model, 'comment' => $comment)); ?>

Thank you for your reply. Due to some constraints in the project requirements, I am not using any of the provided Yii database functions, including ActiveRecord.


$someModel->isNewRecord

gives me CException Property "SomeForm.isNewRecord" is not defined.

I was therefore looking for a way to do this only using the CFormModel class. Also, I would rather use the form builder way of doing things rather than using CHtml in the view file.

Your suggestion did give me the idea of putting the label code within the model class, but it seems like setting labels in attributeLabels() only applies to, well, attributes …

Ouch. I overlooked that you were using CForm… Sorry. I don’t know the answer then, off the cuff.???

To refer to the model in the form configuration use :


<?php

$this->model

?>



$this referes the CForm object.