Archives for category: Code

I’ve promised a few people that I would collate various snippets of useful Concrete5 code that I’ve used over the years. I feel somewhat obliged to since it seems that an awful lot of people have taken to this CMS on my recommendation.

You might notice the irony of posting this on a WordPress blog. I’m not happy about it, but the theme was just about acceptable and so that sold it. It will be migrated to a C5 instance in the near future.

On to the code.

If you have used C5, you will know what an area is and how it works. Let’s say you want to show some default content while that area contains no blocks, and then hide that content once someone has added some content.

$a= new Area('Main'); 

if ($c->isEditMode() || $a->getTotalBlocksInArea($c) > 0 )
{
    $a->display($c);
}
else
{
    echo 'This area is empty';
}

I’ll be honest, I thought this was going to be a 5 minute job to a add nice be of autocompleteness to a project. However, if the requirement to pass 3 parameters as your data array (id, value, label) was in the documentation, I missed it.

The JSON, should look like this;

{"response":"true","message":[{"value":"CSS3","label":"CSS3","id":"3"},{"value":"Slider","label":"Slider","id":"4"},{"value":"PSD","label":"PSD","id":"5"},{"value":"CSS","label":"CSS","id":"7"}]}

I was using CodeIngiter, so my controller looks like this (ignoring the DB selects which should be moved to a model). Also, ensure that you output the correct headers (application/json), otherwise you’ll just be setting yourself up for a whole load of new, difficult to spot problems;


function get_tags_as_json()
{
$tag = $_REQUEST['term']; //get term parameter sent via text field.

$this->db->select('*');
$this->db->from('tags');
$this->db->like('tag', $tag);
$this->db->limit('5');
$query = $this->db->get();

if ($query->num_rows() > 0)
{
$data['response'] = 'true';
$data['message'] = array();

foreach ($query->result() as $row)
{
$data['message'][] = array(
'value' => $row->tag,
'label' => $row->tag,
'id' => $row->id
);
}

}
else
{
$data['response'] = 'false';
}
header("Content-type: application/json");
echo json_encode($data);
}

and then my jQuery;


$(function() {
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://linkspro.dev/admin/get_tags_as_json",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
},
minLength: 1

});
});