CakePHP why is associated null? - php

I have several tables and corresponding models, that is to say, Staffs, Dpmembers, Subjects and Positions tables.
In my Staff model I create hasOne on Department because I want to retrieve data from Department table which is working.
But I have also created more associations of hasMany on Dpmember, Subject and Position models because I want to save the corresponding staff records.
The view newstaff.ctp looks like this
<div class="staff form">
<?php echo $this->Form->create('Staff');?>
<h3><?php echo __('Add a new staff member'); ?></h3>
<?php
echo $this->Form->input('name');
echo $this->Form->input('marital',array('label'=>'Marital status','options'=>array('empty'=>'Choose status','Single'=>'Single','Divorced'=>'Divorced','Married'=>'Married')));
echo $this->Form->input('Children');
echo $this->Form->input('nationality');
echo $this->Form->input('location');
echo $this->Form->input('email');
echo $this->Form->input('phone',array('label'=>'Phone number'));
echo $this->Form->input('nextofkeen',array('label'=>'Next of keen'));
echo $this->Form->input('keenrelation',array('label'=>'Next of keen relationship','options'=>array('Choose option'=>'Choose option','Husband'=>'Husband','Wife'=>'Wife','Guardian'=>'Gaurdian','Child'=>'Child')));
echo $this->Form->input('school');
echo $this->Form->input('award');
echo $this->Form->input('schoolperiod');
echo $this->Form->input('workplace',array('label'=>'Workplace'));
echo $this->Form->input('workposition');
echo $this->Form->input('workperiod');
echo $this->Form->input('dpmember.department.',array('options'=>$department,'empty'=>'Choose Department','label'=>'Department'));
echo $this->Form->input('subject.subjcet',array('options'=>array('Choose option'=>'Choose option','Science'=>'Science','Social Studies'=>'Social studies','English'=>'English','Mathematics'=>'Mathematics'),'label'=>'Subject'));
echo $this->Form->input('position.role',array('options'=>array('Choose option'=>'Choose option','Class teacher'=>'Class teacher','Bursar'=>'Bursar','Cook'=>'Cook'),'label'=>'Position'));
echo $this->Form->submit('Save staff', array('class' => 'btn btn-success', 'title' => 'Click here to add the user') );
?>
<?php echo $this->Form->end(); ?>
</div>
My Staff Model Staff.php like this
<?php
class Staff extends AppModel{
public $hasOne = array(
'Department'=>array(
'className'=>'Department'
));
public $hasMany = array(
'Dpmember'=>array(
'className'=>'Dpmember',
'foreign_key'=>'Dpmember.staff_id'
),
'Subject'=>array(
'className'=>'Subject',
'foreign_key'=>'Subject.staff_id'
),
'Position'=>array(
'className'=>'Position',
'foreign_key'=>'Position.staff_id'
)
);
}
?>
In my StaffsController.php I have a function newstaff() with the code below
public function newstaff() {
/*Create a select form field for departments */
$department = $this->Staff->Department->find('list',array('fields'=>array('Department.title','Department.title')));
$this->set('department', $department);
/*End creation of a select form field for departments */
if (!empty($this->request->data)) {
debug($this->request->data); // returns all data
debug($this->Staff->Subject->subject); // has returned null
debug($this->Staff->Position->position); // has returned null
debug($this->Staff->Dpmember->departement); // has returned null
}
}
I don't know why but for some reason, I have not been able to found out. Running debug($this->request->data) returns expected data.
But accessing individual associated form fields returns null values not the expected data. Please help me.
Thank you

You seem to be using CakePHP 3.0 syntax, while using CakePHP 2.3. The data returned is an array in Cake 2, not an object. So the data is under array keys, like:
$this->request->data['Staff']['Subject']['subject'];
$this->request->data['Staff']['Position']['position'];
$this->request->data['Staff']['Dpmember']['departement'];

Well I think finally I have got the values which are not null. Since I created relationships or rather associations among the models and am using CakePHP 2.3 the right way is
$this->request->data['associateModel']['FormField'];
Therefore I was supposed to do.
$this->request['Subject']['subject'];
$this->request['Subject']['position'];
$this->request['Subject']['department'];
Thank you very much #Oldskool

