How to Delete Records from Database Table in CakePHP

Delete Records from Database Table in CakePHP

To delete a record in database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to delete.

Call the get() method with this new instance and pass the primary key to find a record which will be saved in another instance. Use the TableRegistry class’s instance to call the delete method to delete record from database.

Example

Make changes in the config/routes.php file as shown in the following code.

config/routes.php

<?php use CakeCorePlugin;
use CakeRoutingRouteBuilder;
use CakeRoutingRouter;
Router::defaultRouteClass(‘DashedRoute’);
Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘/users/delete’,
[‘controller’ => ‘Users’, ‘action’ => ‘delete’]); $routes->fallbacks(‘DashedRoute’); });
Plugin::routes();

Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.

src/controller/UsersController.php

<?php namespace AppController;
use AppControllerAppController;
use CakeORMTableRegistry;
use CakeDatasourceConnectionManager;
class UsersController extends AppController{ public function index(){ $users = TableRegistry::get(‘users’);
$query = $users->find(); $this->set(‘results’,$query); }
public function delete($id){ $users_table = TableRegistry::get(‘users’); $users = $users_table->get($id); $users_table->delete($users);
echo “User deleted successfully.”; $this->setAction(‘index’); } } ?>

Just create an empty View file under Users directory called delete.ctp.

src/Template/Users/delete.ctp

Create a directory Users at src/Template, ignore if already created, and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Users/index.ctp

Add User

 

ID Username Password Edit Delete

Execute the above example by visiting the following URL and click on Delete link to delete record.

http://localhost:85/CakePHP/users

Discuss on CakePHP Framework

Discuss on CakePHP Framework

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on an MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers guarantee a strict but natural separation of business logic from data and presentation layers.

CakePHP can be asked and both the community and core developers will get a chance to help and contribute. Please keep discussion friendly and constructive. Click here to join in CakePHP Official Forum

Cakephp official website: https://book.cakephp.org

How to Handle Errors and Exception in CakePHP

How to Handle Errors and Exception in CakePHP

Failure of system needs to be handled effectively for smooth running of the system. CakePHP comes with default error trapping that prints and logs error as they occur. This same error handler is used to catch Exceptions. Error handler displays errors when debug is true and logs error when debug is false. CakePHP has number of exception classes and the built in exception handling will capture any uncaught exception and render a useful page.

Errors and Exception Configuration

Errors and Exception can be configured in file configapp.php. Error handling accepts a few options that allow you to tailor error handling for your application −

Option Data Type Description
errorLevel int The level of errors you are interested in capturing. Use the built-in php error constants, and bitmasks to select the level of error you are interested in.
trace bool Include stack traces for errors in log files. Stack traces will be included in the log after each error. This is helpful for finding where/when errors are being raised.
exceptionRenderer string The class responsible for rendering uncaught exceptions. If you choose a custom class, you should place the file for that class in src/Error. This class needs to implement a render() method.
log bool When true, exceptions + their stack traces will be logged to CakeLogLog.
skipLog array An array of exception classnames that should not be logged. This is useful to remove NotFoundExceptions or other common, but uninteresting logs messages.
extraFatalErrorMemory int Set to the number of megabytes to increase the memory limit by when a fatal error is encountered. This allows breathing room to complete logging or error handling.

Example

Make changes in the config/routes.php file as shown in the following code.

config/routes.php

<?php use CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', 
function (RouteBuilder $routes) { $routes->connect('/exception/:arg1/:arg2',[ 'controller'=>'Exps','action'=>'index'],['pass' => ['arg1', 'arg2']]); $routes->fallbacks('DashedRoute'); }); 
Plugin::routes();

Create ExpsController.php file at src/Controller/ExpsController.php. Copy the following code in the controller file.

src/Controller/ExpsController.php

<?php namespace AppController; 
use AppControllerAppController; 
use CakeCoreExceptionException; 
class ExpsController extends AppController{ public function index($arg1,$arg2){ try{ $this->set('argument1',$arg1); $this->set('argument2',$arg2); 
if(($arg1 < 1 || $arg1 > 10) || ($arg2 < 1 || $arg2 > 10)) throw new Exception("One of the number is out of range[1-10]."); }
catch(Exception $ex)
{ echo $ex->getMessage(); } } } ?>

Create a directory Exps at src/Template and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Exps/index.ctp

This is CakePHP tutorial and this is an example of Passed arguments. Argument-1: <?=$argument1?> Argument-2: <?=$argument2?>

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/exception/5/0

How to Extend Views in CakePHP

Extend Views in CakePHP

Many times, while making web pages, we want to repeat certain part of pages in other pages. CakePHP has such facility by which one can extend view in another view and for this, we need not repeat the code again. The extend() method is used to extend views in View file. This method takes one argument, i.e., the name of the view file with path. Don’t use extension .ctp while providing the name of the View file.

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', function (RouteBuilder $routes) { $routes->connect('extend',['controller'=>'Extends','action'=>'index']); $routes->fallbacks('DashedRoute'); }); 
Plugin::routes();

