简体   繁体   中英

How to show selected checkbox in multiselect checkbox list in laravel?

I have a multi-select checkbox list. I want to show stored value in list using checkbox selected.

User informations are stored in Partner_Prefence table and user religion column named as p_religion

$profile_data= DB::table('partner_prefence')->select('p_religion')->first();

Fetching religions from religions table

$religion_data=DB::table('religion')->select('religion_id','religion_name')->orderby('religion_name')->get();

Multiselect list

<select  multiple="multiple" name="religion[]">
   @foreach($religion_data as $religion)
     <option value="{{$religion->religion_id}}" {{$profile_data->p_religion == $religion->religion_id  ? 'selected' : ''}}>{{$religion->religion_name}}</option>
   @endforeach
</select>

I'm having trouble with showing which religions user have

{{$profile_data->p_religion == $religion->religion_id  ? 'selected' : ''}}

as I understand you have multi select form, so you need show selected multiple column..

You're storing ids as a string but it's hard check that certain number in string. İf you convert string into a array, you can easly check with in_array() method. This method will return true if given value exist in given array

<select multiple="multiple" name="religion[]">
    {{-- no need to explode every time, it will reduce your performance --}}
    @php($religions = explode(',', $profile_data->p_religion))
    @foreach($religion_data as $religion)
        <option
                value="{{$religion->religion_id}}"
                {{--if user religion id exist in religions then mark as selected--}}
                {{in_array($religion->religion_id,$religions) ? "selected" : ""}}>
            {{$religion->religion_name}}
        </option>
    @endforeach
</select>

Is the p_religion column saving multiple IDs if it is a multi-select list? Would using in_array() work then instead of using $profile_data->p_religion == $religion->religion_id .

in_array ($religion->religion_id, explode(',', $profile_data->p_religion))

Added the explode() call on the off chance you are storing an imploded array.

You could also try and use the blade syntax for an if statement inline to see if it displays differently.

<select  multiple="multiple" name="religion[]">
     @foreach($religion_data as $religion)
          <option value="{{$religion->religion_id}}" @if($profile_data->p_religion == $religion->religion_id) selected @endif>
               {{$religion->religion_name}}
          </option>
     @endforeach
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM