I have an entries field that lives on a user's profile. I am using ajax to add entries to this field.
Example: "Click to add to favorites". Everything works great.
Now I am trying to delete an entry from the entires field, and I'm not quite sure how to pass the right data back to my controller.
Here is what my js looks like:
var data = [];
$('.remove').click(function (event) {
var clicked = $(this).data('id');
$('input[name="fields[myEntriesField][]"]').each(function (key, val) {
var value = $(val).val();
if (clicked != value) {
data.push(value);
}});
});
...
onRemove(data, function (response) {
// response
});
function onRemove(data, callback) {
data[window.csrfTokenName] = window.csrfTokenValue;
...
// ajax
}
What I am doing here is adding all of the entry id's to my data
array EXCEPT the one that I clicked on. I was going to pass that array to my controller.
Let's say I have 3 entries in my entries field. This is what is returned:
["1131", "1363"]
It's every entry except the one I clicked on.
In my controller I was going to loop through the array (of entry ID's) and re-populate the entries field - save the user.
I'm getting stuck trying to add the CSRF token - since I am passing in an array I guess I can't seem to append the CSRF token.
The above is currently getting me this far:
The CSRF token could not be verified
If I log out all of the data just after I append the CSRF token, I get this:
["1131", "1363", _token: "TOKEN_NAME|TOKEN_VALUE"]
I've read through this SO thread. Which works - but I don't want to actually delete the entry - in essence I just need to re-populate the field.
Thank you for any suggestions!
EDIT
I've ben able to pass the value(s) to my controller, but now just struggling how to actually re-populate the entries field.
This is what I'm passing into my controller:
data: Array(2)
0:"1131"
1:"1363"
_token:"TOKEN_NAME|TOKEN_VALUE"
In my controller, I can access the values like this:
error_log(print_r(craft()->request->getPost('myField'), true));
Array(
[0] => 1131
[1] => 1363
)
Now just to repopulate the entries field?
// fields[myEntriesField] is an entries field type.
$userModel->getContent()->setAttributes(array(
'fields[myEntriesField]' => , ???
));
var data = { data: [] }
), and then adding the IDs todata.data
? You'll also need to modify your controller, of course.