I am building a simple mechanism where a user can like a post by clicking on a link. I'm using GET rather than POST as I want to allow the method to fire via the URL.
That been said how do I save data using GET? As the request data doesn't exist in this scenario... My model looks like:
class Like extends AppModel
{
public $name = 'Like';
public $belongsTo = array('User','Post');
}
and the method for adding looks like:
public function add( $id )
{
$post = $this->Post->find('first', array(
'conditions' => array('Post.id'=>Tiny::reverseTiny($id))
));
if (!$post)
{
throw new NotFoundException('404');
}
if($post['Post']['user_id'] == $this->Auth->user('id'))
{
$this->Session->setFlash('You can\'t like your own post... That\'s just silly!');
}
if ($this->Like->create())
{
$liked = $this->Like->find('first', array(
'conditions' => array('Like.id'=>Tiny::reverseTiny($id), 'Like.user_id'=>$this->Auth->user('id') )
));
if(!$liked){
$this->Like->saveField('user_id', $this->Auth->user('id'));
$this->Like->saveField('post_id', $post['Post']['id']);
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('You already like this post!');
}
else
{
$this->Session->setFlash('Server broke!');
}
}
Can anyone help?
<?php echo $this->Html->link('1', array('controller'=>'followers','action'=>'add','id'=>Tiny::toTiny($post['Post']['id'])),
array('title'=>'Follow','class'=>'follow')); ?>
This part all works fine. It's saving a new row in the DB on GET that I'm struggling with.
Hi you just need to make a link to your controller action and pass you variable in the url.
to be clear the link on the post to like is in your post view :
$this->Html->link('like this post', array('controller' => 'like', 'action' => 'add', $postId))
It should render a link like this :
www.yourWebSite/likes/add/1 to like the postId 1,
variables after your action (add) are interpreted as variable for your controller action
if your fonction add had been
public function add($postId, $wathever){
}
the url should look like www.yourWebSite/likes/add/1/blabla
where 1 is the first var for the add action and blabla the second one and so on.
this is the equivalent of a non rewriting url : ?postId=1&whatever=blabla
EDIT :
if(!$liked){
//simulate the post behaviour
$this->request->data['Like']['user_id'] = $this->Auth->user('id');
$this->request->data['Like']['post_id'] = $post['Post']['id'];
//save the data
if ($this->Like->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for your support !'));
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('Server broke!');
}
}
How about using save with id=0 instead of create?
<?php
$like = array(
"Like" => array
(
"id" => 0,
"user_id" => $this->Auth->user("id"),
"post_id" => $post['Post']['id']
)
);
$result = $this->Like->save($like);
if(!$result){$this->Session->setFlash('Server broke!');}
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
?>
Related
I need to use the function in my view/template page.
My code:
public function getAppNumber($id = null){
$aPPLICATIONINFO = $this->AppEstLto->APPLICATIONINFO->find('all', [
'fields'=>['application_number'],
'conditions'=>['application_id'=>$id],
'limit' => 200
]);
foreach($aPPLICATIONINFO as $aPPLICATIONINFO){
$aPPLICATIONINFOx = $aPPLICATIONINFO;
}
return $aPPLICATIONINFOx;
}
You can use set() to use the function variables in your view as given in cookbook:https://book.cakephp.org/3/en/views.html#setting-view-variables
public function get_app_number($id = null){
$applicationInfo = $this->AppEstLto->APPLICATIONINFO->find('all',
[
'fields'=>['application_number'],
'conditions'=>['application_id'=>$id],
'limit' => 200
]);
//Create an array
$applicationArray = new array();
//Store all results in array
foreach($applicationInfo as $application){
$applicationArray = $application;
}
// Pass the array to view
$this->set(compact('applicationArray'));
}
Now, you can use it in your view:
get_app_number.ctp:
<?php
foreach($applicationArray as $application)
{
echo $application['application_number'];
}
?>
You should be doing something like this in your routes.php file inside your Config folder:
Router::connect('/get-app-number', array('controller' => 'yourController', 'action' => 'get_app_number'));
That way you will be able to connect the url that will be used for your view.
Your action corresponds and sends data to your view.
The action is the function that is inside your controller in which you developed for setting the data and variables.
The example of the slug which would be generated:
http://localhost/get-app-number
I am using codeigniter I have an edit page which shows me all information of a vacancy.
The (Vacancy) controller method to load this view looks like this, it makes sure all data is preloaded.
public function editVacancy($vacancyid)
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
// Passing Variables
$data['title'] = 'Titletest';
$data['class'] = 'vacancy';
$orgadminuserid = $this->vacancies_model->getOrgAdminUserId($vacancyid);
if ((!is_null($orgadminuserid)) && ($this->auth_user_id == $orgadminuserid[0]->user_id)) {
$data['vacancyid'] = $vacancyid;
$data['vacancy'] = $this->vacancies_model->get($vacancyid);
$data['test'] = $this->session->flashdata('feedbackdata');
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/edit_vacancy', 'footer' => '_master/footer/footer');
$this->template->load('_master/master', $partials, $data);
}
}
In this view i have different forms for updating different sections.
Every form submit goes to a different method in my 'Vacancy' controller.
public function saveGeneralInfo()
{
$this->is_logged_in();
$this->load->model('vacancy/vacancies_model');
$vacancyid = $this->input->post('vacancyid');
$vacancyUpdateData = $this->vacancies_model->get($vacancyid);
$result = $this->vacancies_model->update($vacancyid, $vacancyUpdateData);
if ($result) {
$feedbackdata = array(
'type' => 'alert-success',
'icon' => 'fa-check-circle',
'title' => 'Success!',
'text' => 'De algemene vacature gegevens zijn geupdate.'
);
$this->session->set_flashdata('feedbackdata', $feedbackdata);
redirect("dashboard/vacancy/editVacancy/" . $vacancyid);
}
}
}
Where I indicated in my code "//HERE ..." is where I would want the feedback message parameter to pass on to my 'main controller method' which loads the view with the prefilled data. (editVacancy).
Is there a clean way to do this?
EDIT:
I tried using flashdata, i updated the code to have the flashdata inserted.
However when i do a var_dump($test); in my view, it remains null.
EDIT 2:
I noticed when i put my $_SESSION in a variable in my editVacancy controller method (which is being redirected to) and var_dump it in my view that this does not contain the ci_vars with the flashdata in.
Instead of using set_header you can use simple redirect function for it.
redirect("dashboard/vacancy/editVacancy/".$vacancyid);
I have a url of a page as
http://localhost/projectname/admin/client/1
In the above url i have a form in which i need to fill details and save it in database. The form on this page is:
<?php
$data = array(
'type'=>'text',
'name'=>'job_title',
'value'=>'Job Title',
'class'=>'form-control');
?>
<?php echo form_input($data); ?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php
echo form_close();
?>
On the submission of the page i wish to save it in a table but along with it i also wish to carry the id/value which is in url (in this case it is 1), and would like to carry it forward till model so that i can perform actions in database based on this id/value. Can anyone please tell how it can be done
Present code for controller
public function form()
{
$this->form_validation->set_rules('job_title','Full Name','trim|required|min_length[3]');
if($this->form_validation->run() == FALSE)
{
$regdata = array
(
'regerrors' => validation_errors()
);
$this->session->set_flashdata($regdata);
redirect('admin/clients');
}
else
{
if($this->user_model->job())
{
redirect ('admin/client');
}
}
}
Present code for model // In the users table i wish to add job title to that row where the id matches the value in url i.e 1
public function job()
{
$data = array(
'job_title' => $this->input->post('job_title')
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}
Try some thing like this:
$clientId = $this->uri->segment('3'); // will return the third parameter of url
Now put this $clientId in form in a hidden input. Now you can get the $clientId on controller function when form submits. Pass it to model or use accordingly.
I'm using CakePHP to show a frontend GUI for a MySQL database table. I've used bake to auto generate the screens and I currently have a fully functioning app with View, Edit and Delete buttons per row. I want to add a button per row, called Accept, which should set IsAccepted = 1 on the SQL row.
I've managed to add an Accept button per row as follows:
echo $this->Html->link(__('Accept'), array('action' => 'accept', $product['Product']['ID']))
But the code in ProductController.php does not work:
public function accept($id = null){
...
$this->Product->IsAccepted = 1; // does not work, silently fails
}
What am I doing wrong? How do I properly edit a row using a per-row button?
public function accept($id = null){
$this->Product->save(array('id' => $id, 'is_accepted' => 1));
}
// assuming cake 2.1+
public function accept($id = null){
if($this->Product->exists($id)) {
$this->Product->saveField('is_accepted', 1);
// success..
}
// else throw not found exception...
}
Thanks to cornelb I found the answer! This is the final code I used to modify a row, with a per-row button.
Modifies the row when the per-row button is pressed (works just like a POST/AJAX button)
A flash message that says "Accepted!" shows if saving succeeds
Redirects back to the listing page (appears to never leave the listing)
This is the code that goes in ProductController.php (or whatever controller class you have):
public function accept($id = null) {
if ($this->Product->exists($id)) {
// save the row
// you absolutely need to fill the 'id' slot, even if its not your primary key!!
// this ensures that the row is EDITED, and not INSERTED!
if($this->Product->save(array('id' => $id, 'ID' => $id, 'IsApproved' => 1, 'ApprovedDate' => date('Y-m-d H:i:s', time())))){
// show a "flash" message
// (not Adobe Flash, just a message that shows on top of the list)
$this->Session->setFlash(__('The product has been accepted!'));
// this action does not have a view so no need to render
$this->autoRender = false;
// redirect to index view
return $this->redirect(array('action' => 'index'));
}
}
}
**Try this.....**
<?php
public function accept($id = null) {
$this->autoRender = false; // if action has not view.
if ($this->Product->exists($id)) {
$this->Product->id = $id;
if ($this->Product->save(array('is_accepted' => 1))) {
$this->Session->setFlash(__('The product has been accepted!'));
return $this->redirect(array('action' => 'index'));
}
}
}
?>
Just run updateAll query from accept function as shown below:
public function accept($id = null){
if(!empty($id)){
$this->Product->updateAll(
array('Product.is_accepted' => 1),
array('Product.id' => $id)
);
}
}
Hope this will help you...
For reference: http://book.cakephp.org/2.0/en/models/saving-your-data.html
I'm setting up pagination to display a list of images belonging to the user in their account. This is what I have in my controller:
class UsersController extends AppController {
public $paginate = array(
'limit' => 5,
'order' => array(
'Image.uploaded' => 'DESC'
)
);
// ...
public function images() {
$this->set('title_for_layout', 'Your images');
$albums = $this->Album->find('all', array(
'conditions' => array('Album.user_id' => $this->Auth->user('id'))
));
$this->set('albums', $albums);
// Grab the users images
$options['userID'] = $this->Auth->user('id');
$images = $this->paginate('Image');
$this->set('images', $images);
}
// ...
}
It works, but before I implemented this pagination I had a custom method in my Image model to grab the users images. Here it is:
public function getImages($options) {
$params = array('conditions' => array());
// Specific user
if (!empty($options['userID'])) {
array_push($params['conditions'], array('Image.user_id' => $options['userID']));
}
// Specific album
if (!empty($options['albumHash'])) {
array_push($params['conditions'], array('Album.hash' => $options['albumHash']));
}
// Order of images
$params['order'] = 'Image.uploaded DESC';
if (!empty($options['order'])) {
$params['order'] = $options['order'];
}
return $this->find('all', $params);
}
Is there a way I can use this getImages() method instead of the default paginate()? The closest thing I can find in the documentation is "Custom Query Pagination" but I don't want to write my own queries, I just want to use the getImages() method. Hopefully I can do that.
Cheers.
Yes.
//controller
$opts['userID'] = $this->Auth->user('id');
$opts['paginate'] = true;
$paginateOpts = $this->Image->getImages($opts);
$this->paginate = $paginateOpts;
$images = $this->paginate('Image');
//model
if(!empty($opts['paginate'])) {
return $params;
} else {
return $this->find('all', $params);
}
Explanation:
Basically, you just add another parameter (I usually just call it "paginate"), and if it's true in the model, instead of passing back the results of the find, you pass back your dynamically created parameters - which you then use to do the paginate in the controller.
This lets you continue to keep all your model/database logic within the model, and just utilize the controller to do the pagination after the model builds all the complicated parameters based on the options you send it.