CakePHP not picking up a javascript - cakephp

I am a totally noob at CakePHP and have been dealing with this site update from traditional php to CakePHP. In the old website there was a folder for javascript and in there, there was a file called paging.js, then, at then end of where i was doing the table loops and stuff you would add this
echo '<div id="pageNavPosition"></div>
<div> </div>';
echo "<script type='text/javascript'><!--
var pagerAdmin = new PagerAdmin('results', 5);
pagerAdmin.init();
pagerAdmin.showPageNav('pagerAdmin', 'pageNavPosition');
pagerAdmin.showPage(1);
//--></script>";
}
In that website works perfectly, it shows only 5 records and with pagination. But now here in cake PHP I have thi code in my view but its not picking up that portion of code
<?php
echo '<div><h3>Admin - Update Data</h3><p>To update data click on name</p></div>';
print("<table id='results'><tr><th>ID</th><th>Image</th><th>Name</th><th>Price</th><th>Description</th></tr>");
$i =0;
foreach ($dishes as $key => $dish):
print("<tr>");
print("<td width='20px'>");
echo '<p style="font-size:14px; color:blue; padding:0;">'.$dishes[$i]['Dish']['id'].'</p>';
echo '<input type="hidden" name="'.$dishes[$i]['Dish']['dish_name'].'" value="'.$dishes[$i]['Dish']['id'].'" id="DishDishId" />';
print("</td>");
print("<td width='10px'>");
print("<img class='custom_rate' alt='' src='/myweb/img/".$dishes[$i]['Dish']['dish_image']."' />");
print("</td>");
print("<td width='100px'>");
print("<a href='index.php?form_type=admin_manager&id=".$dishes[$i]['Dish']['id']."'>".$dishes[$i]['Dish']['dish_name']."</a> ");
print("</td>");
print("<td width='100px'>");
print($dishes[$i]['Dish']['dish_price']);
print("</td>");
print("<td width='100px'>");
print($dishes[$i]['Dish']['dish_disc']);
print("</td>");
print("</tr>");
$i++;
endforeach;
print("</table>");
if($i> 5)
{
echo '<div id="pageNavPosition"></div>
<div> </div>';
echo "<script type='text/javascript'>" ;
echo "var pagerAdmin = new PagerAdmin('results', 5);";
echo 'pagerAdmin.init();';
echo "pagerAdmin.showPageNav('pagerAdmin', 'pageNavPosition');";
echo 'pagerAdmin.showPage(1);';
echo '</script>";';
}
?>
Any idea how i can make this work again? .Any help would be much appreciated.
Thanks

For anyone who runs into this issue, you just need to create a separate .js file and place it in the webroot/js folder with your js code. Then reference it as follows
echo $this->Html->script('myjasfile.js');

Related

How to overwrite the default label generated by the form helper?

How can override the default label of cakephp replacing it on my desire label. my VIEW code in cakePHP is this:
echo $this->Form->create('Add');
echo "<h2>Email</h2>"; //Email
echo $this->Form->input('email'); //email
echo $this->Form->submit('submit');
echo $this->Form->end();
echo $this->Form->input('email', array('label' => 'Your Label'));

cakephp how to add script to view

I wish to add some script to a view and have it que and load at the bottom of the page within the default layout. At the moment it runs before query is loaded and causes an error.
I am using cakephp 2.5
Is there a way to buffer it?
myview.ctp:
<script type="text/javascript">
FWDEVPUtils.onReady(function(){
FWDEVPlayer.useYoutube = "yes";
FWDEVPlayer.videoStartBehaviour = "pause";
new FWDEVPlayer({
//main settings
instanceName:"player",
parentId:"player",
mainFolderPath:"content"
});
});
default.ctp
echo $this->Html->script('//code.jquery.com/jquery-1.10.2.min.js');
echo $this->Html->script('bootstrap.min');
echo $this->Html->script('FWDEVPlayer');
echo $this->fetch('script');
echo $this->Js->writeBuffer();
In myview.ctp:
<?php $this->start('script'); ?>
<script type="text/javascript">
FWDEVPUtils.onReady(function(){
FWDEVPlayer.useYoutube = "yes";
FWDEVPlayer.videoStartBehaviour = "pause";
new FWDEVPlayer({
//main settings
instanceName:"player",
parentId:"player",
mainFolderPath:"content"
});
});
<?php $this->end(); ?>
You script will then be included in your layout default.ctp where you wrote:
echo $this->fetch('script');

pagination not working when clicked next button

Controler
public function search() {
$this->Paginator->settings = $this->paginate;
$this->loadmodel('Usermgmt.User');
if ($this->request -> isPost()) {
$this->User->set($this->data);
$keyword=$this->data['Doctors']['search'];
//$this->loadmodel('Usermgmt.User');
$cond=array('OR'=>array("User.username LIKE '%$keyword%'","User.email LIKE '%$keyword%'", "User.first_name LIKE '%$keyword%'", "User.last_name LIKE '%$keyword%'"));
//$result = $this->paginate('User',array('conditions'=>$cond));
$result = $this->paginate('User',array($cond));
$this->set('result', $result);
}
}
View
<?php
if (!empty($result)) { $sl=0;
foreach ($result as $row1) {
//print_r($row1);
$sl++; ?><div style="width:100%;display:inline-block;">
<div style="float:left">
<?php
//echo $row1['id'];
echo $this->Html->link($this->Html->image('../files/user/photo/'.$row1 ['User']['photo_dir'].'/'.$row1 ['User']['photo'], array('width' => '180', 'height' => '180')),
array('controller'=>'Profiles','action'=>'index',$row1['User']['id']),
array('escape' => false));
?>
</div>
<div>
<?php echo h($row1['User']['first_name'])." ".h($row1['User']['last_name'])."</br>";
echo h($row1['User']['username'])."</br>";
echo h($row1['User']['email'])."</br>";
echo h($row1['User']['mobile'])."</br>";
echo h($row1['UserGroup']['name'])."</br>";
?></div>
<div style="clear:both;"></div>
</div>
<?php }?>
<?php echo $this->Paginator->prev('previous'); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next'); ?>
<?php }?>
here am search the user name or user details like fname, email like and display in view page
here i get output with pagination like 1 2 3 4 only first page displays when i click next page that shows empty pages may be $result getting unset how to solve this ??
The variable result is only sometimes set
if ($this->request->isPost()) {
...
$result = $this->paginate('User',array($cond));
$this->set('result', $result);
}
The variable result is only set for POST requests - clicking a link is not a post request, therefore the result variable is undefined.
Ensure you are paginating a GET request
There are several solutions, but the simplest solution to "How to paginate post data" is to not do so. Change your search form to use GET, and ensure the get parameters persist when paginating a request.
At the very least the controller code needs to call paginate and set for the variables in the view to exist irrespective of how the controller action was reached.

Redirect causing blank screen error cakephp

