Category Archives: PHP

SugarCRM relate field vs 1-2-many relationship

I have been using studio to add custom relate fields to my modules, but until now I wasn’t really aware of its downsides. It seems that Studio is making really nasty shortcuts when it creates a relate field which impacts the ways you can access related fields from the API for example. And when I say impacts, it means it’s basically impossible. So let’s have a look what Studio does when you add a relate field.

Studio creates 2 fields: one called related_user_c and one called user_id6_c. Here are their definitions:

They are linked together via the id_name element of the related_user_c definition. After ‘Repair and Rebuild’ we gonna end up with an user_id6_c column in the table. It all seems to be working well, until you try to use the SugarCRM API. There is now way to fetch data from the related field in one API call. All you can do is to fetch the id from the user_id6_c column and then knowing that it actually links back to Users module fetch the details. It’s all because Studio did not create a proper relationship with the Users module. So, let’s have a look how we could do it with a 1-2-many relationship built in code. Instead of using the studio, let’s just build the required fields manually in the code. For a brand new module I recommend you do that in the modules directory –  modules/<module_name>/vardefs.php, for an existing one create a file in custom/modules/Accounts/Ext/Vardefs/. I prefer to have every field definition in a separate file. It’s up to you. You will need 3 fields – one storing an id in the database – related_user_id, one is gonna be a relate field used on the forms to present the field – releted_user_name and the final one is gonna be a link, that API can use to fetch related record details – requested_by_link. They will roughly look like this:

Please note the fields are linked to each other – releted_user_name links to the releted_user_id field using id_name element and links to the releted_user_link field using link element. releted_user_link field links to releted_user_id using id_name element and links to a relationship called accounts_related_user using relationship element. This relationship doesn’t exist yet, we still have to create it. It’s gonna roughly look like this:

Again, note that it links to the releted_user_id field via rhs_key element.


Now when you repair and rebuild the field will be added to the database and you can add it to your views – edit, details and list views. And most importantly you can access the related field details through the API, by using the link we have created – just pass it through using link_name_to_fields parameter in your request, something like this:

SugarCRM 1-2-many relationship with no middle table

In SugarCRM, when you create a relationship, and it doesn’t matter whether it is a 1-2-many or many-2-many relationship, it always creates you a middle table. Which is kinda annoying, since for 1-2-many relationships you don’t really needed. And when I say middle table, I mean a link table between 2 tables.

It’s the best to describe that in a real life example. Let’s assume, you want to start storing in Sugar your suppliers details and their contact details. What you would normally do, you would create a Suppliers module to store the supplier details – the name, address, contract details, etc and a ContactDetails module to store information about different ways you can contact the supplier – so type of contact details and a value. Then you would create a 1-2-many relationship between them 2:

Now, when you look in the database, Sugar is gonna create for you the 3 “nice” tables:

But, what we really want is 2 tables with a “foreign” key in the contact details table, something like this:

Fortunately, it’s not that difficult. Searching google for a solution brings a few posts. Me personally I have based on 2 posts by John Mertic from SugarCRM:

The problem is, they cover the topic well in terms of concept, but you can’t really follow it step by step, at least not without a good understanding of SugarCRM as a development platform. It took me several hours to match all the dots together, before I made the whole thing work. And that’s because I simply did not understands some of the things John did there (and I am not quite sure whether I understand it now). So here’s the step by step guide, that I follow, and my understanding how it all works. I assume you already have the 2 modules created, and what we will do now, is just create the relationship between them so Sugar modifies db schema for us, add the panel to the parent module so we can see associated records on the Suppliers screen and modify the panel so we can create new records using quick create form.

1. Step 1: Create the relate fields

First we will create fields required for the relationship: the id field and relate field. Create a new file called SupplierRelate.php in custom/Extension/modules/Demo_SupplierContactDetails/Ext/Vardefs/ and define the 2 fields in there as below:

