I am getting data from an outside source to populate some of my fields. It comes in as a string separated with commas. In order to display this data in a list format. I did this:

$commaString = ($items[0]["#markup"]);
$NoCommaString = str_replace("," , "<br />", $commaString);
$items[0]["#markup"] = $NoCommaString;

In field--field-MYFIELD.tpl.php. So now field displays like this:

item 1
item 2 
item 3

instead of

item 1, item 2, item 3

Which is exactly what I want, yay! However, I'm new to Drupal and am worried I'm bypassing something or not using an API when I should be. So is there a better way to do this?


Just for security purposes I would wrap $commaString in check_plain() to get rid of any naughty characters or code that could come through.

And as for doing extremely simple things with PHP, you shouldn't have to worry about doing it the "Drupal way" too often. There are such things as PHP wrapper functions which are useful for keeping your code safe from PHP version quirks.

Also just to add, if the question were: "I want to format this CSV as a bulleted list." Then I would've suggested using a theme() function like the following:

print theme('item_list', array('items' => explode(",", check_plain($commaString))));

Because Drupal's theme layer is your friend and will help you to almost never write markup in your code. And I'm not aware of a theme function that converts a CSV string into a newline separated one. Item list is a good example of a theme function, so is a table theme.

| improve this answer | |
  • Looking back on your question I'm also wondering why your field isn't multivalued to begin with (i.e. each item in the CSV should be a row in the DB). It would make it easier to do these types of manipulations in the future if the data isn't so static. – Alexander Hripak Dec 28 '12 at 22:41
  • I agree it would make it, easier and am working on that as well... – RedRaven Dec 28 '12 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.