Create a ExtendsController.php file at src/Controller/ExtendsController.php. Copy the following code in the controller file.

src/Controller/ExtendsController.php

<?php namespace AppController; use AppControllerAppController; class ExtendsController extends AppController{ public function index(){ } } ?>

Create a directory Extends at src/Template and under that folder create a View file called header.ctp. Copy the following code in that file.

src/Template/Extends/header.ctp

Common Header

<?= $this->fetch('content') ?>

Create another View under Extends directory called index.ctp. Copy the following code in that file. Here we are extending the above view header.ctp.

src/Template/Extends/index.ctp

<?php $this->extend('header'); ?>

This is an example of extending view.

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/extend

Output

Upon execution, you will receive the following output.

 

Folder Structure Overview in CakePHP

Folder Structure Overview in CakePHP

CakePHP – Folder Structure

The following table describes the role of each folder −

S.No Folder Name & Description
1 bin

The bin folder holds the Cake console executables.

2 config

The config folder holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.

3 logs

The logs folder normally contains your log files, depending on your log configuration.

4 plugins

The plugins folder is where the Plugins your application uses are stored.

5 src

The src folder will be where you work your magic: It is where your application’s files will be placed. CakePHP’s src folder is where you will do most of your application development. Let’s look a little closer at the folders inside src.

  • Console Contains the console commands and console tasks for your application.
  • Controller Contains your application’s controllers and their components.
  • Locale Stores string files for internationalization.
  • Model Contains your application’s tables, entities and behaviors.
  • View Presentational classes are placed here: cells, helpers, and template files.
  • Template Presentational files are placed here: elements, error pages, layouts, and view template files.
6 tests

The tests folder will be where you put the test cases for your application.

7 tmp

The tmp folder is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions and sometimes session information.

8 vendor

The vendor folder is where CakePHP and other application dependencies will be installed. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core.

9 webroot

The webroot directory is the public document root of your application. It contains all the files you want to be publically reachable.

 

How to Set Email Configuration in CakePHP

how to set email configuration in cakephp

Email can be configured in file config/app.php. It is not required to define email configuration in config/app.php. Email can be used without it; just use the respective methods to set all configurations separately or load an array of configs. Configuration for Email defaults is created using config() and configTransport().

Email Configuration Transport

By defining transports separately from delivery profiles, you can easily re-use transport configuration across multiple profiles. You can specify multiple configurations for production, development and testing. Each transport needs a className. Valid options are as follows −

  • Mail − Send using PHP mail function
  • Smtp − Send using SMTP
  • Debug − Do not send the email, just return the result

You can add custom transports (or override existing transports) by adding the appropriate file to src/Mailer/Transport.Transports should be named YourTransport.php, where ‘Your’ is the name of the transport. Following is the example of Email configuration transport.

Example

