如何在 Laravel 中提交具有空白或空值和非空白值的表单

Posted

技术标签:

【中文标题】如何在 Laravel 中提交具有空白或空值和非空白值的表单【英文标题】:How to submit form with blank or empty values and non blank values in Laravel 【发布时间】:2021-11-15 17:27:33 【问题描述】:

我有带有表单的模态弹出窗口,在提交表单时,我想插入用户选择或输入的任何数据。目前我无法提交表单,除非我填写所有字段并从下拉列表中选择任何值。

这是我的 html 代码:

<div id="feedbackModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="feedback_form" autocomplete="off">
                <div class="modal-header">
                   <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    csrf_field()
                    <span id="form_output"></span>
                    
                    <div class="form-group">
                       <label>Adjust Risk Level:</label>
                      <select name="FeedRisklevel" id="FeedRisklevel" class="form-control">
                        <option value="">Select Risk Level</option>
                        <option value="High Risk">High Risk</option>
                        <option value="Low Risk">Low Risk</option>
                      </select>       
                    </div>
                    <div class="form-group">
                       <label>Influencers:</label><br/>
                      <select name="Feedinfluencers[]" id="Feedinfluencers" multiple class="form-control">
                        <option value="Long Work Hours">Long Work Hours</option>
                        <option value="No Vacation/Leaves in Recent past">No Vacation/Leaves in Recent past</option>
                        <option value="Salary not per market standards">Salary not per market standards</option>
                        <option value="Lower Salary than Peers">Lower Salary than Peers</option>
                        <option value="No Bonus Received in last one year
                        ">No Bonus Received in last one year</option>
                        <option value="No Salary Revision in last one year">No Salary Revision in last one year</option>
                        <option value="Expecting Relocation">Expecting Relocation</option>
                        <option value="Expecting Progression">Expecting Progression</option>
                        <option value="Looking for Role/Job/Unit change">Looking for Role/Job/Unit change</option>
                        <option value="Upskilling/Learning Programs Missing">Upskilling/Learning Programs Missing</option>
                        <option value="High Work Pressure/Stress">High Work Pressure/Stress</option>
                        <option value="Non-Alignment with Supervisors/Managers">Non-Alignment with Supervisors/Managers</option>
                        <option value="Lower Bonus received than expected in last one year">Lower Bonus received than expected in last one year</option>
                        <option value="Lower Salary Revision than expected in last one year">Lower Salary Revision than expected in last one year</option>
                        <option value="No Work Life Balance">No Work Life Balance</option>
                        <option value="Lack of Job Security">Lack of Job Security</option>
                        <option value="Lack of Recognition">Lack of Recognition
                        </option>
                        <option value="Lack of Career Opportunities">Lack of Career Opportunities</option>
                        <option value="Lack of Employee Care Activities">Lack of Employee Care Activities</option>
                      </select>
                    </div>
                    <div class="form-group">
                        <label>Employee Discussion Feedback:</label>
                        <input type="text" name="feedback" id="feedback" class="form-control" placeholder="Feedback" value="" />
                    </div>
                      <div class="form-group">
                        <label>Action Taken:</label>
                        <input type="radio" class="check" name="check" value="Yes">Yes
                        <input type="radio" class="check" name="check" value="No" checked>No
                        <select name="action[]" id="action" multiple class="action form-control">
                          <option value="Offcycle Salary Revision">Offcycle Salary Revision</option>
                          <option value="Special Bonus">Special Bonus</option>
                          <option value="Retention Bonus">Retention Bonus</option>
                          <option value="Internal Career Opportunity">Internal Career Opportunity</option>
                          <option value="Monthly/Quarterly Recognition">Monthly/Quarterly Recognition</option>
                          <option value="Inline Progression">Inline Progression</option>
                          <option value="Stay Interview">Stay Interview</option>
                          <option value="One on one discussion/Counselling">One on one discussion/Counselling</option>
                          <option value="Personal Development Plan">Personal Development Plan</option>
                          <option value="Relocation Opportunity">Relocation Opportunity</option>
                          <option value="Flexibility in the Schedule">Flexibility in the Schedule</option>
                          <option value="Upskilling/Learning Programs Scheduled">Upskilling/Learning Programs Scheduled</option>
                          <option value="Workload Balanced">Workload Balanced</option>
                        </select>
                      </div>      
                </div>
                <div class="modal-footer">
                     <input type="hidden" name="feedback_id" id="feedback_id" value="" />
                      <input type="hidden" name="FeedRisklevel_id" id="FeedRisklevel_id" value="" />
                      <input type="hidden" name="Feedinfluencers_id" id="Feedinfluencers_id" value="" />
                      <input type="hidden" name="Action_id" id="Action_id" value="" />
                    <input type="hidden" name="button_action" id="button_action" value="insert" />
                    <input type="submit" name="submit" id="Feedback" value="Submit" class="btn" style="background-color: #CA0088;color: #fff" />
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>