Related

Create survey form in Yii2 with multiple choice answers

Im new to Yii, and would appreciate any help.
I need to create a page with multiple choice poll. My models look like this:
PollQuestion:
id int
title varchar
PollAnswer
id char //one letter - answer option
title
question_id //FK pool_question(id)
PollResult
user_id int
question_id int //FK poll_question(id)
answers //will be stored like A,B,C
indicated_answer //alternaive answer specified by user
Sample question looks like:
What do you think about us?
(checkbox)A. Good
(checkbox)B.Bad
(checkbox)C.Other (indicate) (textbox goes here)
Im not sure if Im doing it right, my controller:
public function actionSurvey($user_id)
{
$model = [new PollResult];
foreach($model as $model_item){
$model_item->user_id= $user_id;
if ($model_item->load(Yii::$app->request->post())) {
//only one item received, why??
}
}
return $this->render('survey', ['model' => $model]);
}
View:
<?php $form = ActiveForm::begin(); ?>
<?php foreach(PollQuestion::find()->all() as $question) {?>
<?php foreach($model as $model_item) { ?>
<p><?=$question->title?></p>
<?= Html::activeHiddenInput($model_item , "user_id"); ?>
<?= $form->field($model_item, 'answers')->checkboxList(ArrayHelper::map($question->pollAnswers, 'id', 'title')?>
<?= $form->field($model_item, 'indicated_answer') ->textInput()?>
<?php } }?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Send'), ['class' => 'btn btn-success' ]) ?> </div>
<?php ActiveForm::end(); ?>
The problem is that in controller i receive only one item in array. Im not sure what am I doing wrong.
My suggestion, you need an extra form model to do that.
You can see how to create form model on http://www.yiiframework.com/doc-2.0/guide-input-forms.html.
The form model you create at least has this attributes:
answers[]
indicated_answer[]
and you can save input from user to that attributes and save them into your ActiveRecord model.
It is correct that one model entry is returned. In your form, you are creating a single model and passing that to the form.
public function actionSurvey($user_id)
{
$model = [new PollResult];
// ...
return $this->render('survey', ['model' => $model]);
}
You can then expect a single model back.
Have a look at this related issue on how you can solve this.
Utilising Yii2.0 checkboxlist for Parent-child relation models

How to send the request through POST and how to access attributes of the model?

I am a bit new to the Yii Framework. I am making a product selling website, which has 3 basic models
1. Users model containing the primary key id
2. Products model containing the primary key id
3. Orders model which is basically a mapping between the products and orders. It contains the fields product_id and user_id as foreign keys.
I have made a page where all the products are populated and the logged in user can click on a button on product box to order a particular product.
the code of the link is like this
<?php echo CHtml::link('Order Now',array('order',
'product_id'=>$model->id,
'user_id'=>Yii::app()->user->id)); ?>
(Q1) This is sending a GET request but I want to sent the details as post request. How to do this?
My default controller is the site controller. I have made an actionOrder method in this controller.
The code is:
if(Yii::app()->user->isGuest){
$this->redirect('login');
}else{
$model=new Orders;
if(isset($_POST['products_id']))
{
$model->attributes->products_id=$_POST['product_id'];
$model->attributes->users_id=Yii::app()->user->id;
if($model->save())
$this->redirect(array('index'));
}
$this->render('index');
}
But this code is showing bunch of errors. Also, (Q2) how can I put both products_id and users_id in a single array Orders so that I just have to write $_POST['orders']
Also, (Q3) how can I display a flash message after the save is successful?
Kindly help me to solve my 3 problems and sorry if you feel that the questions are too stupid.
Q1: If you want to use POST request, you're going to have to use a form of sorts, in this case the CActiveForm.
Controller:
public function actionOrder()
{
if(Yii::app()->user->isGuest)
$this->redirect('login');
else
{
$model=new Orders;
if(isset($_POST['Orders']))
{
$model->product_id=$_POST['Orders']['products_id'];
$model->users_id = Yii::app()->user->id;
if($model->save())
{
// Q3: set the flashmessage
Yii::app()->user->setFlash('ordered','The product has been ordered!');
$this->redirect(array('index'));
}
}
$this->render('index', array('model'=>$model)); //send the orders model to the view
}
}
View:
<!-- Q3: show the flash message if it's set -->
<?php if (Yii::app()->user->hasFlash('ordered')): ?>
<?php echo Yii::app()->user->getFlash('ordered'); ?>
<?php endif ?>
...
<?php $form=$this->beginWidget('CActiveForm', array('id'=>'order-form')); ?>
<?php echo $form->hiddenField($model,'products_id',array('value'=>$product->id)); ?> // please note the change of variable name
<?php echo CHtml::submitButton('Order Now'); ?>
<?php $this->endWidget(); ?>
Please note that I have changed the name of the product model variable $model to $product, because we will be using $model for the Orders model for the form.
Q2: In this case I set the users_id value in the controller, so $_POST['Orders'] only contains the value for products_id. In yii you can also mass assign your attributes with:
$model->attributes = $_POST['Orders']
Which basicly means $_POST['Orders'] is already an associative array containing the attribute names and values that are in your form.
Q3: The code shows you how to set and show a flash message after an order is succesfull.
First you have to declare forms send method, if you're using bootsrap it'll be like mine:
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'post',
'id' => 'activity_timeRpt',
));
?>
Second if you want to send custom inputs, you have to specify, otherwise it'll be like
i'll be back to finish this
For your questions 1 and 2 I'd recomend you to use a CActiveForm class. For example
<?php $form = $this->beginWidget('CActiveForm', array(
'action' => 'you_action_here'
'method'=>'post' // this is optinal parameter, as 'post' is default value
)); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->hiddenField($model,'user_id', array('value'=>Yii::app()->user->id)); ?>
<?php $this->endWidget(); ?>
where $model is instance of Orders class, passed by variables thru controller, or set in view file. After that you can use it in way you wanted $model->attributes = $_POST['orders'] in your action method.
For flash message you can use Yii->app()->user->setFlash('orderStatus', 'Successful'), before redirect( or render ) in your actionOrder. To show it:
<?php if(Yii::app()->user->hasFlash('orderStatus')):?>
<div class="info">
<?php echo Yii::app()->user->getFlash('orderStatus'); ?>
</div>
<?php endif; ?>

How to add directly into Join Table cakephp?

When I try to add some entries into the join table of two classes, I run into issues with CakePHP.
Here is my join table:
posts_comments
id
post_id
comment_id
my post Model:
<?php
class Post extends AppModel {
var $hasManyAndBelongsTo = array('Comment')
}
?>
My Comment Model:
<?php
class Commentextends AppModel {
var $hasAndBelongsToMany = array('Post');
}
?>
My Controller:
ForumController:
function save() {
if ($this->data) {
$this->loadModel('PostComment');
$this->layout = null;
debug($this->data);
$this->PostComment->save($this->data);
}
$this->redirect(array('action' => 'view', $this->data['PostComment']['PostId']));
}
And my view.ctp:
<?php
echo $this->Form->create('PostComment', array('url' => 'save', 'id' => 'save')); ?>
echo $this->Form->hidden('PostComment.PostId', array('value' => $id));
echo $this->Form->input('PostComment.CommentId', array('label' => '', 'type' => 'select', 'multiple' => 'checkbox', 'options' => $CommentName, 'selected' => $CommentId));
echo $this->Form->submit('save', array('id' => 'submit'));
echo $this->Form->end();
?>
When I click on submit, nothing is submitted, and the redirection happens, but the data contained in my $this->data is not save in my BDD.
But what I want is that when I submit my form, I don't want that CakePHP create a new post or a new comment, I just want a new relation between the two.
I already succeed to done it, but I used
$this->myObject->query("INSERT INTO blablabla")
The problem is that I have a multiple checkboxes, so I don't really know how I can easily check that one box has been unchecked or checked.
You can work in a simpler way if you create another model with two hasMany relations instead of one with HABTM.
HasAndBelongsToMany between two models is in reality shorthand for
three models associated through both a hasMany and a belongsTo
association.
I found it is one of the simplest ways to save and retrieve data.
For more information: http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated
At the new model, you could do something like:
public addRecord($userId, $postId)
$this->data[$this->alias]['user_id'] = $userId;
$this->data[$this->alias]['post_id'] = $postId;
return $this->save($this->data[$this->alias]);
}

Codeigniter Update database: echo data back in input fields and update on submit

I am developing my skills using the Codeigniter framework. I have already viewed and inserted data into the database and finding it more tricky to update data. Most tutorials i've saw are inputting the values in the code rather than pulling a selected id from the database and echoing in form fields. So far i have:
news_model:
function editArticle($data) {
$data = array(
'title' => $title,
'content' => $content,
'author' => $author
);
$this->db->where('id', $id);
$this->db->update('news', $data, array('id' =>$id));
}
Controller:
public function update_entry() {
//load the upate model
$this->load->model('update_model');
//get the article from the database
$data['news'] = $this->news_model->get_article($this->uri->segment(4));
// perform validation on the updated article so no errors or blank fields
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
// If validation fails, return to the edit screen with error messages
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
//update the news article in the database
if($query = $this->update_model->update()) {
}else{
redirect('admin/edit');
}
}
}
View:
<?php echo form_open('admin/edit/edit_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Edit Article'); ?>
<?php if (isset($error)){echo "<p class='error'>$error</div>";
}?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
1) Im not sure how to echo the data out (from when the user has clicked the edit button from the article view shown) to grab that id, and then display on the edit page in the text fields.
2) And then for the user to then submit the updated data and post in the database?
Any guidance or help with structuring the rest of my controller/view files would be appreciated as ive been on this for more than a day!
Thank You.
You haven't given all of the code for your view, so I'm not sure how much you have right and how much you have wrong, but I'll mention a few things I can see -
You don't seem to be calling your view from your controller like $this->load->view('edit', $data); (see http://codeigniter.com/user_guide/general/views.html) where the current fields' content is in $data.
To pre-populate the form fields, put the current field value in the second parameter of set_value() eg something like set_value('title', $article->title).
Your model also needs to handle the submitted form (in $this->input->post) and then call the update query in the model.
(I have to say that the CodeIgniter docs are not great on this - you have to be looking in Form Helper and Form Validation Class docs, as well as keeping track of Views (link above), Controllers, and Models (plus one or two others, I shouldn't wonder)).

Insert rows in other tables on creation in yii

For the following database:
TABLES:
user: [id,username]
project: [id,name]
project_user_assignment: [user_id,project_id,role]
When a new project is being created I'd like to show a dropdown with the available users to manage the project and when saving it insert into project_user_assignment the row
[user_id,project_id,'manager']
I'm starter with yii and don't know where (class,method) I must do the insert and how to return an error if in the moment of the insert the query fails
To display a drop down list in the you can use the foliowing code:
<?php echo CHtml::dropDownList(null,
'type',
CHtml::listData(
User::model()->findAll(),
'id',
'username',
),
array('empty' => 'Select a manager from the list ... ', 'id'=>'manager_list')
);?>
to update the corresponding field of the project_user_assignment model use the following:
<?php
<div class="row">
<?php echo $form->labelEx($model,'user_id'); ?> // Here I assume you have the $model variable set to Project_user_assignemenet ... if not (which probably is the case since you are creating a new project, set a new $model2 variable in the controller and use $model2 instead of $model)
<?php echo $form->textArea($model,'user_id'); ?>
<?php echo $form->error($model,'user_id'); ?>
</div>
?>
<script>
$('#manager_list').on('change', function(e) {
$('#Project_user_assignemenet_user_id').val($(this).val()); // Here id maybe wrong! Check them.
return true;
});
</script>
and finally in the controller you just save the model.

Categories