CakePHP 3 Pb with saving data into BD - cakephp-3.x

I have a table ComplexesEmployeesImmeubles :
id auto-increment
complex_id foreign key of Complexes.ID
employee_id foreign key of Employees.ID
immeuble_id foreign key of Immeubles.ID
poste_id foreign key of Postes.ID
date_affectation
created
here is my view reaffecter.ctp
<?= $this->Form->create('ComplexesEmployeesImmeubles') ?>
<?php
echo $this->Form->select('complex_id', $complexes);
echo $this->Form->input('employee_id',['type' => 'hidden' , 'value' => h($employee->id)]);
echo $this->Form->select('immeuble_id', $immeubles);
echo $this->Form->select('poste_id', $postes);
echo $this->Form->input('salaire', ['label' => 'Salaire']);
echo $this->Form->input('date_affectation', ['label' => 'Date d\'affectation']);
?>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
In my controller, I try to save data into my BD with the code below but nothing is saved !
if ($this->request->is('post')) {
$complexesEmployeesImmeuble = $this->ComplexesEmployeesImmeubles->newEntity();
$complexesEmployeesImmeuble = $this->ComplexesEmployeesImmeubles->patchEntity($complexesEmployeesImmeuble, $this->request->data);
$this->ComplexesEmployeesImmeubles->save($complexesEmployeesImmeuble);}

Use debug($complexesEmployeesImmeuble->errors()) to check whether validation failed.
if(!$this->ComplexesEmployeesImmeubles->save($complexesEmployeesImmeuble)){
debug($complexesEmployeesImmeuble->errors()); die;
}
If you didn't get errors and still not saved then check for mass assignment , more info http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment

Related

Codeigniter 4 Passing Array to view

Fairly new to codeigniter and i just cant find the right way to load an array into a view.
for example lets say i have an array like
$data = [
'title' => 'my title,
'desc' => 'my desc,
];
i can pass that to my view like
return view('myview',$data);
then simply echo it out in my view like
<h1><?= $title ?></h1>
<p><?= $desc ?></p>
That works fine. but now lets say i have another array like :
$moredata =[
'more_data' => 'some more data',
'even_more_data' => 'even more data',
];
if i try to add that to my data array like
$data[] = $moredata
when i try to access 'more_data' or 'even_more_data' in my view like
<?= $more_data ?>
i get a undefined variable error for $moredata. So how do i access the variables within that new array? am i declaring them properly?
also if i wanted to loop through the secondary array how do i do that. trying
<?php foreach($moredata as $items){ ?>
<li><?php echo $items; ?></li>
<?php } ?>
also gives me an undefined variable error for $moredata
any help on how to do this correctly in codeigniter 4 appreciated.
Codeigniter uses the key of the array you're giving him to create variables name.
You should init it this way :
$moredata =[
'more_data' => 'some more data',
'even_more_data' => 'even more data',
];
// key of your array will be a variable name in your view
$data['my_var_name_in_view'] = $moredata
return view('myview',$data);
Then in your view you will be able to perform this :
<?php foreach($my_var_name_in_view as $items){ ?>
<li><?php echo $items; ?></li>
<?php } ?>

Yii2 update related model makes insert

