Thursday, September 3, 2009

Text Area to HTML Editor

TinyMCE is my visual HTML editor of choice (a.k.a. What You See Is What You Get or WYSIWYG). I use it on a number of websites to allow customers to update content without needing to take a class on HTML and CSS. It has worked pretty good for me thus far and best of all, its free.

One particular feature that I've recently discovered has made me pretty happy. TinyMCE allows me to supply a list of URLs for TinyMCE to make available when a user wishes to insert a hyper link. This is a beautiful thing. Before the user had to copy and paste every URL they wanted to link to.

Just as cool is that I can also supply a list of images and videos that can easily be inserted (no copying and pasting these URLs either). So after uploading an image to the server, they can edit a webpage and TinyMCE already has this image's URL ready if it is to be used.

In order to do all this, at the end of my TinyMCE initialization script I added these three lines:

<script type="text/javascript">
tinyMCE.init({
...
external_link_list_url : "/tiny_mce/links.php",
external_image_list_url : "/tiny_mce/images.php",
media_external_list_url : "/tiny_mce/media.php"
});
</script>

Now, on the other side of these specified URLs I have a PHP script that rounds up every URL (or image or video) on the server and provides it in a JSON encoded list for TinyMCE. This way, when a user wants to insert a link (or image or video), TinyMCE already has a good list of links that the user can choose from.

Let's assume, for the PHP example script, that you have a 2D PHP array called $linkOptions that had every link the user might want to use. Here is a part of links.php, specified above:

<?PHP
header("Content-type: application/javascript");

echo "var tinyMCELinkList = new Array( \n\t";

$firstLink = true;
for ($j = 0; $j < sizeof($linkOptions); $j++) {
// Go through each link of the array
if ($firstLink) {
echo "\n\t"; // No comma for the 1st
$firstLink = false;
} else echo ",\n\t";

echo '['. htmlentities($linkOptions[$j][0]); // Link Name
echo '","'. htmlentities($linkOptions[$j][1]) .'"]'; // Link URL
}

echo "\n".');'; // All done

Then, you would need to do replicate something like this for each of the link lists specified. Hope you find this feature as useful as I. Good luck!

PS. TinyMCE is also the HTML editor used for WordPress.

No comments: