cakephp getLastInsertId not working - cakephp

Here I have used cakephp js helper to send data,After insert One data I need this last id for farther work.Here I have tried bellow code in Addcontroller
if ($this->Patient->save($this->request->data)) {
$lastid=$this->Patient->getLastInsertId();
$patient=$this->Patient->find('all',array(
'conditions'=>array('Patient.id'=>$lastid ),
'recursive' => -1
));
$this->set('patient', $patient);
}
In add.ctp I have tried bellow code but I haven't get last id here.
<?php foreach ($patient as $patient): ?>
<?php echo h($patient['Patient']['id']); ?>
<?php endforeach; ?>

Method getLastInsertId() return id of just saved records.
If you need this id in your view just after save, you must first set that variable in your controller like $this->set(compact('lastid','patient'); and then use in view <?php echo $lastid; ?>

use
if ($this->Patient->save($this->request->data)) {
$id = $this->Patient->id;
$patient=$this->Patient->find('all',array('conditions'=>array('Patient.id'=>$id),'recursive' => -1));
$this->set->('patient', $patient);
//If you are saving the record with ajax which it looks like you
//might be from your question you will need the following instead
//of $this->set->('patient', $patient); try:
return json_encode($patient);
You will then also need to update your js ajax call, you will have a json array to decode so parse it with jquery and append it back into your view.
Cake will always give you the id of record you have just saved, by simply adding $id = $this->MyModel->id; You can use the id to query for the record.

Try below code:
In controller:
$lastid=$this->Patient->getLastInsertId();
$this->set(compact('lastid','patient');
Then use $lastid in View file.
In controller:
$lastid=$this->Patient->getLastInsertId();
$patient['Patient']['last_id'] = $lastid;
then use $patient['Patient']['last_id'] in your view file.

Related

cake - Confused about how to count data

I know this question is very simple. But I fail to find it in Google. I'm very new to cake afterall.
For example I have two Model: Product and Category.
In Product index I want to show a list of available Categories and the amount of Products in that category. Like below:
Food (10)
Beverages (7)
...
I successfully looped the available categories, but not sure how to count it. Below is my loop:
<?php foreach($categories as $c): ?>
<li> ... <?php echo $this->$c->Product->find('count') ?> </li>
<?php endforeach; ?>
// The ... part is echo-ing the category name
I tried many variations and keep getting error like ArrayHelper not found or ProductHelper not found
Anyone have the solution?
Thanks
EDIT
This is my ProductController code before I added the foreach loop you suggested.
public function index() {
//the first two lines is default from cake bake
$this->Product->recursive = 0;
$this->set('products', $this->paginate());
$categories = $this->Product->Category->find('all');
$this->set('categories', $categories);
}
Instead of calculating the count on each request, use the counter cache feature to store the products count for each category and then simply display that.
you are trying to call model in view file, instead you could add the product count to your array from controller itself, like, example code would be:
in your controller:
$categories = $this->Product->Category->find('all',array('recursive'=>-1));
foreach($categories as $key => $category){
$categories[$key]['ProductCount'] = $this->Product->find('count',
array(
'conditions'=>array('Product.category_id'=>$category['Category']['id'])
)
);
}
where ProductCount can be replaced by name of the product

CakePHP: beforeSave not working with saveMany?

So, for some reason, anything I do to data in the beforeSave callback, though it works on single records, does not work when using saveMany.
What gives? If I do the following:
public function beforeSave() {
$this->data['foo'] = 'bar'
die($this->data);
}
I can see that in fact $this->data does DOES get changed, but saveMany just ignores it and saves the original data instead.
Make sure you include the model name when manipulating $this->data, e.g. $this->data['Event']['foo'] = bar. Be sure the method returns true as well or the save will fail.
Edit
I whipped up a quick example and it seems to be working for me, see the code below. My suspicion is that maybe you are calling saveMany incorrectly and passing it the whole $this->request->data object but it's hard to guess without seeing your call as well.
View
<?php echo $this->Form->create('ParentTable'); ?>
Record 1: <br />
<?php echo $this->Form->input('ParentTable.0.name'); ?>
Record 2: <br />
<?php echo $this->Form->input('ParentTable.1.name'); ?>
<?php echo $this->Form->end('Submit'); ?>
Controller
public function index() {
if ($this->request->data) {
$this->ParentTable->saveMany($this->request->data['ParentTable']);
}
}
Model
public function beforeSave() {
$this->data['ParentTable']['name'] .= ' modified';
return true;
}

How to pass database record from Controller to View in CakePHP

I've started a project in CakePHP. I have no experience of it, most of my experience is with Symfony2.
Right now, I have built a view file, a controller, and a model for use with this project and it's database. In one controller I want to pass one record from the database to the view for use on the homepage. However, I'm unable to pass the record as I get this error:
Notice (8): Undefined variable: content [APP\View\Contents\home.ctp,
line 42]
Here is my controller code:
function home() {
$content = $this->Content->query("SELECT title, content FROM content WHERE id = 1;");
$this->set('pagecontent',$content);
}
And here is the code I'm using to display the data in the view file:
<?php $content['content']; ?>
What have I missed?
EDIT:
I have changed the <?php $content['content']; ?> to <?php echo $pagecontent['Content']['content']; ?> inline with the changes outlined in the answer from Ross. However, there is now this error:
Notice (8): Undefined index: Content [APP\View\Contents\home.ctp, line
43]
I have used the <?php echo debug($this->viewVars); ?> and this is the output from that:
app\View\Contents\home.ctp (line 42) Array (
[pagecontent] => Array
(
[0] => Array
(
[content] => Array
(
[title] => <h1>This is a title</h1>
[content] => <p>this is some test text</p>
)
)
)
)
$this->set('pagecontent',$content); - this is where you are setting view variables.
You are trying to access a variable called $content, when in fact it is stored as $pagecontent.
Also based on Cake conventions, the key content should actually be Content, so your output should probably be:
<h1><?php echo $pagecontent['Content']['title']; ?></h1>
<div class="page-content">
<?php echo $pagecontent['Content']['content']; ?>
</div>
You can always do debug($this->viewVars); to see exactly what you have access to.
Seeing the output helps; the error is due to how cake is returning the data.
This is likely due to you using query() rather than find() or read(). (also explains why your content key is lowercase - query() uses the table name, rather than the model name.
Try:
$content = $this->Content->find('first',
array('fields' => array('title', 'content'),
'conditions' => array('Content.id' => 1)
)
);
$this->set('pagecontent', $content);
// view
echo $pagecontent['Content']['title'];
echo $pagecontent['Content']['content'];
should now work.
The alternative is to just access the data through the array index:
echo $pagecontent[0]['content']['title']
which isn't as "cake" like.
to expand = query() returns data in a different structure than using find or read. There's other ways you can do this too.
$this->Content->id = 1;
$this->set('pagecontent', $this->Content->read(array('title', 'content')));
should also be valid.

Using one model to read and another to save data

I have a model named google_news.php which uses the external data, and another model saved_news.php which uses my saved_news table in database,
In my controller I declared that Im using this two models:
var $uses = array('GoogleNews', 'SavedNews');
and my index function reads data:
$this->set('news',$this->GoogleNews->find('all'));
and my view looks like this:
<?php foreach( $news as $newsItem ) : ?>
<?php echo $html->link($newsItem['GoogleNews']['title'], array('action'=>'add', $newsItem['GoogleNews']['title'])); ?>
<?php echo $newsItem['GoogleNews']['encoded']; ?>
<em>
<hr>
<?php endforeach; ?>
How to write the add function in my controller to save each data to my database?
You should assign what you need to be saved into $this->data['ModelName'] as array of fields. Take a look at saving data in the book. That will explain more about the formatting that needs to be followed.

Cakephp Validation

I am using an Account Controller which doesnt have its own table but uses User Model.
All works fine except - when I validate any form. It says validation fails (when I try to fail the validation to check) but doesnt throw the error below the field
View
<?php echo $this->Form->input('id'); ?>
<label for="UserPassword">New Password:</label>
<?php echo $this->Form->text('password', array('type' => 'password', 'value' => 'harsha')); ?><em>Password must be min 6 characters.</em> <?php echo $form->error('password'); ?>
Controller Action
if($this->User->saveField('password', $this->data['User']['password'], array('validate' => 'first'))) {
$this->Session->setFlash('Password has been changed.', 'flash-success');
} else {
$this->Session->setFlash('There was some problem with our system. Please try after some time.', 'flash-warning');
}
Try debug()ing the contents of $this->validationErrors in your view, as well as $this->data in your controller just after a form submission. This should give you a lot more information to work from.
I suspect that your problem is Cake is building form inputs based on the wrong model -- building form fields for Account.id and Account.password instead of User.id and User.password. This is because FormHelper takes its default model from the controller/view it's invoked from, which in your case appears AccountsController.
In order to generate the User.id and User.password fields your controller's submission handling expects, you'll need to prepend User. in your FormHelper calls. Thus:
$this->Form->input('User.id');
$this->Form->text('User.password');
Have you tried:
echo $session->flash();
Note that whatever the manual says, it returns, not echoes. I logged this a while back and it has been changed in the 1.3 manual, but not the 1.2.
Hi you who's asking If you want to show error-message that return from UserModel's validate So you can add line code bellow after input form password
<?php
if ($this->Form->isFieldError('password')) {
echo $this->Form->error('password', array('class' => 'error'));
?>
and if you want to show error-message that set by method setFlash
you must redirect page and then use $this->Session->flash('flash-name') in page you want to show it
<?php
//in UsersController
$this->Session->setFlash('message here', 'flash-name');
//in view
echo $this->Session->flash('flash-name');
?>
Good luck!

Resources