【问题标题】:How to receive multiple checkboxes values and store properly in the database?如何接收多个复选框值并正确存储在数据库中?
【发布时间】:2018-08-25 17:51:30
【问题描述】:

我有一个包含一些字段/问题(您的电子邮件是什么?,您的电话号码是什么?)的表单,然后用户可以选择是否应该为会议存在的注册类型包含该字段,以及是否应该包含该字段通过复选框,每个注册类型的字段应该是强制性的或不是强制性的。表单布局示例:

例如,对于会议“测试会议”,有两种注册类型(RT01 和 RT02)和两个问题“你的电子邮件是什么?”和“你的手机是什么?”。

用户可以在表格中为每个注册类型选择是否要包括两个问题,仅一个问题,无问题,并且对于每个包含的问题,用户可以选择该问题对于每个注册类型是否是强制性的。

因此,例如,如果对于“你的电子邮件是什么?”这个问题。选中所有复选框(“注册类型 RT01 包含”、“注册类型 RT02 包含”、“注册类型 RT01 强制”、“注册类型 RT02 强制”)以及“你的手机是什么?”问题均已选中。所有复选框都被选中,它应该像这样插入到数据透视表“registration_type_questions”中:

registration_type_id question_id required
 1                       1        1      (Include the question with id 1 in the registrationtype with id 1 and the question is mandatory for the registrationtype with id 1)
 2                       1        1    
  1                       2        1       
  2                       2        1 

但是像这样插入:

registration_type_id question_id required
  1                       2        0       
  2                       2        0     

您知道问题出在哪里吗?我现在的代码是这样的:

会议登记表编辑表格:

  <form method="post" class="clearfix" action="{{route('questions.update', ['conf_id' => $conf->id])}}">

      {{csrf_field()}}

      <table class="table table-striped table-responsive-sm">
    <thead>
    <tr>
        <th scope="col">Info</th>
        <th scope="col">Include for registration type</th>
        <th scope="col">Mandatory field</th>
    </tr>
    </thead>
    <tbody>

    @foreach($question as $q)
        <tr>
            <td>{{$q->question}}</td>
            <td>
                @foreach($registration_types as $rtype)
                    <div class="form-check">
                        <input autocomplete="off" name="question[{{$q->id}}][rtypes][]" class="form-check-input {{$rtype->name}}" type="checkbox" value="{{ $rtype->id }}" id="{{$rtype->id}}">
                        <label class="form-check-label" for="exampleRadios1">
                            {{$rtype->name}}
                        </label>
                    </div>
                @endforeach
            </td>
            <td>
                @foreach($registration_types as $rtype)
                    <div class="form-check">
                        <input autocomplete="off"  name="question[{{$q->id}}][mandatories][]"
                               class="form-check-input mandatorycheckbox" type="checkbox" value="{{ $rtype->id }}" id="{{$rtype->id}}">
                        <label class="form-check-label" for="exampleRadios1">
                            for the registration type "{{$rtype->name}}"
                        </label>
                    </div>
                @endforeach
            </td>
        </tr>
    @endforeach

    </tbody>
</table>      

      <input type="submit" class="btn btn-primary float-right mt-3" value="Update"/>
    </form>   

问题模型

class Question extends Model
{

    public function registration_type(){
        return $this->belongsToMany('App\RegistrationType', 'registration_type_questions');
    }
}

注册类型模型

class RegistrationType extends Model
{
    public function conference(){
        return $this->belongsTo('App\Conference');
    }

    public function questions(){
        return $this->belongsToMany('App\Question', 'registration_type_questions');
    }
}

会议模型

class Conference extends Model
{
   // A conference has many registration types
    public function registrationTypes(){
        return $this->hasMany('App\RegistrationType', 'conference_id');
    }
}

QuestionController 更新方法:

 public function update(Request $request, $question_id){
        $question = $request->get('question');

        foreach($question as $key => $q) {
                //with "$outputArray = array_fill_keys($q["rtypes"], $q["mandatories"]);" it appears Undefined index: mandatories
            $outputArray = array_fill_keys($q["rtypes"], ["required" => false]);
            foreach ($outputArray as $lineKey => $line) {
                $line[$lineKey]["required"] = in_array($lineKey, $q["mandatories"]);
            }
        }

        $getQuestion = Question::find($key);
        if($getQuestion);
        $getQuestion->registration_type()->sync($outputArray);

        $this->validate($request, [
            ]);
    }

QuestionController "foreach($question as $key =&gt; $q) {" 中的$questions 有这样的内容:

array:2 [▼
  1 => array:2 [▼
    "rtypes" => array:2 [▼
      0 => "1"
      1 => "2"
    ]
    "mandatories" => array:2 [▼
      0 => "1"
      1 => "2"
    ]
  ]
  2 => array:2 [▼
    "rtypes" => array:2 [▼
      0 => "1"
      1 => "2"
    ]
    "mandatories" => array:2 [▼
      0 => "1"
      1 => "2"
    ]
  ]
]

