CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

CakePHP Common Errors: Saving HasMany relations

The Cake Development Corporation team performs many code reviews. In fact, that is our starting point with every new client, as we offer free quick reviews. This is a good way to see where code stands, and how much work will need to be done to get it functioning properly. 

One of the common errors we have found while doing Code Reviews of existing applications or just working with inherited code, it’s the way HasMany relations data is saved. 

We have noticed that to save HasMany relations, some developers save the target relation, and then when the ID is retrieved after saving, they save one per one each item of the ‘many’ relation. There is no need to do this, as CakePHP can do all this in one single ‘save’! You won’t have any issue related to inconsistent data, because everything will be stored in one single transaction and your code will look much more clean.

Let’s see a quick and easy to follow example - We will have the following relations: ‘Users’ and one User could have many ‘Addresses’.  We wish to save one user and this user will have two addresses. 

First, you need to build the form in the proper way, the request data should follow the structure of your entities. The key in the form is the fieldName for the hasMany inputs. They must follow this format: {entityname}.{position}.{property}, for example: adddress.0.street_1, adddress.0.street_2, etc for the first item so store, for the second one: : adddress.1.street_1, adddress.1.street_2, and so on. More examples can be found here:  https://book.cakephp.org/4/en/views/helpers/form.html#creating-inputs-for-associated-data.


<?= $this->Form->create($user) ?>

<fieldset>

   <legend><?= __('Add User') ?></legend>

   <?php

       echo $this->Form->control('first_name');

       echo $this->Form->control('last_name');

       echo $this->Form->control('phone');

   ?>

   <legend><?= __('Address 1') ?></legend>

   <?php

   echo $this->Form->control('addresses.0.street_1');

   echo $this->Form->control('addresses.0.street_2');

   echo $this->Form->control('addresses.0.zip');

   echo $this->Form->control('addresses.0.city');

   echo $this->Form->control('addresses.0.state');

   ?>

   <legend><?= __('Address 2') ?></legend>

   <?php

   echo $this->Form->control('addresses.1.street_1');

   echo $this->Form->control('addresses.1.street_2');

   echo $this->Form->control('addresses.1.zip');

   echo $this->Form->control('addresses.1.city');

   echo $this->Form->control('addresses.1.state');

   ?>

</fieldset>

<?= $this->Form->button(__('Submit')) ?>

<?= $this->Form->end() ?>


Now that we have the form, we need to convert the request data. The Table class provides an easy and efficient way to convert one or many entities from request data. It’s needed to define which associations should be marshalled, using associated


public function add()

{

   $user = $this->Users->newEmptyEntity();

   if ($this->request->is('post')) {

       $user = $this->Users->patchEntity($user, $this->request->getData(), ['associated' => ['Addresses']]);

       if ($this->Users->save($user)) {

           $this->Flash->success(__('The user has been saved.'));

 

           return $this->redirect(['action' => 'index']);

       }

       $this->Flash->error(__('The user could not be saved. Please, try again.'));

   }

   $this->set(compact('user'));

}

In this example we are saving one user and two addresses for the given user. 

Associated data is validated by default, If you wish to bypass data validation, pass the validate => false option, for example: $this->Users->patchEntity($user, $this->request->getData(), ['associated' => ['Addresses' => [‘validate’ => false]]])

 

We are all about working smarter and in less time, so I hope this information will be useful! Take a look here for more information: https://book.cakephp.org/4/en/orm/saving-data.html#converting-request-data-into-entities 

We will be posting more Common Errors while using CakePHP.  Keep checking back!

Latest articles

Modifying Requests Like A Chef

Since the version 2.x of CakePHP has a requests and response objects, they are provided an abstraction around HTTP Requests and responses. If you are not familiar with CakePHP, it’s a common step when you bake and use $this->request->data instead of $_POST. Most of the time, we need to modify and append values on our Request data. This can be an identifier of logged user or values for any fields. In many situations, implementations will like this: Data can be modified easily - you just need to call withData or withParsedBody method and after set the Request  (you can also modify the query calling withQueryParams): Both implementations will generate the same value, but if you have a keen eye, you will see that the second implementation is more clear. Also, our Request has these values on data. This information can be useful when you use Components from Plugins, as they will expect the values on Requests.   That’s all bakers! I hope this content is useful for you and will improve your requests!  

Where you SHOULD be marketing your business.

Marketing is an essential part of your business’ success. I don’t just say this because I myself am a marketing connoisseur... or maybe I do. But either way, I’m going to shoot you some quick knowledge about getting your name out there... specifically into the cyber world.   

Social media 

