the rss helper doesnt generate the index.rss - cakephp

i have an issue trying to generate rss. I followed all the steps of http://book.cakephp.org/1.3/en/view/1460/RSS, but when i try in the url my index.rss shows me only my index page not in xml format.
this is my index of post_Controller:
var $components = array('Session','RequestHandler');
var $helpers = array('Html','Form','Time','Text');
function index() {
if( $this->RequestHandler->isRss() ){
$posts = $this->Post->find('all', array('limit' => 20, 'order' => 'Post.created DESC'));
$this->set(compact('posts'));
}
$this->set('title_for_layout', 'mi blog');
$this->Post->recursive = 1;
$this->set('posts', $this->paginate());
}
this is my layout in app/views/layouts/rss/default.ctp:
echo $this->Rss->header();
if (!isset($documentData)) {
$documentData = array();
}
if (!isset($channelData)) {
$channelData = array();
}
if (!isset($channelData['title'])) {
$channelData['title'] = $title_for_layout;
}
$channel = $this->Rss->channel(array(), $channelData, $content_for_layout);
echo $this->Rss->document($documentData,$channel);
this the view in app/views/posts/rss/index.ctp
$this->set('documentData', array(
'xmlns:dc' => 'http://purl.org/dc/elements/1.1/'));
$this->set('channelData', array(
'title' => __("Articles", true),
'link' => $this->Html->url('/', true),
'description' => __("Articulos mas recientes.", true),
'language' => 'en-us'));
// content
foreach ($posts as $post) {
$postTime = strtotime($post['Post']['created']);
$postLink = array(
'controller' => 'posts',
'action' => 'view',
$post['Post']['id']);
// You should import Sanitize
App::import('Sanitize');
// This is the part where we clean the body text for output as the description
// of the rss item, this needs to have only text to make sure the feed validates
$bodyText = preg_replace('=\(.*?\)=is', '', $post['Post']['body']);
$bodyText = $this->Text->stripLinks($bodyText);
$bodyText = Sanitize::stripAll($bodyText);
$bodyText = $this->Text->truncate($bodyText, 400, array(
'ending' => '...',
'exact' => true,
'html' => true,
));
echo $this->Rss->item(array(), array(
'title' => $post['Post']['title'],
'link' => $postLink,
'guid' => array('url' => $postLink, 'isPermaLink' => 'true'),
'description' => $bodyText,
'pubDate' => $post['Post']['created']));
}
which could be the problem ... Also i have put the component in the app_controller.php
var $components = array ('Auth', 'Session', 'RequestHandler');
but nothing happens the index.rss is the Same of posts / index

It looks like you are not returning the RSS view in the index controller. Update the RSS section of the index function to return the rss view:
function index() {
if( $this->RequestHandler->isRss() ){
$posts = $this->Post->find('all', array('limit' => 20, 'order' => 'Post.created DESC'));
return $this->set(compact('posts'));
}
// ...snip...
}
UPDATE
It's how Chrome handles the layout. I know it is horrible. FireFox and IE handle RSS layout much better. But you can install the RSS Layout extension for Chrome and it will format it the same way.
https://chrome.google.com/extensions/detail/nlbjncdgjeocebhnmkbbbdekmmmcbfjd

In the action of the controller. You must add
$this->response->type("xml");
at the end.

Related

zf2 URL Helper customization to add achnor for angularjs router

