Populating a dropdown list in Cakephp from database values - database

I'm trying to populate the values in a dropdown list in Cakephp v2.6.1.
The values are being retrieved, but the form helper is not creating dropdown listboxes as expected: All I am getting displayed on the form is the Submit button - The id fields are send as hidden fields to the web page. Can someone point out where I am going wrong?
Coursemembership controller
<?php
App::uses('AppController', 'Controller');
class CoursemembershipsController extends AppController {
public $components = array('Paginator', 'Session');
...
public function add() {
if ($this->request->is('post')) {
$this->Coursemembership->create();
if ($this->Coursemembership->save($this->request->data)) {
$this->Session->setFlash(__('The coursemembership has been saved.'));
if ($this->Coursemembership->saveAssociated($this->request->data)) {
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The coursemembership could not be saved. Please, try again.'));
}
}
}
$students = $this->Coursemembership->Student->find('list');
$courses = $this->Coursemembership->Course->find('list');
$this->set(compact('students', 'courses'));
}
Add view
<div class="coursememberships form">
<?php echo $this->Form->create('Coursemembership'); ?>
<?php echo $this->Form->input('Student.id'); ?>
<?php echo $this->Form->input('Course.id'); ?>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
Variables (from the debug add-in)
View Variables
students(array)
1Cromwell
2Lionheart
3Knight
7four
8five
9six
10seven
11eight
courses(array)
1Applied Speliology
2Aggravated aggrandisement
3Crossword Puzzles 101
5Aggravated aggrandisement
6Applied Speliology

You're not setting the field names for your inputs properly. The id field is the primary key by convention and will be added as a hidden field (usually used for editing, so your Model knows what id to alter).
You should add the fields as they are set in the Coursemembership datasource (probably a database table called coursememberships, if you're following convention for database design). This should show the fields you need and save the proper data:
echo $this->Form->create('Coursemembership');
echo $this->Form->input('Coursemembership.student_id');
echo $this->Form->input('Coursemembership.course_id');
echo $this->Form->end(__('Submit'));
Everything you want to save should go to the Coursemembership model. You should only need to save anything to the Student or Course model if you'd actually wanted to add a new student or course to your application. For assigning a membership of a Student to a Course, the above code should do the trick.

Related

CakePHP 3.10 adding a Form field with '_id' in name, automatically makes it a select field

CakePHP 3.10 adding a Form field with '_id' in name, automatically makes it a select field. I want to know if this is something that is done in our App specifically by previous developer and if so, how/where would I look?
Alternatively, if it's a CakePHP thing, where can I get documentation on it?
Controller:
public function add()
{
$building = $this->Buildings->newEntity();
if ($this->request->is('post')) {
//code for after form submission
}
$this->set(compact('building'));
}
View:
<div>
<?= $this->Form->create($building) ?>
<fieldset>
<legend><?= __('Add Building') ?></legend>
<?php
echo $this->Form->control('test_id'); <!-- this field type will be a select field -->
echo $this->Form->control('name');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
If you read this V3 documentation you can see:
https://book.cakephp.org/3/en/views/helpers/form.html#namespace-Cake\View\Helper
So, the cause of this is because cakephp understand you have a belongsTo or hasOne association between Buildings model and Test model.
If you have a test_id column in buildings table, you are saying to cakephp that tests table has one or has many building/s.
you can force the type of Form Helper using the condition:
$this->Form->control('test_id', ['type' => 'text']);
Extra note: when you have this case you could use virtual fields to show what is the test_id that the Building belongs.
For example: you could show the concatenation of the test name and author name (assuming these two fields exist in the test table) like:
Into TestEntity.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Test extends Entity
{
protected function _getTestIndicator()
{
return $this->name . ' ' . $this->author_name;
}
}
Into the view:
echo $user->test_indicator;

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!

Cakephp 3.0 Not saving DATE and TIME on Associated data model in an Add action

I'm trying to make some kind of custom calendar system in CakePHP. What I'm trying to do is add an agendascreen_activity Model (of which all the fields already get saved correctly) and an associated model agendascreen_no_repetitions which has an id time, date and a FK pointing to the activity.
My problem is that the date and time fields don't get saved properly
here is my code so far:
In my add.ctp file:
<?= $this->Form->input('agendascreen_no_repetitions.date', ['type' => 'date']) ?>
<?= $this->Form->input('agendascreen_no_repetitions.time', ['type' => 'time']) ?>
In my controller:
public function add()
{
$agendascreenActivity = $this->AgendascreenActivities->newEntity();
if ($this->request->is('post')) {
$agendascreenActivity = $this->AgendascreenActivities->patchEntity($agendascreenActivity, $this->request->data);
if ($this->AgendascreenActivities->save($agendascreenActivity)) {
$this->Flash->success(__('The agendascreen activity has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The agendascreen activity could not be saved. Please, try again.'));
}
}
$agendascreens = $this->AgendascreenActivities->Agendascreens->find('list', ['limit' => 200]);
$this->set(compact('agendascreenActivity', 'agendascreens'));
$this->set('_serialize', ['agendascreenActivity']);
}
The datatypes of the fields of the MySql DB are DATE and TIME
In the CakePHP debugger I can see that all the data is being sent correctly in the POST().
However when I look at the result, it adds the agendascreen_no_repetitions record two times with null as value for the date and the time.
After ndm's comment I checked if the data was being patched to the entity correctly.
I noticed that the time and date contents were directly under the agendascreen_no_repetitions object. instead of under time and date.
I tried the following:
<?= $this->Form->input('agendascreen_no_repetitions[0].date', ['type' => 'date']) ?>
<?= $this->Form->input('agendascreen_no_repetitions[0].time', ['type' => 'time']) ?>
which resulted in the following:

Cakephp how to display a particular record when searched using one field

I am new to cakephp.
I have two table related to each other (student and payment_detail).
students hasMany paymentDetails and
paymentDetails belongTo student.
I have a search view:
<?php echo $this->Form->input('Student.roll_no', array('label' => __('Roll No'))); ?>
<?php echo $this->Form->end(__('View')); ?>
view method in controller:
public function view(){
if ($this->request->is('post')) {
$this->request->data;
return $this->redirect(array('action' => 'detailedview'));
}
}
when I click the view button it redirects me to detailedview. So my problem here is how to create detailedview method for controller to retrieve all the fields in a record related to particular roll_no.
You will need to:
1) Change your view function to:
public function view( $id=null ){
if ($this->request->is('post')) {
$this->redirect(array('action' => 'detailedview', $id));
}
}
2) add the following function in your controller:
public function detailedview( $id=null ) {
....
}
Before you do that I recommend reading the documentation again and do the Blog tutorial.

How to use tinymce plugin?

I have tried many times to use this plugin and I failed.
I am following documentation, but it does not work for me.
I am posting the simple code here, to know what wrong I am doing.
1-I put this plugin in this folder app/plugins
2- I add TinyMce helper to articles_controller
<?php
class ArticlesController extends AppController {
// good practice to include the name variable
var $name = 'articles';
// load any helpers used in the views
var $helpers = array('Html', 'Form','TinyMce.TinyMce');
/**
* index()
* main index page of the formats page
* url: /formats/index
*/
function index(){
// get all formats from database where status = 1
$articles = $this->Article->find("all") ;
$this->set('articles', $articles);
}
function admin_add() {
// if the form data is not empty
if (!empty($this->data)) {
// initialise the format model
$this->Article->save($this->data);
// set a flash message
$this->Session->setFlash('The Format has been saved');
// redirect
$this->redirect(array('action'=>'index'));
} else {
// set a flash message
$this->Session->setFlash('The Format could not be saved. Please, try again.','default', array('class' => 'flash_bad'));
}
}
}
?>
3- in the view file articles/admin_add.ctp I added the editor
// i think the problem in this code
<?php $this->TinyMce->editor(array(
'theme' => 'advanced'
)); ?>
<div class="formats form">
<?php echo $form->create('Article');?>
<fieldset>
<legend>Add a article</legend>
<?php
// create the form inputs
echo $this->Form->input('title');
echo $this->Form->input('content'); ?>
</fieldset>
<?php echo $form->end('Add');?>
</div>
<ul class="actions">
<li><?php echo $html->link('List Articles', array('action'=>'index'));?></li>
</ul>
You need to put tinymce files into your js assets
Then you have to add into section of your layout.
Then you'll need to init tinymce according to example provided on tinymce website (ex: full tinymce layout) and configure it according to your requirements.
I'd personally would not rely on such cake plugins, when actions required to get things working are not many and they are simple enough.

Resources