$this->redirect called from any controller method seems to result in a blank screen error, despite turning debug to 2 in my core.php.
In my AdminAppController, located in App/Plugin/Admin/Controller, was this piece of code originally, in my beforefilter():
public function beforeFilter() {
parent::beforeFilter ();
$rusername = $this->Auth->user ( "Username" );
if ($rusername != "admin") {
$this->redirect ( "/" );
return;
}
This results was an admin wide blank screen error, regardless of username. By commenting out the redirect, it allowed me to enter the admin area again.
However, now whenever I use $this->redirect I get blank screen errors.
For example here is my Prices view through my Product controller:
<?php echo $this->Session->flash('flash');?>
<?php echo $this->Form->create('Product', array('action' => 'change')); ?>
<fieldset>
<h3>Products</h3>
<table>
<?php
foreach($products as $k=>$v){
echo $this->Form->hidden("Product.{$k}.id", array('value'=> $v["Product"]['id']));
echo $this->Form->input("Product.{$k}.name", array('value' => $v["Product"]["name"], 'disabled' =>'disabled'));
echo $this->Form->hidden("Product.{$k}.slug", array('value'=>$v["Product"]['slug']));
echo $this->Form->hidden("Product.{$k}.description", array('value'=>$v["Product"]['description']));
echo $this->Form->hidden("Product.{$k}.cateID", array('value'=>$v["Product"]['cateID']));
echo $this->Form->input("Product.{$k}.price", array('value' => $v["Product"]['price']));
echo $this->Form->hidden("Product.{$k}.photo", array('value'=>$v["Product"]['photo']));
echo $this->Form->hidden("Product.{$k}.photo_dir", array('value'=>$v["Product"]['photo_dir']));
echo $this->Form->hidden("Product.{$k}.active", array('value'=>$v["Product"]['active']));
echo $this->Form->hidden("Product.{$k}.views", array('value'=>$v["Product"]['views']));
echo $this->Form->hidden("Product.{$k}.created", array('value'=>$v["Product"]['created']));
echo $this->Form->hidden("Product.{$k}.modified", array('value'=>$v["Product"]['modified']));
}
?>
</table>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
My Products controller contains this method:
public function prices(){
$products = $this->Product->find ("all");
$this->set ("products", $products );
}
And this method is called from this view:
public function change(){
//create() resets model, precaution
$this->Product->create();
$data = $this->request->data;
$this->Product->saveMany($data['Product']);
$this->Session->setFlash( "Prices Saved.");
$this->redirect ( '/' );
return;
}
On submitting a change of price (which does save and alter the database, the redirect line causes the screen to go blank, with no errors, or any other indication of what has gone wrong.
Error logs show no sign of what is happening.
Thanks.
Apologies for the late Answer.
After much struggle it turned out to simple.
AdminAppController included some whitespace before an opening

cakephp $this->request-is("post") return false for just one form, so strange?

I have many forms in the website. They are all created in the similar way like
<?php echo $this->Form->create('SysUser');?>
<fieldset>
<legend><?php echo __('Edit Basic Information'); ?></legend>
<?php
echo $this->Form->input('SysUser.first_name');
echo $this->Form->input('SysUser.family_name',array('label'=>__("Last Name")));
echo $this->Form->input('SysUser.mobile_phone_number');
echo $this->Form->input('SysUser.user_name',array('label'=>__("Screen Name")));
echo $this->Form->input('action', array('type'=>'hidden','value'=>'edit_basic_info'));
echo $this->Form->input('SysUser.id', array('type'=>'hidden','value'=>$user["id"]));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
But the type of one form becomes "put" , not "post". I never explicitly set the type to "post" when I create these forms. I gather CakePHP sets the default value to post. Now it seems something wrong about the way I create this new special form. Oddly, this was working days ago!
I don't know what's wrong. Here is it:
<?php echo $this->Form->create('Member'); ?>
<fieldset>
<legend><?php echo __('Basic Profile Setup'); ?></legend>
<?php
echo $this->Form->input('Member.gender_id');
$w = array();
for ($i = 40; $i < 120; $i++) {
$w[$i] = $i . " kg";
}
$h = array();
for ($i = 120; $i < 230; $i++) {
$h[$i] = $i . " cm";
}
echo $this->Form->input('Member.height', array(
'options' => $h,
'empty' => __("choose one")
));
echo $this->Form->input('Member.weight', array(
'options' => $w,
'empty' => __("choose one")
));
$options['minYear'] = date('Y') - 78;
$options['maxYear'] = date('Y') - 18;
echo $this->Form->input('Member.birthdate', $options);
echo $this->Form->input('Member.residential_location_id', array('label' => __("City/Location")));
echo $this->Form->input('Member.occupation_id',array('id'=>'MemberOccupationId'));
echo $this->Form->input('action', array('type' => 'hidden', 'value' => 'create_member'));
?>
</fieldset>
<?php
echo $this->Form->end(array("label" => __('Save')));
When the Request data contains a Model.id CakeRequest::method() is set to put. The preferred way to handle this in cakephp would be as follows.
if ($this->request->is(array('post', 'put'))) {
// Code
}
You can see this in baked controller, edit actions.
Not sure why it is happening, but you can set the form type this way:
<?php echo $this->Form->create('Member', array('type' => 'post')); ?>
I had this problem as well. In my situation this was happening when I had validation errors. So for the second run, the script thought it was a PUT request instead of a POST request. Now, because it was a PUT, it didn't even get inside the if-clause where I checked if it was a POST, so it would return to the input and try to create a POST request. This was looping forever.
The solution? Checking for a NOT GET.
So you would get something like this:
if (!$this->request->is('get')){
//Save logic here
}
I have seen an example like this in the Cookbook, but I can not find it. So I have a feeling it has been updated, but as far as I am concerned you have to use this method. So you will cover a PUT, as well as a POST request.
UPDATE
It is not recommended to use this approach. It is a PUT/POST based on if the id is set in the form. Since I was setting the id based on the type of request, instead of if it actually exists, it was switching over and over again. I am using 1 form for the add and the edit action. They both use the edit.ctp which is just set up more flexible.
From the Cookbook:
If $this->request->data contains an array element named after the form’s model, and that array contains a non-empty value of the model’s primary key, then the FormHelper will create an edit form for that record.
Is that the case, perhaps? What's Member's primary key?
I had the same issue and after 4 hours searching I just resolved it appending the Model name to the fields in the view like this:
<?php echo $this->Form->create('User');?>
<?php
echo $this->Form->input('User.id');
echo $this->Form->input('User.username', array('readonly' => true));
echo $this->Form->input('User.email', array('readonly' => true));
echo $this->Form->input('User.name');
echo $this->Form->input('User.phone');
echo $this->Form->input('User.gender');
echo $this->Form->input('User.locale', array('id' => 'locale_select', 'options' => array('es' => __('Spanish'), 'en' => __('English'))));
echo $this->Form->input('User.birthday', array('type' => 'date', 'dateFormat' => 'DMY', 'minYear' => date('Y') - 100, 'maxYear' => date('Y')));
?>
<?php echo $this->Form->end(__('Save', true));?>
Well, I have to say that this code is in a plugin, so I don't know if there could be any other problems. But other forms in that plugin work perfect and this one needs to have the Model name.
One of the ways I've handled this situation is to create my own detector that defines the context of post OR put. This goes in the beforeFilter() method in AppController:
// add a simple form post detector
$this->request->addDetector('formPosted', array(
'env' => 'REQUEST_METHOD',
'options' => array('post', 'put')
));
Then when you need to check if a form has been posted (or "putted"), then:
if ($this->request->is('formPosted')) { ... }
Since the detector is added in AppController, the condition can be checked from within any controller method.

Resources