Created
June 15, 2025 16:21
-
-
Save audinue/f8c1aa31e1c423690be614916b3f4af3 to your computer and use it in GitHub Desktop.
Cara handle state di stateless env buat nested sub modals.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// initial state | |
$state = (object) [ | |
'count' => 0, | |
'showModal' => false, | |
'showSubModal' => false, | |
...$_GET | |
]; | |
// generic utility function -- mestinya ditaruh di file lain | |
function render_state() { | |
global $state; | |
return '?' . http_build_query((array) $state); | |
} | |
// action | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
switch ($_POST['action']) { | |
case 'increment': | |
$state->count++; | |
break; | |
case 'decrement': | |
$state->count--; | |
break; | |
case 'openModal': | |
$state->showModal = true; | |
break; | |
case 'closeModal': | |
$state->showModal = false; | |
break; | |
case 'openSubModal': | |
$state->showSubModal = true; | |
break; | |
case 'closeSubModal': | |
$state->showSubModal = false; | |
break; | |
} | |
header('Location: ' . render_state()); | |
exit; | |
} | |
?> | |
<form action="<?= render_state() ?>" method="post"> | |
<p>Count: <?= $state->count ?></p> | |
<button name="action" value="increment">+</button> | |
<button name="action" value="decrement">-</button> | |
</form> | |
<form action="<?= render_state() ?>" method="post"> | |
<button name="action" value="openModal">Open Modal</button> | |
</form> | |
<?php if ($state->showModal): ?> | |
<div> | |
Modal content here. | |
<form action="<?= render_state() ?>" method="post"> | |
<button name="action" value="openSubModal">Open Sub Modal</button> | |
<button name="action" value="closeModal">Close Modal</button> | |
</form> | |
</div> | |
<?php endif ?> | |
<?php if ($state->showSubModal): ?> | |
<div> | |
Sub Modal content here. | |
<form action="<?= render_state() ?>" method="post"> | |
<button name="action" value="closeSubModal">Close Sub Modal</button> | |
</form> | |
</div> | |
<?php endif ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment