This my link in newsses/index.ctp
$this->Html->link(__("Read more >>", TRUE), array('action'=>'view', $newss['Newsse']['title']));
and this my view code in newsses_controller.php:
function view($title = NULL){
$this->set('title_for_layout', __('News & Event', true));
if (!$id) {
$this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error'));
$this->redirect(array('action'=>'index'));
}
$this->set('newsse', $this->Newsse->read(NULL,$title));
$this->set('newsses', $this->Newsse->find('all'));
}
but it does't showing anything,
i want to make route like:
"newsses/view/2" to "newsses/view/title_of_news"
please help me....
You're using the Model::read() method method which takes as the second argument the id of the row in your Model's table that you want to access. It's better to use find in this case. You don't need to build a new method in your model or your controller, you can just edit the current view method.
# in newsses_controller.php:
function view($title = null) {
$this->set('title_for_layout', __('News & Event', true));
if (!$id) {
$this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error'));
$this->redirect(array('action'=>'index'));
}
$this->set('newsse', $this->Newsse->find('first', array(
'conditions' => array('Newsse.title' => $title)
));
$this->set('newsses', $this->Newsse->find('all'));
}
Or, you can make a more hybrid form in which viewing by id is still possible when a numerical title is given (this assumes you never have news items which have a title consisting of only numeric characters, e.g. '12345').
# in newsses_controller.php:
function view($title = null) {
$this->set('title_for_layout', __('News & Event', true));
if (!$id) {
$this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error'));
$this->redirect(array('action'=>'index'));
} else if (is_numeric($title)) {
$this->set('newsse', $this->Newsse->read(NULL, $title));
} else {
$this->set('newsse', $this->Newsse->find('first', array(
'conditions' => array('Newsse.title' => $title)
));
}
$this->set('newsses', $this->Newsse->find('all'));
}
Finally, you can also replace the find method in my example with a (shorter) custom findBy method (see the documentation for more info about this).
$this->Newsse->findByTitle($title);
For this you need to create a new method in your model Which will display result by news title. At this time your using $this->Newsse->read(NULL,$title)). You are using $title in read method while this read method search against news id in model. So you just need to create a new method in model class like readByTitle($title){ write query here to fetch news by title }. And use this method in your controller. $this->Newsse->readByTitle(NULL,$title))
Related
This my database:
http://gyazo.com/c6a86127d6f91aae947cf45ee535cecd
Example:
http://gyazo.com/c23fec3fabb7e4504c42453980fbc372
When I press the edit button , they able to retrieve the data however the page show me empty field instead of the field that have old data.
Secondly, unable to undate because they keep send empty id_field back to controller.
p.s. add,edit,delete method work totally fine.
Below are my code:
Model
<?php
App::uses('AppModel', 'Model');
class EventDate extends AppModel {
public $useTable = 'eventdate';
public $primaryKey = 'eventDate_id';
public $validate = array(
'event_date' => array(
'rule' => array('date','ymd'),
'message' => 'Enter a valid date in YY-MM-DD format.',
'required' => true,
'allowEmpty' => false
)
);
}
Controller
public function edit($id = null) {
//Retrieve from database
$post = $this->EventDate->findByEventdateId($id);
$this->set('edate', $post) ;
// debug($post);
//Without Id
if (!$id) {
throw new NotFoundException(__('Invalid Event Date'));
}
//If Not Exist the id
if (!$post) {
throw new NotFoundException(__('Invalid Event Date'));
}
//After press the submit
if ($this->request->is(array('post','put'))) {
$this->EventDate->eventDate_id = $id;
debug($_POST);
if ($this->EventDate->save($this->request->data)) {
$this->Session->setFlash(__('The Event has been saved.'));
return $this->redirect(array('action' => 'index'));}
else
{$this->Session->setFlash(__('The Event could not be saved. Please, try again.'));}
}
//Set the data same as retrieved
if (!$this->request->data) { $this->request->data = $post;}
}
edit.ctp
<h2>Edit Event</h2>
<?php
echo $this->Form->create('eventdate');
//echo $this->Form->input('eventDate_id', array('type' => 'hidden'));
echo $this->Form->hidden('eventDate_id');
echo $this->Form->input('event_date',array(
'label' => 'Event Date',
'type' => 'text',
'id' => 'datepicker'));
echo $this->Form->end('Save Post');
?>
Below link is the debug($_Post) been shown:
http://gyazo.com/5e569e6cc6b3026fc8896c315197a938
Should be:
echo $this->Form->create('EventDate'); // notice the capital CamelCase
Side note: The info that displays in the fields will be out-of-date, since you 1) get the data from the DB and set to var, THEN do the save based on posted data.
Another side note: There are quite a few things that you're doing that are non-standard and not consistent w/ the recommended conventions. Cleaning that up will make it easier to work with AND easier to receive help.
I am developing an Application using 2 models, Users and profiles.
when I am trying to editing both models at a time, I am getting continuously this error
Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1006]
my $this->request->data array is in
array(
'User' => array(
'password' => '*****',
'id' => '6',
'first_name' => 'some',
'middle_name' => 'kjkj',
'last_name' => 'one',
'username' => 'kadjssa',
'group_id' => '5',
'mobile_no' => '7867868'
),
'Profile' => array(
'skype' => 'shrinet'
)
)
and my User controller edit function contain
public function editClient($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
debug($this->request->data);
if ($this->request->is('post') || $this->request->is('put')) {
$this->request->data['User']['user_id'] = $this->Auth->User('id');
$this->request->data['Profile']['user_id'] = $id;
debug($this->request->data);
print_r (debug($this->User->invalidFields()));
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
in debugging its giving
SQL Query: INSERT INTO `mvs`.`users` (`id`, `first_name`, `middle_name`, `last_name`, `username`, `password`, `group_id`, `mobile_no`, `user_id`, `modified`, `created`) VALUES (Array, Array, Array, Array, Array, Array, Array, Array, Array, '2013-07-05 00:07:13', '2013-07-05 00:07:13')
Please help me... thanks in advance
The docs recommend to use saveAssociated or saveMany depending on the case
This function receives the same options as the former two, and is generally a backwards compatible function. It is recommended using either saveMany or saveAssociated depending on the case
So the first choice is to change that saveAll to saveAssociated, since I think there's just one user and one profile.
All saveAll does is to call Set::numeric(array_keys($data)), and if that is true, calls saveMany, otherwise saveAssociated. The problem probably is in that Set::numeric comparison. If you want to get to the bottom of that, do a debug of
Set::numeric(array_keys($this->request->data));
If that gives you true, it must consider your array to be numerically indexed. Then you'll need to start debugging why is considered that way, check the Set::numeric function, where does the bad check, and change it or report it as a bug.
I think that trying to debug that is more troublesome than to change saveAll to saveAssociated, though, since you commented that the last gives you no problem.
Thank god,
I found resolution......
just use $this->User->saveAll($this->request->data, array('atomic' => false, 'deep' => true)); instead of $this->User->saveAll($this->request->data); because
Be careful when checking saveAssociated calls with atomic option set to false. It returns an array instead of boolean
ch http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
I'm using cakephp 2.
Is it possible to use the form helper postLink function to update a record? Basically I want a "Approve" button that changes the "Approved" field of a record to 1.
Everything I can find only relates to performing a delete function? The docs don't go into much details either.
Any help would be great, thanks in advance
My code:
<?php echo $this->Form->postLink(__('Approve'), array(
'controller' => 'expenseclaims',
'action' => 'edit', $expenseClaim['ExpenseClaim']['id'],
'approved' => '1',
'approved_by' => $adminUser,
), array(
'class' => 'btn btn-danger'
), __('Are you sure you want to Approve # %s?',$expenseClaim['ExpenseClaim']['id']
)); ?>
New code: view post link:
<?php echo $this->Form->postLink(__('Approve'), array('action' => 'approve', $expenseClaim['ExpenseClaim']['id'], 'admin' => true), array('class' => 'btn btn-danger'), __('Are you sure you want to Approve # %s?',$expenseClaim['ExpenseClaim']['id']));
?>
Controller code:
public function admin_approve($id = null) {
debug($this->request);
$this->ExpenseClaim->id = $id;
if (!$this->request->is('post') && !$this->request->is('put')) {
throw new MethodNotAllowedException();
}
if (!$this->ExpenseClaim->exists()) {
throw new NotFoundException(__('Invalid expense claim'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->request->data['ExpenseClaim']['approved'] = '1';
$this->request->data['ExpenseClaim']['approved_by'] = $this->Auth->user('id');
if ($this->ExpenseClaim->save($this->request->data)) {
$this->Session->setFlash('The expense claim has been Approved', 'flash_success');
$this->redirect(array('action' => 'index', 'admin' => true));
} else {
$this->Session->setFlash('The expense claim could not be approved. Please, try again.', 'flash_failure');
}
}
}
yes, of course that is possible.
just post to something like
/expenseclaims/approve/id
to trigger the approve action for example:
public function approve($id = null) {
if (!$this->request->is('post') && !$this->request->is('put')) {
throw new MethodNotAllowedException();
}
//validate/save
}
you can also make it more generic, of course
I can't figure out why this code isn't working. The beforeSave is not being called. It's supposed to fail the save and put some lines in the debug log, but it actually does save OK and no lines are written in the debug log.
<?php
class Link extends AppModel {
var $name = "Link";
var $belongsTo = array('Category' => array('className' => 'Category', 'foreignKey' => 'category_id'));
public function beforeSave(){
if ($this->data[$this->alias]['id'] == null) {
$this->log("new record", 'debug');
$link = $this->find('first',array('conditions' => array('Link.status = 1 AND Link.category_id = '.$this->data[$this->alias]['category_id']), 'order' => array('Link.order DESC') ));
if (is_null($link)) {
$this->data[$this->alias]['order'] = 1;
}else{
$this->data[$this->alias]['order'] = $link['Link']['order'] + 1;
}
}
else {
$this->log("old record", 'debug');
}
return false;
}
}
?>
I am launching a save in the controller like this:
public function add($category_id = null)
{
if ($category_id == null) {
$this->Session->setFlash(__('Category id cant be null'),'default', array('class' => 'error-message'));
$this->redirect(array('action' => 'index', 'controller' => 'categories'));
}
else
{
if($this->request->is('post'))
{
$this->Link->create();
$this->Link->set('category_id' => $category_id));
if($this->Link->save($this->request->data))
{
$this->Session->setFlash(__('The link has been saved'),'default', array('class' => 'success'));
$this->redirect(array('action' => 'index/'.$category_id));
}
else
$this->Session->setFlash(__('The link could not be saved. Please, try again.'),'default', array('class' => 'error-message'));
}
$this->set('category_id',$category_id);
}
}
Another question in StackOverflow points out that the beforeSave method needs to be declared in the Model. I've also done the same thing with another model.
Here's some general advice and some comments on your code for an answer:
1) If a model callback or any model method isn't working, make sure the correct model is being used and not the default model (AppModel). Check filename, class name, extension (in your case), and location.
2) You're using conditions array incorrectly (in this case).
array('conditions' => array('Link.status = 1 AND Link.category_id = '.$this->data[$this->alias]['category_id'])
You should really be doing:
array('conditions' => array('Link.status' => 1, 'Link.category_id' => $this->data[$this->alias]['category_id'])
3) Your redirect is being used wrong
$this->redirect(array('action' => 'index/'.$category_id));
Should be:
$this->redirect(array('action' => 'index', $category_id));
As written, your save() will always fail with this beforeSave(). beforeSave() must return true in order for the save function to succeed.
In fact, yours appears to always return false, guaranteeing a failed save.
From the Cake manual:
Be sure that beforeSave() returns true, or your save is going to fail.
I'm using the Cupcake Forum plugin within CakePHP. There's a form for selecting the desired posts, and then submitting the form to delete the posts. The form data is apparently being sent to the 'moderate' function within the 'topics' controller using POST and GET methods simultaneously. The function first checks to see if the data sent in is POST. However, when the data is received, it shows that it's GET. A fellow programmer and I don't want to completely change someone else's internal code, but we can't figure out how the data is being sent by both methods and being received as GET. The code from the plugin is below:
--------------moderate.ctp (view)---------------------
<?php echo $form->create('Post', array('url' => array('controller' => 'topics', 'action' => 'moderate', $topic['Topic']['slug']))); ?>
-------------topics_controller.php (controller)-------
public function moderate($id) {
if ($this->RequestHandler->isGet()){
$this->log('Is GET!');
}
$user_id = $this->Auth->user('id');
$topic = $this->Topic->getTopicForViewing($id, $user_id, 'id');
// Access
$this->Toolbar->verifyAccess(array(
'exists' => $topic,
'permission' => $topic['ForumCategory']['accessRead'],
'moderate' => $topic['Topic']['forum_category_id']
));
$this->log('ID: '.$id.'\n');
if ($this->RequestHandler->isPost()){
$this->log('Is POST!');
}
if ($this->RequestHandler->isGet()){
$this->log('Is GET!');
}
$this->log($this->RequestHandler->getReferer());
$this->log(serialize($this->data));
// Processing
if ($this->RequestHandler->isPost()) {
$this->log('INSIDE POST!');
if (!empty($this->data['Post']['items'])) {
$items = $this->data['Post']['items'];
$action = $this->data['Post']['action'];
foreach ($items as $post_id) {
$this->log('Action: '.$action.'\n');
$this->log('PostID: '.$post_id.'\n');
if (is_numeric($post_id)) {
if ($action == 'delete') {
$this->Topic->Post->destroy($post_id);
$this->Session->setFlash(sprintf(__d('forum', 'A total of %d post(s) have been permanently deleted', true), count($items)));
}
}
}
}
}
We added the log checks, which show the result of 'Is GET!' in Cake's log file. Since the method is GET, the statement 'if ($this->RequestHandler->isPost())' is never true; therefore, the submitted posts aren't deleted. What are we missing?
Try changing moderate.ctp to
<?php
echo $form->create('Post', array(
'url' => array(
'controller' => 'topics',
'action' => 'moderate',
$topic['Topic']['slug'],
),
'type' => 'post',
));
?>