Home

Saving images to database in SugarCRM

Attention: open in a new window. PDFPrintE-mail

I have a custom module members and I wanted to be able to add a member logo to a record, and I also needed to store it in the database as we have applications scattered across multiple servers that would need this data.

Following files had to be modified in my members module directory:
modules/members/
members.php

Code:
       //Must overwrite the save operation for uploaded file.

function save($check_notify=false){
if (isset($_FILES['member_logo']) && is_uploaded_file($_FILES['member_logo']['tmp_name'])) {
$data = file_get_contents($_FILES['member_logo']['tmp_name']);
$this->member_logo_data = $data;
$this->member_logo_mime_type = $_FILES['member_logo']['type'];

}
parent::save($check_notify);
return $this->id;
}

vardefs.php

Code:
// file stuff
'member_logo' =>
array(
'name' => 'member_logo',
'vname' => 'LBL_MEMBER_LOGO',
'type' => 'file',
'source' => 'non-db',
'comment' => 'The member logo',
),
'member_logo_mime_type' =>
array (
'name' => 'member_logo_mime_type',
'vname' => 'LBL_MIME',
'type' => 'varchar',
'len' => '100',
),
'member_logo_data' =>
array (
'name' => 'member_logo_data',
'vname' => 'LBL_DATA',
'type' => 'longblob',
),
// file stuff end

metadata/editviewdefs.php

Code:
6 =>	array (
0 => array ('name' => 'member_logo', 'label' => 'LBL_MEMBER_LOGO',),
1 => array (),
),

metadata/editviewdefs.php

Code:
	 6 =>  array (
0 => array ( 'name' => 'member_logo', 'label' => 'LBL_MEMBER_LOGO',
'customCode' => '<img src="/dbimage.php?image_name=member_logo&module=members&id={$fields.id.value}">',
),
1 => array (),
),

added a file to the root of sugar called dbimage.php
(you can do the image retrieval however you like it, please note that this particular method does not require authenticated user.)

Code:
<?
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('include/entryPoint.php');
$module = addslashes($_GET['module']);
$id = addslashes($_GET['id']);
$image_name = addslashes($_GET['image_name']);
$query = "SELECT " . $image_name . "_mime_type, " . $image_name . "_data
FROM " . $module . " WHERE id='" . $id . "' and deleted = 0";
$res = $db->query($query);
$row = $db->fetchByAssoc($res, -1, false);

if($row[$image_name . "_data"] != ''){
ob_end_clean();
header("Content-type: " . $row[$image_name . "_mime_type"]);
echo $row[$image_name . "_data"];
die();
}
?>

if you do not need to save the files in a database, then you can use the native file upload handling by sugar, however then you will be restricted to single file per record.

Hope its clear, sorry if its not, its my first post here so far

Add comment


Security code
Refresh

Some work that we have done:

© Simpl Web Solutions 2008
www.simplweb.net