laravel-单选按钮/复选框将错误的值传递给数据库

时间:2019-02-22 12:06:13

标签: php html5 laravel

在创建新调查后,我正在创建调查网站,然后选择问题类型并添加问题和选项。我想检查我是否参加了调查,所有答案都将存储在数据库中。我试过了,但是问题是任何问题的答案(使用单选按钮/复选框类型),数据库中存储的值是“ on”。 文本/文本区域已正确存储。但是无法弄清楚我该如何解决。无论我选择什么,该值都将为“ on”。

这是我的answerController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Survey;
use App\Answer;
use App\Http\Requests;


class AnswerController extends Controller
{

  public function store(Request $request, Survey $survey)
  {
    // remove the token
    $arr = $request->except('_token');
    foreach ($arr as $key => $value) {
      $newAnswer = new Answer();
      if (! is_array( $value )) {
        $newValue = $value['answer'];
      } else {
        $newValue = json_encode($value['answer']);
      }
      $newAnswer->answer = $newValue;
      $newAnswer->question_id = $key;
      $newAnswer->survey_id = $survey->id;

      $newAnswer->save();

      $answerArray[] = $newAnswer;
    };
    return redirect()->action('SurveyController@view_survey_answers', [$survey->id]);
  }
}

这是答案模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Answer extends Model
{
  protected $fillable = ['answer'];
  protected $table = 'answers';

  public function survey() {
    return $this->belongsTo(Survey::class);
  }

  public function question() {
    return $this->belongsTo(Question::class);
  }
}

这是用于创建问题并选择类型的代码:

@extends('master')
@section('title', 'Survey')

@section('content')
<div class="card">
    <div class="card-content">
    <span class="card-title"> {{ $survey->title }}</span>
    <p>
      {{ $survey->description }}
    </p>
    <br/>
    <a href='view/{{$survey->id}}'>Take Survey</a> | <a href="{{$survey->id}}/edit">Edit Survey</a> | <a href="/survey/answers/{{$survey->id}}">View Answers</a> <a href="#doDelete" style="float:right;" class="modal-trigger red-text">Delete Survey</a>
    <!-- Modal Structure -->
    <!-- TODO Fix the Delete aspect -->
    <div id="doDelete" class="modal bottom-sheet">
      <div class="modal-content">
        <div class="container">
          <div class="row">
            <h4>Are you sure?</h4>
            <p>Do you wish to delete this survey called "{{ $survey->title }}"?</p>
            <div class="modal-footer">
              <a href="/survey/{{ $survey->id }}/delete" class=" modal-action waves-effect waves-light btn-flat red-text">Yep yep!</a>
              <a class=" modal-action modal-close waves-effect waves-light green white-text btn">No, stop!</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="divider" style="margin:20px 0px;"></div>
    <p class="flow-text center-align">Questions</p>
    <ul class="collapsible" data-collapsible="expandable">
        @forelse ($survey->questions as $question)
        <li style="box-shadow:none;">
          <div class="collapsible-header">{{ $question->title }} <a href="/question/{{ $question->id }}/edit" style="float:right;">Edit</a></div>
          <div class="collapsible-body">
            <div style="margin:5px; padding:10px;">
                {!! Form::open() !!}
                  @if($question->question_type === 'text')
                    {{ Form::text('title')}}
                  @elseif($question->question_type === 'textarea')
                  <div class="row">
                    <div class="input-field col s12">
                      <textarea id="textarea1" class="materialize-textarea"></textarea>
                      <label for="textarea1">Provide answer</label>
                    </div>
                  </div>
                  @elseif($question->question_type === 'radio')

                    @foreach($question->option_name as $key=>$value)
                      <p style="margin:0px; padding:0px;">
                        <input type="radio" id="{{ $key }}" />
                        <label for="{{ $key }}">{{ $value }}</label>
                      </p>
                    @endforeach
                  @elseif($question->question_type === 'checkbox')
                    @foreach($question->option_name as $key=>$value)
                    <p style="margin:0px; padding:0px;">
                      <input type="checkbox" id="{{ $key }}" />
                      <label for="{{$key}}">{{ $value }}</label>
                    </p>
                    @endforeach
                  @endif
                {!! Form::close() !!}
            </div>
          </div>
        </li>
        @empty
          <span style="padding:10px;">Nothing to show. Add questions below.</span>
        @endforelse
    </ul>
    <h2 class="flow-text">Add Question</h2>
    <form method="POST" action="{{ $survey->id }}/questions" id="boolean">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      <div class="row">
        <div class="input-field col s12">
          <select class="browser-default" name="question_type" id="question_type">
            <option value="" disabled selected>Choose your option</option>
            <option value="text">Text</option>
            <option value="textarea">Textarea</option>
            <option value="checkbox">Checkbox</option>
            <option value="radio">Radio Buttons</option>
          </select>
        </div>
        <div class="input-field col s12">
          <input name="title" id="title" type="text">
          <label for="title">Question</label>
        </div>
        <!-- this part will be chewed by script in init.js -->
        <span class="form-g"></span>

        <div class="input-field col s12">
        <button class="btn waves-effect waves-light">Submit</button>
        </div>
      </div>
      </form>
  </div>
