skip to Main Content

I’d love to share the same form to store/update data on a Laravel AJAX form.
So I would change the form method depending of the action the user want to do.
i.e.
store method:

<form method="post" action="{{action('TechnicianController@store')}}" id="formTec">
    @csrf

update method:

<form method="post" action="{{action('TechnicianController@store')}}" id="formTec">
    @csrf @method('PUT');

I’ve an index page where I include the form that I open via Ajax

{{-- Form include  --}}
<div class="col-9" id="scheda" style="display:none">
  <form method="post" action="{{action('TechnicianController@store')}}" id="formTec">
    @csrf
  @include('technician.form')
</div>

Any idea how can I make I solve this problem?

Thank you

Valerio

2

Answers


  1. Chosen as BEST ANSWER

    In the index file I've a list of technicians that I show in this way

    @foreach ($technicians as $technician)
                  <li><i class="fa-li fa fa-square text-muted"></i><a href="#" onclick="event.preventDefault();tecShow({{ $technician->id }})"><small class="text-muted"># {{$technician->id}}</small>  {{$technician->nome}} {{$technician->cognome}}</a></li>
            @endforeach
    

    I also have a button to create a new tec

    <a onclick="event.preventDefault();openTecForm()" href="" class="btn btn-outline-muted btn-sm text-secondary">
    

    And a hidden div to show the form

    <div class="col-9" id="scheda" style="display:none">
      <form method="post" action="{{action('TechnicianController@store')}}" id="formTec">
        @csrf
      @include('technician.form')
    </div>
    

    Inside my js file I've some functions:

    openForm() -> reset the field, set up buttons and show the hidden div

    tecAdd() -> perform the ajax call, store the content and append the result on the ul in the index file

    tecShow(id) -> fill the form data coming from the base

    tecEdit(id) -> still working on it but it should update the record


  2. You could include the ID of the record you want to update and check to see if its there in your controller. If not, you can create a new record.

    UPDATED

    <div class="col-9" id="scheda" style="display:none">
          <form method="post" action="{{action('TechnicianController@store')}}" id="formTec">
              @csrf
              // only on update form
              <input type="hidden" name="technician_id" value="{{ $technician->id }}">
              @include('technician.form')
          </form>
    </div>
    

    Then in your controller:

    if ($request->input('technician_id'))
    {
        // Update code
    } else {
        // Create new code
    }
    

    UPDATE 2

    This is what I was thinking: https://codepen.io/205media/pen/abOxXzB

    Just to append the hidden input for the technician id when updating and not when creating a new record.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search