Automatically resizing image blocks in Concrete5

1 December, 2011

One of concrete5's greatest strengths, if not its greatest, is that it is easy for novices to use. Developers can further configure a concrete5 site (using features such as the 'composer', page types and custom blocks), to make things even easier. This means that clients can jump in and edit content with little risk of them incorrectly formatting something or placing a page in the wrong spot.

Concrete5 has a built-in image block that allows users to upload and add images to pages. It features the ability to resize images by typing in a width and/or height to resize it. As handy as this is, a potential issue is that there is nothing to indicate what maximum width value (in pixels) you need to enter to make the selected image fit the area. Even the idea of 'pixels' is a technical term and something I feel a client shouldn't have to think about.

A solution:

The behaviour of blocks in concrete5 can be overridden easily by placing files in the top level folders. What we can do is override the default functionality for an image block, getting it to automatically resize placed images depending on what area the image is placed in. It's pretty straightforward:

1. Create an image folder within the top level blocks folder.2. Into this folder, copy the file controller.php from the folder /concrete/blocks/image.In this new controller.php file, look for:

This simply allows the name of the area to be passed into the function that generates the image.

3. Still within controller.php, before the line:

if ($this->maxWidth > 0 || $this->maxHeight > 0) {

we can place some conditional statements to enforce maximum widths. For example, if we have an area on a template called 'Sidebar', we can add the following code:

if ($handle == 'Sidebar') { $this->maxWidth = 285;}

So if the block finds itself within the 'Sidebar' area, it will apply a max width automatically, otherwise it behaves as it normally would. From here, you could add as many of these statements as you need so that images are resized to different sizes for different areas.

4. Finally, in the same folder, create a file called view.php. In this file, place this content:

This is only a small change; it passes in the name of the area the block is in.

Now when you add an image block to a particular area (in this case, we've used 'Sidebar'), we don't have to worry about entering a maximum width - the image will resize to the width we've already specified. It only takes a minute or two to set up, but further adds to the ease with which users can maintain their concrete5 site.