lundi 12 juillet 2021

Laravel: how to handle repeated data in form

In my project I have to link two different models (A and B) in a many-to-many relationship, with a pivot table that has additional fields (additionaldata1 and additionaldata2) together with the model's ids.

My approach has been to create a table where each row is a different B entry, and the user gets to add the additional data for the entries he/she wants to link with the A entry (which is known from the URL myproject/A/{A_id}/linkwithB/).

Each row of the table contains a few input fields, similar to these:

<input type="number" 
       name="data[][additionaldata1]"
       value=>

<input type="number" 
       name="data[][additionaldata2]"
       value=>

isLinkedWith and getB are two internal methods in A's model that tell me whether $B is already linked with $A, and if so retrieve the values for additionaldata1 and additionaldata2.

Server side, I receive an array like

AB: [
    B_id_1 => ['additionaldata1': ad1Value, 'additionaldata2': ad2Value], 
    B_id_2 => ['additionaldata1': ad1Value, 'additionaldata2': ad2Value], 
]

which is what I expect, but I'm still facing two different problems.

Null vs 0

The additionaldata* fields I receive from the form are set to null when the user does not provide them, thus breaking things down to the database, where the corrisponding field is not set to be nullable (and I wish it to stay this way).

I'd like to change those nulls to 0s, and to do so I've tried to override the prepareForValidation function in my custom ABFormRequest class, but since the data comes as an array, I can't use the $request->merge approach, as my fields aren't in the "top" level of the Request.

Validation

Throughout the view, I have set the validation error feedback by including

@if($errors->has('additionaldata1'))
   <p class="help is-danger"></p>
@endif

after each input field. The problem is that all the fields are called additionaldata* (although related to different Bs) and this ends up with the error feedback shown for each one of them, even those who are actually valid.

First of all, if you've reached this far, I thank you.

Second, nothing is written on stone, and I can throw everything away and rebuild it differently, if you have a suggestion for a different approach, but I'd like to know whether I'm doing something completely useless, or how it can be improved.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire