Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Michael Fayez's avatar

save form after filtering

before filltering post by project , I can save the form easily but after I make filtering by

public function updatedSelectedProjectId($projectId)
    {
        $this->posts = Post::where('project_id', $projectId)->get();
        logger('Updated posts for project: ' . $projectId); // Update posts based on selected project
    }

the behavior of the form changes and can's save the data anymore .. here is the create component

<?php

namespace App\Http\Livewire\Design;

use App\Models\Design;
use App\Models\Post;
use App\Models\Project;
use App\Models\Team;
use Livewire\Component;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use App\Listeners\Design\DesignCreatedEmail;
use App\Events\Design\DesignCreated;

class Create extends Component
{
    public Design $design;

    public $posts;
    public $projects;
    public $post;
    public $project;

    public array $mediaToRemove = [];

    public array $listsForFields = [];

    public array $mediaCollections = [];

    public $selectedProjectId = null;

    public function addMedia($media): void
    {
        $this->mediaCollections[$media['collection_name']][] = $media;
    }

    public function removeMedia($media): void
    {
        $collection = collect($this->mediaCollections[$media['collection_name']]);

        $this->mediaCollections[$media['collection_name']] = $collection->reject(fn ($item) => $item['uuid'] === $media['uuid'])->toArray();

        $this->mediaToRemove[] = $media['uuid'];
    }

    protected function syncMedia(): void
    {
        collect($this->mediaCollections)->flatten(1)
            ->each(fn ($item) => Media::where('uuid', $item['uuid'])
                ->update(['model_id' => $this->design->id]));

        Media::whereIn('uuid', $this->mediaToRemove)->delete();
    }

    public function mount(Design $design)
    {
        $this->design = $design;
        $this->projects = Project::all(); // Load all projects
        $this->posts = collect();
        $this->initListsForFields();
    }

    public function updatedSelectedProjectId($projectId)
    {
        $this->posts = Post::where('project_id', $projectId)->get();
        logger('Updated posts for project: ' . $projectId); // Update posts based on selected project
    }



    public function render()
    {
        return view('livewire.design.create');
    }

    public function submit()
    {
        $this->validate();

        $this->design->save();
        $this->syncMedia();
        // event(new DesignCreated($this->design));

        return redirect()->route('admin.designs.index');
    }


    protected function rules(): array
    {
        return [
            'design.project_id' => [
                'integer',
                'exists:projects,id',
                'nullable',
            ],
            'design.post_id' => [
                'integer',
                'exists:posts,id',
                'nullable',
            ],
            'mediaCollections.design_design' => [
                'array',
                'required',
            ],
            'mediaCollections.design_design.*.id' => [
                'integer',
                'exists:media,id',
            ],
            'design.statues' => [
                'nullable',
                'in:' . implode(',', array_keys($this->listsForFields['statues'])),
            ],
            'design.confirmation' => [
                'nullable',
                'in:' . implode(',', array_keys($this->listsForFields['confirmation'])),
            ],
            'design.note' => [
                'string',
                'nullable',
            ],
            'design.review' => [
                'nullable',
                'in:' . implode(',', array_keys($this->listsForFields['review'])),
            ],
            'design.team_id' => [
                'integer',
                'exists:teams,id',
                'required',
            ],
        ];
    }

    protected function initListsForFields(): void
    {
        $this->listsForFields['project']      = Project::pluck('name', 'id')->toArray();
        $this->listsForFields['post']         = Post::pluck('title', 'id')->toArray();
        $this->listsForFields['statues']      = $this->design::STATUES_RADIO;
        $this->listsForFields['confirmation'] = $this->design::CONFIRMATION_RADIO;
        $this->listsForFields['review']       = $this->design::REVIEW_RADIO;
        $this->listsForFields['team']         = Team::pluck('name', 'id')->toArray();
    }
}

here is the view :-

