一个表单中的两个表单都会在提交一个表单时进行验证

时间:2013-07-01 07:07:32

标签: cakephp cakephp-2.0

我必须在页脚和单个页面中使用一个表单,即index.ctp。 为此,我有一个名为contactforms的数据库表。 我创建了一个模型Contactform.php

<?php
App::uses('AppModel', 'Model');
/**
 * Contactform Model
 *
 */
class Contactform extends AppModel {
/**
 * Validation rules
 *
 * @var array
 */
      var $useTable = false;

    public $validate = array(
        'firstname' => array(
            'notempty' => array(
                'rule' => array('notempty')             
            )
        ),
        'contactno' => array(
            'notempty' => array(
                'rule' => array('notempty')             
            )
        ),
        'email' => array(
            'notempty' => array(
                'rule' => array('notempty')         
            )
        )
    );
}
?>

我有一个控制器,我正在尝试发送电子邮件

<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');

class ContactformsController extends AppController {


    public function index() {
        $this->Contactform->recursive = 0;
        $this->set('contactforms', $this->paginate());
    }


        public function contact() {

        $email = new CakeEmail();
            if(isset($this->params['requested']) && $this->params['requested']==true)
    {
         if ($this->request->is('post')) 
            {
             $this->Contactform->set($this->request->data);
                if($this->Contactform->save($this->request->data)) 
                {
                 $name=$this->request->data['Contactform']['firstname'];
                 $lastname=$this->request->data['Contactform']['lastname'];
                 $contact=$this->request->data['Contactform']['contactno'];
                 $mail= $this->request->data['Contactform']['email'];
                 $email->from(array($mail => $name));
                     $email->to('abc@gmail.com');                      
                     $message= $this->request->data['Contactform']['message'];
                     $email->subject('Wombats contact form information');        
                 if($email->send($message))
                 {
                    $this->Session->setFlash('Quote Processed..Thank You For Visiting Our Website!!!');
                                     $this->redirect($this->referer());
                    }   
                    }
                 }

               }
        }
}
?>

然后我创建了一个我在页脚中调用然后在索引文件中使用的元素。 contact.ctp看起来像

<?php echo $this->Html->css('contactfooter.css');?>

<?php $contactforms = $this->requestAction('Contactforms/contact') ?>
<div class="frm">
<?php echo $this->Form->create('Contactform'); ?> 
<div class="firstrow">
    <div class="first">
        <?php echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','div'=>'firstname','style'=>'width:130px; height:20px;' ));?>
        <?php // echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','style'=>'width:130px; height:20px; float:left; margin-right:5px;','error'=>array('attributes'=>array('wrap'=>'div','class'=>'errorfirst'))));?>
    </div>
    <div class="second">
        <?php echo $this->Form->input('lastname',array('label'=>false,'placeholder'=>'lastname','div'=>'lastname','style'=>'width:140px; height:20px; '));?>
    </div>   
</div>
<!--<div class="secondrow">-->
<?php echo $this->Form->input('contactno',array('label'=>false,'placeholder'=>'contactno','div'=>'contactno','style'=>'width:270px; height:20px; margin-bottom:10px;'));?>
<!--</div>-->

<?php echo $this->Form->input('email',array('label'=>false,'placeholder'=>'email','div'=>'email','style'=>'width:270px; height:20px; '));?>
<?php echo $this->Form->input('message',array('label'=>false,'placeholder'=>'message','div'=>'message','style'=>'width:270px; height:25px;margin-top:10px; '));?>
</div>
<!--<br>-->
<div class="sub">
<?php echo $this->Form->end('SUBMIT'); ?> 
    </div>

当我点击其他表格的一个表格的提交以及验证。  我尝试了很多,但不知道如何修复任何人都可以帮忙。

编辑: - @Nunser我很抱歉这些名字对不起。我根据你所说的改变了我的代码,但仍然只是验证了一种形式。 我有一个疑问,根据你我应该改变视图和元素,但我只是有元素。请帮助我发布我编辑的代码

我将索引页面中的元素称为

<?php echo $this->element('Contactform/contact',array('source'=>'index')); ?>\

并从默认页面

<?php echo $this->element('Contactform/contact'); ?>

我的控制器操作是

public function contact() {

        $email = new CakeEmail();

        if(isset($this->params['requested']) && $this->params['requested']==true){

        if ($this->request->is('post')) 

        {
            $index = 'Contactform';
            if (isset($this->request->data['Contactformindex']))
                $index = 'Contactformindex';

        $this->Contactform->set($this->request->data[$index]);

        if($this->Contactform->save($this->request->data[$index])) 

        {

        $name=$this->request->data[$index]['firstname'];

        $lastname=$this->request->data[$index]['lastname'];

        $contact=$this->request->data[$index]['contactno'];

        $mail= $this->request->data[$index]['email'];

        $email->from(array($mail => $name));



        $email->to('skyhi13@gmail.com');               

                $message= $this->request->data[$index]['message'];

                $email->subject('Wombats contact form information');

        //$email->send($message);

        if($email->send($message))

        {
        $this->Session->setFlash('Quote Processed..Thank You For Visiting Our Website!!!');

        //$this->render('/view/elements/quotes/quoteform.ctp');

//        $this->autoRender=FALSE;

        $this->redirect($this->referer());

        }    


        }
        else {
            $this->set('formName',$index);
        }

      }

          }

        }

在元素ctp文件中,我改为

<?php if (!empty($this->validationErrors['Contactform'])) {
     $this->validationErrors[$formName] = $this->validationErrors['Contactform'];
}?>
<div class="frm">
<?php
    if(isset($source)&& $source == 'index')
        echo $this->Form->create('Contactformindex'); 
    else
        echo $this->Form->create('Contactform'); 
 ?>   