I have a following Link in zf2
<?php echo $this->translate('Enquiries') ?>
and this router in zf2
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
which convert above link into
Enquiries
which is fine.
I am using angularjs, which uses anchor fragments a lot.
How can I add achor "#/active" on above zf2 link url, so target url look something like this.
Active Enquiries
do you have a reason why you are not just adding the anchor manually after the url definition url(...).'#/active' ?
if you have, try this:
'route' => '/[:controller[/:action[#/:anchor]]]',
UPDATE:
I checked the source for router and uri and url , it seems that url view helper accepts a 'fragment' key for the third option so try this :
url('[route]',array([params]),array('fragment'=>'/active'));
Zend/View/Helper/Url
Zend/Mvc/Router/Http/TreeRouteStack
Zend/Uri/Uri
Create following view Helper by extending Url
namespace Application\View\Helper;
use Zend\View\Helper\Url;
class MyUrl extends Url {
public function __invoke($name = null, $params = array(), $options = array(), $reuseMatchedParams = false) {
if (isset($params['anchor']) && !empty($params['anchor'])) {
$anchor = $params['anchor'];
unset($params['anchor']);
} else {
$anchor = '';
}
$link = parent::__invoke($name, $params, $options, $reuseMatchedParams);
return $link . $anchor;
}
}
In Module file add following in factory to add newly created helper
public function getViewHelperConfig() {
return array(
'factories' => array(
'myUrl' => function($sm) {
$locator = $sm->getServiceLocator();
$helper = new \Application\View\Helper\MyUrl;
$router = \Zend\Console\Console::isConsole() ? 'HttpRouter' : 'Router';
$helper->setRouter($locator->get($router));
$match = $locator->get('application')
->getMvcEvent()
->getRouteMatch();
if ($match instanceof RouteMatch) {
$helper->setRouteMatch($match);
}
return $helper;
},
),
);
}
Add anchor in URL as parameter
<?php echo $this->translate('Enquiries') ?>

Show Category Listing in Home Page via PagesController in Cake PHP

