使用 FilamentPHP API 进行自动预装

2025-06-04

使用 FilamentPHP API 进行自动预装

您可以使用 API 来使用它,并使用它来自动预装细丝、龙卷风以实现自动化配方和简单易用的驱动。 Vamos aprender,例如,CEP 数字部分的自动渲染器。帕蒂尤?

 

主题

 

介绍

在此基础上,我们将直观地了解干净的代码,并自动完成所有的说明,以便组织我们的工作。例如,您可以使用 ViaCep 的 API 和 vamos 来自动完成渲染,但它不受限制,因此您最好使用 API。 Vamos começar!

 

一步一步

举例来说,使用方法如下:

  • Laravel v11.x
  • PHP v8.2
  • FilamentPHP v3.2

重要提示:请注意以下内容的使用方式: abaixo é feito。

第 1 步:Criando 项目 Laravel 和 FilamentPHP 辅助

Laravel 的主要项目,使用以下命令的方式:

composer create-project laravel/laravel example-app
Enter fullscreen mode Exit fullscreen mode

Onde example-appé o nome do nosso projeto。请注意,在接下来的任务中使用面食,发送或添加 FilamentPHP 的初始信息,以安装 Filament 的疼痛:

composer require filament/filament:"^3.2" -W
 
php artisan filament:install --panels
Enter fullscreen mode Exit fullscreen mode

步骤 2:Criando nossos 模型、迁移和关系

Agora vamos rodar o seguinte comando para criar o nosso Model, onde Addressé o nome do nosso model ea flag -mfará com que a Migration seja criada junto com o Model:

php artisan make:model Address -m
Enter fullscreen mode Exit fullscreen mode

Dentro da nossa Migration vamos adicionar os Campos que vamos utilizar na nossa tabela.使用 ViaCep 的 API 进行连接,可以使用以下格式:


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
    * Run the migrations.
    */
    public function up(): void
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('postal_code')->nullable();
            $table->string('address')->nullable();
            $table->string('number')->nullable();
            $table->string('complement')->nullable();
            $table->string('neighborhood')->nullable();
            $table->string('city')->nullable();
            $table->string('uf')->nullable();
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    */
    public function down(): void
    {
        Schema::dropIfExists('addresses');
    }
};
Enter fullscreen mode Exit fullscreen mode

移民现场的热情,是php artisan migrate我们在没有银行的情况下进行的。
E também, para criar um usuário para acessar nosso painel, usamos php artisan make:filament-user, digitale um nome, um email e uma senha e use-os para fazer seu login no painel.

Agora vamos trabalhar nossos 模型。最初,在各种情况下,最常见的情况是$fillable

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'postal_code',
        'address',
        'number',
        'complement',
        'neighborhood',
        'city',
        'uf',
    ];
}

Enter fullscreen mode Exit fullscreen mode

这就是我们之间的关系模型。考虑一下常见的渲染效果,以及渲染效果与常见的关系,有关类型的相关说明有一个:

地址.php

public function users()
{
    return $this->hasOne(User::class);
}

用户.php

public function addresses()
{
    return $this->hasOne(Address::class);
}

步骤 3:Criando nossa 资源

Vamos agora criar nossa resources de User, para isso utilizamos or seguinte comando:

php artisan make:filament-resource User --view --generate

// onde --view gera uma página de visualização e
// -- generate gerará nosso formulário e tabela automaticamente
Enter fullscreen mode Exit fullscreen mode

com isso, será criada sua resources em àpp/Filament/Resourcesjá com seus Campos e sua tabela gerada。您知道资源是模型的结尾部分,还是发送给用户“用户可以使用资源,是否可以使用模型结尾?” Vamos lá,lembram da nossa relação? Então, vamos fazer o seguinte:

与 Fieldset 相关的所有标记都没有布局示例->relationship()


<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Exception;
use Filament\Forms;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Fieldset;
use Filament\Forms\Form;
use Filament\Forms\Set;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Http;

