Dynamically add form fields in Laravel

Asked

Viewed 728 times

1

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

These certificates should be added to the form as required.

How can I do this in Laravel? I’ve tried it with Jquery (turning fields into arrays, for example, "name='Certificate[]'") but I couldn’t.

Is there any other way to do this than with Jquery?

Code of the forms 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 by 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 couldn’t find a way to do it without Jquery, but at least I could solve the problem.

I removed some validations that Blade does in conjunction with the Standard 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();
});

});

1 answer

1


Dude, you can try using this way. Follow 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>

    <div class="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>

  • Thanks for the answer, I couldn’t replicate it, but it served as the basis for my code.

Browser other questions tagged

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