I am not clear on the actual challenge you are facing.
From my understanding…You want the user to:
Scenario A:
Enter (500) into field1, But you want (250) saved into field1
or do you mean?
Scenario B:
Enter (500) into field1 and (2) into field2, and the result of (250) saved into field3
This is how I would approach this task…
-
Generate the models for db as usual.
-
Then add the additional calculation purpose two fields to the model, with rules etc. (note you will need to add the view for the extra fields)
-
Collect your fields in view, perform the calculation logic in model or controller, assigning the total output to the field to be saved.
Calc Model
class Calc extends CActiveRecord
{
public $field1; // not in db
public $field2; // not in db
.......................
......................
public function rules()
{
return array(
array('field1, field2', 'required'),
array('field1, field2, total', 'numerical', 'integerOnly'=>true),
array('id, total', 'safe', 'on'=>'search'),
);
}
CalcController
class CalcController extends Controller
{
......................
......................
public function actionCreate()
{
$model=new Calc;
if(isset($_POST['Calc']))
{
$model->attributes=$_POST['Calc'];
$model->total=$model->field1 / $model->field2;
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
......................
......................
}
View
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'cart-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'field1'); ?>
<?php echo $form->textField($model,'field1'); ?>
<?php echo $form->error($model,'field1'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field2'); ?>
<?php echo $form->textField($model,'field2'); ?>
<?php echo $form->error($model,'field2'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
If there are many fields to be calculated, I would build a separate model for collection purpose, then perform total calculation and assign total to class::model->field that will save to db. (Tip: See wiki for collecting two models for a single form).