Home > Back-end >  How to submit form with blank or empty values and non blank values in Laravel
How to submit form with blank or empty values and non blank values in Laravel

Time:09-27

I have modal pop up window with form, on submission of form I want to insert data whatever user has selected or entered. Currently I am not able to submit form unless I fill all the field and select any values from dropdown.

Here is my Html code:

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

This is my script:

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

This is my Controller:

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

I am able to store data but have to select all the values what I need is it should submit the data whaterver user have selected if it is blank it should insert blank data in DB. Can someone help me out how I can do that?

CodePudding user response:

Step 1: Firstly make all fields as nullable in database table. Step 2: After that modify your select tag as:

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

Step 3: change other select as per your code:

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

After this you can add or upadte nullable fields

Apart from that if you want to add or update data direct you can above code: Step 1: In App\Model make specific changes as:

<?php

namespace App;

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

class Prediction extends Model
{
    protected $table = 'prediction';
    protected $primaryKey = 'id';
    protected $guarded = ['id'];

}

Step 2: After this you can directly use in controller as:

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

Above is the snippet example for your code you can use it as per you requirments.

  • Related