Tag Archives: PHP

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.

Ubuntu/Debian

git

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

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

PHP

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

PEAR

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

$ sudo pear upgrade PEAR

PHPUnit

Then finally you will be able to install PHPUnit:

$ sudo pear config-set auto_discover 1
$ sudo pear install pear.phpunit.de/PHPUnit
$ phpunit --version

Windows

git

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.

PHP

  1. First download PHP 5.4 binaries from http://windows.php.net/ 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]
    zend_extension=ext\php_xdebug.dll
  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

PEAR

Next we have to install PEAR.

  1. Download go-pear.phar from http://pear.php.net 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

PHPUnit

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 pear.phpunit.de/PHPUnit

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 http://www.grumpy-testing.com/.

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!

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 joind.in, 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 proofek.github.com/pear
$> 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!

PHPUnit assertion gotcha

A recent discovery. If you found yourself upgrading from PHPUnit 3.5.x to PHPUnit 3.6.x be aware of a subtle change. assertEquals() and I guess all related assertions will behave a bit differently after the upgrade. When you assert 2 values and one of them is an object with defined __toString() function PHPUnit 3.5.x will fail the test, while PHPUnit 3.6 will happily pass it (by I am guessing converting the object to string). See an example on gisthub for more details:

$ phpunit testCaseTest.php
PHPUnit 3.5.15 by Sebastian Bergmann.
F.
Time: 1 second, Memory: 4.50Mb
There was 1 failure:
1) TestCase::testAssertStringWithObject
Failed asserting that
myClass Object
(
)
matches expected .
/private/tmp/Testing/testCaseTest.php:16
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
$ phpunit testCaseTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
..
Time: 1 second, Memory: 5.50Mb
OK (2 tests, 2 assertions)

PHP Benelux 2012 – 4 days of awesomeness

PHP BeneluxI was extremely pleased that I was invited to talk at the annual PHP Benelux conference in Antwerp. It was my first time in Antwerp, but I have heard about this conference so much before. And I must tell, all of it was true.

The arrival

But starting from the beginning, which was the landing of PHPNWAir plane (as named by Michelangelo van Dam) with a representation of 7 people from British PHP NorthWest Community (including 3 speakers – Rowan Merewood, Jeremy Coates and me) in Brussels Charleoi. And yes, I do admit it was a poor choice of mine to decide to fly Ryanair from Manchester to this airport. Connection is bad, it’s about an hour drive from Antwerp, and if not the help from PHP Benelux crew (namely @DragonBe and @Martin1982) we would be in trouble. So I am sorry once again guys, I won’t do it again! :D

Socials

From then on I will only guess what heppened next, as I have problems recalling what happened on what day. Speakers dinner was an amazing opportunity to meet the conference crew and speak to the other speakers. A rare occasion indeed. Some of them I already knew from previous conferences like PHPNW, PHPUK and 4developers, but some of them I had the pleasure of meeting for the first time, face to face. There is nothing better, then speaking to other experienced developers at a conference, truly amazing and unique experience. How often you have an opportunity to meet people like @derickr, @weierophinney, @rdohms, @davidcoallier, @dzuelke, @joshholmes, @h, @DragonBe, @skoop and @ianbarber in one place at the same time? And that’s only a short list, cause I could go and go and go naming them one after another!

The conference was executed perfectly! I couldn’t be looked after better even by my own mother! @ThijsFeryn@DragonBe@Martin1982 and the rest of the crew – it’s a massive thank you from me! Sponsors did great too – @ibuildings and @engineyard responsible for the afterconference socials helped a lot with maintaining the spirit and helping everybody enjoy the conference to its very limits! We had so much fun bowling on Friday night (and yes I won!) and watching @juokaz and @dzuelke competing – whether it was about which phone is better or who’s better at Kinect Tennis! Can’t deny the fact that beer tasting session and Belgian fries and spécialités also helped during that day.

The winter BBQ, well… it was bloody cold, but again the beers, liquors, hot food and @Orchestra_io scarf helped to survive the evening. We even managed to go for a pizza to Antwerp late night when we got hungry! Some people even managed to come back in a car’s boot!

Learning

But conference it’s not about fun, but first of all about learning. And hell yeah, there was a lot to learn! I have seen a number of talks (and shamefully missed a few ones for reasons I am not gonna mention here ;)).

I’ll start with @dzuelke‘s  “Large-Scale Data Processing with Hadoop and PHP”. David is always an inspiration for me – an excellent speaker with really good talk. This one definitely gave me a few ideas how I could use Hadoop in my daily job. Hopefully I will find some time to come up with some prototypes.

Helgi Þorbjörnsson also gave a solid talk on “PHAR, the PHP .exe format”. While I already knew a few things about phar, he definitely managed to mention some interesting things about phar I didn’t know before. I really liked the way he engaged the audience. Really good idea!

Rowan Merewood and his “Estimation or, “How to Dig you own Grave”” was another great performance. Nothing new for me there (well, we worked together for a number of years), but I always admire Rowan for his slides and the way he talks. A true masterpiece.

Matthew Weier O’Phinney’s “VIM + *nix Toolchain == PHP IDE” definitely inspired me again to come back and learn a few new things about vim. Inspirational speaker with a lot of charisma!

“PHP traits, treat or threat?” by Nick Belhomme was the talk I really wanted to see since I really didn’t have any time to look at PHP 5.4. While the talk was a bit chaotic at times for me, I still learned a lot about traits, and as of now, I know one thing – I don’t think I like them and I don’t think I will use them – it’s more of a threat for me. They seem to be too messy.

You could tell Marcel was nervous during his “The lust for knowledge and experience” talk. But still it was a good talk with very good professional slides. It was a chance for me to rethink a few things about the relations between “the master”, “apprentice” and “a junior”.

Finally, the best talk of the conference from David Coallier “Taking it to the next level”. I absolutely loved the way he did his talk and how he engaged the audience. He only made me realise how rarly we tell other how much we appriciate their work and how we all take the work of others for granted. Thanks you very much for that David!

My software metrics talk

At last I’d like to thank everybody for attending my “Magic Behind the Numbers – Software Metrics In Practice” talk. I am really glad, that more and more people are looking at improving the quality of their code and want to learn more about it. I was impressed with the fact how many people in Benelux are using tools like PHP Depend and PHP Mess Detector! Keep it up guys! Thank you very much for all the feedback. I’ll definitely use it in the future to improve my presentation and make it more interesting. You can find the slides from my talk on slideshare.

Summary

I will definitely do my best to come back to Antwerp next year, but until then I hope to see you next month in London at PHPUK 2012!