SweetAlert - viames/pair GitHub Wiki

Pair framework: SweetAlert

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').

Constructor

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.

Methods

  • confirm(string $text, ?string $callback = null, ?string $buttonColor = null): self
  • cancel(string $text, ?string $callback = null, ?string $buttonColor = null): self
  • deny(string $text, ?string $callback = null, ?string $buttonColor = null): self
  • input(string $type): self
  • outsideClick(bool $allowOutsideClick): self
  • loader(bool $showLoaderOnConfirm): self
  • preConfirm(string $callback): self
  • didRender(string $callback): self
  • getText(): string
  • render(): string

Callback behavior

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 call window["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.

Rendering behavior

  • render() returns JS code only, not a <script> tag.
  • If Swal is missing, generated code logs SweetAlert2 library not found..
  • If confirm() is not set, Pair explicitly sets showConfirmButton: false.
  • loader(true) is applied only when preConfirm(...) is set.

Examples

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")');

Notes

  • 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.

⚠️ **GitHub.com Fallback** ⚠️