PagesController.php
$this->loadModel('Category');
$categories = $this->Category->find('all',
array(
'limit' => 5,
'order' => 'Category.id ASC',
'fields' => array('Category.id','Category.category'),
'contain' => false,
'conditions' => array('Category.super_id' => 1),
'recursive' => 0
)
);
//pr($categories); Here showing all category listing
$this->set(compact('categories'));
//$this->set('categories',$categories); that code also used
Show Category Listing in Home Page via PagesController in Cake PHP
But In View file i m getting below error (In view/Pages/home.ctp)
<?php pr($categories); ?>
Notice (8): Undefined variable: categories [APP/View/Pages/home.ctp, line 142]
pagesController.php
public function display() {
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
$page = $subpage = $title_for_layout = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
try {
$this->render(implode('/', $path));
} catch (MissingViewException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
$this->loadModel('Category');
$categories = $this->Category->find('all',
array(
'order' => 'Category.id ASC',
'fields' => array('Category.id','Category.category'),
'contain' => false,
'conditions' => array('Category.super_id' => 1),
'recursive' => 0
)
);
$this->set('categories',$categories);
//$this->set(compact('categories'));
//pr($categories);
}
Routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
EDITED IN RESPONSE TO FULL PagesController:
I don't think your find and set are being executed (until after the view is rendered) as they are after the call to $this->render. Try moving them like this:
$this->loadModel('Category');
$categories = $this->Category->find('all',
array(
'order' => 'Category.id ASC',
'fields' => array('Category.id','Category.category'),
'contain' => false,
'conditions' => array('Category.super_id' => 1),
'recursive' => 0
)
);
$this->set('categories',$categories);
try {
$this->render(implode('/', $path));
} catch (MissingViewException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
EDITED IN RESPONSE TO -1:
Please show us your whole PagesController.php so we can see if there are any problems getting the data through to home.ctp. You have already established that the data are there before the $this->set in your controller but that $categories is not in fact set in the view ('Undefined variable') so this would seem a logical thing to explore next.
I appreciate this is not an 'Answer' but I am not allowed to 'Comment' on the original post so this is the only way I can communicate my request.
ORIGINAL RESPONSE:
Can't comment because not enough reputation but could you show us a bit more of your Pages controller as I wonder if the data are not actually getting through to your view because of some problem there..
because the render call is before your set statement
in other words the page is rendered before you set the categories
move your code at the beginning of the action

rawurlencode() expects parameter 1 to be string, array given [CORE\Cake\Routing\Route\CakeRoute.php, line 506]

I am new in CakePHP. I wanted to create menu in cakePHP 2.3.9 but when I run the application it gives following warning "rawurlencode() expects parameter 1 to be string, array given [CORE\Cake\Routing\Route\CakeRoute.php, line 506]"
I am giving the complete code here. I can not understand how to eliminate the warning message above.
At first I have created this file at /app/Model/menu.php. Which looks like this
<?php
class Menu extends AppModel {
var $name = 'Menu';
var $useTable = false;
function main ($selected = 'home') {
return array(
'divClass' => 'menu',
'ulClass' => 'menu',
'tabs' => array(
array(
'controller' => 'pages',
'action' => '',
'params' => '',
'aClass' => $selected == 'home' ? 'selected' : '',
'liClass' => '',
'text' => 'Home'
),
array(
'controller' => 'pages/service',
'action' => '',
'params' => '',
'aClass' => $selected == 'Service' ? 'selected' : '',
'liClass' => '',
'text' => 'Service'
),
array(
'controller' => 'pages/user',
'action' => '',
'params' => '',
'aClass' => $selected == 'users' ? 'selected' : '',
'liClass' => '',
'text' => 'Users'
),
)
); // end return
} // end Main
} // end class Menu
?>
Then I have created this file at /app/Controller/MenusController.php. Which looks like this
<?php
class MenusController extends AppController {
var $name = 'Menus';
private $menus;
function beforeFilter () {
parent::beforeFilter();
$this->menus[] = array(
'name' => 'main',
'selected' => 'users'
);
// $this->set('menuList', $this->menus);
}
function index() {
$this->menus[] = array(
'name' => 'users',
'selected' => 'users'
);
$this->set('menuList', $this->menus);
}
function menus($menus) {
$output = array();
foreach ($menus as $menu):
$output[] = $this->Menu->{$menu['name']}($menu['selected']);
endforeach;
return $output;
}
}
?>
Then, this file I have created at /app/View/Elements/menu.ctp, which looks like this
<?php
if (empty($menuList)):
$menuList = array(
array(
'name' => 'main',
'selected' => 'home'
)
);
endif;
$menus = $this->requestAction(
array(
'controller' => 'menus',
'action' => 'menus'
),
array('pass' => array( $menuList))
);
if (! empty($menus)):
foreach ($menus as $menu):
$tabs = '';
foreach ($menu['tabs'] as $tab):
$url = array(
'controller' => $tab['controller'],
'action' => $tab['action']
);
if (! empty($tab['params'])):
$url[] = $tab['params'];
endif;
$tabs .= $this->html->tag(
'li',
$this->html->link(
$tab['text'],
$url,
array('class' => $tab['aClass'])),
array('class' => $tab['liClass'])
);
endforeach;
echo '<div class="' . $menu['divClass'] . '">
<div class="container_12">
<div class="grid_12">' . $this->html->tag('ul', $tabs, array('class' =>
$menu['ulClass'])) . '</div></div></div>';
endforeach;
endif;
?>
accept my advance gratitude for help
Your framework might have a default helper function which uses php's rawurlencode() function by default too. You might want to check the parameters you should pass for $this->html->link() since php's rawurlencode() function accepts only a string as a parameter.
Although the documentation says requestAction now supports 'array based cake style URLs' which 'bypass the usage of Router::url()', try passing a string as the first parameter to request action.
For example where you currently have:
array(
'controller' => 'menus',
'action' => 'menus'
),
Try:
'menus/menus',

CakePHP: Keep the same checkboxes checked after submit