</div>

@endsection

这是JS文件:

$(document).ready(function() {
  $('.collapsible').collapsible({
    accordion: false
  });

  $('.modal-trigger').leanModal();

  $(document).on('click', '.delete-option', function() {
    $(this).parent(".input-field").remove();
  });

  // will replace .form-g class when referenced
  var material = '<div class="input-field col input-g s12">' +
    '<input name="option_name[]" id="option_name[]" type="text">' +
    '<span style="float:right; cursor:pointer;"class="delete-option">Delete</span>' +
    '<label for="option_name">Options</label>' +
    '<span class="add-option" style="cursor:pointer;">Add Another</span>' +
    '</div>';

  // for adding new option
  $(document).on('click', '.add-option', function() {
    $(".form-g").append(material);
  });
  // allow for more options if radio or checkbox is enabled
  $(document).on('change', '#question_type', function() {
    var selected_option = $('#question_type :selected').val();
    if (selected_option === "radio" || selected_option === "checkbox") {
      $(".form-g").html(material);
    } else {
      $(".input-g").remove();
    }
  });
});

我遵循了一个教程,他说: 目前,典型的答案提交可能如下所示:

{
  4: {
    answer: "My answer"
  },
  5: {
    answer: "on"
  },
  6: {
    answer: "on"
  }
}

因此我们的函数store()的foreach部分($ arr as $ key => $ value)经过上述JSON对象,则键将为例如4,则值将为$值['answer']

通过这种方式,我们可以迭代并获取指向哪个问题ID的密钥,然后将答案存储在$ value ['answer']中。


^ 但是他没有解决这个问题。

因此Radio和Checkbox将是一个数组,但是代码没有参与用户从这些数组中选择的部分。 您是否知道如何更改AnswerController以告诉代码仅接受用户选择的代码?

这是负责商店部分的answerController

public function store(Request $request, Survey $survey)
  {
    // remove the token
    $arr = $request->except('_token');
    foreach ($arr as $key => $value) {
      $newAnswer = new Answer();
      if (! is_array( $value )) {
        $newValue = $value['answer'];
      } else {
        $newValue = json_encode($value['answer']);
      }
      $newAnswer->answer = $newValue;
      $newAnswer->question_id = $key;
      $newAnswer->survey_id = $survey->id;

      $newAnswer->save();

      $answerArray[] = $newAnswer;
    };
    return redirect()->action('SurveyController@view_survey_answers', [$survey->id]);
  }
}

这是答案表:

public function up()
    {
        Schema::create('answers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('question_id');
            $table->integer('survey_id');
            $table->string('answer');
            $table->timestamps();
        });
    }

有人可以帮我吗?

0 个答案:

没有答案