‘EmailTransport’ => [ ‘default’ => [ ‘className’ => ‘Mail’, // The following keys are used in SMTP transports ‘host’ => ‘localhost’, ‘port’ => 25, ‘timeout’ => 30, ‘username’ => ‘user’, ‘password’ => ‘secret’, ‘client’ => null, ‘tls’ => null, ‘url’ => env(‘EMAIL_TRANSPORT_DEFAULT_URL’, null), ], ],

Email Delivery Profiles

Delivery profiles allow you to predefine various properties about email messages from your application and give the settings a name. This saves duplication across your application and makes maintenance and development easier. Each profile accepts a number of keys. Following is an example of Email delivery profiles.

Example

‘Email’ => [ ‘default’ => [ ‘transport’ => ‘default’, ‘from’ => ‘you@localhost’, ], ],

Tutorials on Form Handling, Building HTML in CakePHP

Tutorials on Form Handling, Building HTML in CakePHP

Form is a simple input taker in applications, defined inputs by users need authentication and formatting to be stored. Cakephp makes easy FormHelper to work with form. It is quick and will streamline validation, re-population and layout.

CakePHP – Form Handling

CakePHP provides various in built tags to handle HTML forms easily and securely. Like many other PHP frameworks, major elements of HTML are also generated using CakePHP. Following are the various functions used to generate HTML elements.

The following functions are used to generate select options.

Syntax _selectOptions( array $elements array(), array $parents array(), boolean $showParents null, array $attributes array() )
Parameters
  • Elements to format
  • Parents for OPTGROUP
  • Whether to show parents
  • HTML attributes
Returns array
Description Returns an array of formatted OPTION/OPTGROUP elements

The following functions are used to generate HTML select element.

Syntax select( string $fieldName, array $options array(), array $attributes array() )
Parameters Name attribute of the SELECT

Array of the OPTION elements (as ‘value’=>’Text’ pairs) to be used in the SELECT element

The HTML attributes of the select element.

Returns Formatted SELECT element
Description Returns a formatted SELECT element

The following functions are used to generate button on HTML page.

Syntax Button (string $title, array $options array() )
Parameters
  • The button’s caption. Not automatically HTML encoded.
  • Array of options and HTML attributes.
Returns HTML button tag.
Description Creates a <button> tag. The type attribute defaults to type=”submit“. You can change it to a different value by using $options[‘type’].

The following functions are used to generate checkbox on HTML page.

Syntax Checkbox (string $fieldName, array $options array() )
Parameters
  • Name of a field, like this “Modelname.fieldname”
  • Array of HTML attributes. Possible options are value, checked, hiddenField, disabled, default.
Returns An HTML text input element.
Description Creates a checkbox input widget.

The following functions are used to create form on HTML page.

Syntax create( mixed $model null, array $options array() )
Parameters
  • The model name for which the form is being defined. Should include the plugin name for plugin models. e.g. ContactManager.Contact. If an array is passed and $options argument is empty, the array will be used as options. If false no model is used.
  • An array of html attributes and options. Possible options are type, action, url, default, onsubmit, inputDefaults, encoding
Returns A formatted opening FORM tag.
Description Returns an HTML FORM element.

The following functions are used to provide file uploading functionality on HTML page.

Syntax file(string $fieldName, array $options array() )
Parameters
  • Name of a field, in the form “Modelname.fieldname”
  • Array of HTML attributes.
Returns A generated file input.
Description Creates file input widget.

The following functions are used to create hidden element on HTML page.

Syntax hidden( string $fieldName, array $options array() )
Parameters
  • Name of a field, in the form of “Modelname.fieldname”
  • Array of HTML attributes.
Returns A generated hidden input
Description Creates a hidden input field

The following functions are used to generate input element on HTML page.

Syntax Input (string $fieldName, array $options array() )
Parameters
  • This should be “Modelname.fieldname”
  • Each type of input takes different options
Returns Completed form widget
Description Generates a form input element complete with label and wrapper div

The following functions are used to generate radio button on HTML page.

Syntax Radio (string $fieldName, array $options array(), array $attributesarray() )
Parameters
  • Name of a field, like this “Modelname.fieldname”
  • Radio button options array.
  • Array of HTML attributes, and special attributes above.
Returns Completed radio widget set
Description Creates a set of radio widgets. Will create a legend and fieldset by default. Use $options to control this.

The following functions are used to generate submit button on HTML page.

Syntax Submit (string $caption null, array $options array() )
Parameters
  • The label appearing on the button OR if string contains :// or the extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension exists, AND the first character is /, image is relative to webroot, OR if the first character is not /, image is relative to webroot/img.
  • Array of options. Possible options are div, before, after, type etc.
Returns An HTML submit button
Description Creates a submit button element. This method will generate <input/> elements that can be used to submit, and reset forms by using $options. Image submits can be created by supplying an image path for $caption.

The following functions are used to generate textarea element on HTML page.

Syntax Textarea (string $fieldName, array $options array() )
Parameters
  • Name of a field, in the form “Modelname.fieldname”
  • Array of HTML attributes, special option like escape
Returns A generated HTML text input element
Description Creates a textarea widget

Example

Make changes in the config/routes.php file as shown in the following code.

config/routes.php

<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘register’,[‘controller’=>’Registrations’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a RegistrationController.php file at src/Controller/RegistrationController.php. Copy the following code in the controller file.

src/Controller/RegistrationController.php

<?php namespace AppController; use AppControllerAppController; class RegistrationsController extends AppController{ public function index(){ $country = array(‘India’,’United State of America’,’United Kingdom’); $this->set(‘country’,$country); $gender = array(‘Male’,’Female’); $this->set(‘gender’,$gender); } } ?>

Create a directory Registrations at src/Template and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Registrations/index.ctp

<?php echo $this->Form->create(“Registrations”,array(‘url’=>’/register’)); echo $this->Form->input(‘username’); echo $this->Form->input(‘password’); echo $this->Form->input(‘password’); echo ‘<label for=”country”>Country</label>’; echo $this->Form->select(‘country’,$country); echo ‘<label for=”gender”>Gender</label>’; echo $this->Form->radio(‘gender’,$gender); echo ‘<label for=”address”>Address</label>’; echo $this->Form->textarea(‘address’); echo $this->Form->file(‘profilepic’); echo ‘

‘.$this->Form->checkbox(‘terms’). ‘

‘; echo $this->Form->button(‘Submit’); echo $this->Form->end(); ?>

Execute the above example by visiting the following URL − http://localhost:85/CakePHP/register

Output