怎么知道场是空的?

时间:2016-04-12 07:26:25

标签: php cakephp

此代码在Cakephp中,我想检查名称和移动字段是否为空。

这是我的ctp文件代码: -

<div class="form-group">
  <?= $this->Form->label('Name','Name',array('class' => 'col-sm-2 control-label')); ?>
  <div class="col-sm-4">
      <?= $this->Form->text('name', ['class' => 'form-control input-sm', 'style'=>'float:left', 'placeholder' => "Name"]); ?> 
  </div>
</div>
<div class="form-group">
<?= $this->Form->label('Mob No.','Mob No.',array('class' => 'col-sm-2 control-label')); ?>
 <div class="col-sm-4">
     <?= $this->Form->text('mobile', ['class' => 'form-control input-sm', 'style'=>'float:left', 'placeholder' => "Mob No."]); ?>
 </div>
</div>

这是控制器代码: -

public function details_data(){
  if($this->request->is('post')){
      $result = null;
      $_Post['Name']= $name;
      $_Post['Mobile'] = $mobile;
      if(!empty($name) && !empty($mobile)){
          echo "Fields are not empty.";
      } else{
          echo  "Fields are empty.";
      }
  } 
}

帮助我。

1 个答案:

答案 0 :(得分:4)

首先,当你使用CakePHP时,你永远不应该使用$ _POST。最好遵循惯例并使用$ this-&gt; request-&gt; data [&#39; Modelname&#39;] [&#39; fieldname&#39;]代替。

其次,您可以在模型中指定验证规则。它将在表单提交时显示上述错误消息。

回到你已经做过的事情,你可以尝试下面提到的代码:

      if($this->request->is('post')){
           $name   = $this->request->data['Modelname']['name'];
           $mobile = $this->request->data['Modelname']['mobile']; 
           // Specify your Model name for both. Eg: if your database table is users, your model name should be User.
           if(!empty($name) && !empty($mobile)){
               echo "Fields are not empty.";
           } else{
               echo  "Fields are empty.";
           }
       }