Adding a Photo to a Contact Record

Article Update 11/8/16 — SugarCRM now offer the Image field type via Studio in 7.x versions. 

Article Update 7/14/2014 — Before diving into this code level tutorial, you should know that a module has been released to solve this scenario which is located on SugarOutfitters.

There are cases where it would be helpful to be able to add a photo to a SugarCRM contact record in order to put a face with the name. However, there isn’t a way to do this out of the box in SugarCRM Commnunity version. Thankfully with SugarCRM’s customizable structure we can create that functionality on our own. Why stop with just contacts? After this tutorial we could add a photo to a lead, account, or any other module. Section 1 — Creating a Photo «Sugar Field» First, we need to create three files which will tell Sugar how to display the field on the edit and detail views. 1.1 — custom/include/SugarFields/Fields/Photo/DetailView.tpl

    {if !empty({{sugarvar key='value' string=true}})}
    <img src='cache/images/{$fields.{{$displayParams.id}}.value}_{{sugarvar key='value'}}' height='100'>
    {/if}

1.2 -custom/include/SugarFields/Fields/Photo/EditView.tpl

    <input type="hidden" id="old_{{sugarvar key='name'}}" name="old_{{sugarvar key='name'}}" value="{$fields[{{sugarvar key='name' stringFormat=true}}].value}"/>
    <input id="{{sugarvar key='name'}}" name="{{sugarvar key='name'}}" type="file" title='{{$vardef.help}}' size="{{$displayParams.size|default:30}}" {{if !empty($vardef.len)}}maxlength='{{$vardef.len}}'{{elseif !empty($displayParams.maxlength)}}maxlength="{{$displayParams.maxlength}}"{{else}}maxlength="255"{{/if}} value="{$fields[{{sugarvar key='name' stringFormat=true}}].value}" {{$displayParams.field}}>
    {$fields[{{sugarvar key='name' stringFormat=true}}].value}
    {if !empty({{sugarvar key='value' string=true}})}
    <img src='cache/images/{$fields.{{$displayParams.id}}.value}_{{sugarvar key='value'}}' height='100'>
    {/if}

1.3 — custom/include/SugarFields/Fields/Photo/SugarFieldPhoto.php

    <?php
    require_once('include/SugarFields/Fields/Base/SugarFieldBase.php');

    class SugarFieldPhoto extends SugarFieldBase {
       function getDetailViewSmarty($parentFieldArray, $vardef, $displayParams, $tabindex) {
           global $app_strings;
           if(!isset($displayParams['id'])) {
               $error = $app_strings['ERR_SMARTY_MISSING_DISPLAY_PARAMS'] . 'id';
               $GLOBALS['log']->error($error); 
               $this->ss->trigger_error($error);
               return;
          } 
 
        $this->setup($parentFieldArray, $vardef, $displayParams, $tabindex);
        return $this->fetch('custom/include/SugarFields/Fields/Photo/DetailView.tpl');
      }
    }
    ?>

Section 2 — Create a Photo Field in Studio 2.1 — Go to Admin->Studio 2.2 — Open Contacts->Fields and «Add Field» 2.3 — Select «TextField» for Data Type, enter «contact_photo» for Field Name, change Label to «Photo», and change Max Size to «255». 2.4 — Add the new contact_photo_c field to the edit and detail views by opening Layouts->EditView, selecting Photo in the left column, and dragging to an empty slot in the grid layout. If there isn’t an empty spot you may need to drag «New Row» to the desired area in the grid. Once done «Save & Deploy». 2.5 — Repeat for the DetailView and «Save & Deploy». Section 3 — Editing the Views 3.1 — Open custom/modules/Contacts/metadata/detailviewdefs.php and look for «contact_photo_c». Now add the type and displayParams so that it looks like the following code. Don’t forget to save!

    ....
    'name' => 'contact_photo_c',
    'label' => 'LBL_CONTACT_PHOTO',
    'type' => 'photo',
    'displayParams' =>
         array (
             'id' => 'id',
        ),
    ....

3.2 — Open custom/modules/Contacts/metadata/editviewdefs.php and look for «contact_photo_c». Now add the type and displayParams so that it looks like the following code.

    ....
    'name' => 'contact_photo_c',
    'label' => 'LBL_CONTACT_PHOTO',
    'type' => 'photo',
    'displayParams' =>
         array (
             'id' => 'id',
        ),
    ....