How can I keep the same checkboxes checked after submit? All the other input fields on the form automatically keeps the values. I thought this would also go for checkboxes, but nope.
echo $this->Form->input('type_id', array(
'multiple' => 'checkbox',
'options' => array(
'1' => 'Til salgs',
'2' => 'Ønskes kjøpt',
'3' => 'Gis bort'
),
'div' => false,
'label' => false
));
I believe this can be done in the controller, but how?
Edit:
Since I posted this question I've changed to CakeDcs Search plugin, because I've gotten this to work with that before. Still... I can't get it to work this time.
Adding model and controller code:
AppController
public $components = array('DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginAction' => '/',
'loginRedirect' => '/login',
'logoutRedirect' => '/',
'authError' => 'Du må logge inn for å vise denne siden.',
'authorize' => array('Controller'),
),
'Search.Prg'
);
public $presetVars = true; //Same as in model filterArgs(). For Search-plugin.
AdsController
public function view() {
$this->set('title_for_layout', 'Localtrade Norway');
$this->set('show_searchbar', true); //Shows searchbar div in view
$this->log($this->request->data, 'debug');
//Setting users home commune as default filter when the form is not submitted.
$default_filter = array(
'Ad.commune_id' => $this->Auth->user('User.commune_id')
);
$this->Prg->commonProcess(); //Search-plugin
$this->paginate = array(
'conditions' => array_merge($default_filter, $this->Ad->parseCriteria($this->passedArgs)), //If Ad.commune_id is empty in second array, then the first will be used.
'fields' => $this->Ad->setFields(),
'limit' => 3
);
$this->set('res', $this->paginate());
}
Model
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'search_field' => array('type' => 'query', 'method' => 'filterSearchField'),
'commune_id' => array('type' => 'value'),
'type_id' => array('type' => 'int')
);
public function filterSearchField($data) {
if (empty($data['search_field'])) {
return array();
}
$str_filter = '%' . $data['search_field'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $str_filter,
$this->alias . '.description LIKE' => $str_filter,
)
);
}
/**
* Sets the fields which will be returned by the search.
*
* #access public
* #return array Database table fields
* #author Morten Flydahl
*
*/
public function setFields() {
return array(
'Ad.id',
'Ad.title',
'Ad.description',
'Ad.price',
'Ad.modified',
'User.id',
'User.first_name',
'User.middle_name',
'User.last_name',
'User.link',
'User.picture_url',
'Commune.name',
'Type.id',
'Type.name'
);
}
You have to set manually the selected option of the input, as an array with "keys = values = intval(checkbox id)"
I cannot explain why this format, but this is the only way I get it to work.
Here is my code:
echo $this->Form->create('User');
// Read the submitted value
$selected = $this->Form->value('User.Albums');
// Formats the value
if (empty($selected)) {
$selected = array(); // avoid mess
} else {
$selected = array_map('intval', $selected);
$selected = array_combine ($selected, $selected);
}
// Renders the checkboxes
echo $this->Form->input('Albums',array(
'type' => 'select',
'multiple' => 'checkbox',
'options' => $albums, // array ( (int)id => string(label), ... )
'selected' => $selected, // array ( (int)id => (int)id, ... )
));
Hope this helps.
++

cakephp beforeSave callback in Behaviors don't save data correctly

Controller:
$data =
array(
'ContentI18n' =>
array(
0 =>
array(
'title' => 'first',
'author' => 'first',
'source' => 'sgfsdfrst',
'lang' => 'fa',
),
),
'Content' =>
array(
'publish' => 1,
'type' => 3,
'pages' => 8,
'volume' => 7,
'modified' => '2012-05-27 14:16:37',
'created' => '2012-05-27 14:16:37',
'lang' => 'fa',
),
);
$this->Content->create();
$this->Content->saveAll($data);
Model:
public $hasMany = array(
'ContentI18n' => array(
'className' => 'ContentI18n',
)
);
beforeSave function in behavior:
public function beforeSave(Model $model) {
// Define the new Translate model
App::uses($model->name . 'I18n', 'Model');
$varI18n = $model->name . 'I18n';
$modelI18n = new $varI18n;
foreach ($model->data[$model->name] as $key => $data) {
if (!in_array($key, $this->setting))
$modelData[$model->name][$key] = $data;
else
$modelData[$model->name . 'I18n'][0][$key] = $data;
}
$modelData[$model->name . 'I18n'][0]['lang'] = $model->locale;
$modelData[$model->name]['lang'] = $model->locale;
$model->data = $modelData;
//pr($model->data);
return TRUE;
}
every things seems be cause when is save it directly it's save with saveAll. but when i use same structure of data in behavior did not work without any error.
I found out that beforeSave callback will not trigger by saveAll. for executing some code before saveAll we must override saveAll function in our model.
public function saveAll($data, $options = array()) {
/*
your code you want execute before saving...
*/
parent::saveAll($data, $options);
}
for other saving methods such as saveMany,saveAssociated,... beforeSave trigger by them.

Resources