How to popular an input autocomplete from a select data in the Standard

Asked

Viewed 150 times

0

I’m developing an application where I came across a bit complicated, I have a select and would like to change the autocomplete of a input according to the item chosen in this select.

Below is the controller:

public function cadastroAtividade($id, Request $request)
{
    $maqId = $this->manutencaoMaquinasM->find($id);

    $user = Auth::user();

    $resultado = [];

    $resultadoI = [];

    $nomes = '';

    $userNames = '';

    $usuario = $this->manutencaoUserM
        ->join('colaboradors', 'colaboradors.id', '=', 'manutencao_users.colaborador_id')
        ->select('colaboradors.nomecolaborador', 'manutencao_users.colaborador_id')
        ->get();

    $servico = $this->manutencaoServicoM
        ->select('descricao', 'id', 'classificacao')
        ->where('periodicidade', '>', '0')
        ->get();

    $maquina = $this->manutencaoMaquinasM
        ->join('setores', 'id_setor', '=', 'setores.id')
        ->select('manutencao_maquinas.*', 'setores.nome')
        ->where('manutencao_maquinas.id', $maqId->id)
        ->get();

    $maqServ = $this->manutencaoServicoM
        ->join('manutencao_maq_servs', 'manutencao_servicos.id', '=', 'manutencao_maq_servs.id_serv')
        ->join('manutencao_maquinas', 'manutencao_maq_servs.id_maq', '=', 'manutencao_maquinas.id')
        ->select('manutencao_servicos.classificacao', 'manutencao_servicos.descricao', 'manutencao_servicos.periodicidade')
        ->where('manutencao_maquinas.id', $maqId->id)
        ->get();

    $manuList = $this->manutencaoAtividadeM
        ->join('manutencao_servicos', 'manutencao_atividades.id_serv', '=', 'manutencao_servicos.id')
        ->join('colaboradors', 'manutencao_atividades.id_user', '=', 'colaboradors.id')
        ->select('manutencao_atividades.*', 'manutencao_servicos.classificacao', 'colaboradors.nomecolaborador', 'manutencao_servicos.descricao AS servico')
        ->where('id_maq', $maqId->id)
        ->get();

    $service = $this->manutencaoServicoM
        ->where('manutencao_servicos.descricao', $request->servico)
        ->get();

    foreach ($servico as $servicos) {
        $resultado[] = '"'.trim($servicos->descricao).'"';
    }

    if ($resultado <> []) {
        $nomes = (implode(',', $resultado));
    }

    foreach ($usuario as $manUser) {
        $resultadoI[] = '"'.trim($manUser->nomecolaborador).'"';
    }

    if ($resultadoI <> []) {
        $userNames = (implode(',', $resultadoI));
    }

    return view('portal.manutencao.servicos.atividades',
    compact('user', 'maquina', 'nomes', 'servico', 'maqId', 'maqServ', 'usuario', 'userNames', 'service', 'manuList'));
}

This is the _form:

<div class="container">
<div class="form-row">
    <div class="form-group col-md-4">
        <label for="tipo"><h4>Classificação do Serviço: </h4></label>
        <select name="tipo" id="tipo" class="form-control">
            <option value="1">Preventiva</option>
            <option value="2">Corretiva</option>
            <option value="3">Planejada</option>
            <option value="4">Limpeza</option>
        </select>
    </div>

    <div class="form-group col-md-4">
        <label for="servico"><h4>Serviço: </h4></label>
        <input name="servico" id="servico" class="form-control" placeholder="Digite o serviço a ser associado...">
    </div>

    <div class="form-group col-md-4">
        <label for="maquina"><h4>Maquina: </h4></label>
        @foreach($maquina as $maquinas)
            <input name="maquina" id="maquina" class="form-control" value="<?=$maquinas->descricao?>">
            <input type="hidden" name="maquinas" id="maquinas" value="<?=$maquinas->id?>">
        @endforeach
    </div>
</div>

<div class="form-row">
    <div class="form-group col-md-4">
        <label for="usuario"><h4>Técnico: </h4></label>
        <input name="usuario" id="usuario" class="form-control" placeholder="Digite o nome do técnico...">
    </div>

    <div class="form-group col-md-4">
        <label for="data"><h4>Data do Serviço: </h4></label>
        <input type="date" name="data" id="data" class="form-control">
    </div>

    <div class="form-group col-md-4">
        <label for="tempo"><h4>Tempo do Serviço: </h4></label>
        <input type="time" name="tempo" id="tempo" class="form-control">
    </div>
</div>

<div class="for-row">
    <div>
        <label for="descricao"><h4>Descrição da manutenção feita: </h4></label>
        <textarea name="descricao" id="descricao" class="form-control" rows="10"></textarea>
    </div>
</div>

This is the view.Lade:

@extends('portal.template')

@section('JSTopo')
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script>
    $( function() {
        var availableServices = [
            <?=$nomes?>
        ];
        $( "#servico" ).autocomplete({
            source: availableServices
        });

        var availableUsers = [
            <?=$userNames?>
        ];
        $( "#usuario" ).autocomplete({
            source: availableUsers
        });
    });
</script>

@endsection

@section('JSTopo')
@if($user->email == '[email protected]' or $user->email == '[email protected]')
@else
    <script type='text/javascript'>//<![CDATA[
        $(window).load(function(){
            $(function() {
                $("td[colspan=9]").find("p").hide();
                $("table").click(function(event) {
                    event.stopPropagation();
                    var $target = $(event.target);
                    if ( $target.closest("td").attr("colspan") > 1 ) {
                        $target.slideUp();
                    } else {
                        $target.closest("tr").next().find("p").slideToggle();
                    }
                });
            });
        });//]]>
    </script>