Depending on this question: Yii2 updating two related models does not show data of the second. I have manged calling the related model InvoiceItems to the Invoices model it hasMany relation.
However, updating leads to insert new records in invoice_items table instead of updating the current related records to the invoices table.
I tried to add the id field of each InvoiceItems record in the _form view to solve this issue, but it still exist.
The following is actionUpdate of the InvoicesController:
public function actionUpdate($id)
{
$model = $this->findModel($id);
//$invoiceItems = new InvoiceItems();
$count = count(Yii::$app->request->post('InvoiceItems', []));
//Send at least one model to the form
$invoiceItems = [new InvoiceItems()];
//Create an array of the products submitted
for($i = 1; $i < $count; $i++) {
$invoiceItems[] = new InvoiceItems();
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//$invoiceItems->invoice_id = $model->id;
if (Model::loadMultiple($invoiceItems, Yii::$app->request->post())){
foreach ($invoiceItems as $item){
$item->invoice_id = $model->id;
//$item->id = $model->invoiceItems->id;
$item->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
}
else{
return var_dump($invoiceItems);
}
} else {
//$invoiceItems->invoice_id = $model->id;
$invoiceItems = $this->findInvoiceItemsModel($model->id);
return $this->render('update', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]);
}
}
This is the code of _form view of InvoicesController:
<div class="invoices-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'created')->textInput() ?>
<?= $form->field($model, 'type')->textInput(['maxlength' => true]) ?>
<hr />
<?php if (is_array($invoiceItems)): ?>
<?php foreach ($invoiceItems as $i => $item): ?>
<?= $form->field($item, "[$i]id")->textInput();?>
<?= $form->field($item, "[$i]item_id")->textInput();?>
<?= $form->field($item, "[$i]unit_id")->textInput();?>
<?= $form->field($item, "[$i]qty")->textInput();?>
<?php endforeach; ?>
<?php else: ?>
<?= $form->field($invoiceItems, "item_id")->textInput();?>
<?= $form->field($invoiceItems, "unit_id")->textInput();?>
<?= $form->field($invoiceItems, "qty")->textInput();?>
<?php endif; ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The following screen shot, visually, demonstrates what I have got:
if you in update you don't need new record you should remove
this part
$count = count(Yii::$app->request->post('InvoiceItems', []));
//Send at least one model to the form
$invoiceItems = [new InvoiceItems()];
//Create an array of the products submitted
for($i = 1; $i < $count; $i++) {
$invoiceItems[] = new InvoiceItems();
}
The $invoiceItems you create in this way are obviuosly "new" and then are inserted ..for an update the model must to be not new..
You have already the related models to save they came from post.. and from load multiple
If you however need to manage new model (eg: because you added new record in wide form update operation) you can test
$yourModel->isNewRecord
and if this is new check then if the user have setted properly the related fields you can save it with
$yourModel->save();
otherwise you can simple discart.. (not saving it)
I am pretty sure that this code below of course fills a array named $invoiceItems with the submitted data.
if (Model::loadMultiple($invoiceItems, Yii::$app->request->post())){
foreach ($invoiceItems as $item){
$item->invoice_id = $model->id;
//$item->id = $model->invoiceItems->id;
$item->save(false);
}
}
But all $items have the scenario "insert" (could be that you allow the setting of the attribute 'ID' but normally this isn't allowed in the Gii generated code. and then you get "new items" whenever you save.
if you add a return var_dump($invoiceItems);after the loadMultiple you will see that only the safe attributes are filled with the submitted data.
You are also not validating them before saving, which is also kind of bad.
if (Model::loadMultiple($invoiceItems, Yii::$app->request->post()) && Model::validateMultiple($invoiceItems)) {
http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html
According to scaisEdge answer and this widget documentation. I could able to determine the problem solution.
Simply, in my code I neglected the relation between the two models, when I say:
$count = count(Yii::$app->request->post('InvoiceItems', []));
//Send at least one model to the form
$invoiceItems = [new InvoiceItems()];
The value of $invoiceItems should be obtained using the relation like the following:
$invoiceItems = $model->invoiceItems;
However, I still have another issue with adding new records to the related model InvoiceItems during the update.

Dependanat Drop down is not working when it has only one value in yii framework

I am using dependant dropdownlist for get value for subject dropdown when select value from 'Grade' dropdown. It is working fine. But the problem is when there are only one value in grade dropdown the subject dropdown is not updated.
this is my code:-
Grade DropDown----------
($data is consist of grade)
<?php echo CHtml::dropDownList('myDropDown1','',$data,array(
'id'=>'gr',
'empty' => '(Select Grade)',
'style'=>'width:200px',
'ajax' =>
array(
'type'=>'POST', //request type
'url'=>CController::createUrl('sub'), //action to call
'update'=>'#cls', // which HTML element to update
)
)); ?>
Subject Dropdown (which depend on grade dropdown)------------
<?php echo CHtml::label('Subject',''); ?>
<?php echo CHtml::dropDownList('myDropDown3','',array(),array(
'id'=>'sub',
'prompt'=> 'Please select a class', 'style'=>'width:150px',
'style'=>'width:200px',
)); ?>
<?php //echo $form->error($model,'sub_id'); ?>
In controller-------------------
public function actionClass()
{
$grd = $_POST['myDropDown1'];
$c_id = TbClass::model()->findAll('id=:id',
array(':id'=>$grd,));
$data3 = CHtml::listData($c_id,'id','grade');
$grd2 = array_shift($data3);
$sub1 = TbClass::model()->findAll('grade=:grade',
array(
':grade'=>$grd2,
));
$data4 = CHtml::listData($sub1,'id','class');
foreach($data4 as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
This code is working fine. Problem is when grade has only one value in the dropdown , cannot update the subject dropdown.
I think your problem is in array_shift,
have you checked the value of $grd2 ?

Yii - Saving data back to Many-to-Many Relation database, from a dropdownlist with multiple-selection

(Please pardon my poor English.)
I am having 3 tables, say Blog, User and user_blog.
Blog
CREATE TABLE `Blog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
User
CREATE TABLE `User` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
user_blog
CREATE TABLE IF NOT EXISTS `user_blog` (
`user_id` int(11) NOT NULL,
`blog_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`blog_id`)
) ENGINE=InnoDB;
and i have declared their relations in the respective AR models.
Blog.php
public function relations() {
return array(
'users' => array(self::MANY_MANY, 'User', 'user_blog(blog_id, user_id)'),
);
}
User.php
public function relations() {
return array(
'blogs' => array(self::MANY_MANY, 'Blog', 'user_blog(user_id, blog_id)'),
);
}
And now, I have in my view the following codes:
<?php
$data = CHtml::listData(User::model()->findAll(), "id", "name");
echo $form->dropDownList($blog,'users', $data, array('multiple'=>'multiple', 'size' => '5'));
?>
With the above code, a dropdownlist with multiple selection is successfully created, and the data from the database are successfully retrieved and the items that are supposed to be selected are successfully highlighted.
But here comes the problem. I have no idea how to implement the saving/updating function. No matter what options I have selected, the results are not saved back to the database.
Could anyone please help?
Thank you in advance.
You should use CRUD generator or do it yourself like this:
Controller:
public function actionUpdate($id)
{
$model = $this->loadModel($id, 'User');
if(isset($_POST['User']))
{
$model->setAttributes($_POST['Message']);
if($model->validate())
{
if($model->save()) {
//do something here, eg. view updated record
}
}
}
$this->render('update',array('model'=>$model));
}
view/update.php
<?php $form = $this->beginWidget('GxActiveForm', array(
'id' => 'user-form',
));
?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model, 'username', array('maxlength' => 32)); ?>
<?php echo $form->error($model,'username'); ?>
</div><!-- row -->
...
...
<div class="row">
<?php echo $form->labelEx($model,'users'); ?>
<?php
$data = CHtml::listData(User::model()->findAll(), "id", "name");
echo $form->dropDownList($blog,'users', $data, array('multiple'=>'multiple', 'size' => '5'));
?>
<?php echo $form->error($model,'users'); ?>
...
...
<?php
echo GxHtml::submitButton(Yii::t('app', 'Save'));
?>
P.s read this: http://www.yiiframework.com/doc/guide/1.1/en/form.overview

Codeigniter and Tank_auth sending validation to view not working

Hi I am new to Codeigniter but have hit a brick wall.
I am trying to see if a user already exists.
First I upload the data via a form to a controller which does its validation etc but breaks on only that issue. I managed to find where it breaks but cant fix it from there.
Prior to all this it querys the database finds there is in fact a match username and then reaches the snippet below
$errors = $this->tank_auth->get_error_message();
//find the correct error msg
foreach ($errors as $k => $v) $data['errors'][$k] =$this->lang->line($v);
//loop and find etc
$temp_mess = $data['errors'][$k];
//stores relevant stuff in the string
}
}
//echo $temp_mess; it outputs to the html so i can see it "says user exists"
$data['temp_mess'] = $tempmess; /// put this into a array
$this->load->view('layout', $data); ///send
}
}
Now for the view, it then calls the layout view etc but alas there is no output
$username1 = array(
'name' => 'username1',
'id' => 'username1',
'value' => set_value('username1'),
'maxlength' => $this->config->item('username_max_length', 'tank_auth'),
'size' => 30,
);
<?php echo form_open('register', $form_reg_id ); ?>
<fieldset>
<legend align="center">Sign up</legend>
<?php echo form_label('Username', $username1['id']); ?>
<?php echo form_input($username1); ?>
<?php $tempmess; ?>
<div class="error"><?php echo form_error($username1['name']); ?>
<?php echo isset($errors[$username1['name']])?$errors[$username1['name']]:''; ?>
<?php echo form_close(); ?>
</fieldset>
Thanks for any help on this
also could some one explain this line please. (for a really dumb person)
<?php echo isset($errors[$username1['name']])?$errors[$username1['name']]:''; ?>
Tank_auth automatically returns an error when the username exists. Juste have to check the errors array.

Resources