class UserResource extends Resource
{
    protected static ?string $model = User::class;
    protected static ?string $navigationIcon = 'heroicon-o-users';

    public static function form(Form $form): Form
    {
        return $form
        ->schema([
            Forms\Components\TextInput::make('name')
                ->required()
                ->maxLength(255),
            Forms\Components\TextInput::make('email')
                ->email()
                ->required()
                ->maxLength(255),
            Forms\Components\DateTimePicker::make('email_verified_at'),
            Forms\Components\TextInput::make('password')
                ->password()
                ->required()
                ->maxLength(255),
            Fieldset::make('address')->label('Address')
                ->relationship('addresses') // chamando nosso relacionamento
                ->schema([
                    Forms\Components\TextInput::make('postal_code')
                        ->maxLength(255),
                    Forms\Components\TextInput::make('address')
                        ->maxLength(255),
                    Forms\Components\TextInput::make('number')
                        ->maxLength(255),
                    Forms\Components\TextInput::make('complement')
                        ->maxLength(255),
                    Forms\Components\TextInput::make('neighborhood')
                        ->maxLength(255),
                    Forms\Components\TextInput::make('city')
                        ->maxLength(255),
                    Forms\Components\TextInput::make('uf')
                        ->maxLength(255),
            ]),
        ]);
    }



    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable(),
                Tables\Columns\TextColumn::make('email')
                    ->searchable(),
                Tables\Columns\TextColumn::make('email_verified_at')
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

// restante o código da resource...

}
Enter fullscreen mode Exit fullscreen mode

字段集不是一个与相关关系布局相关的组件,可以管理与坎波斯/组件和兼容性相关关系的技巧。

您可以更喜欢在表格中组织布局,在文档中添加布局(公式布局表格布局)、组件和示例,以组织您的表格。

步骤 4:autopreenchimento com API 的附加功能

Enfim, vamos adicionar nossa funcionalidade, para isso vamos utilizar a flag ->suffixActionnosso Campo de CEP ( postal_code), ela adicionará um botão no Final do nosso Campo que ao clicar disparará a ação que definirmos dentro dela:

Forms\Components\TextInput::make('postal_code')->mask('99999-999')
    ->suffixAction(
        Action::make('search')
            ->icon('heroicon-o-magnifying-glass')
            ->action()
    )
    ->maxLength(255),
Enter fullscreen mode Exit fullscreen mode
  • 您可以从英雄图标中的动作开始,并与 Pelo Filament 的支持图标进行对抗
  • 使用 CEP 睫毛膏的方法->mask(),重新使用睫毛膏或使用一些不适合的睫毛膏。

后续形式的视觉效果:

后缀动作视觉

集市,我们的行动,我们的旗帜,->action()我们的乐趣。请注意,我们的功能参数为 vamos usar uma variável Set $set(para setar valores nos outros Campos) 和 uma variável $state(usada no Filament para pegar o valor atual do Campo)。

阿西姆(Assim)是一名初出茅庐的人,他在布兰科(Branco)的野营中证明了自己的勇气,并在夏季恢复了正常生活。无示例,请注意使用通知或细丝通知:

Forms\Components\TextInput::make('postal_code')->mask('99999-999')
    ->suffixAction(
        Action::make('search')
            ->icon('heroicon-o-magnifying-glass')
            ->action(function(Set $set, $state){
                if (blank($state)) {
                    Notification::make()
                        ->title('Postal Code is required')
                        ->danger()->send();
                        return;
                }
            })
    )
    ->maxLength(255),
Enter fullscreen mode Exit fullscreen mode

集市、集体、我们所需要的一切try catchtry各种附加信息都可以接收到所需的所有信息,并且所有所需的 URL 都没有端点,无法与总线和 API 一起使用,无法与数字化应用程序$cepData相关$state

我们通知您需要修复catch计算错误。