@endif
@endsection

@section('content')
<ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{{ url('/portal-cambos') }}">Portal Cambos</a></li>
    <li class="breadcrumb-item"><a href="{{ url('/portal-cambos/manutencao') }}">Manutenção</a></li>
    <li class="breadcrumb-item active">Cadastro de Manutenção</li>
    <li class=" ml-auto">
        <button type="button" class="btn btn-secondary btn-sm" onclick="goBack()">
            <i class="fa fa-reply"></i> Voltar
        </button>
    </li>
</ol>

<div class="ml-auto float-right">
    <a href="{{route('ordem')}}" class="btn btn-secondary btn-sm">
        <i class="fa fa-cogs"></i> Nova Ordem de Serviço
    </a>

    @if($user->email == '[email protected]' or $user->role == 'admin')
        <a href="{{route('manutencao-relatorios')}}" class="btn btn-secondary btn-sm ">
            <i class="fa fa-list-alt"></i> Relatórios
        </a>
    @endif
</div>

<h2>Cadastro de manutenção</h2><hr>

<div class="container form-group col-md-8">

    {!! Form::open(['route'=>'manutencao-save-atividades',  'method'=>'post', 'onsubmit'=>'ShowLoading()']) !!}

    @include('portal.manutencao.servicos._atividades-form')

</div>

<div class="container form-group col-md-8">

    {!! Form::submit('Salvar', ['class' => 'btn btn-primary form-control']) !!}

    {!! Form::close() !!}
</div><hr>

<h2>Manutenções Feitas nesta Máquina.</h2>

<div>
    <table class="table table-responsive table-striped">
        <thead>
            <tr>
                <th style="width: 5%"><h4>ID</h4></th>
                <th style="width: 10%"><h4>Tipo</h4></th>
                <th style="width: 15%"><h4>Técnico</h4></th>
                <th style="width: 20%"><h4>Serviço</h4></th>
                <th style="width: 10%"><h4>Data</h4></th>
                <th style="width: 10%"><h4>Tempo</h4></th>
                <th style="width: 30%"><h4>Descrição</h4></th>
            </tr>
        </thead>

        <tbody>
        @foreach($manuList as $list)
            <tr>
                <td>{{$list->id}}</td>
                <td>
                    @if($list->classificacao == 1)
                        Preventiva
                    @elseif($list->classificacao == 2)
                        Corretiva
                    @elseif($list->classificacao == 3)
                        Planejada
                    @else
                        Limpeza
                    @endif
                </td>
                <td>{{$list->nomecolaborador}}</td>
                <td>{{$list->servico}}</td>
                <td>{{$list->data}}</td>
                <td>{{$list->tempo}}</td>
                <td>{{$list->descricao}}</td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

@endsection

My biggest question is, can it be done directly in PHP or will I have to use Vuejs or something? How can it be done? I tried using loops and conditionals in the controller but, it didn’t work of course.

Could someone please help me?

I searched a lot of places but couldn’t find anything that could help me.

Thank you so much.

  • 1

    just create a method within this controller what return json with jQuery.

  • Thank you so much for the @Virgilio Novic reply, I will try here and put the resolution as soon as I reach a.

  • Thanks for the help @Virgilionovic...

1 answer

0

After a lot of head-breaking, I managed to reach a resolution... Next, my controller I left so:

public function serviceSearch(Request $request)
{
    $user = Auth::user();

    $userid = $user->id;

    $setor = Setores::all();


    $nomes= '';

    $servico = ManutencaoServicos::where('descricao', $request->conteudo)
        ->orwhere('manutencao_servicos.id', $request->conteudo)
        ->orderBy('id')
        ->paginate(14);

    foreach ($servico as $servicos) {
        $resultado[] = '"'.trim($servicos->descricao).'"';
    }

    if ($resultado <> []) {
        $nomes = (implode(',', $resultado));
    }

    return view('portal.manutencao.servicos.index', compact('user', 'userid', 'setor', 'nomes', 'servico'));
}

public function ajaxServices()
{
    $tipo = Input::get('tipo');

    $tipoSelection = ManutencaoServicos::where('classificacao', '=', $tipo)->select('classificacao')->first();

    $tiposSelected = ManutencaoServicos::select('descricao')->where('classificacao', '=', $tipoSelection->classificacao)->get();

    $nomes= '';

    $resultado = [];

    foreach ($tiposSelected as $servicos) {
        $resultado[] = trim($servicos->descricao).' ';
    }

    if ($resultado <> []) {
        $nomes = $resultado;
    }

    return $nomes;
}

In my view, the only thing I really changed was my script:

<script>
    $( function() {
        var availableUsers = [
            <?=$userNames?>
        ];
        $( "#usuario" ).autocomplete({
            source: availableUsers
        });

        $('#tipo').on('change', function (e) {
            var tipo = e.target.value;

            //ajax
            $.get('/portal-cambos/manutencao/manutencao-servicos/ajax-tipo?tipo=' + tipo, function(data){
                $( "#servico" ).autocomplete({
                    source: data
                });
            });
        });
    });
</script>

And in the form I changed my input this way:

<div class="form-group col-md-4">
        <label for="servico"><h4>Serviço: </h4></label>
        <input name="servico" id="servico" class="form-control" value="{{($tiposSelected == '')?'':$tiposSelected}}"
               placeholder="Digite o serviço a ser associado...">
    </div>

Now it’s all working out the way I wanted... Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.