Creating a Dropdown Menu from Database - cakephp

I'm trying to create a Dropdown menu from the table Holidays for the column name. But I'm too dumb to make it work.
I already tried some of the things people wrote but most of them have a second database. But I only have one.
My goal is to show all the names from the Holiday name column so, if I create a new holiday, I just get the name of the date from the Dropdown menu and don't need to write it down every time.
HolidaysController.php
public function index()
{
$holidays = $this->paginate($this->Holidays);
$this->set(compact('holidays'));
$name =$this->name->find('list');
$this->set(compact('name'));
}
Holidays add.ctp
<?php
echo $this->Form->control('date', array('label' => __('Datum', true)));
echo $this->Form->control('name', ['options' => $name, 'empty' => true]);
?>
I thought he would show me now a dropdown list from the names of the holidays but i just have a normal field and get the error:
Notice (8): Undefined variable: name [APP/Template\Holidays\add.ctp, line 19]
I'm probably missing something really basic here, I'm still learning coding so if I missed any information, you need, just let me know.
EDIT:
My add function after the edit
HolidaysController
public function add()
{
$name =$this->name->find('list');
$this->set(compact('name'));
$holiday = $this->Holidays->newEntity();
if ($this->request->is('post')) {
$holiday = $this->Holidays->patchEntity($holiday, $this->request->getData());
if ($this->Holidays->save($holiday)) {
$this->Flash->success(__('Der Feiertag wurde gespeichert.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Der Feiertag wurde nicht gespeichert. Bitte, versuchen sie es erneut.'));
}
$this->set(compact('holiday'));
}

You must find and set list in your add() method, like :
public function add()
{
// your add code here .. then:
$name =$this->Holidays->find('list');
$this->set(compact('name'));
}
By default every controller method has own view template:
index() >> index.ctp
add() >> add.ctp
edit() >> edit.ctp
myCustomMethod() >> my_custom_method.ctp
// ...
EDIT:
If I add your code to function add() i get an Error: Call to a member
function find() on string.
I copy code from your question. But you must update:
from: $this->name->find('list'); to
$this->Holidays->find('list', [
'keyField' => 'name',
]);

Related

search bar using cakephp

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
}

Edit associated model from view of another model (CakePHP 3)

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!

Basic CakePHP: Edit Post Method become Add Post Method

Currently following the blog tutorial however my database and their variable are different.
I was looking through the "Edit Post" method and follow the step they given however they turn into "Add Post" method.
What is the reason that cause it ?
(I have set the hidden field at view pass to controller however they will show the error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '45' for key 'PRIMARY' because they doing insert statement instead of update).
DateOfEventController.php
public function edit($id = null) {
//Retrieve from database
$post = $this->dateofevent->findByeventdateId($id);
debug($post);
//Without Id
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
//If Not Exist the id
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
//After press the submit
if ($this->request->is(array('post','put'))) {
echo "yo";
$this->dateofevent->eventDate_id = $id;
if ($this->dateofevent->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
// return $this->redirect(array('action' => 'index'));
}
else{$this->Session->setFlash(__('Unable to update your post.'));}
}
//Set the data same as retrieved
if (!$this->request->data) { $this->request->data = $post;}
}
edit.ctp
<?php
echo $this->Form->create('dateofevent');
//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');
?>
Sql Query
SQL Query: INSERT INTO fyp_seatmanagment.dateofevent
(eventDate_id, event_date, modified) VALUES (45, '2015-06-10',
'2015-06-17 10:19:45')
You're not using Cake's standard naming conventions so you need to make sure you override model attributes that Cake would normally auto-generate. Cake expects the primaryKey to be id which it uses to determine whether to insert or update a record. As you're using eventDate_id you need to tell Cake this in your model:-
class DateOfEvent extends AppModel {
public $primaryKey = 'eventDate_id';
}
Unless there is a specific reason why you can't use Cake's naming convention you should do. Using your own naming convention will create considerable more work for you and problems.
I've also noticed you're incorrectly camel casing methods and variable names in your controller that may cause problems. For example $post = $this->dateofevent->findByeventdateId($id) should be:-
$post = $this->DateOfEvent->findByEventdateId($id);

CakePHP form input filed empty after get submit

echo $this->Form->create('Driver', array('type' => 'get'));
echo $this->Form->input('name');
echo $this->Form->end('Search');
as result $this->request:
query => array(
'name' => 'some name'
)
Problem is input form is empty after search although $this->request->query['name'] = 'some name'
Everything works as expected when change form back to post
Edit. Included the model and the controller. For testing I use clean install.
Model (Driver.php):
App::uses('AppModel', 'Model');
class Driver extends AppModel {
public $displayField = 'name';
}
Controller (DriversController.php):
App::uses('AppController', 'Controller');
class DriversController extends AppController {
public function index() {
$drivers = $this->Driver->find('all');
$this->set(compact('drivers'));
}
}
In your controller code you do not show us where you are trying to access the submitted form values so I will try and give some general information to get you moving.
To access your form data, you need to cool use request. To see exactly what is going on, enter in your controller one of the below...
print_r($this->request->data);
or
print_r($this->request);
Either of those will show you any data registered with CakePHP.
If you want to save this save using your Models. use...
$this->Driver->save($this->request->data)
You might want to check it is a post first though.. lets complete the code...
public function submit() {
if ($this->request->is('post')) {
$this->Driver->create();
if ($this->Driver->save($this->request->data)) {
$this->Session->setFlash('Saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('FAILED');
}
}
}
The information above can be read in further detail here.
You can set form values by assigning to $this->data.
$this->data = $this->request->query;

select list association in cakephp

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.

Resources