dpvr49226 2014-03-28 03:36
浏览 24
已采纳

在模型中使用其他模型

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

  • 写回答

1条回答 默认 最新

  • doudai8783 2014-03-28 08:31
    关注

    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)')); ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功