首页 > 解决方案 > 在 laravel 中搜索标签

问题描述

我正在 Laravel 中构建一个应用程序,除了一件事之外,一切都运行良好。

我想做一些搜索标签(不知道这是否是正确使用的术语),以便更容易搜索信息。我的目标是做这样的事情:

图1

这就是我所拥有的:

图2

这是我页面的代码:

@extends('layouts.app')
@section('css')
<link rel="stylesheet" href="{{ asset('css/bootstrap-datepicker.min.css') }}">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
@endsection

@section('js')
<script src="{{ asset('js/sweetalert.min.js') }}" defer></script>
<script src="{{ asset('js/jquery.dataTables.js') }}" defer></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js" defer></script>
<script src="{{ asset('js/bootstrap-datepicker.min.js') }}" defer></script>
<script src="{{ asset('js/bootstrap-datepicker.pt.min.js') }}" defer></script>
@endsection

@section('content')
<div class="container">
<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between">
        <span>
            <i class="fas fa-building"></i>
            <strong class="text-uppercase">Gestão de Obras</strong>
        </span>

        <a href="{{ route('constructions.create') }}" class="btn btn-outline-primary">
            <i class="fas fa-plus"></i>
            Criar obra
        </a>
    </div>

    <div class="card-body">
        <table class="table table-striped table-bordered guaca-table">
            <thead>
                <tr>
                    <th>Referência</th>
                    <th>Nome</th>
                    <th>Descrição</th>
                    <th>Morada</th>
                    <th>Terminada em</th>
                    <th class="guaca-table-head-actions" style="text-align:center">Ações</th>
                </tr>
            </thead>

            <tbody>
                @foreach ($constructions as $construction)
                    <tr>
                        <td>{{ $construction->reference }}</td>
                        <td>{{ $construction->name }}</td>
                        <td>{{ \Illuminate\Support\Str::limit($construction->description, 50, '...') }}</td>
                        <td>{{ \Illuminate\Support\Str::limit($construction->address, 100, '...') }}</td>
                        <td>
                            @if ($construction->has_ended)
                                {{ $construction->end_date }}
                            @else
                                -
                            @endif
                        </td>
                        <td class="d-flex justify-content-around">
                            @if (!$construction->is_system)
                                    <a href="{{ route('constructions.edit', $construction->id) }}" class="btn btn-sm btn-outline-primary">
                                        <i class="far fa-edit"></i>
                                    </a>
                                    @if (!$construction->has_ended)
                                        <!-- BOTÂO DE TERMINAR OBRAS -->
                                        <button type="button" class="btn btn-sm btn-outline-primary"
                                            data-toggle="modal" data-target="#end-modal-{{ $construction->id }}">
                                            <i class="far fa-calendar-times"></i>
                                        </button>
                                        <!-- MODAL DE TERMINAR OBRAS -->
                                        <div class="modal fade" id="end-modal-{{ $construction->id }}" tabindex="-1" role="dialog" 
                                            aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered" role="document">
                                                <div class="modal-content">
                                                    <form method="POST" action="{{ route('constructions.end', ['id' => $construction->id]) }}">
                                                        @csrf
                                                        <div class="modal-header">
                                                            <h5 class="modal-title" id="exampleModalLongTitle">
                                                                Terminar obra
                                                            </h5>
                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                <span aria-hidden="true">&times;</span>
                                                            </button>
                                                        </div>

                                                        <div class="modal-body">
                                                            <strong>
                                                                Referência:
                                                            </strong>
                                                            <div>
                                                                {{ $construction->reference }} 
                                                            </div>
                                                            <br>
                                                            <strong>
                                                                Nome:
                                                            </strong>
                                                            <div>
                                                                {{ $construction->name }} 
                                                            </div>
                                                            <br>
                                                            <strong>
                                                                Morada:
                                                            </strong>
                                                            <div>
                                                                {{ $construction->address }} 
                                                            </div>
                                                            <br>
                                                            <strong>
                                                                Data de Término:
                                                            </strong>
                                                            <input id="end_date" 
                                                                type="date" class="form-control datepicker {{ $errors->has('end_date') ? 'is-invalid' : '' }}" 
                                                                name="end_date" value="{{ old('end_date') }}" required>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                                                            <button type="submit" class="btn btn-primary">Terminar obra</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    @endif
                                    <form method="POST" class="delete-form" 
                                        action="{{ route('constructions.destroy', $construction->id) }}">
                                        @csrf
                                        @method('delete')
                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                            <i class="far fa-trash-alt"></i>
                                        </button>
                                    </form>
                            @else
                                <span class="badge badge-primary">
                                    SISTEMA
                                </span>
                            @endif
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>

