Расширяет MoonShineComponent
Когда вам нужно добавить кнопку с определенным действием, на помощь приходят ActionButtons.
В MoonShine они уже используются - в формах, таблицах, на страницах.
ActionButton::make(
Closure|string $label,
Closure|string|null $url = null,
mixed $item = null
)
ActionButton::make(
Closure|string $label,
Closure|string|null $url = null,
mixed $item = null
)
ActionButton::make(
Closure|string $label,
Closure|string|null $url = null,
mixed $item = null
)
ActionButton::make(
Closure|string $label,
Closure|string|null $url = null,
mixed $item = null
)
ActionButton::make(
Closure|string $label,
Closure|string|null $url = null,
mixed $item = null
)
label
- текст кнопки,
url
- URL ссылки кнопки,
item
- опциональные данные кнопки, доступные в замыканиях.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Заголовок кнопки',
url: 'https://moonshine-laravel.com',
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Заголовок кнопки',
url: 'https://moonshine-laravel.com',
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Заголовок кнопки',
url: 'https://moonshine-laravel.com',
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Заголовок кнопки',
url: 'https://moonshine-laravel.com',
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Заголовок кнопки',
url: 'https://moonshine-laravel.com',
)
];
}
Также доступен хелпер, который можно использовать в Blade:
<div>
{!! actionBtn('Нажми меня', 'https://moonshine-laravel.com') !!}
</div>
<div>
{!! actionBtn('Нажми меня', 'https://moonshine-laravel.com') !!}
</div>
<div>
{!! actionBtn('Нажми меня', 'https://moonshine-laravel.com') !!}
</div>
<div>
{!! actionBtn('Нажми меня', 'https://moonshine-laravel.com') !!}
</div>
<div>
{!! actionBtn('Нажми меня', 'https://moonshine-laravel.com') !!}
</div>
Метод blank()
позволяет открыть URL в новом окне.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: '/',
)
->blank()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: '/',
)
->blank()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: '/',
)
->blank()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: '/',
)
->blank()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: '/',
)
->blank()
];
}
Метод icon()
позволяет указать иконку для кнопки.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: fn() => 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->icon('heroicons.outline.pencil')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: fn() => 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->icon('heroicons.outline.pencil')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: fn() => 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->icon('heroicons.outline.pencil')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: fn() => 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->icon('heroicons.outline.pencil')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: fn() => 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->icon('heroicons.outline.pencil')
];
}
Для получения более подробной информации обратитесь к разделу Иконки.
Для ActionButton
есть набор методов, которые позволяют установить цвет кнопки:
primary()
, secondary()
, warning()
, success()
и error()
.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: fn() => 'https://moonshine-laravel.com',
)
->primary()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: fn() => 'https://moonshine-laravel.com',
)
->primary()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: fn() => 'https://moonshine-laravel.com',
)
->primary()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: fn() => 'https://moonshine-laravel.com',
)
->primary()
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: fn() => 'https://moonshine-laravel.com',
)
->primary()
];
}
Метод badge()
позволяет добавить бейдж к кнопке.
badge(Closure|string|int|float|null $value)
badge(Closure|string|int|float|null $value)
badge(Closure|string|int|float|null $value)
badge(Closure|string|int|float|null $value)
badge(Closure|string|int|float|null $value)
use MoonShine\ActionButtons\ActionButton;
ActionButton::make('Кнопка')
->badge(fn() => Comment::count())
use MoonShine\ActionButtons\ActionButton;
//...
ActionButton::make('Кнопка')
->badge(fn() => Comment::count())
//...
use MoonShine\ActionButtons\ActionButton;
//...
ActionButton::make('Кнопка')
->badge(fn() => Comment::count())
//...
use MoonShine\ActionButtons\ActionButton;
//...
ActionButton::make('Кнопка')
->badge(fn() => Comment::count())
//...
use MoonShine\ActionButtons\ActionButton;
//...
ActionButton::make('Кнопка')
->badge(fn() => Comment::count())
//...
Метод onClick
позволяет выполнить js-код при клике:
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->onClick(fn() => "alert('Пример')", 'prevent')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->onClick(fn() => "alert('Пример')", 'prevent')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->onClick(fn() => "alert('Пример')", 'prevent')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->onClick(fn() => "alert('Пример')", 'prevent')
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->onClick(fn() => "alert('Пример')", 'prevent')
];
}
Основы
Для вызова модального окна при нажатии на кнопку используйте метод inModal()
.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
title
- заголовок модального окна,
content
- содержимое модального окна,
buttons
- кнопки модального окна,
async
- асинхронный режим,
wide
- максимальная ширина модального окна,
auto
- ширина модального окна по содержимому,
closeOutside
- закрытие модального окна при клике вне области окна,
attributes
- дополнительные атрибуты,
autoClose
- автоматическое закрытие модального окна после успешного запроса.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inModal(
title: fn() => 'Заголовок модального окна',
content: fn() => 'Содержимое модального окна',
buttons: [
ActionButton::make('Нажми меня в модальном окне', 'https://moonshine-laravel.com')
],
async: false
)
];
}
Вы также можете открыть модальное окно с помощью метода toggleModal
, а если ActionButton находится внутри модального окна, то просто openModal
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\Modal;
public function components(): array
{
return [
MoonShine\Components\Modal::make(
'Заголовок',
fn() => 'Содержимое',
)->name('my-modal')
ActionButton::make(
label: 'Открыть модальное окно',
url: '#',
)->toggleModal('my-modal')
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\Modal;
public function components(): array
{
return [
MoonShine\Components\Modal::make(
'Заголовок',
fn() => 'Содержимое',
)->name('my-modal')
ActionButton::make(
label: 'Открыть модальное окно',
url: '#',
)->toggleModal('my-modal')
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\Modal;
public function components(): array
{
return [
MoonShine\Components\Modal::make(
'Заголовок',
fn() => 'Содержимое',
)->name('my-modal')
ActionButton::make(
label: 'Открыть модальное окно',
url: '#',
)->toggleModal('my-modal')
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\Modal;
public function components(): array
{
return [
MoonShine\Components\Modal::make(
'Заголовок',
fn() => 'Содержимое',
)->name('my-modal')
ActionButton::make(
label: 'Открыть модальное окно',
url: '#',
)->toggleModal('my-modal')
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\Modal;
public function components(): array
{
return [
MoonShine\Components\Modal::make(
'Заголовок',
fn() => 'Содержимое',
)->name('my-modal')
ActionButton::make(
label: 'Открыть модальное окно',
url: '#',
)->toggleModal('my-modal')
];
}
Асинхронный режим
Если вам нужно загрузить содержимое в модальное окно асинхронно, то переключите параметр async на true
.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: to_page('action_button', fragment: 'doc-content'),
)
->inModal(
title: fn() => 'Заголовок модального окна',
async: true
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: to_page('action_button', fragment: 'doc-content'),
)
->inModal(
title: fn() => 'Заголовок модального окна',
async: true
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: to_page('action_button', fragment: 'doc-content'),
)
->inModal(
title: fn() => 'Заголовок модального окна',
async: true
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: to_page('action_button', fragment: 'doc-content'),
)
->inModal(
title: fn() => 'Заголовок модального окна',
async: true
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: to_page('action_button', fragment: 'doc-content'),
)
->inModal(
title: fn() => 'Заголовок модального окна',
async: true
)
];
}
О Fragment можно узнать в разделе "Компоненты"
Метод withConfirm()
позволяет создать кнопку с подтверждением действия.
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->withConfirm(
'Заголовок модального окна подтверждения',
'Содержимое модального окна подтверждения',
'Кнопка модального окна подтверждения',
)
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->withConfirm(
'Заголовок модального окна подтверждения',
'Содержимое модального окна подтверждения',
'Кнопка модального окна подтверждения',
)
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->withConfirm(
'Заголовок модального окна подтверждения',
'Содержимое модального окна подтверждения',
'Кнопка модального окна подтверждения',
)
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->withConfirm(
'Заголовок модального окна подтверждения',
'Содержимое модального окна подтверждения',
'Кнопка модального окна подтверждения',
)
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->withConfirm(
'Заголовок модального окна подтверждения',
'Содержимое модального окна подтверждения',
'Кнопка модального окна подтверждения',
)
withConfirm
не работает с async
режимами. Для асинхронного режима нужно сделать свою реализацию через Modal или inModal().
Для того чтобы при нажатии на кнопку вызывалась боковая панель, используйте метод inOffCanvas()
.
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inOffCanvas(
fn() => 'Заголовок боковой панели',
fn() => form()->fields([Text::make('Текст')]),
isLeft: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inOffCanvas(
fn() => 'Заголовок боковой панели',
fn() => form()->fields([Text::make('Текст')]),
isLeft: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inOffCanvas(
fn() => 'Заголовок боковой панели',
fn() => form()->fields([Text::make('Текст')]),
isLeft: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inOffCanvas(
fn() => 'Заголовок боковой панели',
fn() => form()->fields([Text::make('Текст')]),
isLeft: false
)
];
}
use MoonShine\ActionButtons\ActionButton;
public function components(): array
{
return [
ActionButton::make(
label: 'Нажми меня',
url: 'https://moonshine-laravel.com',
)
->inOffCanvas(
fn() => 'Заголовок боковой панели',
fn() => form()->fields([Text::make('Текст')]),
isLeft: false
)
];
}
Если вам нужно выстроить логику с несколькими ActionButton
, однако некоторые должны быть скрыты или отображены в выпадающем меню, в этом случае используйте компонент ActionGroup
.
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->canSee(fn() => false),
ActionButton::make('Кнопка 2', '/', $model)->canSee(fn($model) => $model->active)
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->canSee(fn() => false),
ActionButton::make('Кнопка 2', '/', $model)->canSee(fn($model) => $model->active)
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->canSee(fn() => false),
ActionButton::make('Кнопка 2', '/', $model)->canSee(fn($model) => $model->active)
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->canSee(fn() => false),
ActionButton::make('Кнопка 2', '/', $model)->canSee(fn($model) => $model->active)
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->canSee(fn() => false),
ActionButton::make('Кнопка 2', '/', $model)->canSee(fn($model) => $model->active)
])
];
}
Отображение
Благодаря ActionGroup вы также можете изменить отображение кнопок, отображать их в линию или в выпадающем меню для экономии места.
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->showInLine(),
ActionButton::make('Кнопка 2', '/')->showInDropdown()
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->showInLine(),
ActionButton::make('Кнопка 2', '/')->showInDropdown()
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->showInLine(),
ActionButton::make('Кнопка 2', '/')->showInDropdown()
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->showInLine(),
ActionButton::make('Кнопка 2', '/')->showInDropdown()
])
];
}
use MoonShine\ActionButtons\ActionButton;
use MoonShine\Components\ActionGroup;
public function components(): array
{
return [
ActionGroup::make([
ActionButton::make('Кнопка 1', '/')->showInLine(),
ActionButton::make('Кнопка 2', '/')->showInDropdown()
])
];
}
Метод bulk()
позволяет создать кнопку массового действия для ModelResource.
public function indexButtons(): array
{
return [
ActionButton::make('Ссылка', '/endpoint')->bulk(),
];
}
public function indexButtons(): array
{
return [
ActionButton::make('Ссылка', '/endpoint')->bulk(),
];
}
public function indexButtons(): array
{
return [
ActionButton::make('Ссылка', '/endpoint')->bulk(),
];
}
public function indexButtons(): array
{
return [
ActionButton::make('Ссылка', '/endpoint')->bulk(),
];
}
public function indexButtons(): array
{
return [
ActionButton::make('Ссылка', '/endpoint')->bulk(),
];
}
Метод bulk()
, используется только внутри ModelResource.
Метод async()
позволяет реализовать асинхронную работу для ActionButton
.
async(
string $method = 'GET',
?string $selector = null,
array $events = []
?string $callback = null
)
async(
string $method = 'GET',
?string $selector = null,
array $events = []
?string $callback = null
)
async(
string $method = 'GET',
?string $selector = null,
array $events = []
?string $callback = null
)
async(
string $method = 'GET',
?string $selector = null,
array $events = []
?string $callback = null
)
async(
string $method = 'GET',
?string $selector = null,
array $events = []
?string $callback = null
)
$method
- метод асинхронного запроса,
$selector
- селектор элемента, содержимое которого изменится,
$events
- события, поднимаемые после успешного запроса,
$callback
- js функция обратного вызова после получения ответа.
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async()
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async()
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async()
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async()
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async()
];
}
Уведомления
Если вам нужно отобразить уведомление или сделать редирект после клика, то достаточно реализовать json ответ согласно структуре:
{message: 'Toast', messageType: 'success', redirect: '/url'}
{message: 'Toast', messageType: 'success', redirect: '/url'}
{message: 'Toast', messageType: 'success', redirect: '/url'}
{message: 'Toast', messageType: 'success', redirect: '/url'}
{message: 'Toast', messageType: 'success', redirect: '/url'}
Параметр redirect
является необязательным.
HTML содержимое
Если вам нужно заменить область html по клику, то можно вернуть HTML содержимое или json с ключом html в ответе:
{"html": "Html content"}
{"html": "Html content"}
{"html": "Html content"}
{"html": "Html content"}
{"html": "Html content"}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(selector: '#my-selector')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(selector: '#my-selector')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(selector: '#my-selector')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(selector: '#my-selector')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(selector: '#my-selector')
];
}
События
После успешного запроса вы можете поднять события:
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(events: ['table-updated-index-table'])
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(events: ['table-updated-index-table'])
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(events: ['table-updated-index-table'])
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(events: ['table-updated-index-table'])
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(events: ['table-updated-index-table'])
];
}
Обратный вызов
Если вам нужно обработать ответ иным способом, необходимо реализовать функцию-обработчик и указать ее в методе async()
.
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(callback: 'myFunction')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(callback: 'myFunction')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(callback: 'myFunction')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(callback: 'myFunction')
];
}
public function components(): array
{
return [
ActionButton::make(
'Нажми меня',
'/endpoint'
)
->async(callback: 'myFunction')
];
}
document.addEventListener("moonshine:init", () => {
MoonShine.onCallback('myFunction', function(response, element, events, component) {
if(response.confirmed === true) {
component.$dispatch('toast', {type: 'success', text: 'Успех'})
} else {
component.$dispatch('toast', {type: 'error', text: 'Ошибка'})
}
})
})
document.addEventListener("moonshine:init", () => {
MoonShine.onCallback('myFunction', function(response, element, events, component) {
if(response.confirmed === true) {
component.$dispatch('toast', {type: 'success', text: 'Успех'})
} else {
component.$dispatch('toast', {type: 'error', text: 'Ошибка'})
}
})
})
document.addEventListener("moonshine:init", () => {
MoonShine.onCallback('myFunction', function(response, element, events, component) {
if(response.confirmed === true) {
component.$dispatch('toast', {type: 'success', text: 'Успех'})
} else {
component.$dispatch('toast', {type: 'error', text: 'Ошибка'})
}
})
})
document.addEventListener("moonshine:init", () => {
MoonShine.onCallback('myFunction', function(response, element, events, component) {
if(response.confirmed === true) {
component.$dispatch('toast', {type: 'success', text: 'Успех'})
} else {
component.$dispatch('toast', {type: 'error', text: 'Ошибка'})
}
})
})
document.addEventListener("moonshine:init", () => {
MoonShine.onCallback('myFunction', function(response, element, events, component) {
if(response.confirmed === true) {
component.$dispatch('toast', {type: 'success', text: 'Успех'})
} else {
component.$dispatch('toast', {type: 'error', text: 'Ошибка'})
}
})
})
method()
позволяет указать имя метода в ресурсе и вызвать его асинхронно при нажатии на ActionButton
без необходимости создания дополнительных контроллеров.
method(
string $method,
array|Closure $params = [],
?string $message = null,
?string $selector = null,
array $events = [],
string|AsyncCallback|null $callback = null,
?Page $page = null,
?ResourceContract $resource = null
)
method(
string $method,
array|Closure $params = [],
?string $message = null,
?string $selector = null,
array $events = [],
string|AsyncCallback|null $callback = null,
?Page $page = null,
?ResourceContract $resource = null
)
method(
string $method,
array|Closure $params = [],
?string $message = null,
?string $selector = null,
array $events = [],
string|AsyncCallback|null $callback = null,
?Page $page = null,
?ResourceContract $resource = null
)
method(
string $method,
array|Closure $params = [],
?string $message = null,
?string $selector = null,
array $events = [],
string|AsyncCallback|null $callback = null,
?Page $page = null,
?ResourceContract $resource = null
)
method(
string $method,
array|Closure $params = [],
?string $message = null,
?string $selector = null,
array $events = [],
string|AsyncCallback|null $callback = null,
?Page $page = null,
?ResourceContract $resource = null
)
$method
- имя метода,
$params
- параметры для запроса,
$message
- сообщения,
$selector
- селектор элемента, содержимое которого изменится,
$events
- события, которые будут вызваны после успешного запроса,
$callback
- js функция обратного вызова после получения ответа,
$page
- страница, содержащая метод,
$resource
- ресурс, содержащий метод.
public function components(): array
{
return [
ActionButton::make('Нажми меня')
->method('updateSomething'),
];
}
public function components(): array
{
return [
ActionButton::make('Нажми меня')
->method('updateSomething'),
];
}
public function components(): array
{
return [
ActionButton::make('Нажми меня')
->method('updateSomething'),
];
}
public function components(): array
{
return [
ActionButton::make('Нажми меня')
->method('updateSomething'),
];
}
public function components(): array
{
return [
ActionButton::make('Нажми меня')
->method('updateSomething'),
];
}
public function updateSomething(MoonShineRequest $request)
{
MoonShineUI::toast('МоеСообщение', 'success');
return back();
}
public function updateSomething(MoonShineRequest $request)
{
throw new \Exception('Мое сообщение');
}
public function updateSomething(MoonShineRequest $request)
{
return MoonShineJsonResponse::make()->toast('МоеСообщение', ToastType::SUCCESS);
}
// С уведомлением
public function updateSomething(MoonShineRequest $request)
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
MoonShineUI::toast('МоеСообщение', 'success');
return back();
}
// Исключение
public function updateSomething(MoonShineRequest $request)
{
throw new \Exception('Мое сообщение');
}
// Пользовательский JSON-ответ
public function updateSomething(MoonShineRequest $request)
{
return MoonShineJsonResponse::make()->toast('МоеСообщение', ToastType::SUCCESS);
}
// С уведомлением
public function updateSomething(MoonShineRequest $request)
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
MoonShineUI::toast('МоеСообщение', 'success');
return back();
}
// Исключение
public function updateSomething(MoonShineRequest $request)
{
throw new \Exception('Мое сообщение');
}
// Пользовательский JSON-ответ
public function updateSomething(MoonShineRequest $request)
{
return MoonShineJsonResponse::make()->toast('МоеСообщение', ToastType::SUCCESS);
}
// С уведомлением
public function updateSomething(MoonShineRequest $request)
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
MoonShineUI::toast('МоеСообщение', 'success');
return back();
}
// Исключение
public function updateSomething(MoonShineRequest $request)
{
throw new \Exception('Мое сообщение');
}
// Пользовательский JSON-ответ
public function updateSomething(MoonShineRequest $request)
{
return MoonShineJsonResponse::make()->toast('МоеСообщение', ToastType::SUCCESS);
}
// С уведомлением
public function updateSomething(MoonShineRequest $request)
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
MoonShineUI::toast('МоеСообщение', 'success');
return back();
}
// Исключение
public function updateSomething(MoonShineRequest $request)
{
throw new \Exception('Мое сообщение');
}
// Пользовательский JSON-ответ
public function updateSomething(MoonShineRequest $request)
{
return MoonShineJsonResponse::make()->toast('МоеСообщение', ToastType::SUCCESS);
}
Методы, вызываемые через ActionButton
в ресурсе, должны быть публичными!
Для доступа к данным из запроса вы должны передать их в параметрах.
Передача текущего элемента
Если в запросе присутствует resourceItem, вы можете получить доступ к текущему элементу в ресурсе через метод getItem()
.
- Когда в данных есть модель, и кнопка создается в методе
buttons()
TableBuilder, CardsBuilder или FormBuilder, она автоматически заполняется данными, и параметры будут содержать resourceItem
.
- Когда кнопка находится на странице формы ModelResource, вы можете передать id текущего элемента.
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: ['resourceItem' => $this->getResource()->getItemID()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: ['resourceItem' => $this->getResource()->getItemID()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: ['resourceItem' => $this->getResource()->getItemID()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: ['resourceItem' => $this->getResource()->getItemID()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: ['resourceItem' => $this->getResource()->getItemID()]
)
- Когда кнопка находится в индексной таблице ModelResource, нужно использовать замыкание
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: fn($item) => ['resourceItem' => $item->getKey()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: fn($item) => ['resourceItem' => $item->getKey()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: fn($item) => ['resourceItem' => $item->getKey()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: fn($item) => ['resourceItem' => $item->getKey()]
)
ActionButton::make('Нажми меня')
->method(
'updateSomething',
params: fn($item) => ['resourceItem' => $item->getKey()]
)
Значения полей
Метод withParams()
позволяет передавать значения полей с запросом, используя селекторы элементов.
ActionButton::make('Асинхронный метод')
->method('updateSomething')
->withParams([
'alias' => '[data-column="title"]',
'slug' => '#slug'
]),
ActionButton::make('Асинхронный метод')
->method('updateSomething')
->withParams([
'alias' => '[data-column="title"]',
'slug' => '#slug'
]),
ActionButton::make('Асинхронный метод')
->method('updateSomething')
->withParams([
'alias' => '[data-column="title"]',
'slug' => '#slug'
]),
ActionButton::make('Асинхронный метод')
->method('updateSomething')
->withParams([
'alias' => '[data-column="title"]',
'slug' => '#slug'
]),
ActionButton::make('Асинхронный метод')
->method('updateSomething')
->withParams([
'alias' => '[data-column="title"]',
'slug' => '#slug'
]),
use MoonShine\Http\Responses\MoonShineJsonResponse;
use MoonShine\MoonShineRequest;
public function updateSomething(MoonShineRequest $request): MoonShineJsonResponse
{
return MoonShineJsonResponse::make()
->toast($request->get('slug', 'Ошибка'));
}
use MoonShine\Http\Responses\MoonShineJsonResponse;
use MoonShine\MoonShineRequest;
public function updateSomething(MoonShineRequest $request): MoonShineJsonResponse
{
return MoonShineJsonResponse::make()
->toast($request->get('slug', 'Ошибка'));
}
use MoonShine\Http\Responses\MoonShineJsonResponse;
use MoonShine\MoonShineRequest;
public function updateSomething(MoonShineRequest $request): MoonShineJsonResponse
{
return MoonShineJsonResponse::make()
->toast($request->get('slug', 'Ошибка'));
}
use MoonShine\Http\Responses\MoonShineJsonResponse;
use MoonShine\MoonShineRequest;
public function updateSomething(MoonShineRequest $request): MoonShineJsonResponse
{
return MoonShineJsonResponse::make()
->toast($request->get('slug', 'Ошибка'));
}
use MoonShine\Http\Responses\MoonShineJsonResponse;
use MoonShine\MoonShineRequest;
public function updateSomething(MoonShineRequest $request): MoonShineJsonResponse
{
return MoonShineJsonResponse::make()
->toast($request->get('slug', 'Ошибка'));
}
При использовании метода withParams()
запросы будут отправляться через POST
.
Скачивание
Вызываемый метод может возвращать BinaryFileResponse
, что позволяет скачать файл.
ActionButton::make('Скачать')->method('download')
ActionButton::make('Скачать')->method('download')
ActionButton::make('Скачать')->method('download')
ActionButton::make('Скачать')->method('download')
ActionButton::make('Скачать')->method('download')
public function download(): BinaryFileResponse
{
return response()->download($file);
}
public function download(): BinaryFileResponse
{
// ...
return response()->download($file);
}
public function download(): BinaryFileResponse
{
// ...
return response()->download($file);
}
public function download(): BinaryFileResponse
{
// ...
return response()->download($file);
}
public function download(): BinaryFileResponse
{
// ...
return response()->download($file);
}
Для отправки javascript-событий вы можете использовать метод dispatchEvent()
.
dispatchEvent(array|string $events)
dispatchEvent(array|string $events)
dispatchEvent(array|string $events)
dispatchEvent(array|string $events)
dispatchEvent(array|string $events)
ActionButton::make('Обновить', '#')
->dispatchEvent(AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table')),
ActionButton::make('Обновить', '#')
->dispatchEvent(AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table')),
ActionButton::make('Обновить', '#')
->dispatchEvent(AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table')),
ActionButton::make('Обновить', '#')
->dispatchEvent(AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table')),
ActionButton::make('Обновить', '#')
->dispatchEvent(AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table')),
По умолчанию при вызове события с запросом будут отправлены все query параметры из href у ActionButton.
Некоторые исключить можно через параметр exclude
:
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
exclude: ['something']
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
exclude: ['something']
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
exclude: ['something']
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
exclude: ['something']
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
exclude: ['something']
)
Также можно полностью исключить отправку withoutPayload
:
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
withoutPayload: true
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
withoutPayload: true
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
withoutPayload: true
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
withoutPayload: true
)
->dispatchEvent(
AlpineJs::event(JsEvent::TABLE_UPDATED, 'index-table'),
withoutPayload: true
)