Sunday, March 19, 2017

Laravel dynamic warning message

I have a DB model with 3 tables: Equipment, Method and Column.

Equipment can have one Column currently installed. Equipment M:M Method. Method M:M Column.

When making a reservation, I need to check if chosen method supports the column which is currently installed in equipment, and if not, I need to throw a warning (without making a request).

I wanted to make it with jQuery, but I think I am overcomplicating, and it does not work as it should.

<!-- Methods -->
<div class="form-group">
    <label for="group" class="col-md-2 control-label">Method</label>

    <div class="col-md-6">
        <select class="form-control" name="method_id"
                data-equipment-method-column-id=
                        id="method_id" required="">
            <option value="">Select</option>
            @foreach($equipment->equipment_methods as $method)
                <?php $method_column = $method->columns->where('pivot.method_column_id', $equipment->method_column_id)->first() ?>
                <option id="option_id_" value=""
                        data-method-column-id="@if($method_column != null)  @else 0 @endif"
                        @if($method->id == old('method_id'))
                        selected="selected"
                        @endif ></option>
            @endforeach
        </select>
    </div>
</div>

This is a dropdown with all the methods an equipment is capable of performing. And if user chooses one which isn't supported by column currently installed, it should throw a warning.

jQuery:

<script>
    $('#method_id').on('change', function (e) {
        if ($(e.currentTarget).data('equipment-method-column-id') != $('#option').data('method-column-id')) {
            $('.form-group').find('#column_message')
                    .replaceWith('<div class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>');
        } else {
            console.log('here')
        }
    })
</script>

This throws error each time I select something, because it is fetching only first option_id I guess...but I think it must be an easier way to do it?



via Norgul

Advertisement