这是我的脚本:

 $('#feedback_form').on('submit', function(event)
        event.preventDefault();
        var form_data = $(this).serialize();
        $.ajax(
            url:" route('Predictions.store') ",
            method:"POST",
            data:form_data,
            dataType:"json",
            success:function(data)
            
                if(data.error.length > 0)
                
                    var error_html = '';
                    for(var count = 0; count < data.error.length; count++)
                    
                        error_html += "<div class='alert alert-danger'>"+data.error[count]+"</div>";
                    
                    $('#form_output').html(error_html);
                
                else
                
                    $('#form_output').html(data.success);
                    $('#feedback_form')[0].reset();
                    $('#feedback').val('');
                    $('#FeedRisklevel').val('');
                    $('#Feedinfluencers').val('');
                    $('#action').val('');
                    $('.modal-title').text('Submit Feedback');
                    $('#button_action').val('insert');
                    $('#members_data').DataTable().ajax.reload();
                
            
        )
    );

这是我的控制器:

public function store(Request $request)
     

        // $validation = Validator::make($request->all(), [
        //         'feedback' => 'required',
        //         'FeedRisklevel' => 'required',
        //         'Feedinfluencers' => 'required',
        //         'action' => 'required'
                
        //     ]);
            
            $error_array = array();
            $success_output = '';
            // if ($validation->fails())
            // 
            //     foreach ($validation->messages()->getMessages() as $field_name => $messages)
            //     
            //         $error_array[] = $messages; 
            //     
            // 
            // else
            // 
                if($request->get('button_action') == 'insert')
                
                    $data = new Prediction([
                        'Feedback'    =>  $request->get('feedback'),
                        'Feedinfluencers' => $request->get('Feedinfluencers'),
                        'FeedRisklevel' => $request->get('FeedRisklevel'),
                        'Action' => $request->get('action')
                        
                    ]);
                    $data->save();
                    $success_output = "<div class='alert alert-success'>Data Inserted</div>";
                

                if($request->get('button_action') == 'update')
                
                    $data = Prediction::find($request->get('feedback_id'));
                    $data->Feedback = $request->get('feedback');
                    $data->save();

                    $data1 = Prediction::find($request->get('FeedRisklevel_id'));
                    $data1->FeedRisklevel = $request->get('FeedRisklevel');
                    $data1->save();

                    $data2 = Prediction::find($request->get('Feedinfluencers_id'));
                    $data2->Feedinfluencers = $request->get('Feedinfluencers');
                    $data2->save();

                    $data3 = Prediction::find($request->get('Action_id'));
                    $data3->Action = $request->get('action');
                    $data3->save();

                    $success_output = '<div class="alert alert-success">Thanks for your Feedback!</div>';
                
                
            
            
            $output = array(
                'error'     =>  $error_array,
                'success'   =>  $success_output
            );
            echo json_encode($output);
        

我能够存储数据,但必须选择我需要的所有值,它应该提交用户选择的数据,如果它是空白的,它应该在数据库中插入空白数据。有人可以帮我看看我该怎么做吗?

【问题讨论】:

【参考方案1】:

步骤1:首先将数据库表中的所有字段都设为可空。 第 2 步:之后将您的选择标签修改为:

<select name="Feedinfluencers[]" id="Feedinfluencers" multiple class="form-control">
   

> <option value="">Select</option>

   <option value="Long Work Hours">Long Work Hours</option>
   <option value="No Vacation/Leaves in Recent past">No Vacation/Leaves in Recent past</option>
   .
   .
</select>

第 3 步:根据您的代码更改其他选择:

<select name="action[]" id="action" multiple class="action form-control">
   

> <option value="">Select</option>

   <option value="Offcycle Salary Revision">Offcycle Salary Revision</option>
   <option value="Special Bonus">Special Bonus</option>

之后,您可以添加或更新可为空的字段

除此之外,如果您想直接添加或更新数据,您可以使用上面的代码: 第1步: 在 App\Model 中进行具体更改:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class Prediction extends Model

    protected $table = 'prediction';
    protected $primaryKey = 'id';
    protected $guarded = ['id'];



第2步:之后你可以直接在控制器中使用:

public function store(Request $request)
    
      if($request->get('button_action') == 'insert')
      
          $param = $request->all();
          $param['button_action'] = 'insert'; // if you want to overload you field with new data
          $prediction= Prediction::create($param);
      
      if($request->get('button_action') == 'update')
      
         $param = $request->all();
          $param['button_action'] = 'update'; // if you want to overload you field with new data
          $prediction= Prediction::where('id',$id)->update($param);
      
     

以上是您的代码的 sn-p 示例,您可以根据需要使用它。

【讨论】:

以上是关于如何在 Laravel 中提交具有空白或空值和非空白值的表单的主要内容,如果未能解决你的问题,请参考以下文章

从 Pyspark 中的数据框中计算空值和非空值

Python 空值和非空值

mysql创建表时的空值和非空值设置有啥讲究

数据库数据插入,空值和非空判断,自动排序,约束主键,唯一约束,外健约束

仅当非空值时,如何在输入和过滤数据中具有默认的 NULL 值?

在此查询中,我需要添加啥使其永远不会显示空白或空值?