I want to use router.php to change URL ( In CakePHP version 2.1.3):
Currently, I have URL like:
http://domain.com/register/add?userName=123&fullName=abc
Now I want to change (rewrite) that URL to new :
http://domain.com/regis-new?cus_name=123&cus_full_name=abc
My code in Controller:
class RegisterController extends AppController{
function index(){
$userName = $this->request->query['userName'];
$fullName = $this->request->query['fullName'];
}
}
How i can config router to apply new URL?
Thanks
Router::connect('/regis-new/*',
array(
'controller' => 'register'
'action' => 'add' // or new action name
)
);
When you put start after alias means that pass any thing after alias.
The parameters doesn't have any thing to do with Routing.
:) Now check your input names in your view. e.g. if the input name was "userName" rename it to "cus_name"
echo $this->Form->input('cus_name' array(
'name' => 'cus_name'
));
Make sure when you get input values by their new names. e.g. in your action:
$this->request->data["cus_name"];
I have followed the cakephp documentation for 2.0 to create a restFUL. I am not sure if I have it right.
If I was to just put the URL into the browser should I see the xml called back. I am just trying to test it but all I see is the standard view and not the xml view. I just want a quick test to see if I have it right.
The URL
http://www.mydomain.com/members/123.xml
The controller is Members and the method I am calling is view
Here is my code:
routes.php
Router::mapResources('members');
Router::parseExtensions('xml', 'json');
MembersController.php
public function view($id = null) {
if (!$this->Member->exists($id)) {
throw new NotFoundException(__('Invalid member'));
}
$options = array('conditions' => array('Member.' . $this->Member->primaryKey => $id));
$members = $this->Member->find('first', $options);
$this->set(array(
'member' => $members,
'_serialize' => array('member')
));
}
app/view/members/xml/view.ctp
echo $xml->serialize($member)
Have you the RequestHandler in your components array? If not put it in there.
See this page in the CakePHP book.
You don't need any view, CakePHP handles it automatically. Delete folder app/view/members/ with all files inside.
i am new to cake and using version 2.
i have models
hgcylinder.php
class HgCylinder extends AppModel {
//put your code here
var $name= "HgCylinder";
var $belongsTo = array('HgKeyGase');
}
hgkeygase.php
class HgKeyGase extends AppModel {
//put your code here
var $name= "HgKeyGase";
public $belongsTo = array(
'HgKeyColor' => array(
'className' => 'HgKeyColor',
'foreignKey' => 'hg_key_color_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
Controller HgCylindersController.php
<?php
class HgCylindersController extends AppController
{
var $name = "HgCylinders";
// var $scaffold;
function index()
{
$this->set('hey',$this->HgCylinder->find('all'));
}
public function edit($id = null) {
$this->HgCylinder->id = $id;
if ($this->request->is('post')) {
var_dump($this->request->data);
exit;
if ($this->HgCylinder->save($this->request->data)) {
$this->Session->setFlash(__('Cylinder has been updated successfull'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The cylinder could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->HgCylinder->read(null, $id);
}
$hg_key_gase_id = $this->HgCylinder->HgKeyGase->find('list');
$this->set(compact('hg_key_gase_id'));
}
}
?>
View : edit.ctp
<?php
echo $this->form->create('HgCylinder',array('action'=>'edit'));
echo $this->form->input('hg_key_gase_id',);
echo $this->form->input("capacityM3");
echo $this->form->input("weightEmpty");
echo $this->form->input("weightFilled");
echo $this->form->input("isFilled");
echo $this->form->end('Add');
?>
my problem is hg_key_gase_id is become select list with no options. if i changed the name to "hgKeyGas" in view and controller it shows the options from the hg_key_gases table. but on saving does not saving the value of hg_key_gase_id field in hg_cylinders table instead it stores null in this field.
second i want to know that it is necessary to have variable name passing to view from controller exactly same for as field in table.
try to stick to conventions.
so its
$hgKeyGases = $this->HgCylinder->HgKeyGase->find('list');
$this->set(compact('hgKeyGases'));
the pluralized form will be able to populate your select box (as documented in the cook book)
also use $this->Form->input() (note the capital F). $name is not necessary.
dont use read(), use find(first) instead. dont set the action (the form will post to itself by default).
and most importantly. ALWAYS respect the casing of files in your filesystem. especially if you plan on deploying on NIX systems (which are case sensitive).
so it would be HgCylinder.php and HgKeyGase.php as Model class files.
last tip: use baking (cake bake via shell console) to bake your crud files. this way you learn how its done the right way. it would have also answered your question itself by the way.
the documentation can be found here: http://book.cakephp.org/2.0/en/index.html
maybe you found an old outdated version, the 2.x one is the one you should have used.
I have developed a full website with CakePHP framework and we'd like to make a very light version of the website for mobile devices (mainly iPhone/iPad).
Is there a way to use the existing website with a new sub domain (for instance mobile.mywebsite.com) which will render specific views? I would like to avoid copying and simplifying the current one to match the new one requirements. I do not want to have to "re-develop" a new CakePHP website and do the changes twice every time I need to change a controller action.
I've done this using a quick addition to the beforeFilter() in my app_controller.php file.
function beforeFilter() {
if ($this->RequestHandler->isMobile()) {
$this->is_mobile = true;
$this->set('is_mobile', true );
$this->autoRender = false;
}
}
This uses the CakePHP RequestHandler to sense if it's a mobile device visiting my site. It sets a property and view variable to allow actions an views to adjust themselves based on the new layout. Also turns off the autoRender because we'll take care of that in an afterFilter.
In the afterFilter() it looks for and uses a mobile view file if one exists. Mobile versions are stored in a 'mobile' folder inside the controller's view folder and are named exactly the same as the normal non-mobile versions. (ie. add.ctp becomes mobile/add.ctp)
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$view_file = new File( VIEWS . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
$this->render($this->action, 'mobile', ($view_file->exists()?'mobile/':'').$this->action);
}
}
Dan's answer worked for me. However, I used file_exists instead of the File constructor and added the ability to use mobile layouts. The before filter was the same, but the afterFilter looked like this:
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$view_file = file_exists( VIEWS . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
$layout_file = file_exists( LAYOUTS . 'mobile/' . $this->layout . '.ctp' );
$this->render($this->action, ($layout_file?'mobile/':'').$this->layout, ($view_file?'mobile/':'').$this->action);
}
}
You can use Theme feature in CakePHP 2.x for mobile layout.
Simply do:
if($this->RequestHandler->isMobile())
$this->theme = 'mobile';
I found this better, as you can share View file on mobile and desktop theme easily.
I modified this technique for a CakePHP 2.1 app. Here is my beforeFilter():
public function beforeFilter() {
if ($this->request->isMobile()){
$this->is_mobile = true;
$this->set('is_mobile', true );
$this->autoRender = false;
}
}
And here is my afterFilter():
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$view_file = file_exists( 'Views' . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
$layout_file = file_exists( 'Layouts' . 'mobile/' . $this->layout . '.ctp' );
if($view_file || $layout_file){
$this->render($this->action, ($layout_file?'mobile/':'').$this->layout, ($view_file?'mobile/':'').$this->action);
}
}
}
This helps account for deprecated verbiage and constants in CakePHP 2.
The simple solution is to create a new 'mobile' layout with respective stylesheet(s) and turn it on in AppController:
public $components = array('RequestHandler');
public function beforeRender() {
parent::beforeRender();
if ($this->RequestHandler->isMobile()) {
$this->layout = 'mobile';
}
}
It is important to do that in beforeRender() in case if you change $this->layout in your controllers' methods.
CakePHP v2.2.1 Solution (+ Cookies to persist mobile/desktop/other layout)
This solution is based on answers by #Dan Berlyoung, #deewilcox and #Chris K.
Parts of those answers failed to work (for me) in CakePHP 2.2.1.
I also extended the solution to support "forcing" a mobile/desktop/other layout from the frontend - useful for debugging and for users that don't want to be stuck on a "mobile" themed layout.
/app/Controller/AppController.php
class AppController extends Controller {
public $components = array('Cookie');
public $is_mobile = false;
public $layouts = array('desktop', 'mobile');
// executed before every action in the controller
function beforeFilter()
{
// Using "rijndael" encryption because the default "cipher" type of encryption fails to decrypt when PHP has the Suhosin patch installed.
// See: http://cakephp.lighthouseapp.com/projects/42648/tickets/471-securitycipher-function-cannot-decrypt
$this->Cookie->type('rijndael');
// When using "rijndael" encryption the "key" value must be longer than 32 bytes.
$this->Cookie->key = 'qSI242342432qs*&sXOw!adre#34SasdadAWQEAv!#*(XSL#$%)asGb$#11~_+!##HKis~#^'; // When using rijndael encryption this value must be longer than 32 bytes.
// Flag whether the layout is being "forced" i.e overwritten/controlled by the user (true or false)
$forceLayout = $this->Cookie->read('Options.forceLayout');
// Identify the layout the user wishes to "force" (mobile or desktop)
$forcedLayout = $this->Cookie->read('Options.forcedLayout');
// Check URL paramaters for ?forcedLayout=desktop or ?forcedLayout=mobile and persist this decision in a COOKIE
if( isset($this->params->query['forcedLayout']) && in_array($this->params->query['forcedLayout'], $this->layouts) )
{
$forceLayout = true;
$forcedLayout = $this->params->query['forcedLayout'];
$this->Cookie->write('Options.forceLayout', $forceLayout);
$this->Cookie->write('Options.forcedLayout', $forcedLayout);
}
// We use CakePHP's built in "mobile" User-Agent detection (a pretty basic list of UA's see: /lib/Cake/Network/CakeRequest.php)
// Note: For more robust detection consider using "Mobile Detect" (https://github.com/serbanghita/Mobile-Detect) or WURL (http://wurfl.sourceforge.net/)
if( ( $forceLayout && $forcedLayout == 'mobile' ) || ( !$forceLayout && $this->request->is('mobile') ) ) {
$this->is_mobile = true;
$this->autoRender = false; // take care of rendering in the afterFilter()
}
$this->set('is_mobile', $this->is_mobile);
}
// executed after all controller logic, including the view render.
function afterFilter() {
// if in mobile mode, check for a vaild layout and/or view and use it
if( $this->is_mobile ) {
$has_mobile_view_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . $this->name . DS . 'mobile' . DS . $this->action . '.ctp' );
$has_mobile_layout_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . 'Layouts' . DS . 'mobile' . DS . $this->layout . '.ctp' );
$view_file = ( $has_mobile_view_file ? 'mobile' . DS : '' ) . $this->action;
$layout_file = ( $has_mobile_layout_file ? 'mobile' . DS : '' ) . $this->layout;
$this->render( $view_file, $layout_file );
}
}
}
/app/View/Elements/default_footer.ctp
<ul>
<?php
$paramsQuery = $this->params->query;
if(!is_array($paramsQuery))
{
$paramsQuery = array();
}
$paramsQuery['url'] = ( isset($paramsQuery['url']) ) ? $paramsQuery['url'] : '';
$url = $paramsQuery['url'];
unset($paramsQuery['url']);
$params = $paramsQuery;
$mobile_url = '/' . $url . '?' . http_build_query( array_merge( $params, array( 'forcedLayout' => 'mobile' ) ) );
$desktop_url = '/' . $url . '?' . http_build_query( array_merge( $params, array( 'forcedLayout' => 'desktop' ) ) );
?>
<?php if($is_mobile): ?>
<li><?= $this->Html->link('Desktop Site', $desktop_url, array('target' => '', 'class' => '')) ?></li>
<?php else: ?>
<li><?= $this->Html->link('Mobile Site', $mobile_url, array('target' => '', 'class' => '')) ?></li>
<?php endif; ?>
</ul>
/app/View/Layouts/default.ctp
<h1>Desktop Site Layout</h1>
<?= $this->fetch('content') ?>
/app/View/Layouts/mobile/default.ctp
<h1>Mobile Site Layout</h1>
<?= $this->fetch('content') ?>
/app/View/Pages/home.ctp
<h2>Home - on Desktop</h2>
<?= $this->element('default_footer') ?>
/app/View/Pages/mobile/home.ctp
<h2>Home - on Mobile</h2>
<?= $this->element('default_footer') ?>
Usage
Use the default_footer links to change layout - or these direct urls
http://example.com/pages/home?forcedLayout=desktop
http://example.com/pages/home?forcedLayout=mobile
A session COOKIE persists the option you've chosen... e.g. try setting to "mobile" and then visit a url without the forcedLayout= param.
http://example.com/pages/home
The default_footer links persist existing params (except for the "fragment" #gohere)
http://example.com/pages/home/a/b/c:d?this=that&foo=bar#gohere
Desktop Site url is:
http://example.com/pages/home/a/b/c:d?this=that&foo=bar&forcedLayout=desktop
For more robust device User-Agent detection consider using the Mobile Detect PHP Library ... you could then target Tablets, and even specific devise OS versions.... Oh what fun! ^_^
The solution I went with was a lightweight modification based on a few of the answers here, for CakePHP 2.5.5. The handling is all done in the beforeRender (note that beforeRender is only run on controller actions that will actually render a page, so this saves overhead as opposed to beforeFilter/afterFilter for private methods):
$mobile = $this->request->is('mobile');
$this->set('mobile',$mobile);
//Check if an alternate mobile view and/or layout exists for this request.
if($mobile){
if(file_exists(APP.'View'.DS.$this->name.DS.'mobile'.DS.$this->view.'.ctp')){
//Render this action on its mobile view.
$this->view = 'mobile'.DS.$this->view;
}
if(file_exists(APP.'View'.DS.'Layouts'.DS.'mobile'.DS.$this->layout.'.ctp' )){
//Render this action on its mobile layout.
$this->layout = 'mobile'.DS.$this->layout;
}
}
The $mobile variable can be used on any view if you have small tweaks to make, otherwise you can optionally replace any view with View/{controller}/mobile/same_file_name.ctp or layout with View/Layouts/mobile/same_file_name.ctp to have a separate page structure entirely.
Note that this uses $this->view and $this->layout and then modifies them, instead of using $this->action and $this->render(view,layout), because your view won't always match your action (same view, multiple actions, for example, break using $this->action), and this solution prevents needing to worry about when $this->render() will be forced, and allows it to happen naturally.
Yes, you can re use all of your domain and controllers, have a look to Tera-WURLF
And even better, you don't need a subdomain for the mobile version.
I have set up the RSS Helper (with CakePHP 1.3.4) and all is working - I can access my feeds by /news/feed.rss - as exampled at http://book.cakephp.org/view/1461/Creating-an-RSS-feed-with-the-RssHelper
But I want to be able to do this conditionally, in sudo, something like:
if (!empty($var)) {
switch ($var) {
case one :
$xml = $this->method->find('$var conditions...');
... use RSS Helper to serve results as XML.
case two :
$xml = $this->method->find('other $var conditions...');
... use RSS Helper to serve results as XML.
}
}
Can I use the RSS Helper in this circumstance? What calls/syntax do I use?
There are 2 ways to do this.
Basically you can pass a variable like this:
http://yourserver.com/news/feed.rss?recent=20
and then in the controller you can access this variable with
$this->params['url']['recent']; //20
Or you can add a line in your Router file like this:
Router::connect('/feed-:recent/*', array('plugin'=>false, 'controller' => 'news', 'action' => 'feed'), array('recent'=>'[0-9]+'));
This way your url will look like:
http://yourserver.com/news/feed-20.rss
and finally I believe that url like this will work as well:
http://yourserver.com/news/feed.rss/recent:20
You can pass params to the function the same as any other controller call.
IE
public function rss( $limit = 20, $topic = null ){
if( !$topic ){
$xml = $this->Article->find( 'all', array( 'limit' => $limit ));
...
} else {
$xml = $this->Article->find( 'all', array( 'limit' => $limit, 'conditions' => array( 'Article.topic' => $topic )));
}
...
}
}
?>
Then you can access the rss feed with: http://domain/articles/rss.rss
If you need to pass parameters: http://domain/articles/rss/100.rss (fetch all with 100 results)
Or like this: http://domain/articles/rss/10/obama.rss (fetch all with the topic "obama" and return 10 items.
The RequestHandler allows you to use a url like /posts/index.rss and it automatically loads the RSS Helper and sends the output to /views/posts/rss/index.ctp, and uses layout at /views/layouts/rss/default.ctp.
But if you want to use the RSS Helper on it's own you need to:
1) include it the controller
var $helpers = array('Rss');
2) in your controller action you need to specify where the output goes, so
$this->render('/posts/rss/index','/rss/default');
In this case I also specified which layout to use in the 2nd argument. The first arg - the index.ctp file location is relative to your views/ directory. The second arg - the layout is relative to your views/layouts/ directory.
So I have a method in my posts_controller that I use to identify which feed is wanted (through a passed var) and subsequently finds the posts and sends them to the correct views and layouts:
function rss(){
if (!empty($this->params['pass'])){
$ops=array(
'conditions'=>'where feedname_id=' . $this->params['pass'][0],
'order' => 'Post.created DESC',
'limit' => 10
);
$this->set('posts', $this->Post->find('all',$ops));
$this->render('/posts/rss/index','/rss/default');
} else {
$this->redirect(array('controller'=>'feednames','action'=>'index'));
}
}
There might be better ways to code this - if so please let me know.