I'm new when it comes to work with CakePHP. I'm facing a problem that is bothering me since i started doing it. I got a form with an input and when a person types in what he/she wants (it is a classified website where you can search for something that you'd like to buy eg. a blue pen) it shows the page that refers to the desired object. For example. if i type in 'blue pen', it retrieves all the data that i have in my database related to the blue pen.
Hope you can help me, there is my code:
index.ctp
<?php
echo $this->Form->create('Location', array('type' => 'get'));
echo $this->Form->input('Find');
echo $this->Form->end();
?>
and my ArticlesController
public function search() {
$obj = '';
if (!empty($this->data)) {
$obj = $this->data['Location']['Procurar'];
$opts = array(
'conditions' => array('Location.Procurar' => $obj)
);
}
$this->set('obj', $obj); // so the keyword is saved. Can also get it via $this->data
}
Related
I created a form with input type file, button submit to access to a function in controller, the problem is I can't get data from that file.
in controller when I call :
function displayAll() {
$adherents = $_FILES['file']['tmp_name'];
prd($adherents);
}
I found this error
Undefined index: file [APP\controllers\adherents.php, line 36]
and this is the view:
<h2>Upload filer</h2>
<br>
<fieldset class="pano bleu">
<?php echo $this->Form->create('adherentsSuph', array('action'=>'displayAll'));?>
<?php
echo $this->Form->input('file', array('type' => 'file'));
echo $bouton->block(array(
'cancel'=>array('action'=>'index'),
'submit'=>array('id'=>'addAdherentFile')
));
echo $this->Form->end();?>
</fieldset>
Add 'type' => 'file' to your form options like this:
<?php echo $this->Form->create('adherentsSuph', array('action'=>'displayAll', 'type' => 'file')); ?>
Check if is a valid request and a valid file, then use file() to read the entire file into an array and loop it.
if (!empty($this->data)) {
if (is_file($this->data['file']['tmp_name'])) {
$file = file($this->data['file']['tmp_name']);
foreach ($file as $key => $row) {
var_dump($row); die;
}
}
}
See also:
file()
is_file()
Form > Options > Type
Field naming convention
Debug $this->data to check if you need to change $this->data['file'] to $this->data['adherentsSuph']['file']
Your question is of poor quality since you are giving incomplete code. I will try to help you anyway.
Please check the following things:
Are you using the CakePHP FormHelper?
If so make sure you initialize the Form with 'type' => 'file' (see here).
Finally check, what you get in $this->request->data in your Controller.
I am still fairly new to CakePHP, though I like to think I have some basic understanding.
I have made a basic blog, based on an 'articles' table and bake all, piece of cake so far ;D. Now I've added a 'comments' table. 'articles' hasMany 'comments' and 'comments' belongsTo 'articles'. I again baked all for both tables and edited the 'view' action in ArticlesController.php and Articles/view.ctp to display all the comments of an article. No issues yet.
Now I'd like to be able to add a comment on the 'view' page of an article, much like you can comment on this forum. So I've added an Html->Form to view.ctp and copied some parts from the comment's add() to the article's view(). Article's view action:
public function view($id = null) {
$article = $this->Articles->get($id, [
'contain' => ['Comments']
]);
// Part from the add-action from Comments
$comment = $this->Comments->newEntity();
if ($this->request->is('post')) {
$comment = $this->Comments->patchEntity($comment, $this->request->data);
if ($this->Comments->save($comment)) {
$this->Flash->success(__('The comment has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The comment could not be saved. Please, try again.'));
}
}
// Set the selected article
$this->set('article', $article);
$this->set('_serialize', ['article']);
}
A part from Articles/view.ctp :
<?php foreach ($article->comments as $comment) : ?>
<h5><?= $comment->author ?></h5>
<p><?= $comment->body ?></p>
<?php endforeach; ?>
<b>Add comment</b>
<?= $this->Form->create($comment) ?>
<?php
echo $this->Form->input('comment.author');
echo $this->Form->input('comment.body');
?>
<?= $this->Form->button(__('Submit Comment')) ?>
<?= $this->Form->end() ?>
But this gives me a fatal error, :
Error: Call to a member function newEntity() on boolean File
C:\xampp\htdocs\blog_simple\src\Controller\ArticlesController.php
Line: 45
Any suggestions on how to accomplish what I'm looking for?
Error: Call to a member function newEntity() on boolean File
C:\xampp\htdocs\blog_simple\src\Controller\ArticlesController.php
Line: 45
Because you are in Articles Controller and you are trying Comments related functions (without Loading Model).
You have two option.
If you have correct relationship set up, then append Articles to calls like,
$comment = $this->Comments->newEntity();
to
$comment = $this->Articles->Comments->newEntity();
Similarly do for all the comments PatchEntity and Save function.
Add
$this->loadModel('Comments');
before calling Comments related functions. No need to append Articles like mentioned in previous point. Because, we are loading model.
Try which one you prefer. Good luck!
I'm working with cakephp for project development. I wrote a function to get data from the database and do a summation.I have created a table called user with height and weight in it. I want to retrieve that data,add them, and to return that. Here is the function I wrote.
public function calculate()
{
$Height=$this->set('user',$this->User->find('first'));
$Weight=$this->set('user1',$this->User->find('first'));
$sum=($Height+$Weight);
$this->set('SUM',$sum);
}
In the view I wrote the following code.
<div class="page-content">
<?php echo $user['User']['weight']; ?>
<?php echo $user1['User']['height']; ?>
<?php echo $SUM ?>
</div
Height and weight values are getting displayed. But the sum value is displayed as zero. Please help me to fix this.
I found a better way to do the above calculation. I used the following code in the controller.
public function calculate($id=null)
{
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user1',$this->User->find('first', array('fields' => ('height'),'conditions' => array('User.id' =>$id))));
$this->set('user',$this->User->find('first', array('fields' => ('weight'),'conditions' => array('User.id' =>$id))));
}
My view looks similar to the one mentioned above. This works fine with me...
First you need get the field from find. (You can use find condition to filter de user id for example).
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $id),
'fields' => array('User.height', 'User.weight') // fields from your DB
));
So, you can do a pr($user) to see the data and know what use.
After do the sum and set to the view. Cakephp Set
i've created a method in my UsersController.php file , so that my users can change their password.
My method php code is:
public function changepass() {
$this->User->id = $this->Auth->user('id');
if($this->User->exists()) {
$new_pass = $this->request->data['User']['newpass'];
$repeat_pass = $this->request->data['User']['newrepeat'];
if($new_pass == $repeat_pass) {
$this->User->saveField('password',$new_pass);
$this->Session->setFlash(__('Updated successfully'));
$this->redirect(array('controller' => 'users','action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Passwords did not match'));
$this->redirect(array('controller' => 'users','action' => 'changepass'));
}
}
}
and my changepass.ctp View file is:
<?php
echo $this->Form->create();
echo $this->Form->input('newpass',array('type'=>'text','label'=>array('text'=>'Enter new password')));
echo $this->Form->input('newrepeat',array('type'=>'text','label'=>array('text'=>'Confirm new password')));
?>
<button type="submit">Save</button>
<?php echo $this->Form->end(); ?>
When i try to browse under the users/changepass,it returns me 2 errors about an undefined index:
Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 108]
Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 109]
pointing at this part of my code:
$new_pass = $this->request->data['User']['newpass'];
$repeat_pass = $this->request->data['User']['newrepeat'];
and also it (immediately) changes the user password in my database to blank.
I cannot find out what's wrong in any way. I'd be very grateful if you could help me at this point.
Thank you in advance.
You forgot one vital part about form processing in the controller: Check on POST.
if ($this->request->is('post')) {
// only then try to access $this->request->data['User'] content!
}
In the case thats it not a post (get), you just display the form - especially without trying to save anything.
Tip: Take a look at baked code (using cake bake) and you will see how it's done properly.
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.