<div class="form-group {{ $errors->has('design.project_id') ? 'invalid' : '' }}">
    <label class="form-label" for="project">{{ trans('cruds.design.fields.project') }}</label>
        <select wire:model="selectedProjectId" name="project"
            class="mt-2 text-sm sm:text-base pl-2 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
            required>
        <option value="">-- choose project --</option>
        @foreach ($projects as $project)
            <option value="{{ $project->id }}">{{ $project->name }}</option>
        @endforeach
    </select>
    <div class="validation-message">
        {{ $errors->first('design.project_id') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.project_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('design.post_id') ? 'invalid' : '' }}">
    <label class="form-label" for="post">{{ trans('cruds.design.fields.post') }}</label>

        <select wire:model="design.post_id" name="post"
            class="mt-2 text-sm sm:text-base pl-2 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400" required>
        @foreach ($posts as $post)
            <option value="{{ $post->id }}">{{ $post->title }}</option>
        @endforeach
    </select>
    <div class="validation-message">
        {{ $errors->first('design.post_id') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.post_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('mediaCollections.design_design') ? 'invalid' : '' }}">
    <label class="form-label required" for="design">{{ trans('cruds.design.fields.design') }}</label>
    <x-dropzone id="design" name="design" action="{{ route('admin.designs.storeMedia') }}" collection-name="design_design" max-file-size="5" max-width="1200" max-height="630" />
    <div class="validation-message">
        {{ $errors->first('mediaCollections.design_design') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.design_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('design.statues') ? 'invalid' : '' }}">
    <label class="form-label">{{ trans('cruds.design.fields.statues') }}</label>
    @foreach($this->listsForFields['statues'] as $key => $value)
        <label class="radio-label"><input type="radio" name="statues" wire:model="design.statues" value="{{ $key }}">{{ $value }}</label>
    @endforeach
    <div class="validation-message">
        {{ $errors->first('design.statues') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.statues_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('design.confirmation') ? 'invalid' : '' }}">
    <label class="form-label">{{ trans('cruds.design.fields.confirmation') }}</label>
    @foreach($this->listsForFields['confirmation'] as $key => $value)
        <label class="radio-label"><input type="radio" name="confirmation" wire:model="design.confirmation" value="{{ $key }}">{{ $value }}</label>
    @endforeach
    <div class="validation-message">
        {{ $errors->first('design.confirmation') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.confirmation_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('design.note') ? 'invalid' : '' }}">
    <label class="form-label" for="note">{{ trans('cruds.design.fields.note') }}</label>
    <input class="form-control" type="text" name="note" id="note" wire:model.defer="design.note">
    <div class="validation-message">
        {{ $errors->first('design.note') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.note_helper') }}
    </div>
</div>
<div class="form-group {{ $errors->has('design.review') ? 'invalid' : '' }}">
    <label class="form-label">{{ trans('cruds.design.fields.review') }}</label>
    @foreach($this->listsForFields['review'] as $key => $value)
        <label class="radio-label"><input type="radio" name="review" wire:model="design.review" value="{{ $key }}">{{ $value }}</label>
    @endforeach
    <div class="validation-message">
        {{ $errors->first('design.review') }}
    </div>
    <div class="help-block">
        {{ trans('cruds.design.fields.review_helper') }}
    </div>
</div>
@if(auth()->user()->is_Admin)
    <div class="form-group {{ $errors->has('design.team_id') ? 'invalid' : '' }}">
        <label class="form-label required" for="team">{{ trans('cruds.design.fields.team') }}</label>
        <x-select-list class="form-control" required id="team" name="team" :options="$this->listsForFields['team']" wire:model="design.team_id" />
        <div class="validation-message">
            {{ $errors->first('design.team_id') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.team_helper') }}
        </div>
    </div>
@endif
<div class="form-group">
    <button class="btn btn-indigo mr-2" type="submit">
        {{ trans('global.save') }}
    </button>
    <a href="{{ route('admin.designs.index') }}" class="btn btn-secondary">
        {{ trans('global.cancel') }}
    </a>
</div>
0 likes
1 reply
LaryAI's avatar
Level 58

It seems like the issue you're facing is related to the form not being able to save data after applying a filter to the posts by project. This could be due to several reasons, but without a specific error message or behavior, it's a bit challenging to diagnose the exact problem. However, I can provide some general advice and a potential solution that might help you resolve the issue.

First, ensure that your Livewire component is correctly updating the selectedProjectId and that the posts collection is being updated accordingly. From the code you've provided, it looks like this part is working as expected.

Next, check the submit method in your Livewire component. This method is responsible for validating and saving the form data. Make sure that the validation rules are correct and that the save method is being called on the correct model instance.

Here's a potential solution that might help:

  1. Ensure that the submit method is being called when the form is submitted. You can add a wire:click directive to your submit button to explicitly call the submit method.
<button class="btn btn-indigo mr-2" type="button" wire:click="submit">
    {{ trans('global.save') }}
</button>
  1. In your submit method, you might want to dispatch browser events to ensure that the form is not submitted traditionally (which would cause a full page refresh). You can prevent the default form submission behavior by adding wire:submit.prevent="submit" to your form tag.
<form wire:submit.prevent="submit">
    <!-- form fields -->
</form>
  1. Check if there are any JavaScript errors in the browser console that might be preventing the form from being submitted.

  2. Ensure that the Design model is being filled with the correct data before calling the save method. You might want to log the $this->design attributes before saving to make sure all the data is correct.

public function submit()
{
    $this->validate();

    logger('Saving design with data: ', $this->design->toArray());

    $this->design->save();
    $this->syncMedia();

    return redirect()->route('admin.designs.index');
}
  1. If you're using events like DesignCreated, make sure that they are not interfering with the form submission process. You can temporarily comment out the event dispatching to see if that resolves the issue.
// event(new DesignCreated($this->design));
  1. Lastly, check your validation rules to ensure they are not causing the issue. If a field is required and not being filled, or if there's a mismatch between the form data and the validation rules, the form will not submit.

If you've tried these steps and are still facing issues, please provide more details about the behavior you're experiencing, including any error messages or logs, so that I can offer a more precise solution.

Please or to participate in this conversation.