There is a few things you have to pay attention to. First of all make sure the module name is correct in the $dictionary array. In my case it is Demo_SupplierContactDetails, following the convention of <PackageName>_<ModuleName> – I named my package Demo and the module SupplierContactDetails. Next the field name is really important and it has to follow the pattern of <ParentBean>_<FieldName>, so in my case it is demo_suppliers_name and demo_suppliers_id (all lowercase). If you don’t do it right, later on the quick create form is not gonna work. If you change the values in the field definitions to match appropriate parent module name, everything should be fine. Take a note of name and id_name in demo_suppliers_name field definition and name in demo_suppliers_id field definition. The relate field (‘name’ one) we will be using to associate SupplierContactDetails data with a parent supplier, while the ‘id’ field will be used to alter the demo_suppliercontactdetails table and add the parent id column in there (which will be called demo_suppliers_id)

2. Step 2: Define the relationship

Next, we will define the relationship. Will do that in the same file, as follows:

First is the link to the relationship – note the relationship element of the first array that is used below for the relationship definition itself and module and bean name of the parent module.  Secondly note the 2 sides of the relationship in the relationship definition – the left hand side (lhs) pointing at Demo_SupplierContactDetails table and demo_suppliers_id key (the same name we have define above in the id field definition) and right hand side (rhs) pointing at Demo_Suppliers table with id key.

To complete the relationship we also have to define the link in the parents module. So let’s create another file called SupplierContactDetailsRelate.php in custom/Extension/modules/Demo_Suppliers/Ext/Vardefs/:

Note the module name in the $dictionary array which point at our parent module Demo_Suppliers, the name of the field that point at the child module (although I am not sure whether it is important, but I guess even for clarity and readability it is worth to stick to it) and finally the relationship name which has to be the same as the one we have used in the definition in the child module above.

3. Step 3: Add missing labels in the language pack

Don’t forget about the label definitions. I only care about en_UK packs so I have added the new label definitions into:

  • modules/Demo_Suppliers/language/en_UK.lang.php
  • modules/Demo_SupplierContactDetails/language/en_UK.lang.php

That includes:

  • ‘LBL_SUPPLIER_NAME’ => ‘Supplier name’,
  • ‘LBL_SUPPLIER_ID’ => ‘Supplier ID’,
  • ‘LBL_SUPPLIERS’ => ‘Suppliers’,
  • ‘LBL_SUPPLIER_CONTACTDETAILS’ => ‘Supplier Contact Details’,

4. Step 4: Repair and rebuild

Now, when you go to the admin panel and run Quick Repair and Rebuild Sugar will generate the SQL query you need to run to alter the child table (instead of creating the middle table):

and achieve what we wanted from the very beginning, no middle table.

5. Step 5: Add relate field to SupplierContactDetails layout

But, that’s not it. While we have created the relationship, we can’t associate the records together yet. First thing we have to do, is to add the newly created relate field (Supplier name) onto detail, edit, quick create and list view of the Demo_SupplierContactDetails module. You can easily do that via Studio:

Now we can easily associate and see the parent record information.

6. Step 6: Create the subpanel for Suppliers module

The final step will be to add subpanel in the Suppliers module, so we can easily see the associated records and create them from within the same module. All we have to do is create a new file called demo_suppliercontactdetails_subpanel.php in custom/Extension/modules/Demo_Suppliers/Ext/Layoutdefs/ with the following contents:

Once again, note the name of the subpanel in $layout_defs array – demo_suppliercontactdetails (although I don’t know whether it has to match the child module – again will definitely make it easier to understand what the panel is for), module and get_subpanel_data need to point at the child module. It’s extremly important that get_subpanel_data points at the child module, otherwise no data will be retrieved. And finally top buttons will allow us to create new contact details record using quick create form. I have also added the label to modules/Demo_Suppliers/language/en_UK.lang.php and run ‘Repair and Rebuild’.

But that’s not it. We now have to define the subpanel itself. Create a brand new file called Demo_Suppliers_subpanel_demo_suppliercontactdetails.php in custom/modules/Demo_SupplierContactDetails/metadata/subpanels/. It’s very important that this filename matches the name of the subpanel defined in the file above – Demo_Suppliers_subpanel_demo_suppliercontactdetails, and follows the pattern I used. If you live that file empty (with only opening php tag at the top) you will be able to go into Studio and drag the columns you want on the subpanel and simply click ‘Save and Deploy’.


The file will then look something like this:

Please note the 2 elements of the array at the bottom – edit_button and remove_button. Studio won’t have them on the column list – I have added them manually afterwards. These 2 buttons will allow you to edit and delete a record on the list. And so here it is our completed subpanel:

