Reputation: 2309
I have an a problem I know how to tackle it but not 100% clear on what the implementation would look like.
This is a Symfony 3 app but the problem is a pure PHP one which involves some kind of recursion.
I have a multi-dimensional array which represents my nested form and and an errors that need to be mapped to a form field (that bit I know how to do).
Here is my array:
I need to loop over the children of fields
recursively and when I reach the end of a node and it contains message
key (just a way to confirm I have reached the error) then apply that to the form // apply to form here
then remove that index/node so that the recursion doesn't go down that route again?
Can anyone help with the function that will do this. Like I said it is not important to know Symfony just help with the function that will recurs a mutli-dimensional array and remove that node before calling itself again.
My class at it stands but I can cut atleast 50% of this if I can just follow the array keys:
Any help will be greatly appreciated :)
Upvotes: 2
Views: 392
Reputation:
When looping through your array, use a for loop so you can easily manipulate indexes:
for($i = 0; $i < count($fields); $i++) {
// You can use $fields[$i] here for the current item
}
Using isset()
, you can check if the message
key exists in the fields
array. If that is true, use the continue
keyword to skip over the current item and continue with the next one.
It will look something like this, you can change it according to your needs:
for($i = 0; $i < count($fields); $i++) {
if (isset($fields[$i]['message')) {
// error exists...
continue;
}
// Delete the item from your array
unset($fields[$i]);
}
Upvotes: 1
Reputation: 2309
This is my fix. I created a form map which consists of the number of fields each with child arrays for the path to the element and the error.
I then loop over them and pass them through Symfonys mapViolation
method in Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper
.
Here is complete class: https://gist.github.com/linxlad/3ec76c181f717fba532bf43484b7c970
Upvotes: 0