Just wanted to find out what is the best way to calculate age from DOB on the fly using the Yii framework.
I have a model with the following fields.
        'id' => 'ID',
        'firstname' => 'Firstname',
        'surname' => 'Surname',
        'dob' => 'Dob',
        'age' => 'Age',
Then in my _form.php file I am trying to edit it so that the age is calculated on the fly
<?php $form = ActiveForm::begin(); ?>
<?php
    $currentDate=date('Y-m-d');
    $dob=$model->dob; //Careful with initialization???
    $model->age=$currentDate-$dob; 
?>
<?= $form->field($model, 'firstname')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'surname')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'dob')->widget(
    DatePicker::className(), [
    // inline too, not bad
    'inline' => false, 
    // modify template for custom rendering
    'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
    'clientOptions' => [
        'autoclose' => true,
        'format' => 'yyyy-mm-dd'
    ]
]);?>
<?php echo Html::activeHiddenInput($model, 'age') ; 
<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Of course there is a problem here as to get the $model->dob, the form first has to be submitted, so when the calculation of age is done dob is uninitiated.
What I want to know is there someway I can read from the dob field first so that the age can be computed correctly?
Or is this best done by something like a trigger in the database?
Looking forward to hearing responses.
Cheers.
 
    