and the quick create form (I have already tweaked it in Studio to show only relevant fields):

Note: I have noticed, that the remove button actually doesn’t work. Will have to find out why.

Test your code like a pro – PHPUnit in practice – preparation guide

As promised, here’s a quick guide that will allow you to prepare for my “Test your code like a pro – PHPUnit in practice” tutorial at PHPNW12 conference in Manchester on 5th October. If you still haven’t decided whether to go or not have a look at the official abstract and my previous blog posts. There is still time to get the tickets!

There are really 2 things that you will need, to get smoothly through the tutorial: git client and working installation of PHPUnit. So please make sure you have installed them and you can use them. Being able to open PDF files is also recommended as I will be giving out a tutorial’s manual/instructions in a PDF format.

Well this above obviously requires a computer. I guess you will decide to bring a laptop with you, although if you prefer to take your desktop computer with you, it will do too. While most of the stuff will be in the PDF file, going through the tutorial without a laptop will be difficult to follow and you will not learn as much. I will not have any spare laptops to borrow, sorry.

I strongly discourage brining in a Windows machine with you, unless you feel comfortable with solving any problems related with php, pear and PHPUnit in a very short period of time or you come really well prepared. We will not have a lot of time to spend configuring each other machines and we also don’t want the others to wait and do nothing while you set everything up. We only have 3 hours, and believe me it will go fast.



Using apt to install git should set you up pretty quickly. Just type in the below:

$ sudo apt-get install git-core
$ git --version


You will need at least PHP 5.3.3 installed, but I strongly recommend installing PHP 5.4. Again with apt it should be pretty instant to get you set up:

$ sudo apt-get install php5-cli
$ sudo apt-get install php-pear
$ sudo apt-get install php5-xdebug
$ php -v


Before you can install PHPUnit you need to make sure PEAR is at the latest version. So upgrade it first

$ sudo pear upgrade PEAR


Then finally you will be able to install PHPUnit:

$ sudo pear config-set auto_discover 1
$ sudo pear install
$ phpunit --version



You can install git client on a Windows machine by using the installer package that you can download from msysgit project downloads page.

Just accept all the default options. All you really need is to be able to clone a repo and change branches.


  1. First download PHP 5.4 binaries from and unzip it into c:\php.
  2. Then download xdebug library from xdebug downloads page and copy it over to c:\php\ext directory.
  3. Rename the library to php_xdebug.dll.
  4. Copy c:\php\php.ini-development to c:\php\php.ini
  5. Make sure date.timezone is set to “Europe/London”
  6. Activate xdebug by adding the snippet bellow at the end of c:\php\php.ini
  7. [xdebug]
  8. Add c:\php to system path via Computer’s Advanced Properties -> Environment Variables
  9. Restart windows
  10. In the command prompt run:
  11. c:\> php -v
    PHP 5.4.7 (cli) (built: Sep 12 2012 23:48:31)
    Copyright (c) 1997-2012 The PHP Group
    Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
        with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans


Next we have to install PEAR.

  1. Download go-pear.phar from and copy it over to c:\php\
  2. Run the following command and from the presented options change option 1 – Installation base to c:\php and option 11 – Name of configuration file to c:\php\pear.ini
  3. c:\> php c:\php\go-pear.phar
  4. Then hit enter to finish installation
  5. Let installer change your include path at the end by answering y to the question “Would you like to alter php.ini?”
  6. Double-click the PEAR_ENV.reg file in c:\php
  7. Reboot again to make sure PEAR_ENV registry entries have taken effect


Finally it’s time to install PHPUnit. At this point just running the below should set you up.

c:\> pear config-set auto_discover 1
c:\> pear install

c:\> phpunit --version
PHPUnit 3.7.0 by Sebastian Bergmann.

If at any point you have a problem with installing it all on Windows please drop me an email. You can also have a look at Stu Herbert’s blog post about Getting PEAR working on Windows 7

I hope this short guide will let you come to my tutorial well prepared. I will see you in Manchester soon!

The Grumpy Programmer’s Book at PHPNW12

