If solution will be implemented in controller, all math should and data’s save logic should be written in it… But, in this case, the new questions appear, if we want to process our data somewhere else
class DocumentController extends Controller{
public function actionUpdate() {
/** Getting already saved data */
$values = $document->values;
/** Going over every field and create models for a values*/
foreach ($allFields as $fieldId) {
if (!$values[$fieldId]) {
$value = new Value();
$value->documentId = $document->id;
$value->fieldId = $fieldId;
$values[$fieldId] = $value;
}
/** Is Form submitted? */
if (isset($_POST['Document'])) {
/** Checking values */
$valuesValid = true;
foreach ($values as $i => $value) {
if (isset($_POST['Document'][$i]))
$value->attributes = $_POST['Document'][$i];
$valuesValid = $value->validate() && $valuesValid;
}
if ($valuesValid) {
/** Do and validate the math */
$allOk = true || false;
}
/** Saving if all's ok */
if ($allOk) {
foreach ($values as $value) {
$value->save(false);
}
$this->redirect('somewhere');
}
/** Render */
$this->render('view' array(
'document' => $document,
'values' => $values,
'fields' => $fields,
));
}
}
If math is implemented in model, there is a problem: we can’t work with $document->fields: it doesn’t exist before save, and this field is read-only. That’s why we should make a fuss wigh extra field:
class Document extends CActiveRecord{
public $tempFields;
/**
* Math and validation by this extra field $tempFields
* @return boolean */
public function calc(){ }
/** saving values */
public function Document::saveData(),
}
In controller we should:
get all data and validate each field
assign data to $document->tempFields
call $document->calc(), which will do the math and raise errors
if all’s fine, call $document->saveFields(),
Finally, controller’s code won’t get less, and what should we do if we need to change the data.
It will be already in $document->field, but math is tied on $document->tempFields.
Should we assign all values to temp ones? Pass as parameters to math function?