Add fields dynamically in form in Laravel

1

I have a business registration form, within this register, the company can have 'n' certificates.

These certificates should be added to the form as needed.

How can I do this in Laravel? I have tried with Jquery (transforming the fields into arrays, example, "name = 'certificate []'") but I could not.

Is there any other way to do this without being Jquery?

Forms code below (both Blade).

Base form:

<?php ?>
<div class="row">
    <div class="col-md-6">
        <div class="form-group{{ $errors->has('simplesNacional') ? ' has-danger' : '' }}">
            <label for="name">Simples Nacional</label>
            @if(!$clientPassword)
                <input type="text" class="form-control" placeholder="Simples Nacional" name="simplesNacional" value="{{ old('simplesNacional') }}" required autofocus>
            @else
                <input type="text" class="form-control" placeholder="Simples Nacional" name="simplesNacional" value="{{$clientPassword->simplesNacional}}">
            @endif
            @if ($errors->has('simplesNacional'))
                <span class="help-block">
                    <strong>{{ $errors->first('simplesNacional') }}</strong>
                </span>
            @endif
        </div>
    </div>
    <div class="col-md-6">
        <div class="form-group{{ $errors->has('siare') ? ' has-danger' : '' }}">
            <label for="name">SIARE</label>
            @if(!$clientPassword)
                <input type="text" class="form-control" placeholder="SIARE" name="siare" value="{{ old('siare') }}" required autofocus>
            @else
                <input type="text" class="form-control" placeholder="SIARE" name="siare" value="{{$clientPassword->siare}}">
            @endif
            @if ($errors->has('siare'))
                <span class="help-block">
                    <strong>{{ $errors->first('siare') }}</strong>
                </span>
            @endif
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <h4>Certificados</h4>
    </div>
</div>

<div class="row">
    <div class="col-md-3">
            <button type="button" id="addDigitalCertificate" class="btn btn-primary">Adicionar certificado digital</button>
    </div>
</div>

<div id="digitalCertificates">

</div>

Certificate form fields (which needs to be added to the base form when clicking the 'Add digital certificate' button.)

<div class="row">
    <div class="col-md-2">
        <div class="form-group{{ $errors->has('issueDate') ? ' has-danger' : '' }}">
            <label for="issueDate">Data de emissão</label>
            @if(!$digitalCertificate)
                <input type="date" class="form-control" placeholder="Data de emissão" name="issueDate" value="{{ old('issueDate') }}" required autofocus>
            @else
                <input type="date" class="form-control" placeholder="Data de emissão" name="issueDate" value="{{$digitalCertificate->issueDate}}">
            @endif
            @if ($errors->has('issueDate'))
                <span class="help-block">
                    <strong>{{ $errors->first('issueDate') }}</strong>
                </span>
            @endif
        </div>
    </div>
    <div class="col-md-2">
        <div class="form-group{{ $errors->has('expirationDate') ? ' has-danger' : '' }}">
            <label for="expirationDate">Data de expiração</label>
            @if(!$digitalCertificate)
                <input type="text" class="form-control" placeholder="Data de esxpiração" name="expirationDate" value="{{ old('expirationDate') }}" required autofocus>
            @else
                <input type="text" class="form-control" placeholder="Data de esxpiração" name="expirationDate" value="{{$digitalCertificate->expirationDate}}">
            @endif
            @if ($errors->has('expirationDate'))
                <span class="help-block">
                    <strong>{{ $errors->first('expirationDate') }}</strong>
                </span>
            @endif
        </div>
    </div>
    <div class="col-md-8">
        <div class="form-group{{ $errors->has('certifyingEntity') ? ' has-danger' : '' }}">
            <label for="certifyingEntity">Certificadora</label>
            @if(!$digitalCertificate)
                <input type="text" class="form-control" placeholder="Certificadora" name="certifyingEntity" value="{{ old('certifyingEntity') }}" required autofocus>
            @else
                <input type="text" class="form-control" placeholder="Certificadora" name="certifyingEntity" value="{{$digitalCertificate->certifyingEntity}}">
            @endif
            @if ($errors->has('certifyingEntity'))
                <span class="help-block">
                    <strong>{{ $errors->first('certifyingEntity') }}</strong>
                </span>
            @endif
        </div>
    </div>
</div>

EDIT:

I did not find a way to do this without Jquery, but at least it solved the problem.

I removed some validations that Blade does in conjunction with laravel and then created a JS file to clone the fields.

Certificate Form:

<div id="digitalCertificates">
    <div class="teste">
        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="certificate[][issueDate]">Data de emissão</label>
                    <input type="date" class="form-control" placeholder="Data de emissão" name="certificate[][issueDate]" required autofocus>
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label for="certificate[][expirationDate]">Data de expiração</label>
                    <input type="text" class="form-control" placeholder="Data de esxpiração" name="certificate[][expirationDate]" required autofocus>
                </div>
            </div>
            <div class="col-md-8">
                <div class="form-grou">
                    <label for="certificate[][certifyingEntity]">Certificadora</label>
                    <input type="text" class="form-control" placeholder="Certificadora" name="certificate[][certifyingEntity]" required autofocus>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="certificate[][type]">Tipo</label>
                    <select name="certificate[][type]" class="form-control" required>
                            <option value="">Selecione um tipo</option>
                            @foreach($types as $type)
                                <option value='{{ $type }}'>{{ $type }}</option>
                            @endforeach
                    </select>
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label for="certificate[][subType]">Subtipo</label>
                    <select name="certificate[][subType]" class="form-control" required>
                        <option value="">Selecione um subtipo</option>
                            @foreach($subTypes as $subType)
                                <option value='{{ $subType }}'>{{ $subType }}</option>
                            @endforeach
                    </select>
                </div>
            </div>
            <div class="col-md-8">
                <div class="form-group">
                    <label for="certificate[][physicalLocation]">Localização física</label>
                    <input type="text" class="form-control" placeholder="Localização física" name="certificate[][physicalLocation]" required autofocus>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-10">
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" name="certificate[][inPossession]" required autofocus>
                    <label class="form-check-label" for="certificate[][inPossession]">Em posse</label>
                </div>
            </div>
            <div class="col-md-2">
                <button class="removerCampo btn btn-danger">Remover certificado</button>
            </div>
        </div>
        <hr>
    </div>
</div>

JS that clones the fields:

$(function () {

hideBtnDel();

function hideBtnDel() {
    if ($("#digitalCertificates .teste").length <= 1) {
        $("#digitalCertificates .teste .removerCampo").addClass('disabled');
    }else{
        $("#digitalCertificates .teste .removerCampo").removeClass('disabled');
    }
    removeCampo();
}

function removeCampo() {
    $(".removerCampo").unbind("click");
    $(".removerCampo").bind("click", function () {
        $(this).parents('.teste').remove();
        hideBtnDel();           
    });
}

$("#addDigitalCertificate").click(function () {
    event.preventDefault();
    novoCampo = $("#digitalCertificates .teste:first").clone();
    novoCampo.find("input").val("");
    novoCampo.insertAfter("#digitalCertificates .teste:last");            
    hideBtnDel();
});

});

    
asked by anonymous 29.08.2018 / 17:45

1 answer

1

Dude, you can try using it that way. Here's an example:

(function ($) {
    $(function () {

        var addFormGroup = function (event) {
            event.preventDefault();

            var $formGroup = $(this).closest('.form-group');
            var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
            var $formGroupClone = $formGroup.clone();

            $(this)
                .toggleClass('btn-success btn-add btn-danger btn-remove')
                .html('–');

            $formGroupClone.find('input').val('');
            $formGroupClone.find('.concept_sistema').text('Sistema');
            $formGroupClone.find('.concept').text('Estado');
            $formGroupClone.insertAfter($formGroup);

            var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
            if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
                $lastFormGroupLast.find('.btn-add').attr('disabled', true);
            }
        };

        var removeFormGroup = function (event) {
            event.preventDefault();

            var $formGroup = $(this).closest('.form-group');
            var $multipleFormGroup = $formGroup.closest('.multiple-form-group');

            var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
            if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
                $lastFormGroupLast.find('.btn-add').attr('disabled', false);
            }

            $formGroup.remove();
        };

        var countFormGroup = function ($form) {
            return $form.find('.form-group').length;
        };

        $(document).on('click', '.btn-add', addFormGroup);
        $(document).on('click', '.btn-remove', removeFormGroup);

    });
})(jQuery);
<section class="container-fluid">
    <div class="container-fluid">
        <h2 class="pull-left"> Exemplo </h2>
    </div>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<!-- Optional theme -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><hr><divclass="clearfix form-group" id="carterinha_oab">
        <div class="col-md-4">
            <div class="clearfix">
                <label class="pull-left"> Campo </label>
            </div>
            
            <div class="form-group multiple-form-group input-group">
                <div class="input-group-btn input-group-select">
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        <span class="concept"> Estado </span> <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                    
                        <li><a href="#"> ### </a></li>
                    </ul>
                    <input type="hidden" class="input-group-select-val" name="estado[]" id="estado">
                </div>
                <input type="text" name="descricao[]" maxlength="45" id="descricao" class="form-control">
                <span class="input-group-btn">
                    <button type="button" class="btn btn-success btn-add">+</button>
                </span>
            </div>
        </div>
    </div>
</section>
    
29.08.2018 / 18:15