【问题讨论】:

  • 你总是将 required 插入为 false,这就是为什么它总是 0
  • 谢谢,我将 required 插入为 false 以进行测试,因为我没有成功获得强制复选框的值。如果我使用“ $outputArray = array_fill_keys($q["rtypes"], $q["mandatories"]); ”,则会出现错误“未定义索引:rtypes”。但即使使用“false”这个静态,在数据透视表中也只存储 id 为“2”的问题的信息。
  • 你输入的名字也错了 name="rypes[]
  • 谢谢。我将用该更正更新问题。但在我的例子中,我有 rtypes[].
  • 您不能在对象名称中使用 []。 php 不会读取它

标签: php laravel


【解决方案1】:

试试这个...[表单和控制器都更新了]

更新注册表

@foreach($question as $q)
    <tr>
        <td>{{$q->question}}</td>
            <td>
                @foreach($registration_types as $rtype)
                    <div class="form-check">
                        <input autocomplete="off" name="include[{{ $q->id }}][{{ $rtype->id }}]" class="form-check-input {{$rtype->name}}" type="checkbox" value="1" id="{{$rtype->id}}">
                            <label class="form-check-label" for="exampleRadios1">
                                {{$rtype->name}}
                            </label>
                    </div>
                @endforeach
            </td>
            <td>
                @foreach($registration_types as $rtype)
                    <div class="form-check">
                        <input autocomplete="off"  name="mandatory[{{ $q->id }}][{{ $rtype->id }}]"
                                   class="form-check-input mandatorycheckbox" type="checkbox" value="1" id="{{$rtype->id}}">
                            <label class="form-check-label" for="exampleRadios1">
                                for the registration type "{{$rtype->name}}"
                            </label>
                        </div>
                    @endforeach
                </td>
            </tr>
        @endforeach

更新的控制器

public function update(Request $request, $question_id)
{
    $includeArray = [];
    $includes     = $request->get('include');
    $mandatory    = $request->get('mandatory');

    //fetch all questions using required where conditions
    $questions = Question::get();    

    foreach($questions as $key => $question) { 
        if(!empty($includes[$question->id])) { 
            foreach($includes[$question->id] as $include => $value) { 
                if (!empty($mandatory[$question->id][$include]) && $mandatory[$question->id][$include] == 1) { 
                    $includeArray[$include] = ['required' => 1]; 
                } else { 
                    $includeArray[$include] = ['required' => 0]; 
                } 
            } 
        } else if(!empty($mandatory[$question->id])) { 
            foreach($mandatory[$question->id] as $mandatoryKey => $value) { 
                if (!empty($mandatory[$question->id][$mandatoryKey]) && $mandatory[$question->id][$mandatoryKey] == 1) { 
                    $includeArray[$mandatoryKey] = ['required' => 1]; 
                } else { 
                    $includeArray[$mandatoryKey] = ['required' => 0]; 
                } 
            } 
        } 
        $question->registration_type()->sync($includeArray); 
        $includeArray = []; 
    } 
}

【讨论】:

  • 谢谢,但这样不会在数据库中插入任何东西。它正在执行一个 conf_id 为 null 的查询:""select * from questions where conf_id is null""。
  • 删除where('conf_id', $request-&gt;get('conf_id')并将行更改为` $questions = Question::get();`
  • 谢谢,但它不能正常工作。执行的查询是: string(25) "select * from questions" string(88) "select registration_type_id from registration_type_questions where question_id = ?" string(110) "插入registration_type_questions (question_id, registration_type_id, required) 值(?, ?, ?)" string(88) "从registration_type_questions中选择registration_type_id 其中question_id = ?” string(110) "插入registration_type_questions (question_id, registration_type_id, required) 值 (?, ?, ?)"
  • 如果选中所有复选框,则显示结果,第一行:“registration type id(1)”、“question_id(1)”、“required(0)”。第二行“注册类型id(1)”、“question_id(2)”、“required(0)”。
  • @JohnZ 如果选中所有复选框,dd($request-&gt;get('include')($request-&gt;get('mandatory') 会返回什么。
【解决方案2】:

您需要通过-&gt;withPivot 在您的模型中声明您的枢轴。

class Question extends Model
{

    public function registration_type(){
        return $this->belongsToMany('App\RegistrationType', 'registration_type_questions')->withPivot('required');
    }
}

然后你可以像这样更新它:

$getQuestion->registration_type()->updateExistingPivot($id, ['required' => 1]);

其中$id 变量应包含registration_type id。

【讨论】:

  • 谢谢,您知道如何获取registration_type id吗?我没有成功获得它们以及如何正确存储强制复选框?
猜你喜欢
  • 2011-08-12
  • 2019-08-13
  • 2019-02-26
  • 1970-01-01
  • 2018-03-29
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多