Utilizing Laravel to Send Table Data to Modal for Form Submission to Controller

In our users table, there is an edit modal that needs to retrieve specific user data from the table list and display it within the modal's input fields. This requires using Laravel logic to edit the data and submit it back to the controller as a form.

Table list

<div id='recipients' class="p-8 mt-6 rounded shadow bg-white">
        <table id="users" class=" dt-responsive display nowrap" style="width:100%; padding-top: 1em;  padding-bottom: 1em;">
            <thead>
                <tr>
                    <th data-orderable="false">Username </th>
                    <th data-orderable="false">Email</th>
                    <th data-orderable="false">Role </th>
                    <th data-orderable="false">Active</th>
                    <th data-orderable="false"></th>
                </tr>
            </thead>
            <tbody>
                @foreach ($users as $user)
                    <tr>
                        <input type="hidden" id="way-id" value="{{ $user->id }}"/>
                        <td id="editable">{{ $user->name }}</td>
                        <td id="editable">{{ $user->email }}</td>
                        <td id="editable">
                            @foreach ($user->getRoleNames() as $roleNames)
                                {{ $roleNames }}
                            @endforeach
                        </td>
                        <td id="editable">
                            <label class="switch mb-3">
                                <input type="checkbox" id="active-user" />
                                <div class="slider"></div>
                            </label>
                        </td>
                        <td>
                            <button type="button" class="btn btn-default btn-edit js-edit" id="{{$user->id}}"><img
                                    class="mb-1 duration-300 ml-4 inset-0 h-6 w-6" src="/../../img/grey-edit.svg" alt="edit"
                                    onclick="(function(){var listInput = document.getElementById('way-id').value;
                                    document.getElementById('testInout').value = listInput;
                                    })();toggleModal('modal-edit-user'); "></button>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
        <div class="flex justify-between mt-4 mb-4">
            <button type="button"
                class="shadow float-left md:shadow-lg rounded-full font-bold px-10 bg-gray-500 text-white">
                <img class="inline-block mb-2 mt-2 w-4 h-4 mr-2" src="../../img/Icon-white-search.png" alt="search icon">
                <a class="no-underline inline-block text-white " onclick="toggleModal('modal-user-types')">User Types</a>
            </button>
            <button type="button"
                class="shadow float-right md:shadow-lg rounded-full font-bold px-10 grantors-btn text-white">
                <img class="inline-block mb-2 mt-2 w-4 h-4 mr-2" src="../../img/Icon-plus-white.png" alt="plus icon">
                <a class="no-underline inline-block text-white " onclick="toggleModal('modal-new-user')">New User</a>
            </button>
        </div>
    </div>

Edit User modal

<div class="hidden overflow-x-hidden overflow-y-auto fixed inset-0 z-50 outline-none focus:outline-none justify-center items-center"
        id="modal-edit-user">
            ... (content continues)
        </div>
        <!--footer-->
    </div>

The calling modal

   <script type="text/javascript">
        //
        function toggleModal(modalID) {
            document.getElementById(modalID).classList.toggle("hidden");
            document.getElementById(modalID + "-backdrop").classList.toggle("hidden");
            document.getElementById(modalID).classList.toggle("flex");
            document.getElementById(modalID + "-backdrop").classList.toggle("flex");

        }
    </script>

Initial attempts to pass the user ID to the modal form using inline JavaScript have proved challenging. The ID does not update with each button click, and transitioning back to Laravel variables and logic for displaying query data is problematic.

Answer №1

If you want to improve user experience, consider creating individual modals for each user. You can generate modals with unique IDs for all users and then trigger the specific modal when needed.

Here is an example of how you can create modals for each user:

@foreach($users as $user)
<div class="modal" tabindex="-1" role="dialog" id="modal-{{$user->id}}">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
@endforeach

Then, you can easily open the corresponding modal in the table:

<a onclick="$('#modal-{{$user->id}}').modal('show')">Edit User</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Opening multiple dialogs in Jquery Dialog box

I have several images displayed on a single page. When each image is clicked, I want a dialog box to open. I currently have 6 instances of this setup in my HTML. However, when I click on an image, all 6 dialogs pop up with the same information as the first ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

