SweetAlert - viames/pair GitHub Wiki
Pair\Html\SweetAlert generates JavaScript code for SweetAlert2 modals (Swal.fire(...)) from PHP.
If you need SweetAlert2 toast notifications instead of modal dialogs, use
Pair\Html\SweetToast and/or configure the application driver with
$app->setToastDriver('sweetalert').
new SweetAlert(string $title, string $text, ?string $icon = null)Valid icons are info, success, error, warning, question.
If the icon is not valid, it is ignored.
confirm(string $text, ?string $callback = null, ?string $buttonColor = null): selfcancel(string $text, ?string $callback = null, ?string $buttonColor = null): selfdeny(string $text, ?string $callback = null, ?string $buttonColor = null): selfinput(string $type): selfoutsideClick(bool $allowOutsideClick): selfloader(bool $showLoaderOnConfirm): selfpreConfirm(string $callback): selfdidRender(string $callback): selfgetText(): stringrender(): string
When you pass a callback string (for buttons, preConfirm, didRender):
- If the string is a plain function name (
[a-zA-Z0-9_]+), Pair tries to callwindow["name"](). - If the function does not exist, it logs a console message.
- If the string contains other characters (for example
myFn(42)or inline JS), it is emitted as raw JS.
-
render()returns JS code only, not a<script>tag. - If
Swalis missing, generated code logsSweetAlert2 library not found.. - If
confirm()is not set, Pair explicitly setsshowConfirmButton: false. -
loader(true)is applied only whenpreConfirm(...)is set.
Confirm + cancel with callbacks:
$alert = (new \Pair\Html\SweetAlert('Delete user', 'This action cannot be undone', 'warning'))
->confirm('Delete', 'deleteUser', '#d33')
->cancel('Cancel', 'undoDelete', '#6c757d');
echo '<script>' . $alert->render() . '</script>';Input modal with async preConfirm flow:
$alert = (new \Pair\Html\SweetAlert('Reset password', 'Insert email', 'question'))
->input('email')
->outsideClick(false)
->preConfirm('requestPasswordReset')
->loader(true)
->confirm('Send');Using raw JS callback:
$alert = (new \Pair\Html\SweetAlert('Saved', 'Record updated', 'success'))
->confirm('OK', 'console.log("confirmed")')
->didRender('console.log("modal rendered")');- Include SweetAlert2 in the page before running the generated script.
-
getText()is useful for logging/auditing the modal message server-side.
See also: Application, IziToast, SweetToast, AppTrait.