I’ve got some good news for the people that already have decided to attend my tutorial “Test your code like a Pro – PHPUnit in practise” at PHPNW12 conference in ManchesterChris Hartjes has kindly offered to give away 3 digital copies of his famous “Guide To Building Testable Applications in PHP” book to attendees of my tutorial! I strongly believe this will nicely compliment the tutorial itself and give the people such a boost in their further adventures with testing. You can learn more about the book itself at

Your still have a chance to get a ticket to my tutorial on 5th October and only one more reason to buy it! For these who already know PHPUnit and already have started they journey through unit testing PHP code I strongly recommend buying the book and reading it. There is plenty of hints and tips that will help you understand how to write unit testable code and increase its quality!

Big thanks to Chris again and I hope to see you all in Manchester soon!

Test your code like a pro – PHPUnit in practice at PHPNW12

PHP NW12 conference is nearly upon us, so I guess it’s about time to tell you more about the workshop that I will be having there on the 5th October morning. I wanted to do that for a very long time, especially that I am a big fan of quality assurance in software engineering. You can read the official abstract at the conference homepage, but here I am gonna tell you a little bit more about what we gonna do during the 3 hour tutorial.

My main focus will be to teach you and lead you through main concepts of unit testing PHP code. It’s a beginners course, so we will go though all the basics of organising your test suite, understanding the benefits of unit tests and making you feel comfortable and confident with the code you write. We’ll do it all big band TDD style – so we will write the tests first and implement the functionality afterwards. It’s very important to get this right and to set up the mindset from the very beginning.

PHPUnit is de-facto a standard in PHP world, so it is also important that you are aware of the main features of the tool. We’ll go through the set up, configuration and options that are the most useful at the beginning – so you can get the most out of the tool. The concepts that I am gonna go through will include:

  • working with typical test suites
  • basic assertions – strings, integers, booleans, object
  • PHPUnit from the command line
  • using phpunit.xml configuration file
  • testing exceptions
  • testing PHP errors, warnings and notices
  • asserting output
  • data driving your tests by using data providers
  • generating code coverage report

If you have never had a chance to unit test your code, but you’d like to try now, it’s the best time to get started. I will do my best to make you feel confident and to help you start your own Journey Towards Continuous Integration, but what you have to do is to go to your boss and convince him to buy you a ticket to my tutorial ( and the conference). There is still plenty of time and there are still some tickets left.

No matter whether you have already bought a ticker or you’re thinking about right now, if there is anything specific you you want me to go through during the tutorial please let me know. I’ll do my best to fit that in. We can also change the course of the tutorial if the group will prefer to touch on some slightly different subjects of unit testing – I am open for suggestions. And I will be accessible after the tutorial too, for any questions, help or even quick hacks. You will even get more chances to speak to me over the next 2 days, during the main conference days – on the 6th and 7th October.

It’s a lot of things to go through so it is very important that you come prepared and focused on the day. We only have 3 hours and I’d like to avoid situation where the hardware/operational issues will stand in our way. While I will try to help everybody out if there are any issues I will encourage you to install PHPUnit on your laptops before, so it is working without a problem. I want to focus on writing the tests and using PHPUnit, not on trying to make PHP itself working on your machines.  I strongly recommend using a non-Windows system. Windows has been proved to be very unreliable if it comes to setting up PHP and PEAR. It does work, but it requires some strong skills and patience. So you’d rather install ubuntu or debian, as this is an environment that everything just works out of the box.

During the course of the next 2 days I will post more detailed instructions about how you can prepare your laptops to make sure you can run PHPUnit on them without any issues, so watch this space closely.

I hope to see you at my tutorial in about 3 weeks!

Symfony2 Live! London – aftermatch

Symfony Live LondonI am sitting on the train back to Sheffield coming back from an awesome Symfony Live London event. It was my first time at Symfony Live conference, and at the same time it was first edition of the conference held in London. Conference was organised perfectly, but was else could you expect from  people like Lorna Jane and Wes Thompson! Great event guys and very well done!

For a person like me, who only started working with Symfony2 a few months ago, it was a mind blowing mine of information about Symfony2, tools that support symfony2 applications like composer and behat and general practises around using the framework itself. I was pretty impressed by the fact how Drupal8 and Symfony2 work together, and get the famous CRM event better. It definitely proves that PHP as the language, environment and surrounding community matures. The talks in fact were only the background of the opportunities that I had today – meeting in person and being able to talk to people like Fabien Potencier (creator of Symfony2), Jordi Boggiano (the man behind composer), Konstantin Kudryashov (the Behat man) and Marcello Duarte (the PHPSpec man). The conference venue was all buzzing – people talking and exchanging experiences.

I have seen 6 talks in total:

Every talk was unique and touched on different subject, but I have to admit Konstantin and Marcello just blown my mind off with they approach to testing with BDD. I still can’t get all the things together and they gave me plenty of things to think about. The next thing I will do will be to replicate what they have done with Behat and PHPSpec2 during their presentation.  I do not agree with what they have said about unit testing, and I still believe that unit testing has it’s own place in the development processes, just needs to be used right and for the right purpose. For me the BBD way they have shown us it’s a different approach to testing only complementing xUnit. Anyway have a look at their slides and at Behat and PHPSpec2 if you haven’t yet. PHPSpec2 is still pre,pre,pre,pre,pre,pre,pre,[pre,] alpha, but looks really promising and I can see myself including it in my toolset.

Finally, I’d like to thank everybody who attended my talk Effective Code Reviews and asked all the questions afterwards. It’s been a pleasure to be able to meet you all and exchange all the experiences around code review process. Thanks to everybody who left the feedback on, and if you have seen my talk and not yet gave me the feedback please do so. It’s very important for me to know what did you like and what not, so I can improve it in the future.

Enough writing, I am too excited about Behat and PHPSpec2 so I am gonna download it and play with it for another hour, and I hope to meet you all again in a year time at the the next Symfony Live! London Conference!

Speaking at Symfony Live London

Symfony Live London It’s quite late now, but there are still some tickets and time to get on board and come to London to participate at Symfony Live London conference this Friday (14th Sept 2012). The lineup is pretty impressive, including well known speakers like Fabien PotencierJordi BoggianoRowan MerewoodRichard Miller and Konstantin Kudryashov. The more honoured I feel to be able to speak amongst them. I will be talking about code reviews and will share my experiences “straight from the field”. I count on you to challenge me and discuss all the things about development processes, specifically around code quality.

See you in London!

Speaking at Forum PHP Paris 2012

I am getting very excited about next week. I will be speaking in Paris at Forum PHP Paris 2012 conference about software metrics. So if you are interested in software metrics or you want to learn how to read them and use them to produce better software grab a ticket and come to Paris next week. I am looking forward to meet some old friends and also to make some new friendships. Hopefully my inability to speak French will not stop me 😉

PHP54Compatibility 0.2 released

Last night I have merged in a few pull requests adding additional sniffs to the existing collection and packaged it all. List of all supported checks is in the README file. Check the repository on github to see it. Big thanks go to Laura Beth, Nathaniel McHugh and Ben Selby for all the contributions. I have created a pear package and published it on my github pear channel so you can easily install it from there. No more alpha release either, so even easier to install.

$> pear channel-discover
$> pear install proofek/PHP54Compatibility

There are 2 dependencies at the moment: PHP 5.4 and PHP_CodeSniffer 1.3+. A few people asked my to downgrade the minimum PHP version to 5.3. The reason why I want PHP 5.4 is I want to use 5.4 tokaniser to make sure  code is parsed the way it will be parsed on the target PHP 5.4 platform. If you want to run pre-checks, before you actually upgrade to 5.4, use -f flag to perform forced installation:

$> pear install -f proofek/PHP54Compatibility

But I would still encourage you to upgrade first to get the best results.

PHP 5.4 Compatibility Coding Standard for PHP_CodeSniffer

So with PHP 5.3 upgrade underway (and PHP 5.4 out of the door now!) I thought it’s time to prepare for PHP 5.4 and make sure we’re compatible. So by looking at Wim Godden’s PHP53Compatibility code sniffs I have created a base for PHP 5.4 sniffs that we want to use to make sure we’re compatible. It’s a base, so it’s not finished/perfect in any sense so I will be relying heavily on PHP Community to help me out with it. I will obviously be working on it hard, but any pull requests are greatly appreciated.

So where is it then?! It’s on github! I have also set up my personal github PEAR channel and will release a first alpha package so you can install it easily.

Right, back to work!