1

I have a dynamic table, where I can add and delete rows. In each row, there are some inputs where the user can add data to an object.

Right now, I am hardcoding each index number to the name attr. Like this:

<input type="text" name="reports[0][title]">
<input type="text" name="reports[0][description]">
<input type="text" name="reports[1][title]">
<input type="text" name="reports[1][description]">

Is it possible to do something like this:

<input type="text" name="reports[][title]">
<input type="text" name="reports[][description]">
<input type="text" name="reports[][title]">
<input type="text" name="reports[][description]">

And receive the request just like when it was hardcoded indexes?

I need to post multiple objects to the store method in the controller. When I receive the request, I want the data to be like this without hardcoding the indexes.

"reports": [
    {
        "title": "Title 1",
        "description": "Description 1"
    },
    {
        "title": "Title 2",
        "description": "Description 2"
    }
]

Thanks in advance.

1 Answer 1

2

Option number 2 is not possible, that will result in something like this:

{
 _token: "OFjlTsy3Jws9xW9H0cI9ARVGGNnQokLtRI6Tn478",
 reports: [
  {
     title: "title 1"
  },
  {
     description: "description 1"
  },
  {
     title: "title 2"
  },
  {
     description: "description 2"
  },
 ],
}

So when adding dynamically your fields you need to add them with the numbers for each set:

Lets assume this is your form

<form action="save-reposts" method="POST">
  <!-- Your crsf token field here -->
  <input type="text" name="reports[0][title]">
  <input type="text" name="reports[0][description]">
  <input type="text" name="reports[1][title]">
  <input type="text" name="reports[1][description]">
  <input type="submit" id="submitButton" value="Submit" />
</form>
<button id="addMoreReports"> Add more </button>

Using jQuery that could be something like that:

let i = 2;
$('#addMoreReports').click(function(){
   $('#submitButton').before(addFieldSet(i));
   i++;
});

function addFieldSet(index){
   return '<input type="text" name="reports[' + index + '][title]"><input type="text" name="reports[' + index + '][description]">';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.