BlogUmbraco and Things
Umbraco Custom DataType - Select An Image Crop
Author: Nigel Wilson
Posted: 20 October 2011
I have just finished working on www.foursquare.co.nz and
near the end of the project it was identified that one document
type was lacking in some functionality.
The document type had a media picker associated with it but the
document type could be used in both the main column and also the
right hand column. The issue was one of which image should be
displayed.
Several options existed for a solution, but the one I chose (as
I love a challenge) was to see if I could develop a custom datatype
that lists all the defined Image Crops for a given Data Type
("Image Cropper" datatype by default).
I had previously come across a Creating
Custom Umbraco Datatypes blog post by Tim Geyssens before
and it was this I used as my starting point.
I found the image crop data in
the cmsDataTypePreValues table stored as a
string with multiple delimiters.
I then copied Tim's code for each of the classes and made my
necessary amendments.
And so my
first custom datatype was born - a healty little dropdown list,
weighing very little and with all the right bits (ability to set
which datatype, validation within a document type).
One thing I did discover when testing it within an xslt file was
that you first needed to assign the value to a variable prior to
trying to output the image path. See the following code
snippet.
<xsl:variable name="selectedCrop" select="./selectImageCrop"/>
<img>
<xsl:attribute name="src">
<xsl:value-of select="umbraco.library:GetMedia(./portfolioImage,0)/imageCrops/crops/crop[@name = $selectedCrop]/@url"/>
</xsl:attribute>
</img>
A possible progression of this datatype would be to incorporate
it into a modified media picker datatype so that they work in
tandem. Also (and even better) would be to run a check against the
selected media item and list only those crops that exist... Now
that would be funky !
Here's the source code if anyone is interested - drop me a line
if you download it and use it - I'd love to hear from you.
How To Use
- Download
the source code
- Compile and place the resulting dll in your bin directory
- Go to Developer - Datatypes and create a new DataType - there
will be an option called Image Crop Selector - choose this
one.
- Once initially created you then have a field called "Data Type
Name" - enter the relevant datatype name for your image cropper
(the default one is called Image Cropper).
- Add to your document type as required.
Drop me a
note if you download this and find it useful. Also I'd love to
get feedback on my coding - I am always keen to advance my coding
skills.