来自一种模型的两种形式,两种形式均在提交一种形式时进行验证 [英] Two forms from one model both forms validate when one form is submittted

查看:86
本文介绍了来自一种模型的两种形式,两种形式均在提交一种形式时进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to use a form once in footer and in individual page i.e. index.ctp. For that I have a database table named contactforms. I have created a model 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')         
            )
        )
    );
}
?>

我有一个试图从中发送电子邮件的控制器

I have a controller from where I am trying to send an email

<?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 看起来

And then I created an element which I used called in footer and then in index file. contact.ctp looks like

<?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>

当我单击一种形式的提交以及其他形式时,也会进行验证。
我尝试了很多,但是不知道如何解决。

When I click submit of one form other form as well validates. I tried a lot but don't know how to fix Can anyone please help.

编辑:-
@Nunser我很困惑这些名字对此感到抱歉。我已根据您的要求更改了代码,但仍仅验证一种形式。
我有一个疑问,根据您的说法,我也应该更改视图和元素,但我只有元素。请您能帮我发布我编辑后的代码

- @Nunser I am very confused with these names sorry for that. I have changed my code according to what u told but still its validating one form only. I have a doubt, according to you I should change in view and elements too but I just have elements.Please can u help I am posting my edited code

我从索引页中将元素称为

I called element from index page as

<?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文件中,我将更改为

In the elements ctp file I changed as

<?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>

仍然使用此代码仅验证一种形式,而该形式是我在不使用<$ c的情况下调用的形式$ c>源作为索引,当单击索引提交按钮时,它将验证另一个形成。我不确定是否必须使用您指定的相同 Fromindex 名称,这很重要。我找不到我要去哪里了。请帮助并提前谢谢。

Using this code still it validated one form only and form is that which I have called without source as index and when clicked on index submit button it validates the other form. I am not sure as do I have to use the same Fromindex name as specified by you, does that matter. I am not able to find as where I am going wrong.Please help and Thanks in advance.

推荐答案

首先,你为什么

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

您的元素?我没有看到该requestAction的使用,只是减慢了处理速度……

in your element? I don't see the use of that requestAction except slowing down the processing...

好,但是您的问题...

在调用一个元素时,没有简单的方法来避免同时验证这两种形式。通常,当有两个与同一模型相对应的表单时,两种方法都不进行验证的方法是更改​​表单的名称

Ok, but your problem...
Since you're calling an element, there's no easy way to avoid the validation of both forms. Usually, when there are two forms corresponding to the same model, the way to not validate both is to change the "name" of the form like this

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

但是,由于要使用元素创建该表单,因此没有简单的方法来更改名称

But, since you are creating that form with an element, there's no easy way of changing the name of the form in one place and not in the other...

所以这是您应该做的(也许有其他方式可以做您想要的事情,但这是我能想到的那个)。当您调用contact.ctp元素时,向其传递一个变量

So this is what you should do (there may be other ways of doing what you want, but this is the one I can think of). When you call the contact.ctp element, pass a variable to it

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

例如,您知道您正在从index.ctp调用该元素。然后,在元素中,根据变量更改表单声明

With that, you know you're calling the element from the index.ctp, for example. Then, in the element, change the form declaration depending on the variable

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

您还需要修改操作,以读取中的数据FromIndex FromContact 中,具体取决于它来自何处

You'll also need to modify your action, to read the data in FromIndex or in FromContact, depending on where it came from

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());
                }   
                }
             }

           }
    }
}

保存或设置某些内容时(除非使用 saveAssociated saveAll 或这类函数,当您保存多个模型时,无需在要保存的数组中指定模型。

When you save or set something (unless is with saveAssociated, saveAll or those kind of functions, when you're saving more than one model), there's no need to specify the model in the array to be saved.

$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 索引将以任何一种方式工作。但是验证将针对特定索引( FromContact FromIndex )。

That's why the change of $this->request->data indexes will work either way. But the validation will be for the specific index (FromContact or FromIndex).

注意:我尚未测试代码,因此请确保检查缺少括号,未闭合的'以及那些

Note: I haven't tested the code, so be sure to check for missing parenthesis, unclosed ' and those kind of things.

EDiT

@winnie指出,验证仅针对一种形式进行,这是因为我忽略了一些东西。如果视图中的变量 $ this-&>; validationErrors ['ModelName'] 中设置了某些内容,则验证错误会显示在视图中。这就是我想念的。因此,重新更改操作以将模型的 $ index 传递给视图,以便视图知道调用该操作的形式,如

EDiT
@winnie pointed out that the validation only happened for one form, and that's because I overlooked something. The validation errors get displayed in the view if there's something set in this variable $this->validationErrors['ModelName'] in the view. And that's what I missed. So, re-change the action to pass the $index of the model to the view, so the view knows which form called the action, like this

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);

            }
    }
}

现在将复制模型中的错误所需的视图复制到我们提供的假模型名称中。在您的视图的第一行中(在元素中也是如此)

Now in the view you need to copy the errors you get in the model, to the "fake model name" we gave the form. In the first line of your view do this (and in the element too)

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

这篇关于来自一种模型的两种形式,两种形式均在提交一种形式时进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