John Davidson

api - Bootstrap Modal - updating modal id in a php for each loop

0 comments
Message:


I am using bootstrap and cards with pop out modals. I want to update my modal and populate them using my api in a foreach loop. The cards are updating perfectly the issue is the button id for the modal. I am trying to set a new id on each iteration of the loop so that the correct information is displayed within the modal. If I just manually name it the id stays the same on each loop and then the information from the first item in the assoc array is being displayed.




 <?php
foreach ($goals as $row) {



$title = $row['title'];
$description = $row['description'];
$url_cover = $row['url_cover'];
$url_info = $row['url_info'];
$id =$row['id'];
$num = 5;

echo "

<div class='card'>
<div
<div class='card bg-dark text-white'>
<img src= $url_cover class='card-img' alt=''...''>
<div class='card-img-overlay'>
<h5 class='card-title'>$title</h5>
<!-- Button trigger modal -->
<button type='button' class='btn btn-dark' data-toggle='modal' data-target='#approve{$num}'>
+
</button>
</div>
</div>

</div>


<div class='modal fade' id='approve{$num}' tabindex='-1' role='dialog' aria-labelledby='exampleModalLongTitle' aria-hidden='true'>
<div class='modal-dialog' role='document'>
<div class='modal-content'>
<div class='modal-header'>
<h5 class='modal-title' id='exampleModalLongTitle'>$description</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>
<a href=$url_info <img src=$url_info title='source: imgur.com'/></a>
</p>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button>

</div>
</div>
</div>
</div>

";

$num++;
}
?>


My Answer:
To update the modal id in a PHP foreach loop, you can dynamically generate unique ids for each modal by appending a unique identifier to the base id. Here's an example of how you can achieve this:

php
// Sample data from API
$apiData = [
['id' => 1, 'name' => 'Item 1', 'description' => 'Description 1'],
['id' => 2, 'name' => 'Item 2', 'description' => 'Description 2'],
['id' => 3, 'name' => 'Item 3', 'description' => 'Description 3'],
];

foreach ($apiData as $key => $item) {
$modalId = 'modal' . $item['id']; // Generate unique modal id

echo '
';
echo '
';
echo '
' . $item['name'] . '
';
echo '

' . $item['description'] . '

';
echo '';
echo '
';
echo '
';

// Modal markup
echo '';
}
?>


In this code snippet, we are generating a unique modal id for each item in the API data array and using that id to target the corresponding modal in the button's `data-target` attribute. This way, each button will open the correct modal with the respective item's information.

Rate this post

3 of 5 based on 8410 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us