Forms\Components\TextInput::make('postal_code')->mask('99999-999')
    ->suffixAction(
        Action::make('search')
            ->icon('heroicon-o-magnifying-glass')
            ->action(function(Set $set, $state){
                if (blank($state)) {
                    Notification::make()
                        ->title('Postal Code is required')
                        ->danger()->send();
                        return;
                }
                try {
                    $cepData = 
                        Http::get("https://viacep.com.br/ws/{$state}/json")
                        ->throw()->json();

                } catch (Exception $e) {
                    Notification::make()
                        ->title('Postal Code not found')
                        ->danger()->send();
                }
            })
    )
    ->maxLength(255),
Enter fullscreen mode Exit fullscreen mode

详细说明,ViaCep 的 API、CEP 和 CEP 的情况,以及数组中的错误和异常(大多数图像是 abaixo),并且不存在任何问题,我们不使用catch通知。

阵列与错误

解析器是这样的,在 Exception para que nosso bloco catch "agarre" este erro ea notificação ao usuário seja enviada, fazemos isso da seguinte forma:

Forms\Components\TextInput::make('postal_code')->mask('99999-999')
    ->suffixAction(
        Action::make('search')
            ->icon('heroicon-o-magnifying-glass')
            ->action(function(Set $set, $state){
                if (blank($state)) {
                    Notification::make()
                        ->title('Postal Code is required')
                        ->danger()->send();
                        return;
                }
                try {
                    $cepData = 
                        Http::get("https://viacep.com.br/ws/{$state}/json")
                        ->throw()->json();

                    // forçando a Exception
                    if (in_array('erro', $cepData)) {
                        throw new Exception('Postal Code not found');
                    }

                } catch (Exception $e) {
                    Notification::make()
                        ->title('Postal Code not found')
                        ->danger()->send();
                }
            })
    )
    ->maxLength(255),
Enter fullscreen mode Exit fullscreen mode

集市上,考虑一下我们所需要的条件$cepData,接收所需的条件,并利用我们所需要的条件来确定需要的$set条件null

Forms\Components\TextInput::make('postal_code')->mask('99999-999')
    ->suffixAction(
        Action::make('search')
            ->icon('heroicon-o-magnifying-glass')
            ->action(function(Set $set, $state){
                if (blank($state)) {
                    Notification::make()
                        ->title('Postal Code is required')
                        ->danger()->send();
                        return;
                }
                try {
                    $cepData = 
                        Http::get("https://viacep.com.br/ws/{$state}/json")
                        ->throw()->json();

                    // forçando a Exception
                    if (in_array('erro', $cepData)) {
                        throw new Exception('Postal Code not found');
                    }

                } catch (Exception $e) {
                    Notification::make()
                        ->title('Postal Code not found')
                        ->danger()->send();
                }

                $set('address', $cepData['logradouro'] ?? null);
                $set('neighborhood', $cepData['bairro'] ?? null);
                $set('city', $cepData['localidade'] ?? null);
                $set('uf', $cepData['uf'] ?? null);
            })
    )
    ->maxLength(255),
Enter fullscreen mode Exit fullscreen mode

快点!市场上有自动预装功能。 Abaixo mostro uma demostração da nossa funcionalidade em ação。

结论

为了快速完成自动准备工作,我们将使用各种项目和相关公式来准备预付款和更多的恐龙。此功能可帮助您轻松使用生活并减少公式编写过程中的错误。
您可以通过链接与示例存储库链接来获取该示例的书籍。 Espero que você tenha gostado e qualquer dúvida estou a disposição ^^
Até a próxima !!

 

参考文献

 

Obrigada @clintonrocha98 mais uma vez pelos 反馈! 💜

文章来源:https://dev.to/adryannekelly/autopreenchimento-de-campos-no-filamentphp-usando-api-3i2
PREV
如何构建 Instagram 导航栏克隆 | HTML CSS 和 Js AWS GenAI LIVE!
NEXT
学习和提高编程语言使用的 5 种方法