Bootstrap CRUD

Bootstrap CRUD

Bootstrap is a popular front-end framework used to create responsive, mobile-first web pages. While Bootstrap is primarily used for UI design, it can be effectively combined with backend services (like REST APIs) to perform Create, Read, Update, and Delete (CRUD) operations. This guide demonstrates how to implement CRUD functionality using Bootstrap for the frontend and a REST API to interact with the backend.

1. Setting up the frontend with bootstrap

Install Bootstrap

You can include Bootstrap in your project using a CDN in your HTML file:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

Alternatively, you can install Bootstrap via npm if using a build tool like Webpack or if you're working with a front-end framework (React, Angular, etc.):

bash

npm install bootstrap


For this guide, we’ll focus on creating the user interface and integrating it with a backend API to perform CRUD software operations.

2. Implementing CRUD with Bootstrap UI

Create (POST)

In the Create operation, users will input data into a form that is submitted to a backend API via a POST request. The form UI is styled using Bootstrap components.

Example: HTML Form

<div class="container">
  <h2>Create User</h2>
  <form id="createUserForm">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter name" required>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" required>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>

<script>
  document.getElementById("createUserForm").addEventListener("submit", function(event) {
    event.preventDefault();
    const name = document.getElementById("name").value;
    const email = document.getElementById("email").value;

    fetch("https://example.com/api/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, email }),
    })
      .then(response => response.json())
      .then(data => alert("User created: " + data.name))
      .catch(error => console.error("Error:", error));
  });
</script>

Explanation:

  • The form uses Bootstrap for styling and input fields.
  • The JavaScript code handles the form submission and sends the data to the backend API using the fetch()method.

Read (GET)

The Read operation involves fetching data from the API and displaying it in a Bootstrap-styled table.

Example: Display Data in a Table

<div class="container">
  <h2>User List</h2>
  <table class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="userTableBody">
      <!-- Data will be inserted here -->
    </tbody>
  </table>
</div>

<script>
  window.onload = function() {
    fetch("https://example.com/api/users")
      .then(response => response.json())
      .then(data => {
        const tableBody = document.getElementById("userTableBody");
        data.forEach(user => {
          const row = document.createElement("tr");
          row.innerHTML = `
            <td>${user.name}</td>
            <td>${user.email}</td>
            <td><button class="btn btn-warning" onclick="editUser(${user.id})">Edit</button> 
            <button class="btn btn-danger" onclick="deleteUser(${user.id})">Delete</button></td>
          `;
          tableBody.appendChild(row);
        });
      })
      .catch(error => console.error("Error fetching users:", error));
  };

  function editUser(id) {
    alert(`Editing user with ID: ${id}`);
  }

  function deleteUser(id) {
    fetch(`https://example.com/api/users/${id}`, {
      method: "DELETE",
    })
      .then(response => response.json())
      .then(() => alert(`User with ID ${id} deleted.`))
      .catch(error => console.error("Error deleting user:", error));
  }
</script>

Explanation:

  • The table displays users fetched from the backend.
  • Each row has Edit and Delete buttons to trigger updates or deletion of the respective user.

Update (PUT)

In the Update operation, users can edit existing data, which is sent to the backend via a PUT request.

Example: Edit User Form

<div class="container">
  <h2>Edit User</h2>
  <form id="editUserForm">
    <div class="form-group">
      <label for="editName">Name:</label>
      <input type="text" class="form-control" id="editName" required>
    </div>
    <div class="form-group">
      <label for="editEmail">Email:</label>
      <input type="email" class="form-control" id="editEmail" required>
    </div>
    <button type="submit" class="btn btn-primary">Update</button>
  </form>
</div>

<script>
  function editUser(id) {
    fetch(`https://example.com/api/users/${id}`)
      .then(response => response.json())
      .then(user => {
        document.getElementById("editName").value = user.name;
        document.getElementById("editEmail").value = user.email;
        document.getElementById("editUserForm").onsubmit = function(event) {
          event.preventDefault();
          const updatedUser = {
            name: document.getElementById("editName").value,
            email: document.getElementById("editEmail").value,
          };

          fetch(`https://example.com/api/users/${id}`, {
            method: "PUT",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(updatedUser),
          })
            .then(response => response.json())
            .then(data => alert("User updated"))
            .catch(error => console.error("Error:", error));
        };
      })
      .catch(error => console.error("Error fetching user:", error));
  }
</script>

Explanation:

  • The Edit form is pre-filled with the current user data.
  • When the form is submitted, the updated user data is sent to the backend using a PUT request.

Delete (DELETE)

The Delete operation removes data from the backend, typically triggered by a delete button next to each record.

Example: Delete Button in Table

<button class="btn btn-danger" onclick="deleteUser(1)">Delete</button>

<script>
  function deleteUser(id) {
    fetch(`https://example.com/api/users/${id}`, {
      method: "DELETE",
    })
      .then(response => response.json())
      .then(() => alert(`User with ID ${id} deleted.`))
      .catch(error => console.error("Error deleting user:", error));
  }
</script>

Explanation:

  • The Delete button triggers the deleteUser function, which sends a DELETE request to the backend to remove the user.

Notable libraries and example projects

  1. REST Admin - Admin panel framework for building CRUD apps with Vue.js and Element UI
  2. Laravel Vue Boilerplate - Boilerplate for building CRUD apps using Laravel and Vue.js
  3. CrudDIY - Low-code framework for creating CRUD apps without coding expertise