簡體   English   中英

如何根據存儲在數據庫中的類型更改輸入類型?

[英]How to change the input type based on the type stored in database?

我有一個表單供用戶創建自定義問題。 用戶需要引入問題以及字段類型(文本,長文本,復選框,選擇菜單,單選按鈕)來創建自定義問題:

<form method="post" class="clearfix" action="{{route('questions.store', ['conference_id' => $conference->id])}}" enctype="multipart/form-data">
    {{csrf_field()}}
    <div class="form-group">
        <label for="question">Question</label>
        <input type="text" class="form-control" name="question" id="question">
    </div>
    <div class="form-group">
        <label for="type" class="text-heading h6 font-weight-semi-bold">Type of field</label>
        <select class="form-control" name="type" id="type">
            <option value="text">Text</option>
            <option value="long_text">Long Text</option>
            <option value="checkbox">Checkbox</option>
            <option  value="radio_btn">Radio Button</option>
            <option  value="select_menu">Select menu</option>
        </select>
    </div>

    <div>
        <input type="submit" class="btn btn-primary" value="Store"/>
    </div>
</form>

在問題表的數據庫中就像:

id       question                    conference_id        type
1        Whats your phone?               1                 text
2        Want receive notifications?      1                 radio_btn
3       ..............                    1                 checkbox
4       ..............                    1                 long_txt
5       ..............                    1                 select_menu

然后在registration.blade.php中我向用戶顯示自定義問題,以便他可以回答。 問題已經通過以下代碼呈現給用戶。 我懷疑的是如何根據存儲在數據庫中的問題類型更改輸入類型。

你知道怎么做到這一點嗎? 因為它始終是一個文本類型的問題。 但是,如果問題類型是例如復選框,則它應該將問題顯示為復選框而不是輸入類型文本。

@foreach($selectedType['questions'] as $customQuestion)
    <div class="form-group">
        <label for="participant_question">{{$customQuestion->question}}</label>
        <input type="text"
               @if($customQuestion->pivot->required == "1") required @endif
               class="form-control" name="participant_question[]">
        <input type="hidden" name="participant_question_required[]"
               value="{{ $customQuestion->pivot->required }}">
        <input type="hidden" value="{{ $customQuestion->id }}" name="participant_question_id[]"/>
    </div>
@endforeach

在您的Question模型中,創建一個函數以輸出所需的不同類型的輸入。

例如

public function getHtmlInput($name = "", $id = "", $required = false, class="", val = "", $customtype=false) 
{
    switch ($this->type) {
        case "text": 
              return "<input type='".($customtype?:"text")."' name='$name' id='$id' class='$class' value='$val'" . ($required?:"required") . ">";
        case "checkbox":
        ...
    }
}

然后在你的視圖中你可以做$question->getHtmlInput(<params>)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM