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') ?>
Related
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',
I've tried every simple cakedc search setup, and followed code samples from previous posts on this but it just won't seem to cooperate for me. I'm not sure, but there doesn't seem to be any search query generated with the search string, judging from a query log I have running on my database.
When I try to search, from /books/search, I get no results on a title I know is in the database and the URL changes to /books/index/title:sweet (I'm not sure if that is relevant).
Any help would be much appreciated.
Model
public $actsAs = array('Search.Searchable');
public $primaryKey = 'isbn13';
public $hasMany = array(
'Contributor' => array (
'className' => 'Contributor',
'foreignKey' => 'isbn13'
),
'Override' => array (
'className' => 'Override',
'foreignKey' => 'isbn13'
)
);
public $filterArgs = array(
'title' => array('type' => 'query', 'method' => 'filterTitle'),
'main_desc' => array('type' => 'value')
);
public function filterTitle($data, $field = null) {
if (empty($data['title'])) {
return array();
}
$titleField = '%' . $data['title'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $titleField,
));
}
Controller
class BooksController extends AppController {
public $helpers = array ('Html', 'Form');
public $paginate = array();
public $components = array('Search.Prg');
public $presetVars = true;
public function index() {
//get books
$this->set('books', $this->Book->find('all'));
//search
/* $this->Prg->commonProcess();
$this->paginate['conditions'] = $this->Book->parseCriteria($this->Prg->parsedParams());
$this->set('books');
*/
}
public function search($books = NULL) {
$this->Prg->commonProcess();
$this->paginate['conditions'] = $this->Book->parseCriteria($this->passedArgs);
$this->set('books', $this->paginate());
}
View
<h1>Search Results</h1>
<?php
echo $this->Form->create('Book' , array(
'url' => array_merge(array('action' => 'search'), $this->params['pass'])
));
echo $this->Form->input('title', array('div' => false, 'empty' => true)); // empty creates blank option.
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
Routes
Router::connect('/', array('controller' => 'books', 'action' => 'index'));
Router::connect('/index/*', array('controller' => 'books', 'action' => 'search'
));
Router::connect('/view/:url', array('controller' => 'books', 'action' => 'view', array('url' => '[\w\W]*')
));
Router::connect('/edit/:url', array('controller' => 'books', 'action' => 'edit', array('url' => '[\w\W]*')
));
Router::connect('/whatsnew/*', array('controller' => 'books', 'action' => 'whatsnew'
));
Router::connect('/search/*', array('controller' => 'books', 'action' => 'search'
));
I've renamed the search-master folder to Search and put it in my plugins directory and In my bootstrap.php I've loaded the plugin
CakePlugin::load('Search');
Fixed! Needed
$this->set('books', $this->paginate($this->Book->parseCriteria($this->passedArgs)));'
instead of
$this->set('books', $this->paginate());'
in the controller. Not sure why though..
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.
++
For some reason my allowed_values_function never gets called when showing a field on a user bundle. Code:
function get_business_units()
{
$options = entity_load('business_unit', FALSE, NULL, FALSE);
$opt = bu_to_list_values($options);
return $opt;
}
function MYMODULE_enable()
{
if (!field_info_field('field_user_business_unit')) {
$field = array(
'field_name' => 'field_user_business_unit',
'type' => 'text',
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => 'get_business_units',
)
);
field_create_field($field);
// Create the instance on the bundle.
$instance = array(
'field_name' => 'field_user_business_unit',
'entity_type' => 'user',
'label' => 'Business Unit',
'bundle' => 'user',
'required' => FALSE,
'settings' => array(
'user_register_form' => 1,
),
'widget' => array(
'type' => 'options_select',
),
);
field_create_instance($instance);
}
}
The field is created, and even displayed on the users "edit" page when editing their info. But the only value is "Select" or "None". My method is never called (I even placed a debug point). This is all in MYMODULE.install file.
The problem is: 'type' => 'text'.
You have to use: 'type' => 'list_text'.
Allowed values is meaningless for a text type.
Your get_business_units() function needs to be in the MYMODULE.module file; the .install files aren't included in a normal Drupal bootstrap.
Have you tried
drush features-revert MYMODULE ?
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.