@endsection

我试图在资产文件夹中创建一个app.js,然后在 JS 文件夹中创建一个,这是我的代码,但它不起作用:

require('./bootstrap');

$(document).ready(function () {
var $datepickers = $('.datepicker');

$datepickers.each(function () {
    $(this).datepicker({
        language: 'pt',
        format: 'yyyy-mm-dd',
        useCurrent: true
    });
});

//ao mexer na dropdown no formulario de COMPRAS
$('.form-group-slider').on('change', function () {
    var $target = $(this.dataset.sliderTarget);

    if (!!this.value) {
        $target.slideUp();
    } else {
        $target.slideDown();
    }
});

$('.delete-form').on('submit', function (e) {
    var $form = $(this);

    if ($form.data('allow') !== true) {
        e.preventDefault();

        swal({
          title: "Tem a certeza que pretende apagar?",
          text: "Esta operação é irreversível!",
          icon: "warning",
          dangerMode: true,
          buttons: ["Cancelar", "Sim, tenho a certeza"],
        })
        .then((willDelete) => {
          if (willDelete) {
            $form.data('allow', true);
            $form.submit();
          }
        });
    }
});

$('.select2').each(function () {
    $(this).select2();
});

$('.guaca-table').each(function () {
    var $table = $(this);

    if (!$table) {
        return;
    }

    var initialHeadCount = $table.find('th').length;
    var orderableArray = [];

    for (var i = initialHeadCount - 2; i >= 0; i--) {
        orderableArray.push(i);
    }


    $('.guaca-table thead tr').clone(true).appendTo( '.guaca-table thead' );
    $('.guaca-table thead tr:eq(1) th').each(function (i) {
        var $th = $(this);

        if ($th.hasClass('guaca-table-head-actions')) {
            return;
        }

        var title = $th.text();
        $th.html( '<input type="text" class="form-control form-control-sm" placeholder="Pesquisar ' + title + '" />');

        $('input', this).on('keyup change', function () {
            if (dataTable.column(i).search() !== this.value) {
                dataTable.column(i).search(this.value).draw();
            }
        });
    });

    dataTable = $table.DataTable({
        responsive: true,
        fixedHeader: true,
        orderCellsTop: true,
        columnDefs: [
            { targets: orderableArray, orderable: true },
            { targets: ["_all"], orderable: false }
        ],
        language: {
            decimal: "",
            emptyTable: "Não existem items.",
            info: "Mostrar _START_ a _END_ de um total de _TOTAL_ items",
            infoEmpty: "Mostrar 0 a 0 de um total de 0 items",
            infoFiltered: "(Filtrado de um total de _MAX_ items)",
            infoPostFix: "",
            thousands: ",",
            lengthMenu: "Mostrar _MENU_ items",
            loadingRecords: "A carregar...",
            processing: "A processar...",
            search: "Pesquisar:",
            zeroRecords: "A pesquisa não retornou resultados.",
            paginate: {
                first: "Primeiro",
                last: "Último",
                next: "Próximo",
                previous: "Anterior"
            },
            aria: {
                sortAscending: "Ativar para ordenar coluna por ordem ascendente.",
                sortDescending: "Ativar para ordenar coluna por ordem descendente."
            }
        }
    });
});
});

标签: htmlcsslaraveldatatables

解决方案


您在“想要”中引用的是“DataTables”的一部分,有一个用于集成 DataTables 服务器端的 laravel 包。(https://github.com/yajra/laravel-datatables)。

请参阅 www.datatables.net 以了解如何根据需要进行设置。它是一个非常强大的表格包,有几种不同的初始化方式。似乎数据表实际上并未初始化表 - 可能您的数据表初始化代码中有错误。


推荐阅读