Question

This would be a general question, to specifics (about Yii),

I just want to know if this is a good practice, or simply if its correct:

On my _form view, I am calling a another model not from the current model in used;

// @model Clients
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'myid-form',
'enableAjaxValidation'=>false,
)); ?>

<div class="row">
  <?php echo $form->labelEx($model,'Debtor'); ?>
  <?php echo $form->dropDownList($model, 'Debtor'
        , CHtml::listData(Debtor::model()->findAll(), 'DebtorCode', 'DebtorDesc'),array('empty'=>'(Select Debtor)')); ?>
  <?php echo $form->error($model,'Debtor'); ?>
</div>

If I am wrong, can someone tell me what is the correct way before it becomes a habit..

TIA

Was it helpful?

Solution

I think your question is not correct. You are asking about calling another model in a model. But the code you have provided, you are using another model in the view. Obviously a view is not a model.
Perhaps your question was "Can i use another model in the view aside from yii generated code in which some other model is used".
Answer to your quesiton: Yes you can use it this way nothing wrong with that if you talk about using models. But you have written a DB code(findAll) in your view which is not a good practice.Yii is an MVC framework with the basic theme as to separate the presentation and data access. Yes you can do it Yii will not object but its against the Yii philosophy. Secondly if you access Db in your View then your code is no more a "very good manageable code". It will be an average code because using Db access in your view it will be difficult for you or another coder to determine whats going on and how to modify the code if needed.
You can write that code in your controller like

$debtor=Debtor::model()->findAll();
$debtorList=CHtml::listData($debtor,'DebtorCode','DebtorCode');
$this->render('my _form',array('debtorList'=>$debtorList));

In your view you cna use it like

<?php echo $form->dropDownList($model, 'Debtor'
        , $debtorList,array('empty'=>'(Select Debtor)')); ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top