I would like to add a comma to the beginning and ending of a string onValidateSuccess only IF the string does not already have commas at the beginning and end.
Can anyone help?
You can use PHP’s function array_unshift/array_push to add values to the beginning/end of an array:
if(reset($array) != ","){ // check the first element of the array
array_unshift($array, ",");
}
if(end($array) != ","){ // check the last element of the array
array_push($array, ",");
}
I think this is close, but does not appear to save. Here is my code:
$array = array({itemCategoryArray});
if(reset($array) != “,”){ // check the first element of the array
array_unshift($array, “,”);
}
if(end($array) != “,”){ // check the last element of the array
array_push($array, “,”);
}
sc_commit_trans();
The output looks good as an array but does not save to db (Using OnValidateSuccess event). Any thoughts?
If the field {itemCategoryArray} is a string (sorry, but I focused on this post title, where you wrote “array” lol), just check its first/end character:
if({itemCategoryArray}[0] != ","){ // check the first char of the string
{itemCategoryArray} = "," . {itemCategoryArray};
}
if(substr({itemCategoryArray}, -1) != ","){ // check the last char of the string
{itemCategoryArray} = {itemCategoryArray} . ",";
}
That way it should be saved on database because now you’re changing the value of the field, and not just a new variable.
WORKS! Thank you so much, that solution is something I should have thought of, but didn’t.
Thanks!
Glad to be of help