Khayam Khan
Khayam Khan

Reputation: 1235

If old value then select old value of Select Box otherwise select value coming from Controller

I have a select box in the edit form, and everything is working fine, but the problem is when there is an old value, it always selects the value from the database. I think the issue is loop indexing. When I choose an option down from the original value, it selects the old value, but it retains the initial value when selecting an option above the selected value.

<select class="form-control 
        searchableSelect {{ $errors -> has('Cash_expense_Account') ? 'is-invalid' : '' }}"
        name="Cash_expense_Account">
    <option value="">Search...</option>
    @for($i = 0; $i < count($Cash_Accounts); $i++)
        <option value="{{ $Cash_Accounts[$i]['id'] }}" 
                {{ ( $Cash_Accounts[$i]['id'] == $expense->coa_sub_account_id) ? 'selected' : '' }} 
                {{ old('Cash_expense_Account') == $Cash_Accounts[$i]['id'] ? 'selected' : '' }}>
            {{ $Cash_Accounts[$i]['acc_sub_name'] }}
        </option>
    @endfor
</select>

Upvotes: 0

Views: 211

Answers (1)

Jiglant
Jiglant

Reputation: 56

Limit the comparison to only use old value if it exists, like:

<option value="{{ $Cash_Accounts[$i]['id'] }}" {{ ( (old('Cash_expense_Account')??$Cash_Accounts[$i]['id']) == $expense->coa_sub_account_id) ? 'selected' : '' }}>
{{ $Cash_Accounts[$i]['acc_sub_name'] }}
</option>

the ?? operator checks if old value exists otherwise use one from the loop.

Upvotes: 1

Related Questions