Forum
Perch, Json and textarea
Hi there, I'm using perch to generate json. All going swimmingly well except for when it comes to textareas. My template looks like this
<perch:before>{</perch:before>
"<perch:content id="title" type="text" title="true" label="Client" urlify="true"/>":[
{"name":"<perch:content id="title" type="text" label="Client" required="true" />",
"slug":"<perch:content id="title" type="text" label="Client" urlify="true"/>",
"body":"<perch:content id="body" type="textarea" html="true" label="Body" markdown="true" editor="markitup" required="true" />",
"thumbnail": "<perch:content type="image" id="thumbnail" label="Thumbnail"/>"
<perch:if exists="perch_item_last">}]<perch:else />}],</perch:if>
<perch:after>}</perch:after>
Which is fine, until the textarea includes a new line. In which case I get something like:
"bank-side-films":[
{"name":"Bank Side Films",
"slug":"bank-side-films",
"body":"<h2>Heading</h2>
<p>First paragraph</p>",
"thumbnail": "/admin/resources/bankside-icon.png"
}
When what I actually need is:
"bank-side-films":[
{"name":"Bank Side Films",
"slug":"bank-side-films",
"body":"<h2>Heading</h2><p>First paragraph</p>",
"thumbnail": "/admin/resources/bankside-icon.png"
}
Essentially I need a textarea to parse on one line. Anyone any ideas?
There's a couple of ways, neither as nice as I'd like.
The first would be to use the
skip-template
option to get the content back as a PHP array, loop though to get the structure you want and then run it through PHP's ownjson_encode()
. That might jet you the best results, as you'd be using a proper JSON encoding routine rather than rolling your own with the template. But you don't get the template niceties.Something roughly like:
The second option is to do what you're already doing, but to switch out to a custom field type when outputting the textarea to JSON.
This:
would become:
and then you'd create
perch/addons/fieldtypes/textarea_json_encoded/textarea_json_encoded.class.php
like this:Boom! I'm going with option two and it works a treat.
I love this, so I am tagging this response for future use. Robert Ketter
Field types are really easy and really, really powerful.