2011-04-05 19:45:20 0 评论 Yii 1.0 Boy.Lee

Yii 1.0 表单中使用多模型

{Code}

>Controller

public function actionUpdateAll()
{
  for ($i=1;$i<7;$i++)
      $PMaps[$i]=$this->loadModel($i); //prepare the list

	if(isset($_POST['PPreviewMap']))
	{
	    $valid = true;
	    foreach ($PMaps as $k=>$PMap)
	    {
	        $PMap->attributes = $_POST['PPreviewMap']["$k"];
	        $valid = $valid && $PMap->validate();
	    }

	    if ($valid)
	        foreach ($PMaps as $PMap)
	            $PMap->save();

	}

$this->render('updateAll',
            array('PMaps' =>$PMaps)
            );
}


>View

>>updateAll

echo $this->renderPartial('_formAll', array('PMaps'=>$PMaps)); 

>>_formAll

<?php $form=$this->beginWidget('CActiveForm', array(

'id'=>'ppreview-map-form',

'enableAjaxValidation'=>false,

'htmlOptions' =>array('enctype'=>"multipart/form-data" )

)); ?>

 

<?php 

foreach ($PMaps as $PMap)

    echo '<p>'.$form->errorSummary($PMap).'</p>'; 

?>

 

<?php foreach ($PMaps as $k=>$PMap):?>

<div class="row">

<?php echo $form->labelEx($PMap,"[$k]pre_map_title"); ?>

<?php echo $form->textField($PMap,"[$k]pre_map_title",array('size'=>32,'maxlength'=>32)); ?>

<?php echo $form->error($PMap,$k."[$k]pre_map_title"); ?>

</div>

 

<div class="row">

<?php echo $form->labelEx($PMap,"[$k]img"); ?>

<?php echo $form->fileField($PMap,"[$k]img",array('size'=>60,'maxlength'=>150)); ?>

<?php echo $form->error($PMap,"[$k]img"); ?>

</div>

 

<div class="row">

<?php echo $form->labelEx($PMap,"[$k]url"); ?>

<?php echo $form->textField($PMap,"[$k]url",array('size'=>60,'maxlength'=>1500)); ?>

<?php echo $form->error($PMap,"[$k]url"); ?>

</div>

<hr/>

<?php endforeach;?>

 

{Boy Say}

这是我之前提供的一个相似方法的官方版本,其实原理是一样的。