Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to display pop up modal after store data using alpine js

Method1

I can provide you with a full CRUD (Create, Read, Update, Delete) code example using Laravel Livewire for the backend and Alpine.js for showing the popup modal. Below is the complete code.

Firstly, let's create the Livewire component for the CRUD operations:

// app/Http/Livewire/ItemCrud.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Item;

class ItemCrud extends Component
{
    public $items;
    public $name;
    public $editId;

    protected $rules = [
        'name' => 'required',
    ];

    public function mount()
    {
        $this->items = Item::all();
    }

    public function saveItem()
    {
        $this->validate();

        if ($this->editId) {
            $item = Item::findOrFail($this->editId);
            $item->update(['name' => $this->name]);
        } else {
            Item::create(['name' => $this->name]);
        }

        $this->resetForm();
        $this->emit('itemCreated');
    }

    public function editItem($itemId)
    {
        $item = Item::findOrFail($itemId);
        $this->name = $item->name;
        $this->editId = $itemId;
    }

    public function deleteItem($itemId)
    {
        Item::findOrFail($itemId)->delete();
        $this->items = Item::all();
    }

    private function resetForm()
    {
        $this->name = '';
        $this->editId = null;
        $this->items = Item::all();
    }

    public function render()
    {
        return view('livewire.item-crud');
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, let's create the view file for the Livewire component:

<!-- resources/views/livewire/item-crud.blade.php -->

<div x-data="{ showModal: false }" x-init="
    Livewire.on('itemCreated', () => {
        console.log('data coming');
        showModal = true;
    })
">
    <!-- Button to trigger modal -->
    <button @click="showModal = true">Add Item</button>

    <!-- Modal -->
    <div class="modal" x-show="showModal" style="display: none;">
        <div class="modal-content">
            <span class="close" @click="showModal = false">&times;</span>
            <form wire:submit.prevent="saveItem">
                <input type="hidden" wire:model="editId">
                <label for="name">Name:</label>
                <input type="text" id="name" wire:model="name">
                <button type="submit">Save</button>
            </form>
        </div>
    </div>

    <!-- Items List -->
    <ul>
        @foreach($items as $item)
            <li>
                {{ $item->name }}
                <button @click="showModal = true; $wire.editItem({{ $item->id }})">Edit</button>
                <button wire:click="deleteItem({{ $item->id }})">Delete</button>
            </li>
        @endforeach
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Method 2

here's a simple example of how you can implement a CRUD (Create, Read, Update, Delete) functionality with Livewire and Alpine.js, including the use of a popup modal for editing items:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Livewire CRUD with Alpine.js Modal</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@2.8.2/dist/alpine.min.js" defer></script>
    @livewireStyles
</head>
<body>

<div x-data="{ showModal: false, editId: null }">
    <!-- Button to trigger modal -->
    <button @click="showModal = true">Add Item</button>

    <!-- Modal -->
    <div class="modal" x-show="showModal" style="display: none;">
        <div class="modal-content">
            <span class="close" @click="showModal = false">&times;</span>
            <form wire:submit.prevent="saveItem">
                <input type="hidden" wire:model="editId">
                <label for="name">Name:</label>
                <input type="text" id="name" wire:model="name">
                <button type="submit">Save</button>
            </form>
        </div>
    </div>

    <!-- Items List -->
    <ul>
        @foreach($items as $item)
            <li>
                {{ $item->name }}
                <button @click="showModal = true; editId = {{ $item->id }}">Edit</button>
                <button wire:click="deleteItem({{ $item->id }})">Delete</button>
            </li>
        @endforeach
    </ul>
</div>

@livewireScripts
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And here's the corresponding Livewire component

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Item;

class ItemCrud extends Component
{
    public $items;
    public $name;
    public $editId;

    protected $rules = [
        'name' => 'required',
    ];

    public function mount()
    {
        $this->items = Item::all();
    }

    public function saveItem()
    {
        $this->validate();

        if ($this->editId) {
            $item = Item::findOrFail($this->editId);
            $item->update(['name' => $this->name]);
        } else {
            Item::create(['name' => $this->name]);
        }

        $this->resetForm();
    }

    public function deleteItem($itemId)
    {
        Item::findOrFail($itemId)->delete();
        $this->items = Item::all();
    }

    private function resetForm()
    {
        $this->name = '';
        $this->editId = null;
        $this->items = Item::all();
        $this->showModal = false;
    }

    public function render()
    {
        return view('livewire.item-crud');
    }
}
Enter fullscreen mode Exit fullscreen mode

Make sure you have a Item model set up in your Laravel application for this example to work correctly.

This code provides a basic CRUD functionality with Livewire. When you click on the "Add Item" button, it will open a modal where you can add or edit an item. Items are displayed in a list, and you can delete items from the list. The modal is managed by Alpine.js to show/hide based on the showModal data property.
Method3

Now, let's edit the ModalFormComponent component:

// app/Http/Livewire/ModalFormComponent.php

namespace App\Http\Livewire;

use Livewire\Component;

class ModalFormComponent extends Component
{
    public $showModal = false;
    public $formData = [];

    public function openModal($modalId)
    {
        // Reset form data
        $this->formData = [];
        // Show modal by setting showModal to true
        $this->showModal = true;
        // Dispatch an event to open the specific modal
        $this->dispatchBrowserEvent('openModal', ['modalId' => $modalId]);
    }

    public function closeModal()
    {
        // Hide modal by setting showModal to false
        $this->showModal = false;
        // Reset form data
        $this->formData = [];
    }

    public function submitForm()
    {
        // Handle form submission logic here
        // Example: Save form data to database
        $this->closeModal();
        // Optionally, emit an event or redirect to another page
    }

    public function render()
    {
        return view('livewire.modal-form-component');
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, let's create the corresponding view for the component:

<!-- resources/views/livewire/modal-form-component.blade.php -->

<div>
    <!-- Button 1 -->
    <button wire:click="openModal('modal1')">Open Modal 1</button>
    <!-- Button 2 -->
    <button wire:click="openModal('modal2')">Open Modal 2</button>
    <!-- Button 3 -->
    <button wire:click="openModal('modal3')">Open Modal 3</button>
    <!-- Button 4 -->
    <button wire:click="openModal('modal4')">Open Modal 4</button>

    <!-- Modal 1 -->
    <div wire:ignore.self id="modal1" class="modal">
        <!-- Modal Content 1 -->
        <div class="modal-content">
            <!-- Close Button -->
            <span wire:click="closeModal" class="close">&times;</span>
            <!-- Form 1 -->
            <form wire:submit.prevent="submitForm">
                <!-- Form Fields for Modal 1 -->
                <!-- Example: Input Fields, Textareas, etc. -->
                <button type="submit">Submit Form 1</button>
            </form>
        </div>
    </div>

    <!-- Modal 2 -->
    <div wire:ignore.self id="modal2" class="modal">
        <!-- Modal Content 2 -->
        <div class="modal-content">
            <!-- Close Button -->
            <span wire:click="closeModal" class="close">&times;</span>
            <!-- Form 2 -->
            <form wire:submit.prevent="submitForm">
                <!-- Form Fields for Modal 2 -->
                <!-- Example: Input Fields, Textareas, etc. -->
                <button type="submit">Submit Form 2</button>
            </form>
        </div>
    </div>

    <!-- Modal 3 -->
    <div wire:ignore.self id="modal3" class="modal">
        <!-- Modal Content 3 -->
        <div class="modal-content">
            <!-- Close Button -->
            <span wire:click="closeModal" class="close">&times;</span>
            <!-- Form 3 -->
            <form wire:submit.prevent="submitForm">
                <!-- Form Fields for Modal 3 -->
                <!-- Example: Input Fields, Textareas, etc. -->
                <button type="submit">Submit Form 3</button>
            </form>
        </div>
    </div>

    <!-- Modal 4 -->
    <div wire:ignore.self id="modal4" class="modal">
        <!-- Modal Content 4 -->
        <div class="modal-content">
            <!-- Close Button -->
            <span wire:click="closeModal" class="close">&times;</span>
            <!-- Form 4 -->
            <form wire:submit.prevent="submitForm">
                <!-- Form Fields for Modal 4 -->
                <!-- Example: Input Fields, Textareas, etc. -->
                <button type="submit">Submit Form 4</button>
            </form>
        </div>
    </div>

    <!-- JavaScript to Handle Modal Display -->
    <script>
        // Open modal based on modalId
        window.addEventListener('openModal', event => {
            var modalId = event.detail.modalId;
            var modal = document.getElementById(modalId);
            modal.style.display = "block";
        });

        // Close modal when clicking on close button or outside the modal
        window.onclick = function(event) {
            if (event.target.className == "modal") {
                event.target.style.display = "none";
            }
        }
    </script>
</div>
Enter fullscreen mode Exit fullscreen mode
<style>
    /* CSS for Modal Styling */
    .modal {
        display: none;
        position: fixed;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.4);
    }

    .modal-content {
        background-color: #fefefe;
        margin: 10% auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
    }

    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

Finally, don't forget to include the Livewire assets in your layout file:

<!DOCTYPE html>
<html>
<head>
    <!-- Livewire Styles -->
    @livewireStyles
</head>
<body>

<!-- Livewire Component -->
@livewire('modal-form-component')

<!-- Livewire Scripts -->
@livewireScripts

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This Livewire component will display four buttons, and clicking on each button will open a popup modal containing a form. Each form can have its own unique fields and submit button.

Top comments (0)