Jump to:

23364 Posts in 18125 Topics by 2862 members

General Questions

SilverStripe Forums » General Questions » Image caption

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 1229 Views
  • Christy
    Avatar
    Community Member
    57 Posts

    Image caption Link to this post

    Is there any reasonably easy way for the end user to add a caption to an image inserted through the CMS?

    Thanks.

  • Juanitou
    Avatar
    Community Member
    323 Posts

    Re: Image caption Link to this post

    Hi!

    I’m not sure if it is good practice, I’d prefer to extend Image class instead of this, but I didn’t arrive to. This MyImage class allows for a caption that you can switch on or off in templates with <% if ShowImagesTitle %><p>$Legend</p><% end_if %>:

    mysite/code/MyImage.php

    <?php
    /*
    ** You haven't been able to extend directly Image and add the boolean field
    */
    class MyImage extends DataObject {
       static $db = array (
          'ShowImagesTitle' => 'Boolean',
          'Legend' => 'Text'
       );
       static $has_one = array (
          'Image' => 'Image',
          'Page' => 'Page'
       );
       public function getCMSFields_forPopup()   {
          $myImageField = new ImageField('Image');
          $myImageField->setAllowedExtensions(array('jpg','gif','png'));
          return new FieldSet(
             $myImageField,
             new TextField('Legend'),
             new CheckboxField('ShowImagesTitle', 'Show legend')
          );
       }
    }
    ?>

    Then in your Page class, or a more specific one:

    mysite/code/Page.php

    // Pages can have many images (see MyImage for the other side of the relation)
    public static $has_many = array(
       'Images' => 'MyImage'
    );

    Then later in getCMSFields() you can use, or not, ImageDataObjectManager (included in DOM module):

    // This will add a checkbox on the CMS to switch the legend (Title) on images (function later)
    // $fields->addFieldToTab('Root.Content.Images', new CheckboxField('ShowImagesTitle', 'Show Title as legend.'));
    $fields->addFieldToTab('Root.Content.Images', new ImageDataObjectManager(
       $this,
       'Images',
       'MyImage',
       'Image',
       array(
          'Legend' => 'Legend',
          'ShowImagesTitle' => 'Show'
       ),
       'getCMSFields_forPopup'
       )
    );

    Hope it helps (and that I get corrected with a better way of doing it),
    Juan

    1229 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.