<div class="firstrow">
    <div class="first">
        <?php echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','div'=>'firstname','style'=>'width:130px; height:20px;' ));?>
        <?php // echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','style'=>'width:130px; height:20px; float:left; margin-right:5px;','error'=>array('attributes'=>array('wrap'=>'div','class'=>'errorfirst'))));?>
    </div>
    <div class="second">
        <?php echo $this->Form->input('lastname',array('label'=>false,'placeholder'=>'lastname','div'=>'lastname','style'=>'width:140px; height:20px; '));?>
    </div>   
</div>
<!--<div class="secondrow">-->
<?php echo $this->Form->input('contactno',array('label'=>false,'placeholder'=>'contactno','div'=>'contactno','style'=>'width:270px; height:20px; margin-bottom:10px;'));?>
<!--</div>-->

<?php echo $this->Form->input('email',array('label'=>false,'placeholder'=>'email','div'=>'email','style'=>'width:270px; height:20px; '));?>
<?php echo $this->Form->input('message',array('label'=>false,'placeholder'=>'message','div'=>'message','style'=>'width:270px; height:25px;margin-top:10px; '));?>
</div>
<!--<br>-->
<div class="sub">
<?php echo $this->Form->end('SUBMIT'); ?> 
    </div>

使用此代码仍然只验证了一个表单,表单是我在没有source作为index时调用的表单,当点击index submit button时,它会验证另一个表单。我不确定我是否必须使用您指定的相同Fromindex名称,这是否重要。我无法找到我出错的地方。请提前帮助并致谢。

1 个答案:

答案 0 :(得分:0)

首先,你为什么要这样做

<?php $contactforms = $this->requestAction('Contactforms/contact') ?>

在你的元素中?除了减慢处理速度之外,我没有看到使用requestAction ...

好的,但你的问题......
由于您正在调用元素,因此没有简单的方法可以避免两种形式的验证。通常,当有两个表单对应同一个模型时,不同时验证两者的方法是更改​​表单的“名称”,如下所示

<!--in the first form-->
<?php echo $this->Form->create('Contactform1'); ?> 
<!--in the second form-->
<?php echo $this->Form->create('Contactform2'); ?> 

但是,既然您正在使用元素创建该表单,那么在一个地方而不是在另一个地方更改表单名称的方法并不容易......

所以这就是你应该做的(可能还有其他方法可以做你想要的,但这是我能想到的)。当你调用contact.ctp元素时,将一个变量传递给它

echo $this->element('contact', array(
   "source" => "index"
));

有了这个,你就知道你正在从index.ctp中调用元素。然后,在元素中,根据变量

更改表单声明
//the beginning of your element
<?php
    if (isset($source) && $source == 'index')
      echo $this->Form->create('FromIndex');
    else
      echo $this->Form->create('FromContact');
?>

您还需要修改您的操作,阅读FromIndexFromContact中的数据,具体取决于来自哪里

public function contact() {

   $email = new CakeEmail();
   if(isset($this->params['requested']) && $this->params['requested']==true)  {
     if ($this->request->is('post'))  {

        //change the index of the array depending on where it came form
        $index = 'FromContact';
        if (isset($this->request->data['FromIndex']))
           $index = 'FromIndex';

         $this->Contactform->set($this->request->data[$index]);
            if($this->Contactform->save($this->request->data[$index])) 
            {
             $name=$this->request->data[$index]['firstname'];
             $lastname=$this->request->data[$index]['lastname'];
             $contact=$this->request->data[$index]['contactno'];
             $mail= $this->request->data[$index]['email'];
             $email->from(array($mail => $name));
                 $email->to('abc@gmail.com');                      
                 $message= $this->request->data[$index]['message'];
                 $email->subject('Wombats contact form information');        
             if($email->send($message))
             {
                $this->Session->setFlash('Quote Processed..Thank You For Visiting Our Website!!!');
                                 $this->redirect($this->referer());
                }   
                }
             }

           }
    }
}

当您保存或设置某些内容时(除非使用saveAssociatedsaveAll或这些功能,当您保存多个模型时),无需在要保存的数组。

$saveMe = array('User'=>array('name'=>'John'));
$saveMeToo = array('name'=>'John');
$this->User->save($saveMe); //will work
$this->User->save($saveMeToo); //will work too

这就是为什么$this->request->data索引的更改将以任何方式工作的原因。但验证将针对特定索引(FromContactFromIndex)。

注意:我没有测试过代码,所以一定要检查缺少的括号,未闭合的'以及那些东西。

修改
@winnie指出验证只发生在一个表单上,那是因为我忽略了一些东西。如果视图中此变量$this->validationErrors['ModelName']中设置了某些内容,则验证错误将显示在视图中。这就是我错过的。因此,重新更改操作以将模型的$index传递给视图,以便视图知道哪个表单称为操作,如此

public function contact() {

   $email = new CakeEmail();
   if(isset($this->params['requested']) && $this->params['requested']==true)  {
     if ($this->request->is('post'))  {

        //change the index of the array depending on where it came form
        $index = 'FromContact';
        if (isset($this->request->data['FromIndex']))
           $index = 'FromIndex';

         $this->Contactform->set($this->request->data[$index]);
            if($this->Contactform->save($this->request->data[$index])) 
            {
                //this if is exactly the same as the other one
            } else {
                //now, if there's no save, there's some validation errors
                //tell the view which form called this save
                $this->set('formName', $index);

            }
    }
}

现在,在视图中,您需要将模型中获得的错误复制到我们提供表单的“假模型名称”中。在视图的第一行中执行此操作(以及在元素中)

if (!empty($this->validationErrors['Contactform'])) {
     $this->validationErrors[$formName] = $this->validationErrors['Contactform'];
}