Branding is very important here. This will be another blog for another time... but having a uniform look, format, font, etc will help you look professional and stand out. Some of the platforms I work with for our company is Facebook, Instagram, Twitter. In our industry, Twitter is our cake and frosting (see what I did there). Most developers have a Twitter and use this to interact with other developers, frameworks, and companies. Having a company page allows you to engage with your followers, have conversations, and build relationships. Remember, you need to be posting things that are important for those who follow you to see, and when they reach out, be ready to respond.  For business contacts and networking, I am a big fan of LinkedIn. This platform is an easy way to connect and search for others in your field. Also, it's a good way to find people looking for your specific services. Very business. Very professional.  You definitely need to get to know your audience. Tracking your social analytics will tell you where you stand out most. Then, you utilize that information!  

Ads

 I’m a fan of Google Ads. While I know that the idea of paid advertising isn’t ideal or financially possible for everyone, there are other options. Keeping up with your SEO, or search engine optimization, will help with organic ads. Organic ads is a fancy way of saying free clicks, or free adveritsing. When people are searching Google for services or phrases pertaining to your business, then your site will show in the results. Obviously if you pay for ads, you can manually add phrases and terms that may be searched for... and these are called keywords. I think Google Ads pointers may be a good blog for me to share in the future *makes mental note*.    Speaking of Google, make sure your “my Google business” account is up to date, otherwise you will literally NEVER show up on the search engine. Even when someone specifically searches for you or your company.   

Email Marketing

We must be careful here. Gone are the days of spam emailing... and cold calling? Please don’t. I’d say most people are ready to get restraining orders against telemarketers. Just me?  However, if you have specific things (sales, offers, important news) to share with your customer base, then by all means - onward. At least emails can be ignored if they are unwanted. If you want your email to be opened, make sure that you are offering your recipients something worth clicking (specials. Giveaways. Etc.). A good platform to help you with this is MailChimp, but there are soo many ways to generate these emails, and many even offer pre-made templates... so no excuses.   

Newsletters

Similar to email marketing, there are newsletters. The difference here is that the people who will be receiving your monthly (most likely) newsletter are only those that have chosen to. “Subscribers” sign up to receive these emails. Usually, these aren’t offers of sales, but rather news, events, tips etc. You can get an idea of what I mean by checking out the CakePHP Newsletter archives. 
  So let's close with some quick facts: Newspaper advertising? Out Telemarketing? Out  Print? Maybe  Billboards? If the price is right and you are local to certain areas. International companies, like CakeDC do not benefit from this type of print, unless we could put one in every city around the world. I think that would blow my marketing budget pretty quick.  If you are a freelancer, I definitely suggest Fiverr. Let people find you. Essentially you get quality leads for free.    All of these marketing platforms and items need to be explained in deeper detail, so if you have any questions feel free to reach out to me!  

Benefits Of Upgrading

Let’s talk more about upgrading your CakePHP application. In last week’s blog, we talked about why you should hire externally for all of your upgrade needs. You may have been thinking… but why would I (or my company) even need to spend the time, effort, and money on upgrading our projects. Well… for many reasons. You need better security, compatibility, functionality.  You’ve seen our posts, you know what needs to be done. Your old CakePHP application needs to be updated.  I want to remind you about some of the benefits that there is to upgrading.   

SECURITY

The more maintained a CakePHP version is, the more security it can provide. This not only protects the projects themselves, but can also give you peace of mind knowing that the latest versions will be functional a lot longer than say CakePHP 2.x. And of course, the latest releases fix a number of security issues. No company wants to offer quality services to their customers,  and end up with a security breach that was out of their control. It is extremely important to get ahead of the security issues on the front end. Be proactive, and you won’t have to be reactive.  The biggest concern is that many hosting providers are abolishing old PHP branches, essentially overnight. This is why it is important to be aware of when to migrate/upgrade and do it before it is too late. You can see a list of the end of life date for each unsupported branch of PHP HERE.   

PERFORMANCE

CakePHP 4 follows the latest conventions, helping your application run faster and smoother. Old sites / applications run slow… that is no secret. I promise you one thing, today’s Google searcher will not think twice to do a different search if the site is lagging (ain’t nobody got time for that).  Also, migrating to a current PHP release over 5.6 and using the new ORM, could lead to improvements over 50%. So I mean, win-win.    If you are wondering about your performance, speed, or  which versions of PHP you are running on, you can use tools like Pingdom - https://tools.pingdom.com/ or Google Chrome Devtools - https://developers.google.com/web/tools/chrome-devtools.  

SCALABILITY & TOOLS

CakePHP 4 is shipped with best practices to streamline horizontal scaling and deployment into containers. As new tools and plugins are released, they may only be compatible with the latest versions. Currently, there are over 900 updated plugins, see here: https://plugins.cakephp.org/, covering from background job processing, image processing, CMS, file upload and management, cache, and more. This provides more features and results in developers WANTING to use and work with the framework. 

Of course there is a long list of additional benefits, but these are some of the most important. 2021 seems to be turning into the year of upgrades. Don’t get left behind!

We Bake with CakePHP