init
This commit is contained in:
52 files changed
+5299
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.{json,md,yml,yaml}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
* text=auto
|
||||||
|
|
||||||
|
/.codex export-ignore
|
||||||
|
/.cursor export-ignore
|
||||||
|
/.github export-ignore
|
||||||
|
/.idea export-ignore
|
||||||
|
/.nova export-ignore
|
||||||
|
/.phpunit.cache export-ignore
|
||||||
|
/.vscode export-ignore
|
||||||
|
/.zed export-ignore
|
||||||
|
/node_modules export-ignore
|
||||||
|
/tests export-ignore
|
||||||
|
/vendor export-ignore
|
||||||
|
/phpunit.xml.dist export-ignore
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
.env.backup
|
||||||
|
.env.production
|
||||||
|
.phpactor.json
|
||||||
|
.phpunit.result.cache
|
||||||
|
/.codex
|
||||||
|
/.cursor/
|
||||||
|
/.idea
|
||||||
|
/.nova
|
||||||
|
/.phpunit.cache
|
||||||
|
/.vscode
|
||||||
|
/.zed
|
||||||
|
/auth.json
|
||||||
|
/composer.lock
|
||||||
|
/node_modules
|
||||||
|
/public/build
|
||||||
|
/public/fonts-manifest.dev.json
|
||||||
|
/public/hot
|
||||||
|
/public/storage
|
||||||
|
/storage/*.key
|
||||||
|
/storage/pail
|
||||||
|
/vendor
|
||||||
|
_ide_helper.php
|
||||||
|
Homestead.json
|
||||||
|
Homestead.yaml
|
||||||
|
Thumbs.db
|
||||||
|
screenshots/
|
||||||
|
packages/
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to `nova-form-card` will be documented in this file.
|
||||||
|
|
||||||
|
## 0.1.0 - 2026-07-10
|
||||||
|
|
||||||
|
- Initial standalone Laravel Nova 5 form card package.
|
||||||
|
- Added `FormCard`, `FormFields`, signed submit tokens, package routes, submit controller, and structured responses.
|
||||||
|
- Added Nova-native rendering and submission for supported form fields, including text, choice, date, upload, password, color, code, key-value, and display-only fields.
|
||||||
|
- Added Nova `dependsOn()` sync support, validation errors, loading/disabled submit states, custom submit text, `canSee()`, and `authorizedToSubmit()`.
|
||||||
|
- Added translatable backend PHP messages and Nova frontend JSON messages.
|
||||||
|
- Added Vite-built Nova card assets and card styling fixes for Nova detail/display components.
|
||||||
|
- Added concise README, full documentation, demo screenshot, minimal example card, and full demo card.
|
||||||
|
- Added Pest coverage for serialization, authorization, validation, successful submit, failed submit, uploads, dependent fields, password confirmation, and response formatting.
|
||||||
|
|
||||||
|
### Notes
|
||||||
|
|
||||||
|
- Unsupported in this release: `Trix`, `Markdown`, `Repeater`, Vapor fields, relationship fields, and custom fields.
|
||||||
|
- Display-only fields render but are not validated or submitted.
|
||||||
|
- File-like fields are passed to `handle()` as `UploadedFile` instances; storage is handled by the card author.
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 MeghdadFadaee
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# Nova Form Card
|
||||||
|
|
||||||
|
Submit-capable Laravel Nova 5 cards powered by standard Nova fields.
|
||||||
|
|
||||||
|
`nova-form-card` gives Nova cards an Action-like flow: define fields, validate input, submit to a card endpoint, run `handle()`, and return a structured response.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Nova cards are great for dashboards, but they are usually display-only. This package lets you build reusable form cards without creating a Nova resource page or a custom tool.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Use native Nova fields inside a card
|
||||||
|
- Submit data to a package route
|
||||||
|
- Validate with Nova field `rules()` / `creationRules()`
|
||||||
|
- Receive values through `FormFields`
|
||||||
|
- Show validation errors beside fields
|
||||||
|
- Support `dependsOn()`, uploads, loading state, custom submit text, and authorization
|
||||||
|
- Return success, error, redirect, or refresh responses
|
||||||
|
- Render display-only Nova fields such as `Badge`, `Heading`, `Stack`, `Status`, and `Sparkline`
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- PHP `^8.2`
|
||||||
|
- Laravel `^11|^12|^13`
|
||||||
|
- Laravel Nova `^5`
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require meghdadfadaee/nova-form-card
|
||||||
|
```
|
||||||
|
|
||||||
|
Laravel auto-discovers the service provider.
|
||||||
|
|
||||||
|
Optional publishes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan vendor:publish --tag=nova-form-card-config
|
||||||
|
php artisan vendor:publish --tag=nova-form-card-translations
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Look
|
||||||
|
|
||||||
|
```php
|
||||||
|
class InviteUserCard extends FormCard
|
||||||
|
{
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make(__('Email'))->rules('required', 'email'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
return static::message(__('Invitation sent.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Register it anywhere Nova accepts cards.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function cards(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
new InviteUserCard(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
Read the full documentation in [docs/documentation.md](docs/documentation.md).
|
||||||
|
|
||||||
|
Useful files:
|
||||||
|
|
||||||
|
- [Minimal card example](examples/InviteUserCard.php)
|
||||||
|
- [Full demo card](examples/NovaFormCardDemo.php)
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer install
|
||||||
|
vendor/bin/pest
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nova Form Card is open-sourced software licensed under the [MIT license](LICENSE.md).
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { copyFile, mkdir } from 'node:fs/promises'
|
||||||
|
|
||||||
|
await mkdir('dist/css', { recursive: true })
|
||||||
|
await copyFile('resources/css/card.css', 'dist/css/card.css')
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
{
|
||||||
|
"name": "meghdadfadaee/nova-form-card",
|
||||||
|
"description": "Submit-capable Laravel Nova 5 cards built with standard Nova fields.",
|
||||||
|
"type": "library",
|
||||||
|
"keywords": [
|
||||||
|
"laravel",
|
||||||
|
"nova",
|
||||||
|
"nova-card",
|
||||||
|
"form",
|
||||||
|
"card"
|
||||||
|
],
|
||||||
|
"homepage": "https://github.com/MeghdadFadaee/nova-form-card",
|
||||||
|
"license": "MIT",
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "MeghdadFadaee"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"support": {
|
||||||
|
"issues": "https://github.com/MeghdadFadaee/nova-form-card/issues",
|
||||||
|
"source": "https://github.com/MeghdadFadaee/nova-form-card"
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"php": "^8.2",
|
||||||
|
"illuminate/contracts": "^11.0|^12.0|^13.0",
|
||||||
|
"illuminate/http": "^11.0|^12.0|^13.0",
|
||||||
|
"illuminate/routing": "^11.0|^12.0|^13.0",
|
||||||
|
"illuminate/support": "^11.0|^12.0|^13.0",
|
||||||
|
"illuminate/validation": "^11.0|^12.0|^13.0",
|
||||||
|
"laravel/nova": "^5.0"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"nunomaduro/collision": "^8.0|^9.0|^10.0",
|
||||||
|
"orchestra/testbench": "^9.0|^10.0|^11.0",
|
||||||
|
"pestphp/pest": "^3.0|^4.0",
|
||||||
|
"pestphp/pest-plugin-laravel": "^3.0|^4.0"
|
||||||
|
},
|
||||||
|
"repositories": [
|
||||||
|
{
|
||||||
|
"type": "artifact",
|
||||||
|
"url": "packages"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"MeghdadFadaee\\NovaFormCard\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"MeghdadFadaee\\NovaFormCard\\Tests\\": "tests/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "vendor/bin/pest",
|
||||||
|
"test:feature": "vendor/bin/pest --testsuite=Feature",
|
||||||
|
"test:unit": "vendor/bin/pest --testsuite=Unit"
|
||||||
|
},
|
||||||
|
"extra": {
|
||||||
|
"laravel": {
|
||||||
|
"providers": [
|
||||||
|
"MeghdadFadaee\\NovaFormCard\\FormCardServiceProvider"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"sort-packages": true,
|
||||||
|
"allow-plugins": {
|
||||||
|
"pestphp/pest-plugin": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"minimum-stability": "stable",
|
||||||
|
"prefer-stable": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Route Prefix
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Form card submit routes are registered under Nova's vendor route space so
|
||||||
|
| the package coexists with other Nova cards, tools, and fields.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'route_prefix' => 'nova-vendor/nova-form-card',
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Submit Token TTL
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| A signed token is embedded when a card is serialized. The submit route
|
||||||
|
| requires this token before it will instantiate and run a form card.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'token_ttl_minutes' => 120,
|
||||||
|
];
|
||||||
Vendored
+72
@@ -0,0 +1,72 @@
|
|||||||
|
.nova-form-card {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__header {
|
||||||
|
border-bottom: 1px solid rgba(229, 231, 235, 1);
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .nova-form-card__header {
|
||||||
|
border-bottom-color: rgba(55, 65, 81, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__title {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.5rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__fieldset {
|
||||||
|
border: 0;
|
||||||
|
margin: 0;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__body {
|
||||||
|
padding: 0.75rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__display-field {
|
||||||
|
padding-left: 1.5rem;
|
||||||
|
padding-right: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__footer {
|
||||||
|
align-items: center;
|
||||||
|
border-top: 1px solid rgba(229, 231, 235, 1);
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .nova-form-card__footer {
|
||||||
|
border-top-color: rgba(55, 65, 81, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__fallback-submit {
|
||||||
|
align-items: center;
|
||||||
|
background-color: rgb(14, 165, 233);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
display: inline-flex;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 700;
|
||||||
|
height: 2.25rem;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__fallback-submit:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.65;
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
(function(t){"use strict";const d=(r,e)=>{const o=r.__vccOpts||r;for(const[c,i]of e)o[c]=i;return o};class l{constructor(e={}){this.record(e)}all(){return this.errors}has(e){return e?Object.prototype.hasOwnProperty.call(this.errors,e)||Object.keys(this.errors).some(o=>o.startsWith(`${e}.`)||o.startsWith(`${e}[`)):!1}first(e){return this.get(e)[0]}get(e){return this.errors[e]||[]}record(e={}){this.errors=e}clear(e=null){if(!e){this.errors={};return}Object.keys(this.errors).filter(o=>o===e||o.startsWith(`${e}.`)||o.startsWith(`${e}[`)).forEach(o=>delete this.errors[o])}}function m(){return typeof LaravelNova<"u"&&LaravelNova.Errors?LaravelNova.Errors:l}function a(r={}){const e=m();return new e(r)}const u={provide(){return{removeFile:this.removeFile}},props:{card:{type:Object,required:!0}},data(){return{fields:[],errors:a(),processing:!1,formUniqueId:`nova-form-card-${Math.random().toString(36).slice(2)}`}},computed:{form(){return this.card.formCard||{}},resourceName(){return this.card.resourceName||this.form.resourceName||"nova-form-card"},resourceId(){return this.card.resourceId||this.form.resourceId||"form-card"},resource(){return this.form.resource||{}},submitText(){return this.form.submitText||this.translate("nova-form-card.submit","Submit")},loadingText(){return this.translate("nova-form-card.submitting","Submitting...")},canSubmit(){return this.form.canSubmit!==!1},submitDisabled(){return this.processing||!this.canSubmit},syncEndpoint(){if(!this.form.syncEndpoint||!this.form.token)return;const r=this.form.syncEndpoint.includes("?")?"&":"?";return`${this.form.syncEndpoint}${r}token=${encodeURIComponent(this.form.token)}`},buttonComponent(){return this.resolveNovaUi("Button")||"button"},hasNovaButton(){return this.buttonComponent!=="button"},buttonText(){return this.processing&&!this.hasNovaButton?this.loadingText:this.submitText},validationErrors(){return this.errors}},created(){this.syncFields()},watch:{"card.formCard.fields":{deep:!0,handler(){this.syncFields()}}},methods:{syncFields(){this.fields=(this.form.fields||[]).map(r=>({...r}))},componentName(r){return r.prefixComponent===!1?r.component:r.displayOnly?r.component==="line-field"?`index-${r.component}`:`detail-${r.component}`:`form-${r.component}`},fieldComponent(r){const e=this.componentName(r);return this.resolveNovaComponent(e)||e},fieldWrapperClass(r){return{"nova-form-card__display-field":r.displayOnly}},resolveNovaComponent(r){const e=typeof Nova<"u"?Nova.app?._context?.components:null,o=this.$?.appContext?.components||e||{};return o[r]||o[this.camelize(r)]||o[this.upperFirst(this.camelize(r))]},resolveNovaUi(r){return typeof LaravelNovaUi<"u"?LaravelNovaUi[r]:null},camelize(r){return String(r).replace(/-(\w)/g,(e,o)=>o.toUpperCase())},upperFirst(r){return r=String(r),r.charAt(0).toUpperCase()+r.slice(1)},clearFieldError(r){const e=r.validationKey||r.attribute;e&&this.errors&&typeof this.errors.clear=="function"&&this.errors.clear(e)},formDataFromFields(){const r=new FormData;return this.fields.forEach(e=>{if(!e.displayOnly){if(typeof e.fill=="function"){e.fill(r);return}r.append(e.attribute,e.value??"")}}),r},submissionPayload(){const r=new FormData;return r.append("token",this.form.token),this.formDataFromFields().forEach((e,o)=>{r.append(`fields[${o}]`,e)}),r},submit(){this.submitDisabled||(this.processing=!0,this.errors=a(),Nova.request().post(this.form.endpoint,this.submissionPayload()).then(r=>{this.handleResponse(r.data||{})}).catch(r=>{const e=r.response||{};if(e.status===422){this.errors=a(e.data?.errors||{});return}Nova.error(e.data?.message||this.couldNotSubmitMessage())}).finally(()=>{this.processing=!1}))},removeFile(){return Nova.error(this.translate("nova-form-card.could_not_submit","The form could not be submitted.")),Promise.reject(new Error("Form cards do not delete existing files."))},handleResponse(r){if(r.type==="error"){Nova.error(r.message||this.couldNotSubmitMessage());return}if(r.message&&Nova.success(r.message),r.type==="redirect"&&r.redirect?.url){const e=r.redirect;if(e.remote){Nova.visit({url:e.url,remote:!0});return}Nova.visit(e.url,e.options||{});return}r.refresh&&this.refreshPage()},refreshPage(){if(typeof Nova.visit=="function"){Nova.visit(window.location.pathname+window.location.search,{preserveScroll:!0});return}window.location.reload()},couldNotSubmitMessage(){return this.translate("nova-form-card.could_not_submit","The form could not be submitted.")},translate(r,e){if(typeof this.__=="function"){const o=this.__(r);return o===r?e:o}if(typeof window<"u"&&typeof window.__=="function"){const o=window.__(r);return o===r?e:o}if(typeof Nova<"u"&&typeof Nova.__=="function"){const o=Nova.__(r);return o===r?e:o}return e}}},f={class:"nova-form-card bg-white dark:bg-gray-800 rounded-lg shadow"},h={key:0,class:"nova-form-card__header"},p={class:"nova-form-card__title"},b=["disabled"],_={key:0,class:"nova-form-card__body"},y={class:"nova-form-card__footer"};function v(r,e,o,c,i,s){return t.openBlock(),t.createElementLine truncated
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 690 KiB |
@@ -0,0 +1,283 @@
|
|||||||
|
# Documentation
|
||||||
|
|
||||||
|
This document covers package usage, supported fields, responses, authorization, and development notes for `meghdadfadaee/nova-form-card`.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require meghdadfadaee/nova-form-card
|
||||||
|
```
|
||||||
|
|
||||||
|
The service provider is auto-discovered and registers:
|
||||||
|
|
||||||
|
- Nova card assets from `dist/js/card.js` and `dist/css/card.css`
|
||||||
|
- Submit route at `/nova-vendor/nova-form-card/submit`
|
||||||
|
- Sync route for Nova `dependsOn()`
|
||||||
|
|
||||||
|
Optional publishes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan vendor:publish --tag=nova-form-card-config
|
||||||
|
php artisan vendor:publish --tag=nova-form-card-translations
|
||||||
|
```
|
||||||
|
|
||||||
|
Translations include PHP backend messages and Nova frontend JSON messages.
|
||||||
|
|
||||||
|
## Creating A Card
|
||||||
|
|
||||||
|
Create a class extending `MeghdadFadaee\NovaFormCard\FormCard`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Nova\Cards;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class InviteUserCard extends FormCard
|
||||||
|
{
|
||||||
|
public function title(): string
|
||||||
|
{
|
||||||
|
return __('Invite User');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make(__('Email'))->rules('required', 'email'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
// Custom submit logic...
|
||||||
|
|
||||||
|
return static::message(__('Invitation sent.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Register the card anywhere Nova accepts cards:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use App\Nova\Cards\InviteUserCard;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
|
||||||
|
public function cards(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
new InviteUserCard(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Card API
|
||||||
|
|
||||||
|
Common methods:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function title(): string;
|
||||||
|
public function fields(NovaRequest $request): array;
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed;
|
||||||
|
public function authorizedToSubmit(NovaRequest $request): bool;
|
||||||
|
public function submitButtonText(): string;
|
||||||
|
```
|
||||||
|
|
||||||
|
Per-instance submit text:
|
||||||
|
|
||||||
|
```php
|
||||||
|
(new InviteUserCard())->withSubmitButtonText(__('Send Invite'));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Responses
|
||||||
|
|
||||||
|
Return one of the helper responses from `handle()`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
return static::message(__('Saved.'));
|
||||||
|
return static::success(__('Saved.'));
|
||||||
|
return static::error(__('Could not save.'));
|
||||||
|
return static::danger(__('Could not save.'));
|
||||||
|
return static::refresh(__('Updated.'));
|
||||||
|
return static::visit('/resources/users');
|
||||||
|
return static::redirect('https://example.com', remote: true);
|
||||||
|
```
|
||||||
|
|
||||||
|
Other return values:
|
||||||
|
|
||||||
|
- `string`: success message
|
||||||
|
- `false`: generic error response
|
||||||
|
- `Responsable` or Symfony `Response`: returned directly
|
||||||
|
|
||||||
|
## Authorization
|
||||||
|
|
||||||
|
Use Nova's `canSee()` to control whether the card is visible.
|
||||||
|
|
||||||
|
```php
|
||||||
|
(new InviteUserCard())->canSee(
|
||||||
|
fn (NovaRequest $request) => $request->user()->can('inviteUsers')
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `authorizedToSubmit()` to protect the submit endpoint.
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function authorizedToSubmit(NovaRequest $request): bool
|
||||||
|
{
|
||||||
|
return $request->user()->can('inviteUsers');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The package embeds a signed token when the card is serialized and rechecks submit authorization on every request.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Nova field `rules()` and `creationRules()` are applied where possible.
|
||||||
|
|
||||||
|
Validation failures return HTTP `422`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "The given data was invalid.",
|
||||||
|
"errors": {
|
||||||
|
"email": ["The email field must be a valid email address."]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Errors are displayed beside matching fields in the card.
|
||||||
|
|
||||||
|
## Supported Fields
|
||||||
|
|
||||||
|
Submit-capable fields:
|
||||||
|
|
||||||
|
`Text`, `Textarea`, `Select`, `Boolean`, `Number`, `Date`, `DateTime`, `File`, `Image`, `Avatar`, `Audio`, `Email`, `URL`, `Password`, `PasswordConfirmation`, `Hidden`, `ID`, `Currency`, `Color`, `Code`, `Country`, `Timezone`, `MultiSelect`, `BooleanGroup`, `KeyValue`, `Slug`, `Token`.
|
||||||
|
|
||||||
|
Display-only fields:
|
||||||
|
|
||||||
|
`Badge`, `Heading`, `Line`, `Stack`, `Sparkline`, `Status`, `Gravatar`, `UiAvatar`.
|
||||||
|
|
||||||
|
Unsupported fields throw `UnsupportedFieldException` during card serialization.
|
||||||
|
|
||||||
|
## Field Notes
|
||||||
|
|
||||||
|
- `FormFields` extends Nova's `ActionFields`.
|
||||||
|
- `Password` uses Nova's native fill behavior, so non-empty submitted values are hashed before they appear in `FormFields`.
|
||||||
|
- `PasswordConfirmation` validates but does not appear in `FormFields`, matching Nova.
|
||||||
|
- File-like fields submit as `Illuminate\Http\UploadedFile` instances. Your `handle()` method owns storage and cleanup.
|
||||||
|
- Display-only fields render through Nova native detail/index components and are not validated or submitted.
|
||||||
|
- `Slug` is supported as a manual field. `Slug::from()` requires Nova resource preview endpoints and is not supported.
|
||||||
|
|
||||||
|
## dependsOn
|
||||||
|
|
||||||
|
Nova `dependsOn()` is supported through the package sync endpoint.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Laravel\Nova\Fields\FormData;
|
||||||
|
use Laravel\Nova\Fields\Number;
|
||||||
|
use Laravel\Nova\Fields\Select;
|
||||||
|
|
||||||
|
Select::make(__('Plan'))->options([
|
||||||
|
'starter' => __('Starter'),
|
||||||
|
'enterprise' => __('Enterprise'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
Number::make(__('Seats'))
|
||||||
|
->hide()
|
||||||
|
->dependsOn(['plan'], function (Number $field, NovaRequest $request, FormData $data): void {
|
||||||
|
$data->get('plan') === 'enterprise'
|
||||||
|
? $field->show()->rules('required', 'integer', 'min:50')
|
||||||
|
: $field->hide()->rules('nullable', 'integer');
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Demo Card
|
||||||
|
|
||||||
|
The demo card at `examples/NovaFormCardDemo.php` shows:
|
||||||
|
|
||||||
|
- basic fields
|
||||||
|
- structured fields
|
||||||
|
- display-only fields
|
||||||
|
- uploads
|
||||||
|
- `dependsOn()`
|
||||||
|
- password confirmation
|
||||||
|
- custom submit text
|
||||||
|
- submit authorization
|
||||||
|
- all response helpers
|
||||||
|
|
||||||
|
Register it like any Nova card:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use App\Nova\Cards\NovaFormCardDemo;
|
||||||
|
|
||||||
|
(new NovaFormCardDemo())->width('full');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
Unsupported in this version:
|
||||||
|
|
||||||
|
- `Trix`
|
||||||
|
- `Markdown`
|
||||||
|
- `Repeater`
|
||||||
|
- Vapor fields
|
||||||
|
- relationship fields
|
||||||
|
- custom fields
|
||||||
|
|
||||||
|
Other limits:
|
||||||
|
|
||||||
|
- The package does not recreate Nova resource create/update pages.
|
||||||
|
- Cards should be container-resolvable; per-instance constructor state is not reconstructed on submit.
|
||||||
|
- Existing file delete/download actions are not resource-backed inside form cards.
|
||||||
|
|
||||||
|
Nova does not expose a fully public API for arbitrary field rendering outside resources/actions. Nova-specific behavior is isolated in:
|
||||||
|
|
||||||
|
- `MeghdadFadaee\NovaFormCard\Support\NovaFieldSerializer`
|
||||||
|
- `MeghdadFadaee\NovaFormCard\Support\NovaFieldValidator`
|
||||||
|
- `MeghdadFadaee\NovaFormCard\Support\NovaFieldIntrospector`
|
||||||
|
|
||||||
|
## Translations
|
||||||
|
|
||||||
|
Package messages are translatable. Publish translations with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan vendor:publish --tag=nova-form-card-translations
|
||||||
|
```
|
||||||
|
|
||||||
|
Card titles, field labels, and custom response messages should use your app translations:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Text::make(__('Email'));
|
||||||
|
|
||||||
|
return static::message(__('Invitation sent.'));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
Build assets:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Run tests:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer install
|
||||||
|
vendor/bin/pest
|
||||||
|
```
|
||||||
|
|
||||||
|
Before release:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer validate --strict
|
||||||
|
find . -name '*.php' -not -path './vendor/*' -print0 | xargs -0 -n1 php -l
|
||||||
|
npm run build
|
||||||
|
vendor/bin/pest
|
||||||
|
```
|
||||||
|
|
||||||
|
Nova is distributed from Laravel's private Composer repository, so local and CI environments need valid Nova credentials.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Nova\Cards;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class InviteUserCard extends FormCard
|
||||||
|
{
|
||||||
|
public function title(): string
|
||||||
|
{
|
||||||
|
return __('Invite User');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make(__('Email'))
|
||||||
|
->rules('required', 'email'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
// InviteUser::dispatch($fields->email);
|
||||||
|
|
||||||
|
return static::message(__('Invitation sent.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Nova\Cards;
|
||||||
|
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Laravel\Nova\Fields\Audio;
|
||||||
|
use Laravel\Nova\Fields\Avatar;
|
||||||
|
use Laravel\Nova\Fields\Badge;
|
||||||
|
use Laravel\Nova\Fields\Boolean;
|
||||||
|
use Laravel\Nova\Fields\BooleanGroup;
|
||||||
|
use Laravel\Nova\Fields\Code;
|
||||||
|
use Laravel\Nova\Fields\Color;
|
||||||
|
use Laravel\Nova\Fields\Country;
|
||||||
|
use Laravel\Nova\Fields\Currency;
|
||||||
|
use Laravel\Nova\Fields\Date;
|
||||||
|
use Laravel\Nova\Fields\DateTime;
|
||||||
|
use Laravel\Nova\Fields\Email;
|
||||||
|
use Laravel\Nova\Fields\File;
|
||||||
|
use Laravel\Nova\Fields\FormData;
|
||||||
|
use Laravel\Nova\Fields\Gravatar;
|
||||||
|
use Laravel\Nova\Fields\Heading;
|
||||||
|
use Laravel\Nova\Fields\Hidden;
|
||||||
|
use Laravel\Nova\Fields\ID;
|
||||||
|
use Laravel\Nova\Fields\Image;
|
||||||
|
use Laravel\Nova\Fields\KeyValue;
|
||||||
|
use Laravel\Nova\Fields\Line;
|
||||||
|
use Laravel\Nova\Fields\MultiSelect;
|
||||||
|
use Laravel\Nova\Fields\Number;
|
||||||
|
use Laravel\Nova\Fields\Password;
|
||||||
|
use Laravel\Nova\Fields\PasswordConfirmation;
|
||||||
|
use Laravel\Nova\Fields\Select;
|
||||||
|
use Laravel\Nova\Fields\Slug;
|
||||||
|
use Laravel\Nova\Fields\Sparkline;
|
||||||
|
use Laravel\Nova\Fields\Stack;
|
||||||
|
use Laravel\Nova\Fields\Status;
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Fields\Textarea;
|
||||||
|
use Laravel\Nova\Fields\Timezone;
|
||||||
|
use Laravel\Nova\Fields\Token;
|
||||||
|
use Laravel\Nova\Fields\UiAvatar;
|
||||||
|
use Laravel\Nova\Fields\URL;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class NovaFormCardDemo extends FormCard
|
||||||
|
{
|
||||||
|
public function title(): string
|
||||||
|
{
|
||||||
|
return __('Nova Form Card Demo');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function submitButtonText(): string
|
||||||
|
{
|
||||||
|
return __('Submit Demo Card');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function authorizedToSubmit(NovaRequest $request): bool
|
||||||
|
{
|
||||||
|
return $request->user() !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Heading::make(__('Package Status')),
|
||||||
|
|
||||||
|
Badge::make(__('Health'))->map([
|
||||||
|
'ready' => 'success',
|
||||||
|
])->labels([
|
||||||
|
'ready' => __('Ready'),
|
||||||
|
])->default('ready'),
|
||||||
|
|
||||||
|
Status::make(__('Queue'))->loadingWhen([
|
||||||
|
'waiting',
|
||||||
|
])->failedWhen([
|
||||||
|
'failed',
|
||||||
|
])->default('processed'),
|
||||||
|
|
||||||
|
Line::make(__('Build'))->asSmall()->default(__('Using Nova native field components')),
|
||||||
|
|
||||||
|
Stack::make(__('Snapshot'), [
|
||||||
|
Line::make(__('Fields'))->asHeading()->default(__('Inputs, uploads, display fields')),
|
||||||
|
Line::make(__('Submit'))->default(__('Validation, loading state, and structured responses')),
|
||||||
|
]),
|
||||||
|
|
||||||
|
Sparkline::make(__('Activity'))->data([2, 4, 3, 7, 6, 9, 11])->height(48),
|
||||||
|
|
||||||
|
Gravatar::make(__('User Gravatar'), 'demo_gravatar_email')
|
||||||
|
->default($request->user()?->email ?? 'demo@example.com'),
|
||||||
|
|
||||||
|
UiAvatar::make(__('User Initials'), 'demo_avatar_name')
|
||||||
|
->default($request->user()?->name ?? 'Nova User'),
|
||||||
|
|
||||||
|
Heading::make(__('Basic Inputs')),
|
||||||
|
|
||||||
|
Text::make(__('Name'))
|
||||||
|
->default($request->user()?->name ?? __('Ada Lovelace'))
|
||||||
|
->rules('required', 'string', 'max:255'),
|
||||||
|
|
||||||
|
Email::make(__('Email'))
|
||||||
|
->default($request->user()?->email ?? 'ada@example.com')
|
||||||
|
->rules('required', 'email'),
|
||||||
|
|
||||||
|
URL::make(__('Website'))
|
||||||
|
->default('https://example.com')
|
||||||
|
->rules('nullable', 'url'),
|
||||||
|
|
||||||
|
Textarea::make(__('Notes'))
|
||||||
|
->alwaysShow()
|
||||||
|
->rules('nullable', 'string', 'max:1000'),
|
||||||
|
|
||||||
|
Select::make(__('Plan'))
|
||||||
|
->options([
|
||||||
|
'starter' => __('Starter'),
|
||||||
|
'growth' => __('Growth'),
|
||||||
|
'enterprise' => __('Enterprise'),
|
||||||
|
])
|
||||||
|
->displayUsingLabels()
|
||||||
|
->default('growth')
|
||||||
|
->rules('required', 'in:starter,growth,enterprise'),
|
||||||
|
|
||||||
|
Number::make(__('Enterprise Seats'), 'enterprise_seats')
|
||||||
|
->hide()
|
||||||
|
->min(50)
|
||||||
|
->step(1)
|
||||||
|
->dependsOn(['plan'], function (Number $field, NovaRequest $request, FormData $data): void {
|
||||||
|
if ($data->get('plan') === 'enterprise') {
|
||||||
|
$field->show()->rules('required', 'integer', 'min:50');
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$field->hide()->rules('nullable', 'integer', 'min:50');
|
||||||
|
}),
|
||||||
|
|
||||||
|
Boolean::make(__('Send Welcome Email'), 'send_welcome_email')
|
||||||
|
->default(true),
|
||||||
|
|
||||||
|
MultiSelect::make(__('Channels'))
|
||||||
|
->options([
|
||||||
|
'email' => __('Email'),
|
||||||
|
'sms' => __('SMS'),
|
||||||
|
'push' => __('Push'),
|
||||||
|
])
|
||||||
|
->default(['email'])
|
||||||
|
->rules('nullable', 'array'),
|
||||||
|
|
||||||
|
BooleanGroup::make(__('Permissions'))
|
||||||
|
->options([
|
||||||
|
'read' => __('Read'),
|
||||||
|
'write' => __('Write'),
|
||||||
|
'export' => __('Export'),
|
||||||
|
])
|
||||||
|
->default([
|
||||||
|
'read' => true,
|
||||||
|
'write' => false,
|
||||||
|
'export' => false,
|
||||||
|
]),
|
||||||
|
|
||||||
|
Heading::make(__('Dates And Structured Values')),
|
||||||
|
|
||||||
|
Date::make(__('Start Date'), 'start_date')
|
||||||
|
->default(now()->toDateString())
|
||||||
|
->rules('required', 'date'),
|
||||||
|
|
||||||
|
DateTime::make(__('Reminder At'), 'reminder_at')
|
||||||
|
->default(now()->addDay())
|
||||||
|
->rules('nullable', 'date'),
|
||||||
|
|
||||||
|
Timezone::make(__('Timezone'))
|
||||||
|
->default(config('app.timezone', 'UTC')),
|
||||||
|
|
||||||
|
Country::make(__('Country'))
|
||||||
|
->default('US'),
|
||||||
|
|
||||||
|
Currency::make(__('Budget'))
|
||||||
|
->default('249.00')
|
||||||
|
->rules('nullable', 'numeric', 'min:0'),
|
||||||
|
|
||||||
|
Color::make(__('Accent Color'), 'accent_color')
|
||||||
|
->default('#10b981'),
|
||||||
|
|
||||||
|
Code::make(__('Payload'))
|
||||||
|
->json()
|
||||||
|
->default(json_encode([
|
||||||
|
'source' => 'nova-form-card',
|
||||||
|
'demo' => true,
|
||||||
|
], JSON_PRETTY_PRINT)),
|
||||||
|
|
||||||
|
KeyValue::make(__('Metadata'))
|
||||||
|
->default([
|
||||||
|
'campaign' => 'Demo',
|
||||||
|
'owner' => 'Nova',
|
||||||
|
]),
|
||||||
|
|
||||||
|
Slug::make(__('Workspace Slug'), 'workspace_slug')
|
||||||
|
->default('nova-form-card-demo')
|
||||||
|
->rules('required', 'alpha_dash'),
|
||||||
|
|
||||||
|
Token::make(__('Access Token'), 'access_token')
|
||||||
|
->default('demo-token'),
|
||||||
|
|
||||||
|
Hidden::make(__('Tracking Code'), 'tracking_code')
|
||||||
|
->default('demo-card'),
|
||||||
|
|
||||||
|
ID::make(__('Record ID'), 'record_id')
|
||||||
|
->default(1001),
|
||||||
|
|
||||||
|
Heading::make(__('Security And Uploads')),
|
||||||
|
|
||||||
|
Password::make(__('Secret'), 'secret')
|
||||||
|
->rules('nullable'),
|
||||||
|
|
||||||
|
PasswordConfirmation::make(__('Secret Confirmation'), 'secret_confirmation')
|
||||||
|
->rules('nullable', 'same:secret'),
|
||||||
|
|
||||||
|
File::make(__('Attachment'))
|
||||||
|
->rules('nullable', 'file'),
|
||||||
|
|
||||||
|
Image::make(__('Image'))
|
||||||
|
->rules('nullable', 'image'),
|
||||||
|
|
||||||
|
Avatar::make(__('Profile Photo'), 'profile_photo')
|
||||||
|
->rules('nullable', 'image'),
|
||||||
|
|
||||||
|
Audio::make(__('Audio Note'), 'audio_note')
|
||||||
|
->rules('nullable', 'file'),
|
||||||
|
|
||||||
|
Heading::make(__('Response Demo')),
|
||||||
|
|
||||||
|
Select::make(__('Response Type'), 'response_type')
|
||||||
|
->options([
|
||||||
|
'success' => __('Success message'),
|
||||||
|
'error' => __('Error toast'),
|
||||||
|
'refresh' => __('Refresh page'),
|
||||||
|
'redirect' => __('Visit Nova home'),
|
||||||
|
])
|
||||||
|
->displayUsingLabels()
|
||||||
|
->default('success')
|
||||||
|
->rules('required', 'in:success,error,refresh,redirect'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
$uploads = collect(['attachment', 'image', 'profile_photo', 'audio_note'])
|
||||||
|
->mapWithKeys(fn (string $key): array => [$key => $fields->get($key)])
|
||||||
|
->filter(fn (mixed $value): bool => $value instanceof UploadedFile)
|
||||||
|
->map(fn (UploadedFile $file): string => $file->getClientOriginalName())
|
||||||
|
->all();
|
||||||
|
|
||||||
|
$count = collect($fields->all())
|
||||||
|
->reject(fn (mixed $value): bool => $value === null || $value === '' || $value === [])
|
||||||
|
->count();
|
||||||
|
|
||||||
|
$message = __('Demo submitted with :count handled values and :uploads upload(s).', [
|
||||||
|
'count' => $count,
|
||||||
|
'uploads' => count($uploads),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return match ($fields->get('response_type', 'success')) {
|
||||||
|
'error' => static::error(__('Demo error response selected.')),
|
||||||
|
'refresh' => static::refresh($message),
|
||||||
|
'redirect' => static::visit('/'.trim((string) config('nova.path', 'nova'), '/')),
|
||||||
|
default => static::message($message),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1353
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "nova-form-card",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite build --watch",
|
||||||
|
"build": "vite build && node bin/copy-css.mjs",
|
||||||
|
"prod": "npm run build"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.0.0 || ^6.0.0",
|
||||||
|
"vite": "^6.0.0 || ^7.0.0",
|
||||||
|
"vue": "^3.5.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<phpunit
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||||
|
bootstrap="vendor/autoload.php"
|
||||||
|
colors="true"
|
||||||
|
>
|
||||||
|
<testsuites>
|
||||||
|
<testsuite name="Feature">
|
||||||
|
<directory>tests/Feature</directory>
|
||||||
|
</testsuite>
|
||||||
|
<testsuite name="Unit">
|
||||||
|
<directory>tests/Unit</directory>
|
||||||
|
</testsuite>
|
||||||
|
</testsuites>
|
||||||
|
<php>
|
||||||
|
<env name="APP_KEY" value="base64:MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY="/>
|
||||||
|
<env name="APP_ENV" value="testing"/>
|
||||||
|
</php>
|
||||||
|
</phpunit>
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
.nova-form-card {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__header {
|
||||||
|
border-bottom: 1px solid rgba(229, 231, 235, 1);
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .nova-form-card__header {
|
||||||
|
border-bottom-color: rgba(55, 65, 81, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__title {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.5rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__fieldset {
|
||||||
|
border: 0;
|
||||||
|
margin: 0;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__body {
|
||||||
|
padding: 0.75rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__display-field {
|
||||||
|
padding-left: 1.5rem;
|
||||||
|
padding-right: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__footer {
|
||||||
|
align-items: center;
|
||||||
|
border-top: 1px solid rgba(229, 231, 235, 1);
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark .nova-form-card__footer {
|
||||||
|
border-top-color: rgba(55, 65, 81, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__fallback-submit {
|
||||||
|
align-items: center;
|
||||||
|
background-color: rgb(14, 165, 233);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
display: inline-flex;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 700;
|
||||||
|
height: 2.25rem;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nova-form-card__fallback-submit:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.65;
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import Card from './components/Card.vue'
|
||||||
|
|
||||||
|
Nova.booting(app => {
|
||||||
|
app.component('nova-form-card', Card)
|
||||||
|
})
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
<template>
|
||||||
|
<div class="nova-form-card bg-white dark:bg-gray-800 rounded-lg shadow">
|
||||||
|
<form class="nova-form-card__form" @submit.prevent="submit" autocomplete="off">
|
||||||
|
<div v-if="form.title" class="nova-form-card__header">
|
||||||
|
<h3 class="nova-form-card__title">{{ form.title }}</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset class="nova-form-card__fieldset" :disabled="submitDisabled">
|
||||||
|
<div v-if="fields.length" class="nova-form-card__body">
|
||||||
|
<div
|
||||||
|
v-for="(field, index) in fields"
|
||||||
|
:key="field.uniqueKey || field.attribute"
|
||||||
|
:class="fieldWrapperClass(field)"
|
||||||
|
>
|
||||||
|
<component
|
||||||
|
:is="fieldComponent(field)"
|
||||||
|
:index="index"
|
||||||
|
:resource="resource"
|
||||||
|
:resource-name="resourceName"
|
||||||
|
:resource-id="resourceId"
|
||||||
|
:field="field"
|
||||||
|
:errors="validationErrors"
|
||||||
|
:form-unique-id="formUniqueId"
|
||||||
|
:show-help-text="true"
|
||||||
|
:sync-endpoint="syncEndpoint"
|
||||||
|
mode="form-card"
|
||||||
|
@field-changed="clearFieldError(field)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div class="nova-form-card__footer">
|
||||||
|
<component
|
||||||
|
:is="buttonComponent"
|
||||||
|
as="button"
|
||||||
|
:class="{ 'nova-form-card__fallback-submit': !hasNovaButton }"
|
||||||
|
:label="submitText"
|
||||||
|
:loading="processing"
|
||||||
|
size="large"
|
||||||
|
type="submit"
|
||||||
|
variant="solid"
|
||||||
|
:disabled="submitDisabled"
|
||||||
|
@click.prevent="submit"
|
||||||
|
>
|
||||||
|
{{ buttonText }}
|
||||||
|
</component>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
class FallbackErrors {
|
||||||
|
constructor(errors = {}) {
|
||||||
|
this.record(errors)
|
||||||
|
}
|
||||||
|
|
||||||
|
all() {
|
||||||
|
return this.errors
|
||||||
|
}
|
||||||
|
|
||||||
|
has(field) {
|
||||||
|
if (!field) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.prototype.hasOwnProperty.call(this.errors, field)
|
||||||
|
|| Object.keys(this.errors).some(error => error.startsWith(`${field}.`) || error.startsWith(`${field}[`))
|
||||||
|
}
|
||||||
|
|
||||||
|
first(field) {
|
||||||
|
return this.get(field)[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
get(field) {
|
||||||
|
return this.errors[field] || []
|
||||||
|
}
|
||||||
|
|
||||||
|
record(errors = {}) {
|
||||||
|
this.errors = errors
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(field = null) {
|
||||||
|
if (!field) {
|
||||||
|
this.errors = {}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.keys(this.errors)
|
||||||
|
.filter(error => error === field || error.startsWith(`${field}.`) || error.startsWith(`${field}[`))
|
||||||
|
.forEach(error => delete this.errors[error])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function novaErrors() {
|
||||||
|
return typeof LaravelNova !== 'undefined' && LaravelNova.Errors
|
||||||
|
? LaravelNova.Errors
|
||||||
|
: FallbackErrors
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeErrors(errors = {}) {
|
||||||
|
const Errors = novaErrors()
|
||||||
|
|
||||||
|
return new Errors(errors)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
provide() {
|
||||||
|
return {
|
||||||
|
removeFile: this.removeFile,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
props: {
|
||||||
|
card: {
|
||||||
|
type: Object,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
fields: [],
|
||||||
|
errors: makeErrors(),
|
||||||
|
processing: false,
|
||||||
|
formUniqueId: `nova-form-card-${Math.random().toString(36).slice(2)}`,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
computed: {
|
||||||
|
form() {
|
||||||
|
return this.card.formCard || {}
|
||||||
|
},
|
||||||
|
|
||||||
|
resourceName() {
|
||||||
|
return this.card.resourceName || this.form.resourceName || 'nova-form-card'
|
||||||
|
},
|
||||||
|
|
||||||
|
resourceId() {
|
||||||
|
return this.card.resourceId || this.form.resourceId || 'form-card'
|
||||||
|
},
|
||||||
|
|
||||||
|
resource() {
|
||||||
|
return this.form.resource || {}
|
||||||
|
},
|
||||||
|
|
||||||
|
submitText() {
|
||||||
|
return this.form.submitText || this.translate('nova-form-card.submit', 'Submit')
|
||||||
|
},
|
||||||
|
|
||||||
|
loadingText() {
|
||||||
|
return this.translate('nova-form-card.submitting', 'Submitting...')
|
||||||
|
},
|
||||||
|
|
||||||
|
canSubmit() {
|
||||||
|
return this.form.canSubmit !== false
|
||||||
|
},
|
||||||
|
|
||||||
|
submitDisabled() {
|
||||||
|
return this.processing || !this.canSubmit
|
||||||
|
},
|
||||||
|
|
||||||
|
syncEndpoint() {
|
||||||
|
if (!this.form.syncEndpoint || !this.form.token) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const separator = this.form.syncEndpoint.includes('?') ? '&' : '?'
|
||||||
|
|
||||||
|
return `${this.form.syncEndpoint}${separator}token=${encodeURIComponent(this.form.token)}`
|
||||||
|
},
|
||||||
|
|
||||||
|
buttonComponent() {
|
||||||
|
return this.resolveNovaUi('Button') || 'button'
|
||||||
|
},
|
||||||
|
|
||||||
|
hasNovaButton() {
|
||||||
|
return this.buttonComponent !== 'button'
|
||||||
|
},
|
||||||
|
|
||||||
|
buttonText() {
|
||||||
|
return this.processing && !this.hasNovaButton
|
||||||
|
? this.loadingText
|
||||||
|
: this.submitText
|
||||||
|
},
|
||||||
|
|
||||||
|
validationErrors() {
|
||||||
|
return this.errors
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
created() {
|
||||||
|
this.syncFields()
|
||||||
|
},
|
||||||
|
|
||||||
|
watch: {
|
||||||
|
'card.formCard.fields': {
|
||||||
|
deep: true,
|
||||||
|
handler() {
|
||||||
|
this.syncFields()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
methods: {
|
||||||
|
syncFields() {
|
||||||
|
this.fields = (this.form.fields || []).map(field => ({ ...field }))
|
||||||
|
},
|
||||||
|
|
||||||
|
componentName(field) {
|
||||||
|
if (field.prefixComponent === false) {
|
||||||
|
return field.component
|
||||||
|
}
|
||||||
|
|
||||||
|
if (field.displayOnly) {
|
||||||
|
return field.component === 'line-field'
|
||||||
|
? `index-${field.component}`
|
||||||
|
: `detail-${field.component}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return `form-${field.component}`
|
||||||
|
},
|
||||||
|
|
||||||
|
fieldComponent(field) {
|
||||||
|
const name = this.componentName(field)
|
||||||
|
|
||||||
|
return this.resolveNovaComponent(name) || name
|
||||||
|
},
|
||||||
|
|
||||||
|
fieldWrapperClass(field) {
|
||||||
|
return {
|
||||||
|
'nova-form-card__display-field': field.displayOnly,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
resolveNovaComponent(name) {
|
||||||
|
const novaComponents = typeof Nova !== 'undefined'
|
||||||
|
? Nova.app?._context?.components
|
||||||
|
: null
|
||||||
|
|
||||||
|
const components = this.$?.appContext?.components
|
||||||
|
|| novaComponents
|
||||||
|
|| {}
|
||||||
|
|
||||||
|
return components[name]
|
||||||
|
|| components[this.camelize(name)]
|
||||||
|
|| components[this.upperFirst(this.camelize(name))]
|
||||||
|
},
|
||||||
|
|
||||||
|
resolveNovaUi(name) {
|
||||||
|
return typeof LaravelNovaUi !== 'undefined'
|
||||||
|
? LaravelNovaUi[name]
|
||||||
|
: null
|
||||||
|
},
|
||||||
|
|
||||||
|
camelize(name) {
|
||||||
|
return String(name).replace(/-(\w)/g, (_, character) => character.toUpperCase())
|
||||||
|
},
|
||||||
|
|
||||||
|
upperFirst(value) {
|
||||||
|
value = String(value)
|
||||||
|
|
||||||
|
return value.charAt(0).toUpperCase() + value.slice(1)
|
||||||
|
},
|
||||||
|
|
||||||
|
clearFieldError(field) {
|
||||||
|
const key = field.validationKey || field.attribute
|
||||||
|
|
||||||
|
if (key && this.errors && typeof this.errors.clear === 'function') {
|
||||||
|
this.errors.clear(key)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
formDataFromFields() {
|
||||||
|
const formData = new FormData()
|
||||||
|
|
||||||
|
this.fields.forEach(field => {
|
||||||
|
if (field.displayOnly) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof field.fill === 'function') {
|
||||||
|
field.fill(formData)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
formData.append(field.attribute, field.value ?? '')
|
||||||
|
})
|
||||||
|
|
||||||
|
return formData
|
||||||
|
},
|
||||||
|
|
||||||
|
submissionPayload() {
|
||||||
|
const payload = new FormData()
|
||||||
|
|
||||||
|
payload.append('token', this.form.token)
|
||||||
|
|
||||||
|
this.formDataFromFields().forEach((value, key) => {
|
||||||
|
payload.append(`fields[${key}]`, value)
|
||||||
|
})
|
||||||
|
|
||||||
|
return payload
|
||||||
|
},
|
||||||
|
|
||||||
|
submit() {
|
||||||
|
if (this.submitDisabled) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.processing = true
|
||||||
|
this.errors = makeErrors()
|
||||||
|
|
||||||
|
Nova.request()
|
||||||
|
.post(this.form.endpoint, this.submissionPayload())
|
||||||
|
.then(response => {
|
||||||
|
this.handleResponse(response.data || {})
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
const response = error.response || {}
|
||||||
|
|
||||||
|
if (response.status === 422) {
|
||||||
|
this.errors = makeErrors(response.data?.errors || {})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Nova.error(response.data?.message || this.couldNotSubmitMessage())
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.processing = false
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
removeFile() {
|
||||||
|
Nova.error(this.translate(
|
||||||
|
'nova-form-card.could_not_submit',
|
||||||
|
'The form could not be submitted.',
|
||||||
|
))
|
||||||
|
|
||||||
|
return Promise.reject(new Error('Form cards do not delete existing files.'))
|
||||||
|
},
|
||||||
|
|
||||||
|
handleResponse(response) {
|
||||||
|
if (response.type === 'error') {
|
||||||
|
Nova.error(response.message || this.couldNotSubmitMessage())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.message) {
|
||||||
|
Nova.success(response.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.type === 'redirect' && response.redirect?.url) {
|
||||||
|
const redirect = response.redirect
|
||||||
|
|
||||||
|
if (redirect.remote) {
|
||||||
|
Nova.visit({ url: redirect.url, remote: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Nova.visit(redirect.url, redirect.options || {})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.refresh) {
|
||||||
|
this.refreshPage()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
refreshPage() {
|
||||||
|
if (typeof Nova.visit === 'function') {
|
||||||
|
Nova.visit(window.location.pathname + window.location.search, {
|
||||||
|
preserveScroll: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
window.location.reload()
|
||||||
|
},
|
||||||
|
|
||||||
|
couldNotSubmitMessage() {
|
||||||
|
return this.translate('nova-form-card.could_not_submit', 'The form could not be submitted.')
|
||||||
|
},
|
||||||
|
|
||||||
|
translate(key, fallback) {
|
||||||
|
if (typeof this.__ === 'function') {
|
||||||
|
const translated = this.__(key)
|
||||||
|
|
||||||
|
return translated === key ? fallback : translated
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined' && typeof window.__ === 'function') {
|
||||||
|
const translated = window.__(key)
|
||||||
|
|
||||||
|
return translated === key ? fallback : translated
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof Nova !== 'undefined' && typeof Nova.__ === 'function') {
|
||||||
|
const translated = Nova.__(key)
|
||||||
|
|
||||||
|
return translated === key ? fallback : translated
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Translation Notes
|
||||||
|
|
||||||
|
`messages.php` contains backend translation strings and supports normal PHP translator comments.
|
||||||
|
|
||||||
|
`card.json` files are loaded by `Nova::translations()` for the Vue card. JSON does not support comments, so keep those files as valid JSON. The current frontend keys are:
|
||||||
|
|
||||||
|
- `nova-form-card.submit`: default submit button text.
|
||||||
|
- `nova-form-card.submitting`: loading text while a submission is in progress.
|
||||||
|
- `nova-form-card.could_not_submit`: fallback error toast when a request fails without a server message.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"nova-form-card.submit": "Submit",
|
||||||
|
"nova-form-card.submitting": "Submitting...",
|
||||||
|
"nova-form-card.could_not_submit": "The form could not be submitted."
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Button Labels
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These labels are used by the backend defaults. The frontend card has
|
||||||
|
| matching keys in card.json because Nova consumes JSON translations.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'submit' => 'Submit',
|
||||||
|
'submitting' => 'Submitting...',
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Submission Errors
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These messages are returned by the submit endpoint. Keep them short enough
|
||||||
|
| to work in Nova toast notifications and validation responses.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'cannot_submit' => 'This form card cannot be submitted.',
|
||||||
|
'not_authorized_to_submit' => 'This form card is not authorized for submission.',
|
||||||
|
'fields_payload_must_be_object' => 'The fields payload must be an object.',
|
||||||
|
'invalid_data' => 'The given data was invalid.',
|
||||||
|
'could_not_submit' => 'The form could not be submitted.',
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Developer-Facing Exceptions
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The unsupported_field message is shown to developers during serialization.
|
||||||
|
| Preserve the :field and :supported placeholders in custom translations.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'unsupported_field' => 'The [:field] field is not supported by nova-form-card. Supported fields are: :supported.',
|
||||||
|
'app_key_required' => 'An application key is required to sign form card submissions.',
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Signed Submit Token Errors
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These describe why a submitted form token could not be trusted. They are
|
||||||
|
| intentionally specific for logs and debugging, but are usually returned as
|
||||||
|
| a generic authorization failure to users.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'token' => [
|
||||||
|
'missing' => 'The form card token is missing.',
|
||||||
|
'invalid_signature' => 'The form card token signature is invalid.',
|
||||||
|
'missing_card_class' => 'The form card token does not contain a card class.',
|
||||||
|
'expired' => 'The form card token has expired.',
|
||||||
|
'wrong_user' => 'The form card token belongs to another user.',
|
||||||
|
'invalid_card_class' => 'The form card token references an invalid card class.',
|
||||||
|
'invalid_payload' => 'The form card token payload is invalid.',
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Supported Field Names
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These names are only used in developer-facing unsupported-field messages.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'fields' => [
|
||||||
|
'text' => 'Text',
|
||||||
|
'textarea' => 'Textarea',
|
||||||
|
'select' => 'Select',
|
||||||
|
'boolean' => 'Boolean',
|
||||||
|
'number' => 'Number',
|
||||||
|
'date' => 'Date',
|
||||||
|
'file' => 'File',
|
||||||
|
'image' => 'Image',
|
||||||
|
'audio' => 'Audio',
|
||||||
|
'avatar' => 'Avatar',
|
||||||
|
'email' => 'Email',
|
||||||
|
'url' => 'URL',
|
||||||
|
'password' => 'Password',
|
||||||
|
'hidden' => 'Hidden',
|
||||||
|
'id' => 'ID',
|
||||||
|
'date_time' => 'DateTime',
|
||||||
|
'currency' => 'Currency',
|
||||||
|
'color' => 'Color',
|
||||||
|
'code' => 'Code',
|
||||||
|
'country' => 'Country',
|
||||||
|
'timezone' => 'Timezone',
|
||||||
|
'multi_select' => 'MultiSelect',
|
||||||
|
'boolean_group' => 'BooleanGroup',
|
||||||
|
'key_value' => 'KeyValue',
|
||||||
|
'slug' => 'Slug',
|
||||||
|
'token' => 'Token',
|
||||||
|
'badge' => 'Badge',
|
||||||
|
'heading' => 'Heading',
|
||||||
|
'line' => 'Line',
|
||||||
|
'stack' => 'Stack',
|
||||||
|
'sparkline' => 'Sparkline',
|
||||||
|
'status' => 'Status',
|
||||||
|
'gravatar' => 'Gravatar',
|
||||||
|
'ui_avatar' => 'UiAvatar',
|
||||||
|
'password_confirmation' => 'PasswordConfirmation',
|
||||||
|
],
|
||||||
|
];
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Http\Controllers\SyncFormCardFieldController;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Http\Controllers\SubmitFormCardController;
|
||||||
|
|
||||||
|
Route::patch('/sync', SyncFormCardFieldController::class)
|
||||||
|
->name('nova-form-card.sync');
|
||||||
|
|
||||||
|
Route::post('/submit', SubmitFormCardController::class)
|
||||||
|
->name('nova-form-card.submit');
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Exceptions;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class InvalidFormCardToken extends RuntimeException
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Exceptions;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\SupportedField;
|
||||||
|
|
||||||
|
class UnsupportedFieldException extends RuntimeException
|
||||||
|
{
|
||||||
|
public static function forField(object $field): self
|
||||||
|
{
|
||||||
|
return new self(__('nova-form-card::messages.unsupported_field', [
|
||||||
|
'field' => $field::class,
|
||||||
|
'supported' => implode(', ', SupportedField::names()),
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard;
|
||||||
|
|
||||||
|
use Laravel\Nova\Card;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Http\Responses\FormCardResponse;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\FormCardToken;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\NovaFieldSerializer;
|
||||||
|
|
||||||
|
abstract class FormCard extends Card
|
||||||
|
{
|
||||||
|
protected ?string $submitButtonText = null;
|
||||||
|
|
||||||
|
public function component(): string
|
||||||
|
{
|
||||||
|
return 'nova-form-card';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function title(): string
|
||||||
|
{
|
||||||
|
return __(Str::headline(class_basename(static::class)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Nova fields displayed by the card.
|
||||||
|
*
|
||||||
|
* @return array<int, \Laravel\Nova\Fields\Field>
|
||||||
|
*/
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract public function handle(FormFields $fields, NovaRequest $request): mixed;
|
||||||
|
|
||||||
|
public function authorizedToSubmit(NovaRequest $request): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function submitButtonText(): string
|
||||||
|
{
|
||||||
|
return $this->submitButtonText ?? __('nova-form-card::messages.submit');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function withSubmitButtonText(string $text): static
|
||||||
|
{
|
||||||
|
$this->submitButtonText = $text;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function jsonSerialize(): array
|
||||||
|
{
|
||||||
|
$request = $this->currentNovaRequest();
|
||||||
|
|
||||||
|
app()->instance(NovaRequest::class, $request);
|
||||||
|
|
||||||
|
$this->withMeta([
|
||||||
|
'formCard' => $this->serializeForFormCard($request),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return parent::jsonSerialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected function serializeForFormCard(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$prefix = trim((string) config('nova-form-card.route_prefix', 'nova-vendor/nova-form-card'), '/');
|
||||||
|
$token = app(FormCardToken::class)->issue($this, $request);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => $this->title(),
|
||||||
|
'fields' => app(NovaFieldSerializer::class)->serialize($this->fields($request), $request),
|
||||||
|
'endpoint' => "/{$prefix}/submit",
|
||||||
|
'syncEndpoint' => "/{$prefix}/sync",
|
||||||
|
'submitText' => $this->submitButtonText(),
|
||||||
|
'canSubmit' => $this->authorizedToSubmit($request),
|
||||||
|
'token' => $token,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function currentNovaRequest(): NovaRequest
|
||||||
|
{
|
||||||
|
if (app()->bound(NovaRequest::class) && app(NovaRequest::class) instanceof NovaRequest) {
|
||||||
|
return app(NovaRequest::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
$request = request();
|
||||||
|
|
||||||
|
if ($request instanceof NovaRequest) {
|
||||||
|
return $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NovaRequest::createFrom($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function message(string $message): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::message($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function success(?string $message = null): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::success($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function error(string $message): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::error($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function danger(string $message): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::error($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function redirect(string $url, bool $remote = false): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::redirect($url, $remote);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function visit(string $path, array $options = []): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::visit($path, $options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function refresh(?string $message = null): FormCardResponse
|
||||||
|
{
|
||||||
|
return FormCardResponse::refresh($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Laravel\Nova\Events\ServingNova;
|
||||||
|
use Laravel\Nova\Nova;
|
||||||
|
|
||||||
|
class FormCardServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->mergeConfigFrom(__DIR__.'/../config/nova-form-card.php', 'nova-form-card');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function boot(): void
|
||||||
|
{
|
||||||
|
$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'nova-form-card');
|
||||||
|
|
||||||
|
if ($this->app->runningInConsole()) {
|
||||||
|
$this->publishes([
|
||||||
|
__DIR__.'/../config/nova-form-card.php' => config_path('nova-form-card.php'),
|
||||||
|
], 'nova-form-card-config');
|
||||||
|
|
||||||
|
$this->publishes([
|
||||||
|
__DIR__.'/../resources/lang' => lang_path('vendor/nova-form-card'),
|
||||||
|
], 'nova-form-card-translations');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->app->booted(function (): void {
|
||||||
|
$this->routes();
|
||||||
|
});
|
||||||
|
|
||||||
|
Nova::serving(function (ServingNova $event): void {
|
||||||
|
Nova::script('nova-form-card', __DIR__.'/../dist/js/card.js');
|
||||||
|
Nova::style('nova-form-card', __DIR__.'/../dist/css/card.css');
|
||||||
|
Nova::translations($this->frontendTranslationsPath());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function frontendTranslationsPath(): string
|
||||||
|
{
|
||||||
|
$locale = (string) $this->app->getLocale();
|
||||||
|
|
||||||
|
$paths = [
|
||||||
|
lang_path("vendor/nova-form-card/{$locale}/card.json"),
|
||||||
|
__DIR__."/../resources/lang/{$locale}/card.json",
|
||||||
|
__DIR__.'/../resources/lang/en/card.json',
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($paths as $path) {
|
||||||
|
if (is_file($path)) {
|
||||||
|
return $path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return __DIR__.'/../resources/lang/en/card.json';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function routes(): void
|
||||||
|
{
|
||||||
|
if ($this->app->routesAreCached()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Route::middleware(['nova'])
|
||||||
|
->prefix(trim((string) config('nova-form-card.route_prefix', 'nova-vendor/nova-form-card'), '/'))
|
||||||
|
->group(__DIR__.'/../routes/api.php');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard;
|
||||||
|
|
||||||
|
use Countable;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Laravel\Nova\Fields\ActionFields;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nova-compatible container for values resolved from a submitted form card.
|
||||||
|
*/
|
||||||
|
class FormFields extends ActionFields implements Countable
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed>|\Illuminate\Support\Collection<string, mixed> $values
|
||||||
|
*/
|
||||||
|
public function __construct(array|Collection $values = [], ?Collection $callbacks = null)
|
||||||
|
{
|
||||||
|
parent::__construct(collect($values), $callbacks ?? collect());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get($key, $default = null): mixed
|
||||||
|
{
|
||||||
|
if (! is_string($key)) {
|
||||||
|
return parent::get($key, $default);
|
||||||
|
}
|
||||||
|
|
||||||
|
$attributes = $this->getAttributes();
|
||||||
|
|
||||||
|
if (array_key_exists($key, $attributes)) {
|
||||||
|
return $attributes[$key];
|
||||||
|
}
|
||||||
|
|
||||||
|
$snake = Str::snake($key);
|
||||||
|
|
||||||
|
if (array_key_exists($snake, $attributes)) {
|
||||||
|
return $attributes[$snake];
|
||||||
|
}
|
||||||
|
|
||||||
|
return value($default);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function has($key): bool
|
||||||
|
{
|
||||||
|
if (! is_string($key)) {
|
||||||
|
return parent::has($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
$attributes = $this->getAttributes();
|
||||||
|
|
||||||
|
return array_key_exists($key, $attributes)
|
||||||
|
|| array_key_exists(Str::snake($key), $attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __get($key): mixed
|
||||||
|
{
|
||||||
|
return $this->get($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __isset($key): bool
|
||||||
|
{
|
||||||
|
return $this->has($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function offsetExists($offset): bool
|
||||||
|
{
|
||||||
|
return is_string($offset) && $this->has($offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function offsetGet($offset): mixed
|
||||||
|
{
|
||||||
|
return is_string($offset) ? $this->get($offset) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(): int
|
||||||
|
{
|
||||||
|
return count($this->getAttributes());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Http\Controllers;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Support\Responsable;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Exceptions\InvalidFormCardToken;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Http\Responses\FormCardResponse;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\FormCardToken;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\NovaFieldValidator;
|
||||||
|
|
||||||
|
class SubmitFormCardController
|
||||||
|
{
|
||||||
|
public function __invoke(
|
||||||
|
Request $request,
|
||||||
|
FormCardToken $tokens,
|
||||||
|
NovaFieldValidator $fields,
|
||||||
|
): Response {
|
||||||
|
$novaRequest = $this->novaRequest($request);
|
||||||
|
|
||||||
|
app()->instance(NovaRequest::class, $novaRequest);
|
||||||
|
|
||||||
|
$token = (string) $request->input('token', '');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cardClass = $tokens->resolve($token, $novaRequest);
|
||||||
|
} catch (InvalidFormCardToken) {
|
||||||
|
abort(403, __('nova-form-card::messages.cannot_submit'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$card = app($cardClass);
|
||||||
|
|
||||||
|
if (! $card instanceof FormCard) {
|
||||||
|
abort(403, __('nova-form-card::messages.cannot_submit'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $card->authorizedToSubmit($novaRequest)) {
|
||||||
|
abort(403, __('nova-form-card::messages.not_authorized_to_submit'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = $this->fieldsPayload($request);
|
||||||
|
|
||||||
|
if ($payload === null) {
|
||||||
|
return response()->json([
|
||||||
|
'message' => __('nova-form-card::messages.fields_payload_must_be_object'),
|
||||||
|
'errors' => [
|
||||||
|
'fields' => [__('nova-form-card::messages.fields_payload_must_be_object')],
|
||||||
|
],
|
||||||
|
], 422);
|
||||||
|
}
|
||||||
|
|
||||||
|
$submissionRequest = $fields->requestForPayload($novaRequest, $payload);
|
||||||
|
|
||||||
|
app()->instance(NovaRequest::class, $submissionRequest);
|
||||||
|
|
||||||
|
$cardFields = $card->fields($submissionRequest);
|
||||||
|
|
||||||
|
$validator = Validator::make(
|
||||||
|
$payload,
|
||||||
|
$fields->rules($cardFields, $submissionRequest),
|
||||||
|
[],
|
||||||
|
$fields->attributes($cardFields, $submissionRequest),
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($validator->fails()) {
|
||||||
|
return response()->json([
|
||||||
|
'message' => __('nova-form-card::messages.invalid_data'),
|
||||||
|
'errors' => $validator->errors()->toArray(),
|
||||||
|
], 422);
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $card->handle(
|
||||||
|
$fields->resolve($cardFields, $payload, $submissionRequest),
|
||||||
|
$submissionRequest,
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($result instanceof Responsable) {
|
||||||
|
return $result->toResponse($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($result instanceof Response) {
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
$response = FormCardResponse::from($result);
|
||||||
|
|
||||||
|
return response()->json($response->toArray(), $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function novaRequest(Request $request): NovaRequest
|
||||||
|
{
|
||||||
|
if ($request instanceof NovaRequest) {
|
||||||
|
return $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NovaRequest::createFrom($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>|null
|
||||||
|
*/
|
||||||
|
protected function fieldsPayload(Request $request): ?array
|
||||||
|
{
|
||||||
|
$input = $request->input('fields', []);
|
||||||
|
|
||||||
|
if (! is_array($input)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = $request->file('fields', []);
|
||||||
|
|
||||||
|
if (! is_array($files)) {
|
||||||
|
return $input;
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_replace_recursive($input, $files);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Http\Controllers;
|
||||||
|
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Laravel\Nova\Fields\FieldCollection;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Exceptions\InvalidFormCardToken;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\FormCardToken;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Support\NovaFieldSerializer;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class SyncFormCardFieldController
|
||||||
|
{
|
||||||
|
public function __invoke(
|
||||||
|
Request $request,
|
||||||
|
FormCardToken $tokens,
|
||||||
|
NovaFieldSerializer $serializer,
|
||||||
|
): JsonResponse {
|
||||||
|
$novaRequest = $this->novaRequest($request);
|
||||||
|
|
||||||
|
app()->instance('request', $novaRequest);
|
||||||
|
app()->instance(NovaRequest::class, $novaRequest);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cardClass = $tokens->resolve((string) $request->query('token', ''), $novaRequest);
|
||||||
|
} catch (InvalidFormCardToken) {
|
||||||
|
abort(Response::HTTP_FORBIDDEN, __('nova-form-card::messages.cannot_submit'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$card = app($cardClass);
|
||||||
|
|
||||||
|
if (! $card instanceof FormCard || ! $card->authorizedToSubmit($novaRequest)) {
|
||||||
|
abort(Response::HTTP_FORBIDDEN, __('nova-form-card::messages.not_authorized_to_submit'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$field = FieldCollection::make($card->fields($novaRequest))
|
||||||
|
->authorized($novaRequest)
|
||||||
|
->first(static function (object $field) use ($novaRequest): bool {
|
||||||
|
return $novaRequest->query('field') === ($field->attribute ?? null)
|
||||||
|
&& $novaRequest->query('component') === $field->dependentComponentKey();
|
||||||
|
});
|
||||||
|
|
||||||
|
abort_if($field === null, Response::HTTP_NOT_FOUND);
|
||||||
|
|
||||||
|
$field->syncDependsOn($novaRequest);
|
||||||
|
|
||||||
|
return response()->json($serializer->serializeField($field, $novaRequest));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function novaRequest(Request $request): NovaRequest
|
||||||
|
{
|
||||||
|
if ($request instanceof NovaRequest) {
|
||||||
|
return $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
$novaRequest = NovaRequest::createFrom($request);
|
||||||
|
$novaRequest->setUserResolver($request->getUserResolver());
|
||||||
|
|
||||||
|
return $novaRequest;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Http\Responses;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Support\Arrayable;
|
||||||
|
use Illuminate\Contracts\Support\Responsable;
|
||||||
|
use JsonSerializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @implements Arrayable<string, mixed>
|
||||||
|
*/
|
||||||
|
class FormCardResponse implements Arrayable, JsonSerializable, Responsable
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed>|null $redirect
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
protected string $type = 'success',
|
||||||
|
protected ?string $message = null,
|
||||||
|
protected ?array $redirect = null,
|
||||||
|
protected bool $refresh = false,
|
||||||
|
protected int $status = 200,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function success(?string $message = null): self
|
||||||
|
{
|
||||||
|
return new self('success', $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function message(string $message): self
|
||||||
|
{
|
||||||
|
return self::success($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function error(string $message, int $status = 200): self
|
||||||
|
{
|
||||||
|
return new self('error', $message, status: $status);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function redirect(string $url, bool $remote = false): self
|
||||||
|
{
|
||||||
|
return new self('redirect', redirect: [
|
||||||
|
'url' => $url,
|
||||||
|
'remote' => $remote,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $options
|
||||||
|
*/
|
||||||
|
public static function visit(string $path, array $options = []): self
|
||||||
|
{
|
||||||
|
return new self('redirect', redirect: [
|
||||||
|
'url' => $path,
|
||||||
|
'remote' => false,
|
||||||
|
'options' => $options,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function refresh(?string $message = null): self
|
||||||
|
{
|
||||||
|
return new self('refresh', $message, refresh: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
public static function fromArray(array $payload): self
|
||||||
|
{
|
||||||
|
return new self(
|
||||||
|
type: (string) ($payload['type'] ?? 'success'),
|
||||||
|
message: isset($payload['message']) ? (string) $payload['message'] : null,
|
||||||
|
redirect: isset($payload['redirect']) && is_array($payload['redirect']) ? $payload['redirect'] : null,
|
||||||
|
refresh: (bool) ($payload['refresh'] ?? false),
|
||||||
|
status: (int) ($payload['status'] ?? 200),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function from(mixed $value): self
|
||||||
|
{
|
||||||
|
if ($value instanceof self) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_array($value)) {
|
||||||
|
return self::fromArray($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_string($value)) {
|
||||||
|
return self::message($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($value === false) {
|
||||||
|
return self::error(__('nova-form-card::messages.could_not_submit'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::success();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function status(): int
|
||||||
|
{
|
||||||
|
return $this->status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return array_filter([
|
||||||
|
'type' => $this->type,
|
||||||
|
'message' => $this->message,
|
||||||
|
'redirect' => $this->redirect,
|
||||||
|
'refresh' => $this->refresh,
|
||||||
|
], static fn (mixed $value): bool => $value !== null && $value !== false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function jsonSerialize(): array
|
||||||
|
{
|
||||||
|
return $this->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toResponse($request)
|
||||||
|
{
|
||||||
|
return response()->json($this->toArray(), $this->status);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Support;
|
||||||
|
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use JsonException;
|
||||||
|
use RuntimeException;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Exceptions\InvalidFormCardToken;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
|
||||||
|
class FormCardToken
|
||||||
|
{
|
||||||
|
public function issue(FormCard $card, NovaRequest $request): string
|
||||||
|
{
|
||||||
|
$payload = $this->encode([
|
||||||
|
'class' => $card::class,
|
||||||
|
'user_id' => $this->userIdentifier($request),
|
||||||
|
'expires_at' => now()
|
||||||
|
->addMinutes((int) config('nova-form-card.token_ttl_minutes', 120))
|
||||||
|
->getTimestamp(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $payload.'.'.$this->signature($payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return class-string<FormCard>
|
||||||
|
*/
|
||||||
|
public function resolve(string $token, NovaRequest $request): string
|
||||||
|
{
|
||||||
|
if ($token === '' || ! str_contains($token, '.')) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.missing'));
|
||||||
|
}
|
||||||
|
|
||||||
|
[$payload, $signature] = explode('.', $token, 2);
|
||||||
|
|
||||||
|
if (! hash_equals($this->signature($payload), $signature)) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.invalid_signature'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = $this->decode($payload);
|
||||||
|
|
||||||
|
if (! isset($data['class']) || ! is_string($data['class'])) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.missing_card_class'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! isset($data['expires_at']) || (int) $data['expires_at'] < time()) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.expired'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($data['user_id'] ?? null) !== $this->userIdentifier($request)) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.wrong_user'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! is_subclass_of($data['class'], FormCard::class)) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.invalid_card_class'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data['class'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
protected function encode(array $payload): string
|
||||||
|
{
|
||||||
|
return rtrim(strtr(base64_encode(json_encode($payload, JSON_THROW_ON_ERROR)), '+/', '-_'), '=');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected function decode(string $payload): array
|
||||||
|
{
|
||||||
|
$payload .= str_repeat('=', (4 - strlen($payload) % 4) % 4);
|
||||||
|
$json = base64_decode(strtr($payload, '-_', '+/'), true);
|
||||||
|
|
||||||
|
if ($json === false) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.invalid_payload'));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$decoded = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
|
||||||
|
} catch (JsonException $exception) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.invalid_payload'), previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! is_array($decoded)) {
|
||||||
|
throw new InvalidFormCardToken(__('nova-form-card::messages.token.invalid_payload'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function signature(string $payload): string
|
||||||
|
{
|
||||||
|
return hash_hmac('sha256', $payload, $this->key());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function key(): string
|
||||||
|
{
|
||||||
|
$key = (string) config('app.key');
|
||||||
|
|
||||||
|
if ($key === '') {
|
||||||
|
throw new RuntimeException(__('nova-form-card::messages.app_key_required'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($key, 'base64:')) {
|
||||||
|
$decoded = base64_decode(substr($key, 7), true);
|
||||||
|
|
||||||
|
if ($decoded !== false) {
|
||||||
|
return $decoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function userIdentifier(NovaRequest $request): ?string
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
if ($user === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (string) $user->getAuthIdentifier();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Support;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Support\Arrayable;
|
||||||
|
use JsonSerializable;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use ReflectionClass;
|
||||||
|
use ReflectionFunction;
|
||||||
|
|
||||||
|
class NovaFieldIntrospector
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(object $field): array
|
||||||
|
{
|
||||||
|
if ($field instanceof JsonSerializable) {
|
||||||
|
$serialized = $field->jsonSerialize();
|
||||||
|
|
||||||
|
if (is_array($serialized)) {
|
||||||
|
return $serialized;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($field instanceof Arrayable) {
|
||||||
|
return $field->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function property(object $object, string $property, mixed $default = null): mixed
|
||||||
|
{
|
||||||
|
$class = new ReflectionClass($object);
|
||||||
|
|
||||||
|
while ($class) {
|
||||||
|
if ($class->hasProperty($property)) {
|
||||||
|
$reflection = $class->getProperty($property);
|
||||||
|
$reflection->setAccessible(true);
|
||||||
|
|
||||||
|
return $reflection->getValue($object);
|
||||||
|
}
|
||||||
|
|
||||||
|
$class = $class->getParentClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function evaluate(mixed $value, NovaRequest $request, object $field): mixed
|
||||||
|
{
|
||||||
|
if (! $value instanceof \Closure) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reflection = new ReflectionFunction($value);
|
||||||
|
|
||||||
|
return $reflection->getNumberOfParameters() === 0
|
||||||
|
? $value->call($field)
|
||||||
|
: $value->call($field, $request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Support;
|
||||||
|
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use Traversable;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Exceptions\UnsupportedFieldException;
|
||||||
|
|
||||||
|
class NovaFieldSerializer
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
protected ?NovaFieldIntrospector $introspector = null,
|
||||||
|
protected ?NovaFieldValidator $validator = null,
|
||||||
|
) {
|
||||||
|
$this->introspector ??= new NovaFieldIntrospector();
|
||||||
|
$this->validator ??= new NovaFieldValidator($this->introspector);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
* @return array<int, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function serialize(array $fields, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return $this->validator
|
||||||
|
->fieldsForSerialization($fields, $request)
|
||||||
|
->map(fn (object $field): array => $this->serializeField($field, $request))
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function serializeField(object $field, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$type = SupportedField::typeFor($field);
|
||||||
|
|
||||||
|
if ($type === null) {
|
||||||
|
throw UnsupportedFieldException::forField($field);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->prepareFieldForSerialization($field, $request);
|
||||||
|
|
||||||
|
$raw = $this->introspector->toArray($field);
|
||||||
|
$attribute = $this->validator->attributeForField($field) ?? (string) ($raw['name'] ?? 'field');
|
||||||
|
$value = $raw['value'] ?? $this->defaultValue($field, $request);
|
||||||
|
|
||||||
|
$raw['formCardType'] = $type;
|
||||||
|
$raw['type'] = $this->fieldTypeForNovaComponent($type, $raw, $field);
|
||||||
|
$raw['displayOnly'] = SupportedField::isDisplayOnly($field);
|
||||||
|
$raw['name'] = (string) ($raw['name'] ?? $attribute);
|
||||||
|
$raw['attribute'] = $attribute;
|
||||||
|
$raw['value'] = $this->initialValue($type, $value);
|
||||||
|
$raw['required'] = (bool) ($raw['required'] ?? false)
|
||||||
|
|| $this->validator->fieldIsRequired($field, $request);
|
||||||
|
$raw['readonly'] = (bool) ($raw['readonly'] ?? $this->resolvedProperty($field, 'readonlyCallback', $request, false));
|
||||||
|
$raw['visible'] = (bool) ($raw['visible'] ?? true);
|
||||||
|
$raw['withLabel'] = (bool) ($raw['withLabel'] ?? true);
|
||||||
|
$raw['validationKey'] = (string) ($raw['validationKey'] ?? $attribute);
|
||||||
|
$raw['uniqueKey'] = (string) ($raw['uniqueKey'] ?? "{$attribute}-form-card-field");
|
||||||
|
|
||||||
|
return $raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function prepareFieldForSerialization(object $field, NovaRequest $request): void
|
||||||
|
{
|
||||||
|
if (! SupportedField::isDisplayOnly($field) || ! method_exists($field, 'resolveForDisplay')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$field->resolveForDisplay($this->displayResourceFor($field, $request));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected function displayResourceFor(object $field, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$resource = [];
|
||||||
|
|
||||||
|
foreach ($this->fieldsUsedForDisplayResource($field) as $displayField) {
|
||||||
|
$attribute = $this->rawAttributeFor($displayField);
|
||||||
|
|
||||||
|
if ($attribute === null || $attribute === 'ComputedField') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$resource[$attribute] = $this->displayValueFor($displayField, $request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, object>
|
||||||
|
*/
|
||||||
|
protected function fieldsUsedForDisplayResource(object $field): array
|
||||||
|
{
|
||||||
|
$fields = [$field];
|
||||||
|
$lines = $this->introspector->property($field, 'lines');
|
||||||
|
|
||||||
|
if ($lines instanceof Traversable) {
|
||||||
|
$lines = iterator_to_array($lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_array($lines)) {
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
if (is_object($line)) {
|
||||||
|
$fields[] = $line;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function displayValueFor(object $field, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
$value = $this->introspector->property($field, 'value');
|
||||||
|
|
||||||
|
return $value ?? $this->defaultValue($field, $request);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function rawAttributeFor(object $field): ?string
|
||||||
|
{
|
||||||
|
$attribute = $this->introspector->property($field, 'attribute');
|
||||||
|
|
||||||
|
return is_string($attribute) && $attribute !== '' ? $attribute : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $raw
|
||||||
|
*/
|
||||||
|
protected function fieldTypeForNovaComponent(string $type, array $raw, object $field): string
|
||||||
|
{
|
||||||
|
if ($type === 'password-confirmation') {
|
||||||
|
return 'password';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (SupportedField::isDisplayOnly($field) && is_string($raw['type'] ?? null)) {
|
||||||
|
return $raw['type'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $type;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function initialValue(string $type, mixed $value): mixed
|
||||||
|
{
|
||||||
|
return match ($type) {
|
||||||
|
'boolean' => (bool) $value,
|
||||||
|
'number' => $value,
|
||||||
|
default => $value ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function defaultValue(object $field, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
if (method_exists($field, 'resolveDefaultValue')) {
|
||||||
|
$value = $field->resolveDefaultValue($this->defaultResolvingRequest($request));
|
||||||
|
|
||||||
|
if ($value !== null) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->resolvedProperty($field, 'defaultCallback', $request);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function defaultResolvingRequest(NovaRequest $request): NovaRequest
|
||||||
|
{
|
||||||
|
$defaultRequest = NovaRequest::createFrom($request);
|
||||||
|
$defaultRequest->setUserResolver($request->getUserResolver());
|
||||||
|
$defaultRequest->merge([
|
||||||
|
'editing' => 'true',
|
||||||
|
'editMode' => 'create',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $defaultRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolvedProperty(object $field, string $property, NovaRequest $request, mixed $default = null): mixed
|
||||||
|
{
|
||||||
|
$value = $this->introspector->property($field, $property, $default);
|
||||||
|
|
||||||
|
return $this->introspector->evaluate($value, $request, $field);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Support;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Contracts\Support\Arrayable;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Laravel\Nova\Fields\FieldCollection;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use Laravel\Nova\Support\Fluent;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
use ReflectionFunction;
|
||||||
|
|
||||||
|
class NovaFieldValidator
|
||||||
|
{
|
||||||
|
public function __construct(protected ?NovaFieldIntrospector $introspector = null)
|
||||||
|
{
|
||||||
|
$this->introspector ??= new NovaFieldIntrospector();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
* @return array<string, array<int, mixed>>
|
||||||
|
*/
|
||||||
|
public function rules(array $fields, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$rules = [];
|
||||||
|
|
||||||
|
foreach ($this->fieldsForSubmission($fields, $request) as $field) {
|
||||||
|
foreach ($this->ruleMapForField($field, $request) as $attribute => $fieldRules) {
|
||||||
|
if (! is_string($attribute) || $attribute === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized = $this->normalizeRules($fieldRules, $attribute, $request);
|
||||||
|
|
||||||
|
if ($normalized !== []) {
|
||||||
|
$rules[$attribute] = array_merge($rules[$attribute] ?? [], $normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function attributes(array $fields, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$attributes = [];
|
||||||
|
|
||||||
|
foreach ($this->fieldsForSubmission($fields, $request) as $field) {
|
||||||
|
if (method_exists($field, 'getValidationAttributeNames')) {
|
||||||
|
$attributes = array_merge($attributes, $field->getValidationAttributeNames($request));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$attribute = $this->attributeForField($field);
|
||||||
|
|
||||||
|
if ($attribute === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$attributes[$attribute] = (string) ($this->introspector->toArray($field)['name']
|
||||||
|
?? $this->introspector->property($field, 'name', $attribute));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $attributes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function values(array $fields, array $payload, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return $this->resolve($fields, $payload, $request)->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
public function resolve(array $fields, array $payload, NovaRequest $request): FormFields
|
||||||
|
{
|
||||||
|
$submissionRequest = $this->requestForPayload($request, $payload);
|
||||||
|
$resolved = new Fluent;
|
||||||
|
$callbacks = $this->fieldsForSubmission($fields, $submissionRequest)
|
||||||
|
->mapWithKeys(fn (object $field): array => [
|
||||||
|
$field->attribute => $field->fillForAction($submissionRequest, $resolved),
|
||||||
|
])
|
||||||
|
->filter(static fn (mixed $callback): bool => is_callable($callback));
|
||||||
|
|
||||||
|
return new FormFields($resolved->getAttributes(), $callbacks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
*/
|
||||||
|
public function fieldsForSerialization(array $fields, NovaRequest $request): FieldCollection
|
||||||
|
{
|
||||||
|
$collection = FieldCollection::make($fields)
|
||||||
|
->authorized($request);
|
||||||
|
|
||||||
|
if (method_exists($collection, 'applyDependsOnWithDefaultValues')) {
|
||||||
|
$collection = $collection->applyDependsOnWithDefaultValues($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $collection->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, object> $fields
|
||||||
|
*/
|
||||||
|
public function fieldsForSubmission(array $fields, NovaRequest $request): FieldCollection
|
||||||
|
{
|
||||||
|
return FieldCollection::make($fields)
|
||||||
|
->authorized($request)
|
||||||
|
->applyDependsOn($request)
|
||||||
|
->reject(static fn (object $field): bool => SupportedField::isDisplayOnly($field))
|
||||||
|
->withoutReadonly($request)
|
||||||
|
->withoutUnfillable()
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
public function requestForPayload(NovaRequest $request, array $payload): NovaRequest
|
||||||
|
{
|
||||||
|
$submissionRequest = NovaRequest::createFrom($request);
|
||||||
|
$submissionRequest->setUserResolver($request->getUserResolver());
|
||||||
|
$submissionRequest->merge($payload);
|
||||||
|
$submissionRequest->merge([
|
||||||
|
'editing' => 'true',
|
||||||
|
'editMode' => 'create',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $submissionRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function attributeForField(object $field): ?string
|
||||||
|
{
|
||||||
|
$raw = $this->introspector->toArray($field);
|
||||||
|
$attribute = $raw['attribute'] ?? $this->introspector->property($field, 'attribute');
|
||||||
|
|
||||||
|
return is_string($attribute) && $attribute !== '' ? $attribute : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, mixed>
|
||||||
|
*/
|
||||||
|
public function rulesForField(object $field, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$attribute = $this->attributeForField($field);
|
||||||
|
|
||||||
|
if ($attribute === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->normalizeRules(
|
||||||
|
$this->ruleMapForField($field, $request)[$attribute] ?? [],
|
||||||
|
$attribute,
|
||||||
|
$request
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fieldIsRequired(object $field, NovaRequest $request): bool
|
||||||
|
{
|
||||||
|
foreach ($this->rulesForField($field, $request) as $rule) {
|
||||||
|
if (! is_string($rule)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (explode('|', $rule) as $part) {
|
||||||
|
if (strtolower(trim(strtok($part, ':'))) === 'required') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected function ruleMapForField(object $field, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
if (method_exists($field, 'getCreationRules')) {
|
||||||
|
return $this->normalizeRuleMap($field->getCreationRules($request), $field, $request);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method_exists($field, 'getRules')) {
|
||||||
|
return $this->normalizeRuleMap($field->getRules($request), $field, $request);
|
||||||
|
}
|
||||||
|
|
||||||
|
$attribute = $this->attributeForField($field);
|
||||||
|
|
||||||
|
if ($attribute === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
$attribute => $this->introspector->property($field, 'rules', []),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected function normalizeRuleMap(mixed $rules, object $field, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$rules = $this->evaluateRuleCallback($rules, $request);
|
||||||
|
|
||||||
|
if ($rules instanceof Arrayable) {
|
||||||
|
$rules = $rules->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($rules instanceof Collection) {
|
||||||
|
$rules = $rules->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($rules instanceof \Traversable) {
|
||||||
|
$rules = iterator_to_array($rules);
|
||||||
|
}
|
||||||
|
|
||||||
|
$attribute = $this->attributeForField($field);
|
||||||
|
|
||||||
|
if (! is_array($rules)) {
|
||||||
|
return $attribute === null ? [] : [$attribute => $rules];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (array_is_list($rules)) {
|
||||||
|
return $attribute === null ? [] : [$attribute => $rules];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, mixed>
|
||||||
|
*/
|
||||||
|
protected function normalizeRules(mixed $rules, string $attribute, NovaRequest $request): array
|
||||||
|
{
|
||||||
|
$rules = $this->evaluateRuleCallback($rules, $request);
|
||||||
|
|
||||||
|
if ($rules instanceof Arrayable) {
|
||||||
|
$rules = $rules->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($rules instanceof \Traversable) {
|
||||||
|
$rules = iterator_to_array($rules);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_array($rules) && array_key_exists($attribute, $rules)) {
|
||||||
|
$rules = $rules[$attribute];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($rules === null || $rules === []) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! is_array($rules)) {
|
||||||
|
return [$rules];
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized = [];
|
||||||
|
|
||||||
|
foreach ($rules as $rule) {
|
||||||
|
$rule = $this->evaluateRuleCallback($rule, $request);
|
||||||
|
|
||||||
|
if ($rule instanceof Arrayable) {
|
||||||
|
$rule = $rule->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_array($rule)) {
|
||||||
|
array_push($normalized, ...$this->normalizeRules($rule, $attribute, $request));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($rule !== null) {
|
||||||
|
$normalized[] = $rule;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function evaluateRuleCallback(mixed $rule, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
if (! $rule instanceof Closure) {
|
||||||
|
return $rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reflection = new ReflectionFunction($rule);
|
||||||
|
|
||||||
|
if ($reflection->getNumberOfParameters() <= 1) {
|
||||||
|
return $rule($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rule;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Support;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Audio;
|
||||||
|
use Laravel\Nova\Fields\Avatar;
|
||||||
|
use Laravel\Nova\Fields\Badge;
|
||||||
|
use Laravel\Nova\Fields\Boolean;
|
||||||
|
use Laravel\Nova\Fields\BooleanGroup;
|
||||||
|
use Laravel\Nova\Fields\Code;
|
||||||
|
use Laravel\Nova\Fields\Color;
|
||||||
|
use Laravel\Nova\Fields\Country;
|
||||||
|
use Laravel\Nova\Fields\Currency;
|
||||||
|
use Laravel\Nova\Fields\Date;
|
||||||
|
use Laravel\Nova\Fields\DateTime;
|
||||||
|
use Laravel\Nova\Fields\Email;
|
||||||
|
use Laravel\Nova\Fields\File;
|
||||||
|
use Laravel\Nova\Fields\Gravatar;
|
||||||
|
use Laravel\Nova\Fields\Heading;
|
||||||
|
use Laravel\Nova\Fields\Hidden;
|
||||||
|
use Laravel\Nova\Fields\ID;
|
||||||
|
use Laravel\Nova\Fields\Image;
|
||||||
|
use Laravel\Nova\Fields\KeyValue;
|
||||||
|
use Laravel\Nova\Fields\Line;
|
||||||
|
use Laravel\Nova\Fields\MultiSelect;
|
||||||
|
use Laravel\Nova\Fields\Number;
|
||||||
|
use Laravel\Nova\Fields\Password;
|
||||||
|
use Laravel\Nova\Fields\PasswordConfirmation;
|
||||||
|
use Laravel\Nova\Fields\Select;
|
||||||
|
use Laravel\Nova\Fields\Slug;
|
||||||
|
use Laravel\Nova\Fields\Sparkline;
|
||||||
|
use Laravel\Nova\Fields\Stack;
|
||||||
|
use Laravel\Nova\Fields\Status;
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Fields\Textarea;
|
||||||
|
use Laravel\Nova\Fields\Timezone;
|
||||||
|
use Laravel\Nova\Fields\Token;
|
||||||
|
use Laravel\Nova\Fields\UiAvatar;
|
||||||
|
use Laravel\Nova\Fields\Unfillable;
|
||||||
|
use Laravel\Nova\Fields\URL;
|
||||||
|
|
||||||
|
class SupportedField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array<class-string, string>
|
||||||
|
*/
|
||||||
|
protected const TYPES = [
|
||||||
|
PasswordConfirmation::class => 'password-confirmation',
|
||||||
|
KeyValue::class => 'key-value',
|
||||||
|
BooleanGroup::class => 'boolean-group',
|
||||||
|
MultiSelect::class => 'multi-select',
|
||||||
|
DateTime::class => 'date-time',
|
||||||
|
Currency::class => 'currency',
|
||||||
|
Textarea::class => 'textarea',
|
||||||
|
Timezone::class => 'timezone',
|
||||||
|
Country::class => 'country',
|
||||||
|
Sparkline::class => 'sparkline',
|
||||||
|
Gravatar::class => 'gravatar',
|
||||||
|
UiAvatar::class => 'ui-avatar',
|
||||||
|
Heading::class => 'heading',
|
||||||
|
Status::class => 'status',
|
||||||
|
Badge::class => 'badge',
|
||||||
|
Stack::class => 'stack',
|
||||||
|
Line::class => 'line',
|
||||||
|
Select::class => 'select',
|
||||||
|
Boolean::class => 'boolean',
|
||||||
|
Number::class => 'number',
|
||||||
|
Date::class => 'date',
|
||||||
|
Avatar::class => 'avatar',
|
||||||
|
Image::class => 'image',
|
||||||
|
Audio::class => 'audio',
|
||||||
|
File::class => 'file',
|
||||||
|
Password::class => 'password',
|
||||||
|
Hidden::class => 'hidden',
|
||||||
|
ID::class => 'id',
|
||||||
|
Email::class => 'email',
|
||||||
|
URL::class => 'url',
|
||||||
|
Slug::class => 'slug',
|
||||||
|
Token::class => 'token',
|
||||||
|
Color::class => 'color',
|
||||||
|
Code::class => 'code',
|
||||||
|
Text::class => 'text',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<class-string, true>
|
||||||
|
*/
|
||||||
|
protected const DISPLAY_ONLY = [
|
||||||
|
Badge::class => true,
|
||||||
|
Gravatar::class => true,
|
||||||
|
Heading::class => true,
|
||||||
|
Line::class => true,
|
||||||
|
Sparkline::class => true,
|
||||||
|
Stack::class => true,
|
||||||
|
Status::class => true,
|
||||||
|
UiAvatar::class => true,
|
||||||
|
];
|
||||||
|
|
||||||
|
public static function typeFor(object $field): ?string
|
||||||
|
{
|
||||||
|
if ($field instanceof Unfillable && ! self::isDisplayOnly($field)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (self::TYPES as $class => $type) {
|
||||||
|
if ($field instanceof $class) {
|
||||||
|
return $type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function isSupported(object $field): bool
|
||||||
|
{
|
||||||
|
return self::typeFor($field) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function isDisplayOnly(object $field): bool
|
||||||
|
{
|
||||||
|
foreach (self::DISPLAY_ONLY as $class => $supported) {
|
||||||
|
if ($field instanceof $class) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public static function names(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
__('nova-form-card::messages.fields.text'),
|
||||||
|
__('nova-form-card::messages.fields.textarea'),
|
||||||
|
__('nova-form-card::messages.fields.select'),
|
||||||
|
__('nova-form-card::messages.fields.boolean'),
|
||||||
|
__('nova-form-card::messages.fields.number'),
|
||||||
|
__('nova-form-card::messages.fields.date'),
|
||||||
|
__('nova-form-card::messages.fields.file'),
|
||||||
|
__('nova-form-card::messages.fields.image'),
|
||||||
|
__('nova-form-card::messages.fields.audio'),
|
||||||
|
__('nova-form-card::messages.fields.avatar'),
|
||||||
|
__('nova-form-card::messages.fields.email'),
|
||||||
|
__('nova-form-card::messages.fields.url'),
|
||||||
|
__('nova-form-card::messages.fields.password'),
|
||||||
|
__('nova-form-card::messages.fields.hidden'),
|
||||||
|
__('nova-form-card::messages.fields.id'),
|
||||||
|
__('nova-form-card::messages.fields.date_time'),
|
||||||
|
__('nova-form-card::messages.fields.currency'),
|
||||||
|
__('nova-form-card::messages.fields.color'),
|
||||||
|
__('nova-form-card::messages.fields.code'),
|
||||||
|
__('nova-form-card::messages.fields.country'),
|
||||||
|
__('nova-form-card::messages.fields.timezone'),
|
||||||
|
__('nova-form-card::messages.fields.multi_select'),
|
||||||
|
__('nova-form-card::messages.fields.boolean_group'),
|
||||||
|
__('nova-form-card::messages.fields.key_value'),
|
||||||
|
__('nova-form-card::messages.fields.slug'),
|
||||||
|
__('nova-form-card::messages.fields.token'),
|
||||||
|
__('nova-form-card::messages.fields.badge'),
|
||||||
|
__('nova-form-card::messages.fields.heading'),
|
||||||
|
__('nova-form-card::messages.fields.line'),
|
||||||
|
__('nova-form-card::messages.fields.stack'),
|
||||||
|
__('nova-form-card::messages.fields.sparkline'),
|
||||||
|
__('nova-form-card::messages.fields.status'),
|
||||||
|
__('nova-form-card::messages.fields.gravatar'),
|
||||||
|
__('nova-form-card::messages.fields.ui_avatar'),
|
||||||
|
__('nova-form-card::messages.fields.password_confirmation'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\SerializableCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\DependentCard;
|
||||||
|
|
||||||
|
it('serializes supported Nova fields for the card component', function (): void {
|
||||||
|
$serialized = $this->serializeFormCard(new SerializableCard());
|
||||||
|
$form = $serialized['formCard'];
|
||||||
|
|
||||||
|
expect($form['title'])->toBe('Invite User')
|
||||||
|
->and($form['endpoint'])->toBe('/nova-vendor/nova-form-card/submit')
|
||||||
|
->and($form['submitText'])->toBe('Submit')
|
||||||
|
->and($form['canSubmit'])->toBeTrue()
|
||||||
|
->and($form['token'])->toBeString()->not->toBeEmpty();
|
||||||
|
|
||||||
|
$types = collect($form['fields'])->pluck('formCardType', 'attribute')->all();
|
||||||
|
$components = collect($form['fields'])->pluck('component', 'attribute')->all();
|
||||||
|
|
||||||
|
expect($types)->not->toHaveKey('hidden_secret');
|
||||||
|
|
||||||
|
expect($types)->toMatchArray([
|
||||||
|
'email' => 'text',
|
||||||
|
'message' => 'textarea',
|
||||||
|
'role' => 'select',
|
||||||
|
'active' => 'boolean',
|
||||||
|
'seats' => 'number',
|
||||||
|
'starts_at' => 'date',
|
||||||
|
'starts_at_time' => 'date-time',
|
||||||
|
'work_email' => 'email',
|
||||||
|
'website' => 'url',
|
||||||
|
'password' => 'password',
|
||||||
|
'password_confirmation' => 'password-confirmation',
|
||||||
|
'tracking_code' => 'hidden',
|
||||||
|
'record_id' => 'id',
|
||||||
|
'price' => 'currency',
|
||||||
|
'brand_color' => 'color',
|
||||||
|
'payload' => 'code',
|
||||||
|
'country' => 'country',
|
||||||
|
'timezone' => 'timezone',
|
||||||
|
'tags' => 'multi-select',
|
||||||
|
'permissions' => 'boolean-group',
|
||||||
|
'metadata' => 'key-value',
|
||||||
|
'slug' => 'slug',
|
||||||
|
'api_token' => 'token',
|
||||||
|
'attachment' => 'file',
|
||||||
|
'avatar' => 'image',
|
||||||
|
'profile_photo' => 'avatar',
|
||||||
|
'voice_note' => 'audio',
|
||||||
|
'invite_summary' => 'heading',
|
||||||
|
'queue_label' => 'line',
|
||||||
|
'invite_stats' => 'stack',
|
||||||
|
'invite_trend' => 'sparkline',
|
||||||
|
'health' => 'badge',
|
||||||
|
'import_status' => 'status',
|
||||||
|
'sender_email' => 'gravatar',
|
||||||
|
'sender_name' => 'ui-avatar',
|
||||||
|
])->and($components)->toMatchArray([
|
||||||
|
'email' => 'text-field',
|
||||||
|
'message' => 'textarea-field',
|
||||||
|
'role' => 'select-field',
|
||||||
|
'active' => 'boolean-field',
|
||||||
|
'seats' => 'text-field',
|
||||||
|
'starts_at' => 'date-field',
|
||||||
|
'starts_at_time' => 'date-time-field',
|
||||||
|
'work_email' => 'email-field',
|
||||||
|
'website' => 'url-field',
|
||||||
|
'password' => 'password-field',
|
||||||
|
'password_confirmation' => 'password-field',
|
||||||
|
'tracking_code' => 'hidden-field',
|
||||||
|
'record_id' => 'id-field',
|
||||||
|
'price' => 'currency-field',
|
||||||
|
'brand_color' => 'color-field',
|
||||||
|
'payload' => 'code-field',
|
||||||
|
'country' => 'select-field',
|
||||||
|
'timezone' => 'select-field',
|
||||||
|
'tags' => 'multi-select-field',
|
||||||
|
'permissions' => 'boolean-group-field',
|
||||||
|
'metadata' => 'key-value-field',
|
||||||
|
'slug' => 'slug-field',
|
||||||
|
'api_token' => 'text-field',
|
||||||
|
'attachment' => 'file-field',
|
||||||
|
'avatar' => 'file-field',
|
||||||
|
'profile_photo' => 'file-field',
|
||||||
|
'voice_note' => 'audio-field',
|
||||||
|
'invite_summary' => 'heading-field',
|
||||||
|
'queue_label' => 'line-field',
|
||||||
|
'invite_stats' => 'stack-field',
|
||||||
|
'invite_trend' => 'sparkline-field',
|
||||||
|
'health' => 'badge-field',
|
||||||
|
'import_status' => 'status-field',
|
||||||
|
'sender_email' => 'file-field',
|
||||||
|
'sender_name' => 'file-field',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$displayOnly = collect($form['fields'])->pluck('displayOnly', 'attribute')->all();
|
||||||
|
|
||||||
|
expect($displayOnly)->toMatchArray([
|
||||||
|
'password' => false,
|
||||||
|
'password_confirmation' => false,
|
||||||
|
'invite_summary' => true,
|
||||||
|
'queue_label' => true,
|
||||||
|
'invite_stats' => true,
|
||||||
|
'invite_trend' => true,
|
||||||
|
'health' => true,
|
||||||
|
'import_status' => true,
|
||||||
|
'sender_email' => true,
|
||||||
|
'sender_name' => true,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$email = collect($form['fields'])->firstWhere('attribute', 'email');
|
||||||
|
$role = collect($form['fields'])->firstWhere('attribute', 'role');
|
||||||
|
$passwordConfirmation = collect($form['fields'])->firstWhere('attribute', 'password_confirmation');
|
||||||
|
$line = collect($form['fields'])->firstWhere('attribute', 'queue_label');
|
||||||
|
$badge = collect($form['fields'])->firstWhere('attribute', 'health');
|
||||||
|
$status = collect($form['fields'])->firstWhere('attribute', 'import_status');
|
||||||
|
$stack = collect($form['fields'])->firstWhere('attribute', 'invite_stats');
|
||||||
|
|
||||||
|
expect($email['required'])->toBeTrue()
|
||||||
|
->and($email['value'])->toBe('taylor@example.com')
|
||||||
|
->and($role['options'])->toContain([
|
||||||
|
'label' => 'Admin',
|
||||||
|
'value' => 'admin',
|
||||||
|
])
|
||||||
|
->and($badge['label'])->toBe('OK')
|
||||||
|
->and($passwordConfirmation['type'])->toBe('password')
|
||||||
|
->and($line['type'])->toBe('line')
|
||||||
|
->and($status['type'])->toBe('success')
|
||||||
|
->and($stack['lines'])->toHaveCount(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes and syncs Nova dependent fields', function (): void {
|
||||||
|
$serialized = $this->serializeFormCard(new DependentCard());
|
||||||
|
$form = $serialized['formCard'];
|
||||||
|
$email = collect($form['fields'])->firstWhere('attribute', 'email');
|
||||||
|
|
||||||
|
expect($form['syncEndpoint'])->toBe('/nova-vendor/nova-form-card/sync')
|
||||||
|
->and($email['visible'])->toBeFalse()
|
||||||
|
->and($email['dependsOn'])->toHaveKey('role')
|
||||||
|
->and($email['dependentComponentKey'])->toBeString()->not->toBeEmpty();
|
||||||
|
|
||||||
|
$this->patchJson($form['syncEndpoint'].'?'.http_build_query([
|
||||||
|
'token' => $form['token'],
|
||||||
|
'editing' => 'true',
|
||||||
|
'editMode' => 'create',
|
||||||
|
'field' => 'email',
|
||||||
|
'component' => $email['dependentComponentKey'],
|
||||||
|
]), [
|
||||||
|
'email' => '',
|
||||||
|
'role' => 'admin',
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJson([
|
||||||
|
'attribute' => 'email',
|
||||||
|
'visible' => true,
|
||||||
|
'type' => 'text',
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\AdditionalFieldsCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\CreationRulesCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\FailingCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\FileUploadCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\SuccessfulCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\Fixtures\UnauthorizedCard;
|
||||||
|
|
||||||
|
beforeEach(function (): void {
|
||||||
|
SuccessfulCard::$handled = [];
|
||||||
|
FileUploadCard::$handled = [];
|
||||||
|
AdditionalFieldsCard::$handled = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects unauthorized form card submissions', function (): void {
|
||||||
|
$token = $this->tokenFor(new UnauthorizedCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'email' => 'taylor@example.com',
|
||||||
|
],
|
||||||
|
])->assertForbidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates submitted values using Nova field rules', function (): void {
|
||||||
|
$token = $this->tokenFor(new SuccessfulCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'email' => 'not-an-email',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertStatus(422)
|
||||||
|
->assertJsonValidationErrors(['email']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates submitted values using Nova creation rules', function (): void {
|
||||||
|
$token = $this->tokenFor(new CreationRulesCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'email' => 'taylor@example.com',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertStatus(422)
|
||||||
|
->assertJsonValidationErrors(['invite_code'])
|
||||||
|
->assertJsonMissingValidationErrors(['hidden_secret']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores hidden fields during submit validation', function (): void {
|
||||||
|
$token = $this->tokenFor(new CreationRulesCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'email' => 'taylor@example.com',
|
||||||
|
'invite_code' => 'NOVA',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJson([
|
||||||
|
'type' => 'success',
|
||||||
|
'message' => 'Created.',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes validated field values to handle and returns a success response', function (): void {
|
||||||
|
$token = $this->tokenFor(new SuccessfulCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'email' => 'taylor@example.com',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJson([
|
||||||
|
'type' => 'success',
|
||||||
|
'message' => 'Invitation sent.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(SuccessfulCard::$handled)->toBe([
|
||||||
|
'email' => 'taylor@example.com',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes uploaded file fields to handle', function (): void {
|
||||||
|
$token = $this->tokenFor(new FileUploadCard());
|
||||||
|
|
||||||
|
$this->post('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'attachment' => UploadedFile::fake()->create('terms.pdf', 12, 'application/pdf'),
|
||||||
|
'avatar' => UploadedFile::fake()->image('avatar.jpg'),
|
||||||
|
'voice_note' => UploadedFile::fake()->create('voice.mp3', 12, 'audio/mpeg'),
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJson([
|
||||||
|
'type' => 'success',
|
||||||
|
'message' => 'Files received.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(FileUploadCard::$handled)->toBe([
|
||||||
|
'attachment' => 'terms.pdf',
|
||||||
|
'avatar' => 'avatar.jpg',
|
||||||
|
'voice_note' => 'voice.mp3',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes additional supported field values to handle', function (): void {
|
||||||
|
$token = $this->tokenFor(new AdditionalFieldsCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'work_email' => 'person@example.com',
|
||||||
|
'website' => 'https://example.com',
|
||||||
|
'secret' => 'super-secret',
|
||||||
|
'secret_confirmation' => 'super-secret',
|
||||||
|
'tracking_code' => 'abc123',
|
||||||
|
'record_id' => '123',
|
||||||
|
'starts_at_time' => '2026-07-10T10:30:00',
|
||||||
|
'price' => '12.34',
|
||||||
|
'brand_color' => '#ff0000',
|
||||||
|
'payload' => '{"enabled":true}',
|
||||||
|
'country' => 'IR',
|
||||||
|
'timezone' => 'Asia/Tehran',
|
||||||
|
'tags' => '["news","events"]',
|
||||||
|
'permissions' => '{"read":true,"write":false}',
|
||||||
|
'metadata' => '{"source":"nova"}',
|
||||||
|
'slug' => 'person-example',
|
||||||
|
'api_token' => 'secret-token',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJson([
|
||||||
|
'type' => 'success',
|
||||||
|
'message' => 'Additional fields received.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(AdditionalFieldsCard::$handled)->toMatchArray([
|
||||||
|
'work_email' => 'person@example.com',
|
||||||
|
'website' => 'https://example.com',
|
||||||
|
'tracking_code' => 'abc123',
|
||||||
|
'record_id' => '123',
|
||||||
|
'starts_at_time' => '2026-07-10T10:30:00',
|
||||||
|
'price' => '12.34',
|
||||||
|
'brand_color' => '#ff0000',
|
||||||
|
'payload' => ['enabled' => true],
|
||||||
|
'country' => 'IR',
|
||||||
|
'timezone' => 'Asia/Tehran',
|
||||||
|
'tags' => ['news', 'events'],
|
||||||
|
'permissions' => ['read' => true, 'write' => false],
|
||||||
|
'metadata' => ['source' => 'nova'],
|
||||||
|
'slug' => 'person-example',
|
||||||
|
'api_token' => 'secret-token',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(Hash::check('super-secret', AdditionalFieldsCard::$handled['secret']))->toBeTrue()
|
||||||
|
->and(AdditionalFieldsCard::$handled)->not->toHaveKey('secret_confirmation');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates password confirmation fields', function (): void {
|
||||||
|
$token = $this->tokenFor(new AdditionalFieldsCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'work_email' => 'person@example.com',
|
||||||
|
'website' => 'https://example.com',
|
||||||
|
'secret' => 'super-secret',
|
||||||
|
'secret_confirmation' => 'different-secret',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertStatus(422)
|
||||||
|
->assertJsonValidationErrors(['secret_confirmation']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns structured error responses from handle', function (): void {
|
||||||
|
$token = $this->tokenFor(new FailingCard());
|
||||||
|
|
||||||
|
$this->postJson('/nova-vendor/nova-form-card/submit', [
|
||||||
|
'token' => $token,
|
||||||
|
'fields' => [
|
||||||
|
'email' => 'taylor@example.com',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJson([
|
||||||
|
'type' => 'error',
|
||||||
|
'message' => 'No invitation was sent.',
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\BooleanGroup;
|
||||||
|
use Laravel\Nova\Fields\Code;
|
||||||
|
use Laravel\Nova\Fields\Color;
|
||||||
|
use Laravel\Nova\Fields\Country;
|
||||||
|
use Laravel\Nova\Fields\Currency;
|
||||||
|
use Laravel\Nova\Fields\DateTime;
|
||||||
|
use Laravel\Nova\Fields\Email;
|
||||||
|
use Laravel\Nova\Fields\Hidden;
|
||||||
|
use Laravel\Nova\Fields\ID;
|
||||||
|
use Laravel\Nova\Fields\KeyValue;
|
||||||
|
use Laravel\Nova\Fields\MultiSelect;
|
||||||
|
use Laravel\Nova\Fields\Password;
|
||||||
|
use Laravel\Nova\Fields\PasswordConfirmation;
|
||||||
|
use Laravel\Nova\Fields\Slug;
|
||||||
|
use Laravel\Nova\Fields\Timezone;
|
||||||
|
use Laravel\Nova\Fields\Token;
|
||||||
|
use Laravel\Nova\Fields\URL;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class AdditionalFieldsCard extends FormCard
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array<string, mixed>
|
||||||
|
*/
|
||||||
|
public static array $handled = [];
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Email::make('Work Email', 'work_email')->rules('required', 'email'),
|
||||||
|
URL::make('Website')->rules('required', 'url'),
|
||||||
|
Password::make('Secret')->rules('required'),
|
||||||
|
PasswordConfirmation::make('Secret Confirmation', 'secret_confirmation')->rules('required', 'same:secret'),
|
||||||
|
Hidden::make('Tracking Code'),
|
||||||
|
ID::make('Record ID', 'record_id'),
|
||||||
|
DateTime::make('Starts At Time'),
|
||||||
|
Currency::make('Price'),
|
||||||
|
Color::make('Brand Color'),
|
||||||
|
Code::make('Payload')->json(),
|
||||||
|
Country::make('Country'),
|
||||||
|
Timezone::make('Timezone'),
|
||||||
|
MultiSelect::make('Tags')->options([
|
||||||
|
'news' => 'News',
|
||||||
|
'events' => 'Events',
|
||||||
|
]),
|
||||||
|
BooleanGroup::make('Permissions')->options([
|
||||||
|
'read' => 'Read',
|
||||||
|
'write' => 'Write',
|
||||||
|
]),
|
||||||
|
KeyValue::make('Metadata'),
|
||||||
|
Slug::make('Slug'),
|
||||||
|
Token::make('Api Token'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
self::$handled = $fields->all();
|
||||||
|
|
||||||
|
return static::message('Additional fields received.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class CreationRulesCard extends FormCard
|
||||||
|
{
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make('Email')->rules('required', 'email'),
|
||||||
|
Text::make('Invite Code')->creationRules('required'),
|
||||||
|
Text::make('Hidden Secret')->canSee(fn (): bool => false)->rules('required'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
return static::message('Created.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Select;
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class DependentCard extends FormCard
|
||||||
|
{
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make('Email')
|
||||||
|
->hide()
|
||||||
|
->dependsOn(['role'], function (Text $field, NovaRequest $request, $data): void {
|
||||||
|
$field->visible = $data['role'] === 'admin';
|
||||||
|
}),
|
||||||
|
|
||||||
|
Select::make('Role')->options([
|
||||||
|
'admin' => 'Admin',
|
||||||
|
'staff' => 'Staff',
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
return static::message('Synced.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class FailingCard extends FormCard
|
||||||
|
{
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make('Email')->rules('required', 'email'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
return static::error('No invitation was sent.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Laravel\Nova\Fields\Audio;
|
||||||
|
use Laravel\Nova\Fields\File;
|
||||||
|
use Laravel\Nova\Fields\Image;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class FileUploadCard extends FormCard
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array<string, mixed>
|
||||||
|
*/
|
||||||
|
public static array $handled = [];
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
File::make('Attachment')->rules('required', 'file'),
|
||||||
|
Image::make('Avatar')->rules('required', 'image'),
|
||||||
|
Audio::make('Voice Note')->rules('required', 'file'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
self::$handled = [
|
||||||
|
'attachment' => $fields->attachment instanceof UploadedFile
|
||||||
|
? $fields->attachment->getClientOriginalName()
|
||||||
|
: null,
|
||||||
|
'avatar' => $fields->avatar instanceof UploadedFile
|
||||||
|
? $fields->avatar->getClientOriginalName()
|
||||||
|
: null,
|
||||||
|
'voice_note' => $fields->voice_note instanceof UploadedFile
|
||||||
|
? $fields->voice_note->getClientOriginalName()
|
||||||
|
: null,
|
||||||
|
];
|
||||||
|
|
||||||
|
return static::message('Files received.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Audio;
|
||||||
|
use Laravel\Nova\Fields\Avatar;
|
||||||
|
use Laravel\Nova\Fields\Badge;
|
||||||
|
use Laravel\Nova\Fields\BooleanGroup;
|
||||||
|
use Laravel\Nova\Fields\Code;
|
||||||
|
use Laravel\Nova\Fields\Color;
|
||||||
|
use Laravel\Nova\Fields\Country;
|
||||||
|
use Laravel\Nova\Fields\Currency;
|
||||||
|
use Laravel\Nova\Fields\Boolean;
|
||||||
|
use Laravel\Nova\Fields\Date;
|
||||||
|
use Laravel\Nova\Fields\DateTime;
|
||||||
|
use Laravel\Nova\Fields\Email;
|
||||||
|
use Laravel\Nova\Fields\File;
|
||||||
|
use Laravel\Nova\Fields\Gravatar;
|
||||||
|
use Laravel\Nova\Fields\Heading;
|
||||||
|
use Laravel\Nova\Fields\Hidden;
|
||||||
|
use Laravel\Nova\Fields\ID;
|
||||||
|
use Laravel\Nova\Fields\Image;
|
||||||
|
use Laravel\Nova\Fields\KeyValue;
|
||||||
|
use Laravel\Nova\Fields\Line;
|
||||||
|
use Laravel\Nova\Fields\MultiSelect;
|
||||||
|
use Laravel\Nova\Fields\Number;
|
||||||
|
use Laravel\Nova\Fields\Password;
|
||||||
|
use Laravel\Nova\Fields\PasswordConfirmation;
|
||||||
|
use Laravel\Nova\Fields\Select;
|
||||||
|
use Laravel\Nova\Fields\Slug;
|
||||||
|
use Laravel\Nova\Fields\Sparkline;
|
||||||
|
use Laravel\Nova\Fields\Stack;
|
||||||
|
use Laravel\Nova\Fields\Status;
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Fields\Textarea;
|
||||||
|
use Laravel\Nova\Fields\Timezone;
|
||||||
|
use Laravel\Nova\Fields\Token;
|
||||||
|
use Laravel\Nova\Fields\UiAvatar;
|
||||||
|
use Laravel\Nova\Fields\URL;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class SerializableCard extends FormCard
|
||||||
|
{
|
||||||
|
public function title(): string
|
||||||
|
{
|
||||||
|
return 'Invite User';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make('Email')->default('taylor@example.com')->rules('required', 'email'),
|
||||||
|
Textarea::make('Message'),
|
||||||
|
Select::make('Role')->options([
|
||||||
|
'admin' => 'Admin',
|
||||||
|
'member' => 'Member',
|
||||||
|
]),
|
||||||
|
Boolean::make('Active'),
|
||||||
|
Number::make('Seats')->rules('nullable', 'integer', 'min:1'),
|
||||||
|
Date::make('Starts At'),
|
||||||
|
DateTime::make('Starts At Time'),
|
||||||
|
Email::make('Work Email', 'work_email'),
|
||||||
|
URL::make('Website'),
|
||||||
|
Password::make('Password'),
|
||||||
|
PasswordConfirmation::make('Password Confirmation', 'password_confirmation'),
|
||||||
|
Hidden::make('Tracking Code')->default('abc123'),
|
||||||
|
ID::make('Record ID', 'record_id'),
|
||||||
|
Currency::make('Price'),
|
||||||
|
Color::make('Brand Color'),
|
||||||
|
Code::make('Payload')->json(),
|
||||||
|
Country::make('Country'),
|
||||||
|
Timezone::make('Timezone'),
|
||||||
|
MultiSelect::make('Tags')->options([
|
||||||
|
'news' => 'News',
|
||||||
|
'events' => 'Events',
|
||||||
|
]),
|
||||||
|
BooleanGroup::make('Permissions')->options([
|
||||||
|
'read' => 'Read',
|
||||||
|
'write' => 'Write',
|
||||||
|
]),
|
||||||
|
KeyValue::make('Metadata'),
|
||||||
|
Slug::make('Slug'),
|
||||||
|
Token::make('Api Token'),
|
||||||
|
File::make('Attachment'),
|
||||||
|
Image::make('Avatar'),
|
||||||
|
Avatar::make('Profile Photo'),
|
||||||
|
Audio::make('Voice Note'),
|
||||||
|
Heading::make('Invite Summary'),
|
||||||
|
Line::make('Queue Label')->default('Queue healthy'),
|
||||||
|
Stack::make('Invite Stats', [
|
||||||
|
Line::make('Pending Invites')->asHeading()->default('3 pending'),
|
||||||
|
Line::make('Last Invite')->default('Today'),
|
||||||
|
]),
|
||||||
|
Sparkline::make('Invite Trend')->data([1, 3, 2, 5])->height(48),
|
||||||
|
Badge::make('Health')->map([
|
||||||
|
'ok' => 'success',
|
||||||
|
])->labels([
|
||||||
|
'ok' => 'OK',
|
||||||
|
])->default('ok'),
|
||||||
|
Status::make('Import Status')->loadingWhen(['waiting'])->failedWhen(['failed'])->default('finished'),
|
||||||
|
Gravatar::make('Sender Gravatar', 'sender_email')->default('sender@example.com'),
|
||||||
|
UiAvatar::make('Sender Initials', 'sender_name')->default('Taylor Otwell'),
|
||||||
|
Text::make('Hidden Secret')->canSee(fn (): bool => false)->rules('required'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
return static::message('Serialized.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Fields\Text;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormFields;
|
||||||
|
|
||||||
|
class SuccessfulCard extends FormCard
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array<string, mixed>
|
||||||
|
*/
|
||||||
|
public static array $handled = [];
|
||||||
|
|
||||||
|
public function fields(NovaRequest $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Text::make('Email')->rules('required', 'email'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(FormFields $fields, NovaRequest $request): mixed
|
||||||
|
{
|
||||||
|
self::$handled = $fields->all();
|
||||||
|
|
||||||
|
return static::message('Invitation sent.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests\Fixtures;
|
||||||
|
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
|
||||||
|
class UnauthorizedCard extends SuccessfulCard
|
||||||
|
{
|
||||||
|
public function authorizedToSubmit(NovaRequest $request): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use MeghdadFadaee\NovaFormCard\Tests\TestCase;
|
||||||
|
|
||||||
|
uses(TestCase::class)->in('Feature', 'Unit');
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace MeghdadFadaee\NovaFormCard\Tests;
|
||||||
|
|
||||||
|
use Illuminate\Routing\Middleware\SubstituteBindings;
|
||||||
|
use Laravel\Nova\Http\Requests\NovaRequest;
|
||||||
|
use Orchestra\Testbench\TestCase as Orchestra;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCard;
|
||||||
|
use MeghdadFadaee\NovaFormCard\FormCardServiceProvider;
|
||||||
|
|
||||||
|
abstract class TestCase extends Orchestra
|
||||||
|
{
|
||||||
|
protected function getPackageProviders($app): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
FormCardServiceProvider::class,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function defineEnvironment($app): void
|
||||||
|
{
|
||||||
|
$app['config']->set('app.key', 'base64:MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=');
|
||||||
|
$app['config']->set('nova-form-card.token_ttl_minutes', 120);
|
||||||
|
|
||||||
|
$app['router']->aliasMiddleware('nova', SubstituteBindings::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function novaRequest(string $method = 'GET', string $uri = '/nova'): NovaRequest
|
||||||
|
{
|
||||||
|
$request = NovaRequest::create($uri, $method);
|
||||||
|
|
||||||
|
$this->app->instance('request', $request);
|
||||||
|
$this->app->instance(NovaRequest::class, $request);
|
||||||
|
|
||||||
|
return $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
protected function serializeFormCard(FormCard $card): array
|
||||||
|
{
|
||||||
|
$this->novaRequest();
|
||||||
|
|
||||||
|
return $card->jsonSerialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tokenFor(FormCard $card): string
|
||||||
|
{
|
||||||
|
return (string) data_get($this->serializeFormCard($card), 'formCard.token');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use MeghdadFadaee\NovaFormCard\Http\Responses\FormCardResponse;
|
||||||
|
|
||||||
|
it('formats message responses', function (): void {
|
||||||
|
expect(FormCardResponse::message('Done.')->toArray())->toBe([
|
||||||
|
'type' => 'success',
|
||||||
|
'message' => 'Done.',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats error responses', function (): void {
|
||||||
|
expect(FormCardResponse::error('Failed.')->toArray())->toBe([
|
||||||
|
'type' => 'error',
|
||||||
|
'message' => 'Failed.',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats redirect responses', function (): void {
|
||||||
|
expect(FormCardResponse::visit('/resources/users', ['preserveScroll' => true])->toArray())->toBe([
|
||||||
|
'type' => 'redirect',
|
||||||
|
'redirect' => [
|
||||||
|
'url' => '/resources/users',
|
||||||
|
'remote' => false,
|
||||||
|
'options' => [
|
||||||
|
'preserveScroll' => true,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats refresh responses', function (): void {
|
||||||
|
expect(FormCardResponse::refresh('Updated.')->toArray())->toBe([
|
||||||
|
'type' => 'refresh',
|
||||||
|
'message' => 'Updated.',
|
||||||
|
'refresh' => true,
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
define: {
|
||||||
|
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||||
|
},
|
||||||
|
build: {
|
||||||
|
outDir: 'dist',
|
||||||
|
emptyOutDir: false,
|
||||||
|
cssCodeSplit: true,
|
||||||
|
lib: {
|
||||||
|
entry: path.resolve(process.cwd(), 'resources/js/card.js'),
|
||||||
|
name: 'NovaFormCard',
|
||||||
|
formats: ['iife'],
|
||||||
|
fileName: () => 'js/card.js',
|
||||||
|
},
|
||||||
|
rollupOptions: {
|
||||||
|
external: ['vue'],
|
||||||
|
output: {
|
||||||
|
globals: {
|
||||||
|
vue: 'Vue',
|
||||||
|
},
|
||||||
|
assetFileNames: assetInfo => {
|
||||||
|
if (assetInfo.name && assetInfo.name.endsWith('.css')) {
|
||||||
|
return 'css/card.css'
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'assets/[name][extname]'
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
Reference in new issue
Block a user