I'd like to set the layout's $scripts_for_layout from within the controller.
Is this possible, and if yes how?
Short answer: maybe you're doing it wrong.
Long answer: Scripts should not be controller dependent. It's 'theoretically' wrong, and cake does not like people who doesn't adhere to the mvc pattern.
Workaround (because sometimes you just need to): You can set in beforeRender a var:
function beforeRender() {
parent::beforeRender();
$this->set('scripts', array('script1', 'script2' ...));
}
And in the layout check for $scripts and add them.
In cake 1.2, when you do $this->set('script_for_layout', 'script here...), it will convert this variable to $scriptForLayout so it wouldn't work.
Cake 1.3 fixed this but I haven't tried to see if it works or not but you are violating MVC because script was meant for the View, not set at the Controller level. For dynamic script, you can assign variables to your view like the previous poster has suggested.
I know this is an old question, but I had the same issue today. The solution seems easier than the answers mentioned here. From CakePHP 1.2 cookbook:
inline: whether the block should be printed inline, or written to cached for later output (i.e. $scripts_for_layout).
So, in your view you just need to include scripts setting the inline as false, like this:
$javascript->link('script1', false)
You can do the same for CSS:
$html->css('stylesheet1', null, array(), false)
Attention : I only tested this on CakePHP 1.2. But according to cookbook for 1.3, it is the same thing.
Related
I'm trying to make a reusable component (a weekday dropdown box, simple as pie) and am following the advice in http://book.cakephp.org/view/1081/Elements.
According to that page, I should make a blah.ctp file in app/views/elements, and it will be magically accessible in my view code as $this->element('blah').
So I did it. I'm passing the form and field name to my element in the view code:
$this->element(
'weekday_input',
array('form'=>$this->Form, 'fieldname'=>'weekday')
);
Earlier I created a form using $this->Form->create, so I figured I need to pass it to the element explicitly.
And my element code, in weekday_input.ctp:
echo $form->input(
$fieldname,
array(
'options',
array('Sunday'=>'Sunday',...,'Saturday'=>'Saturday')
)
);
(Weekdays in between omitted for brevity.)
Am I using $this->element properly? Is there something more clean available?
You don't have to pass the Form object. Form, Html and other helpers are available in elements (just as in view). Whether or not you want to pass fieldname depends: Do you need to change it?
An element is a bit too simple I expect. Also it is not very testable. Would focus on Helpers, which is a more advanced way of developing this. But there is another solution I would prefer even more:
For this kind of issues it might be more appropriate to extend the formhelper itself. You can see a simple example here:
http://blog.nlware.com/2012/02/07/cakephp-2-0-how-to-extend-the-formhelper/
A full example can be found for example here:
https://github.com/slywalker/cakephp-plugin-boost_cake/blob/master/View/Helper/BoostCakeFormHelper.php
As you asked for a clean solution think about creating a plugin (or check out existing plugins). That will separate the code out of your project more clean. And it will be available for re-use without much issues.
you can find all files needed for a plugin in the same project:
https://github.com/slywalker/cakephp-plugin-boost_cake
And the documentation here:
http://book.cakephp.org/2.0/en/plugins.html
I use CakePHP 1.3.9 but I can't use other Models in a Controller.
I use $this->loadModel('ModelName); and $this->ModelName->find('all') - always empty.
The variable $uses also doesn't work.
Why is it not working for me?
I used i18n and must set $locale...
Do you mean the data set is empty? If the model is not loaded, you shouldn't be able to call $this->ModelName->find() as $this->ModelName would be null. Does it throw an error? Your usage is correct, as stated in the manual : http://book.cakephp.org/view/992/loadModel
You can also do
App::import('Model', 'ModelName');
$model = new Model();
But I'm guessing that your current resultset is returning empty rather than the model itself not being set.
Have you tried looking at what $this->ModelName actually contains? Do the following and post it here
pr($this->ModelName)
It's considered bad practice to put (un-associated) models in your $uses array.
Depending what you are trying to do, you may be able to make use of containable behaviour.
$this->User->Post->find('all');
If not, you should be able to use loadModel:
$this->loadModel('Article');
$recentArticles = $this->Article->find('all', array('limit' => 5));
To quote Cake:
The loadModel function comes handy when you need to use a model which is not the controller's default model or its associated model.
JohnP and Ross are correct. Controller::loadModel() is clearly working and not your problem if pr($this->ModelName) is working for you.
As they mentioned, you're probably having trouble because the data simply isn't in the database. Or maybe there's something wrong with your query. Have you tried checking the query that's produced by CakePHP and trying to query the database directly through the MySQL command line (assuming you're using MySQL)?
Or is there any chance you've overloaded the Model::find() method?
I just finished the "15 min Blog Post tutorial" included in the documentation for cakephp. I was asked for another tutorial to change the layout for first tutorial.
However, I am fairly new to MVC programming/Cakephp and I have no real clue how to do so. Well, I know I need "default.ctp" placed in app/views/layouts/ and I presume I need to include
to include my data? . . .
I am really at a loss of what to do. I set up my default.ctp as I mentioned above, but when I go to localhost:9999/posts the layout is still the same. I guess I need to include a stylesheet (and if so, where?)
I guess if someone can point me in the right direction to a beginner's guide to layout styling or how to use it I would greatly appreciate any help.
I would advice you to read the following from the cookbook: Layouts and CSS. Then copy the layout from /cake/libs/view/layouts/ to /app/views/layouts/ and modify it to your needs. After that create you stylesheet (or modify existing one) in /app/webroot/css/ and include it in your layout.
Create in app/View/Layout a file named "my_posts_layout.ctp"
In your PostController set $this->layout = 'my_posts_layout';
This way you should view the content defined on my_posts_layout.ctp.
Lack of stylesheets has no impact here.
How MVC works in CakePHP:
The router dispatches an incoming request to an appropriate Contoller.
The appropriate Controller function executes (no output, just fetching data, setting up variables).
The appropriate view is rendered. In fact, the output of the view is just contained in $content_for_layout.
What you really get back in the browser is in the layout. Therefore you can put your view's output into the layout by echo $content_for_layout in default.ctp. (Of course you can also have different layouts.) In addition, the layout can be enhanced with elements.
I really recomend the CakePHP CookBook, easily found from the CakePHP homepage. Modifying default.ctp should edit your applications layout.
A more specific question (eg. code samples of your default.ctp, expected results etc) might help people provide a better answer than mine.
How does cakephp handle a get request? For instance, how would it handle a request like this...
http://us.mc01g.mail.yahoo.com/mc/welcome?.gx=1&.rand=9553121_pg=showFolder&fid=Inbox&order=down&tt=1732&pSize=20&.rand=425311406&.jsrand=3
Would "mc" be the controller and "welcome" be the action?
How is the rest of the information handled?
Also note that you could use named parameters as of Cake 1.2. Named parameters are in key:value order, so the url http://somesite.com/controller/action/key1:value1/key2:value2 would give a a $this->params['named'] array( 'key1' => 'value1', 'key2' => 'value2' ) from within any controller.
If you use a CNN.com style GET request (http://www.cnn.com/2009/SHOWBIZ/books/04/27/ayn.rand.atlas.shrugged/index.html), the parameters are in order of appearance (2009, SHOWBIZ, books, etc.) in the $this->params['pass'] array, indexed starting at 0.
I strongly recommend named paramters, as you can later add features by passing get params, without having to worry about the order. I believe you can also change the named parameter separation key (by default, it's ':').
So it's a slightly different paradigm than the "traditional" GET parameters (page.php?key1=value1&key2=value2). However, you could easily add some logic in the application to automatically parse traditional parameters into an array by tying into how the application parses requests.
CakePHP uses routes to determine this. By default, the routes work as you described. The remainder after the '?' is the querystring and it can be found in $this->params['url'] in the controller, parsed into an associative array.
Since I found this while searching for it, even though it's a little old.
$this->params['url']
holds GET information.
I have tested but it does work. The page in the Cakephp book for it is this link under the 'url' section. It even gives an example very similar to the one in the original question here. This also works in CakePHP 1.3 which is what I'm running.
It doesn't really use the get in the typical since.
if it was passed that long crazy string, nothing would happen. It expects data in this format: site.com/controller/action/var1/var2/var....
Can someone clarify the correct answer? It appears to me that spoulson's and SeanDowney's statements are contradicting each other?
Would someone be able to use the newest version of CakePHP and get the following url to work:
http://www.domain.com/index.php/oauth/authorize?oauth_version=1.0&oauth_nonce=c255c8fdd41bd3096e0c3bf0172b7b5a&oauth_timestamp=1249169700&oauth_consumer_key=8a001709e6552888230f88013f23d5d004a7445d0&oauth_signature_method=HMAC-SHA1&oauth_signature=0bj5O1M67vCuvpbkXsh7CqMOzD0%3D
oauth being the controller and authorize being a method AS WELL as it being able to accept the GET request at the end?
When using the paginator helper in cakephp views, it doesnt remember parts of the url that are custom for my useage.
For example:
http://example.org/users/index/moderators/page:2/sort:name/dir:asc
here moderators is a parameter that helps me filter by that type. But pressing a paginator link will not include this link.
The secret is adding this line to your view:
$paginator->options(array('url'=>$this->passedArgs));
(I created this question and answer because it is a much asked question and I keep having to dig out the answer since i cant remember it.)
To add to Alexander Morland's answer above, it's worth remembering that the syntax has changed in CakePHP 1.3 and is now:
$this->Paginator->options(array('url' => $this->passedArgs));
This is described further in the pagination in views section of the CakePHP book.
$this->passedArgs is the preferred way to do this from the view.
You saved me! This helped me a lot, Thanks.
I needed a way to pass the parameters I originally sent via post ($this->data) to the paging component, so my custom query would continue to use them.
Here is what I did:
on my view I put
$paginator->options(array('url'=>$this->data['Transaction']));
before the $paginator->prev('<< Previous ' stuff.
Doing this made the next link on the paginator like "
.../page:1/start_date:2000-01-01%2000:00:00/end_date:3000-01-01%2023:59:59/payments_recieved:1"
Then on my controller I just had to get the parameters and put them in the $this->data so my function would continue as usual:
foreach($this->params['named'] as $k=>$v)
{
/*
* set data as is normally expected
*/
$this->data['Transaction'][$k] = $v;
}
And that's it. Paging works with my custom query. :)
The options here are a good lead ... You can also check for more info on cakePHP pagination at cakephp.org/view/166/Pagination-in-Views
With that param 'url' you can only put your preferred string before the string pagination in url..
if I use this tecnique:
$urlpagin = '?my_get1=1&my_get2=2';
$paginator->options = array('url'=>$urlpagin);
I only obtain:
url/controller/action/?my_get1=1&my_get2=2/sort:.../...
and Cake lost my get params
Have you an alternative tecnique?