3.3 — Now we need to set the enctype for the edit form so that we can upload the photo. In editviewdefs.php add the enctype to the form key so that it looks like the following code. Then save the file.

    ....
    $viewdefs ['Contacts'] =
    array (
        'EditView' =>
            array (
                 'templateMeta' =>
                  array (
                       'form' =>
                        array (
                            'enctype' => 'multipart/form-data',
    ....

Section 4 — Creating the Logic Hook 4.1 — To let Sugar know to call this file on save we create or use the existing custom/modules/Contacts/logic_hooks.php file and add our ContactPhoto->uploadPhoto function:

<?php
    // Do not store anything in this file that is not part of the array or the hook version. This file will
    // be automatically rebuilt in the future.
    $hook_version = 1;
    $hook_array = Array();
    // position, file, function
    $hook_array['before_save'] = Array();
    $hook_array['before_save'][] = Array(1, 'uploadPhoto', 'custom/modules/Contacts/ContactPhoto.php','ContactPhoto', 'uploadPhoto');
?>

4.2 — Now we need to create a logic hook to save the image. Create a file called ContactPhoto.php in the custom/modules/Contacts directory with the following code:

<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class ContactPhoto {
    function uploadPhoto(&$bean, $event, $arguments)
    {
        require_once('modules/Contacts/Contact.php');
        require_once('include/utils.php');
        
        $GLOBALS['log']->debug("ContactPhoto->uploadPhoto");
        
        //we need to manually set the id if it is not already set
        //so that we can name the file appropriately
        if(empty($bean->id)) {
        $bean->id = create_guid();
        $bean->new_with_id = true;
        }
        
        //this is the name of the field that is created in studio for the photo
        $field_name = 'contact_photo_c';
        if (!empty($_FILES[$field_name]['name'])) {
            global $sugar_config;
            
            //if a previous photo has been uploaded then remove it now
            if(!empty($_REQUEST['old_'.$field_name])) {
            // create a non UTF-8 name encoding
            // 176 + 36 char guid = windows' maximum filename length
            $old_file_name = $_REQUEST['old_'.$field_name];
            $end = (strlen($old_file_name) > 176) ? 176 : strlen($old_file_name);
            $stored_file_name = substr($old_file_name, 0, $end);
            
            $old_photo = $sugar_config['cache_dir'].'images/'.$bean->id.'_'.$old_file_name;
            $GLOBALS['log']->debug("ContactPhoto->uploadPhoto: Deleting old photo: ".$old_photo);
            unlink($old_photo);
            }
            
            $file_name = $bean->id.'_'.$_FILES[$field_name]['name'];
            //save the file name to the database
            $bean->contact_photo_c = $_FILES[$field_name]['name'];
            
            if(!is_uploaded_file($_FILES[$field_name]['tmp_name'])) {
            die("ERROR: file did not upload");
            //return false;
            } elseif($_FILES[$this->field_name]['size'] > $sugar_config['upload_maxsize']) {
            die("ERROR: uploaded file was too big: max filesize: {$sugar_config['upload_maxsize']}");
            }
            
            // create a non UTF-8 name encoding
            // 176 + 36 char guid = windows' maximum filename length
            $end = (strlen($file_name) > 176) ? 176 : strlen($file_name);
            $stored_file_name = substr($file_name, 0, $end);
            
            $destination = $sugar_config['cache_dir'].'images/'.$stored_file_name;
            
            if(!is_writable($sugar_config['upload_dir'])) {
            die("ERROR: cannot write to directory: {$sugar_config['upload_dir']} for uploads");
            }
            
            //$destination = clean_path($this->get_upload_path($bean_id));
            if(!move_uploaded_file($_FILES[$field_name]['tmp_name'], $destination))
            {
                die("ERROR: can't move_uploaded_file to $destination. You should try making the directory writable by the webserver");
            }
        }
    }
}
?>

Section 5 — Trying it All Out 5.1 — Before we can try it we need to first clear the cache so that our changes in the edit and detail view definition files to affect. To do this you can either go to Admin->Repair->Quick Repair and Rebuild and run for the Contacts module or you can delete EditView.tpl and DetailView.tpl from cache/modules/Contacts. 5.2 — We’re ready to rock and roll now. Open a contact to edit. You should see a file browse field now. Browse and select your photo to upload. 5.3 — Save the contact record. You should now see the photo! 5.4 — You can go back at any time and select a new photo to upload instead.

31 комментарий на Adding a Photo to a Contact Record

  1. Die Glücksspiellizenz der Curaçao eGaming wird ihrem schlechten Ruf nicht gerecht.
    Online-Casinos mit einer MGA-Lizenz durften aufgrund der gesetzlichen Grauzone ihr Angebot bis zur Legalisierung auch in Deutschland anbieten. Die bekannteste Glücksspiellizenz für den europäischen Raum ist die
    Malta Gaming Authority. Wer eine Spielhalle im Internet besucht, kann bei dem
    entsprechenden Glücksspielanbieter eine der nachfolgend beschriebenen Lizenzen vorfinden.
    Die Auswahl umfasst Slots, Tischspiele, Live-Casino und Sportwetten.
    Turniere und Wettbewerbe bieten zusätzliche Gewinnchancen. Roulette bietet feste Quoten mit klaren Gewinnchancen. Tischspiele wie Blackjack haben niedrige Hausvorteile von etwa 0,5%.

    References:
    https://online-spielhallen.de/hitnspin-login-schnell-einloggen-direkt-spielen/

  2. Im Gegensatz zu anderen Webseiten müssen Sie
    sich bei uns nicht registrieren oder persönliche Daten angeben, um unsere kostenlosen Spiele zu spielen. Freispiele ohne
    Einzahlung 2025 bieten risikofreies Spielen und die Chance
    auf echte Echtgeldgewinne. Bei kostenlosen Freispielen geht ihr
    – ähnlich zum Bonus ohne Einzahlung mit Geldwert – kein Risiko ein.
    Hier im Gratis-Online-Casino gibt es Freispiele für alle Slots,
    die aktuell zur Verfügung stehen. Wenn die Rollen anhalten und die Symbole in einer bestimmten Reihenfolge erscheinen, gewinnt der Spieler
    im Glücksspiele-Casino Geld oder Sachpreise. Wie erwähnt, können Slots
    in niedergelassenen Casinos und in Form von Video-Slots
    auch online gespielt werden. Sogenannte Slots sind Glücksspielautomaten, die in Casinos und,
    in digitaler Form oder als Video-Slots, auf Online-Glücksspielseiten angeboten werden.
    Die kostenlosen Spiele bieten dafür auch
    keine Echtgeld-Gewinne. Der einfache Unterschied ist,
    dass Du hier stets auf Freispiele zurückgreifen kannst.

    References:
    https://online-spielhallen.de/verde-casino-bonuscode-2025-alle-angebote-im-uberblick/

  3. Spieler haben Zugriff auf verschiedene Tools zur
    Selbstkontrolle sowie auf Hilfsangebote für problematisches Spielverhalten. Höhere Stufen reduzieren die benötigte Punktzahl
    pro Euro, was das Programm besonders attraktiv für Vielspieler macht.

    Je mehr Sie spielen, desto höher steigen Sie in den Stufen auf – von Bronze über Silber bis hin zu VIP-Platin. Über hochauflösende Streams können Sie in Echtzeit mit professionellen Dealern interagieren, während Sie Spiele wie Blackjack, Baccarat oder Poker spielen. Die Gewinne aus den 80 Freispielen müssen nur 5-mal umgesetzt werden, bevor eine Auszahlung möglich
    ist.
    Noch häufiger als neue Casinos online in Deutschland findest
    du neue Spielautomaten. Wir suchen für Sie die besten und neuesten Spielangebote aus dem schnelllebigen Markt heraus.
    Natürlich achten wir auch auf ein ansprechendes Design der
    Casinoseiten und der dort angebotenen Games.
    Bei uns erfahren Sie, welche Casinos das anbieten und was sie hierfür tun müssen.
    Zuerst prüfen wir alle Angebote auf einen attraktiven Willkommensbonus.

    Mit neuen Casinos haben Spieler auch immer die Gelegenheit, von einem erstklassigen Bonusangebot zu profitieren.

    References:
    https://online-spielhallen.de/vulkan-vegas-deutschland-test-angebote/

  4. Neue Online Casinos in Deutschland bieten oftmals ein attraktives Willkommensbonus mit gratis Freispielen an, um
    eine gute Reputation zu bilden. Viele Plattformen bieten optimierte Webseiten oder eigene Apps,
    sodass deutsche Spieler auch unterwegs flexibel
    spielen können. Heutzutage setzen viele deutsche
    spieler auf das Smartphone oder Tablet, um zu spielen. Im online casino deutschland sind Boni üblicherweise
    an Einsatzbedingungen gekoppelt. Ein best online casino für deutsche Nutzer
    wird in der Regel auf der Seite der Behörde gelistet und ist an klaren Labels erkennbar.
    Wer ein online casino deutschland-weit gründet, muss stabile Serversysteme sowie transparente Nutzungsbedingungen vorweisen. Für viele sind online casino-Provider interessant, die
    in Deutschland bereits bekannt sind und über eine große Spielauswahl verfügen.
    Das beste deutsche Online Casino mit Bonus ohne Einzahlung ist SlotMagie.
    Alle Online Casinos mit deutscher Lizenz sind legal und zahlen wirklich aus.
    Alle auf Gamesbasis empfohlenen Online Casinos sind lizenziert
    und zu 100% seriös. Ein seriöses gutes Online Casino in Deutschland besitzt eine virtuelle Automatenspiellizenz der GGL.
    Gute deutsche Online Casinos mit einer gültigen Lizenz der GGL (Gemeinsame Glücksspielbehörde der Länder) unterscheiden sich grundlegend von nicht seriösen Anbietern. Fernab der bereits vorgestellten Vorteile ist es vor allem die sehr große und facettenreiche Spielauswahl,
    mit der Lapalingo überzeugt.

    References:
    https://online-spielhallen.de/hitnspin-casino-test-bonus-top-spiele/

  5. Die Mission von NV Casino beschränkt sich nicht nur darauf,
    Ihnen eine vertrauenswürdige und zuverlässige Spielplattform auf
    jedem Gerät zu bieten. Und Sie können dies mit nur einem Klick über Gmail, Facebook oder TikTok tun. Wenn Sie Unterhaltung
    auf Casino.NV auswählen, erhalten Sie Zugriff auf moderate Roulette-, Blackjack-, Baccarat-
    und Pokertische.
    Sie können die App kostenlos aus den offiziellen App-Stores herunterladen und einfach installieren. Für weitere Informationen zu
    den speziellen Sonderbonus-Angeboten empfehlen wir den Besuch der
    offiziellen NV Casino Website. Das NV Casino bietet mehrere
    bequeme Zahlungsmethoden. Der Ablauf ist einfach und verständlich, selbst für diejenigen,
    die noch nie ein Online-Casino genutzt haben.

    References:
    https://online-spielhallen.de/beste-deutsche-online-casinos-mit-lizenz-nov-2025/

  6. Zuletzt hatte Pierce Brosnan als Bond in „Der Morgen stirbt nie“ in Hamburg einen deutschen Satz („Lass dich net‘ verarschen“).

    Kurz bevor er den Aston Martin DB5 ersteigert, begrüßt er den deutschen Schultz (Jürgen Tarrach) an der
    Bar mit „Guten Abend“ („Nabend“). Einen weiteren Kurzauftritt erkaufte
    sich Milliardär Richard Branson (Virgin), er ist im fertigen Film für einen kurzen Augenblick bei der Personenkontrolle am Miami
    International Airport zu sehen. CASINO ROYALE ist nicht,
    wie fälschlicherweise oft publiziert, der erste Bondfilm ohne
    Q, dieser ist auch in „Dr. Die Deluxe Blu-ray bietet schließlich einen in den Hauptfilm einblendbaren «Bild-im-Bild»-Kommentar mit Regisseur Martin Campbell und Produzent Michael G.
    Wilson.
    In der Hauptrolle ist wieder Daniel Craig zu sehen –
    dann heißt es zum 25. In «Casino Royale» war auch Caterina Murino als Solange Dimitrios zu sehen. 2006 gab
    Daniel Craig sein Debüt in der Filmreihe um den Agenten James Bond
    und seine actiongeladenen Aufträge. «…Energisch, waghalsig, schlagkräftig, schnell, geschmeidig, witzig…. und definitiv besser aussehend. In allem….» Mehr «…Nichts anderes erwartet man.. Klasse Qualität der Blu Ray und viel viel schärfer als im Fernsehen trotz HD Ausstrahlung..» Mehr Einige finden ihn sehenswert, knallhart und spannend.
    Sie beschreiben ihn als super, den besten Bondfilm und schönen Actionfilm.

    References:
    https://online-spielhallen.de/drip-casino-test-bonus-auszahlungen/

  7. VPH777 Online Casino: Official Login, Register, Slots, and App Download for Philippines Players. Experience the best at VPH777 Online Casino! Easy vph777 login and register to play premium vph777 slots. Get the vph777 app download for top-tier gaming in the Philippines. visit: vph777

Добавить комментарий для www.optionshare.tw Отменить ответ

Ваш адрес email не будет опубликован. Обязательные поля помечены *