Node.js assert causes mocha to hang or timeout instead of throwing an error when using assert(false)

I am facing an issue with a mocha test that I have written: describe 'sabah', → beforeEach → @sabahStrategy = _.filter(@strats, { name: 'sabah2' })[0] .strat it 'article list should be populated&ap ...

"Troubleshooting the lack of functionality in nested ajax calls, click events, or event

Initially, a navigation click event was created: $('#inner-navigation li a') .on('click', function (e) { e.preventDefault(); AjaxNavUrl.checkURL(this.hash); }); This event triggers an ajax call and respo ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Permuting sentences to create intricate anagrams

I am faced with a task of creating the correct phrase for a sentence anagram using an array of nearly 2700 strings. The list consists of almost 100k words that could potentially fit. My goal is to combine these words in groups of 1, 2, and 3 words togethe ...

Using jQuery to verify the presence of an element, especially one that may have been dynamically inserted via AJAX

I have a good understanding of how to verify elements that are present when the document is loaded: jQuery.fn.exists = function () { return jQuery(this).length > 0; } However, this approach does not detect elements that are dynamically added via A ...

Guide to creating a production build for electron with react js and next framework

Currently, I am working with electron using react js and next. I am struggling to figure out how to create its production build. Can someone provide me with assistance along with a detailed step-by-step guide? app node_modules pages routes static packa ...

Alignment issue with procedural plane vertices in threeJS

In my project, I am utilizing threeJS along with a Simplex noise algorithm to create a tile system consisting of 50x50 planes. Currently, I am iterating through x+y and adding each plane. The Simplex noise algorithm is then used to calculate the z position ...

Guide on how to compare two arrays in JavaScript and identify mismatches by their respective indices

let x=["e","f","g","h"]; let y=["f","e","g","h"]; I want the following result: Inconsistent array from x Inconsistency array=["e", "f"]; ...

cheerio scraping results in an array that is devoid of any data

Struggling to extract data from a website with the URL https://buff.163.com/market/csgo#tab=buying&page_num=1 using request-promise and cheerio. Check out my code snippet below: const request = require('request-promise'); const cheerio = requ ...

Failure to retrieve data with ajax call in php script

I am a beginner in the world of JS and PHP. I am taking on the challenge of teaching myself. Following the guidance provided in this answer from Stack Overflow, I attempted to implement it in my project. Unfortunately, I am facing challenges and would gre ...

Passing an extra variable to the callback function in AJAX and saving the XMLHttpRequest.response as a variable

Attempting to read a local file on the server using the standard loadDoc(url, cfunc) function, my goal is to: 1) Search for a specific string in the file (getLine()); 2) If possible, save that line to a variable. For point 1, I provide a string to the c ...

Exploring intricate designs using HTML and Javascript

After extensive experience with both WPF and HTML5 JavaScript, one thing that stands out to me is the clear organization provided by XAML's defined panels. Grid, StackPanel, DockPanel, WrapPanel, and others offer a straightforward way to achieve consi ...

Vue JS Image Path

I have a Vue.js structure file that looks like this: --assets ----image ------my-image.png ------my-image2.png --components ----user ------userStart.vue To display the images using an array object, my code in userStart.vue is as follows: ...

Proper Syntax for Laravel Form Building

After spending some time on this and getting bored, I have a question for you! <select> @foreach($items as $item) <option value="{{$item->name}}">{{$item->name}}</option> @endforeach </select> I understa ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

Creating concise AngularJS Controllers for form functionality

While working on a web project with AngularJS, I've observed that most of my form controllers share similar structures. For instance, the only difference between my login controller (as shown below) and a reset password controller is that instead of $ ...

Using .on as a substitute for live will not yield the desired results

I've been aware for some time now that the .on method is meant to replace .live, but I just can't seem to get it working. I've attempted: $(this).on('click', function(){ // Do something... }) $(this).on({ click: function ...

Change the content inside a div depending on the value of a button

I am currently exploring how to change the content of a div based on button values, utilizing angular2+. Below is my implementation in HTML and js export class TestComponent implements OnInit { title:string = "provas"; constructor() { } popula ...