Why the data isn't saved in the relationship tables? - php

I've have this DB Model http://www.dropmocks.com/mBgqjs and I'm using CakePHP to build a simple application just for learning where I have this add() method:
public function add() {
if ($this->request->is('post') && is_uploaded_file($this->request->data['Information']['picture']['tmp_name'])) {
// Handling file uploads
$upload_avatar_dir = WWW_ROOT . "uploads/avatar/";
$new_file_name = $this->createRandomString() . substr($this->request->data['Information']['picture']['name'], -4);
move_uploaded_file($this->request->data['Information']['picture']['tmp_name'], $upload_avatar_dir . $new_file_name);
$this->request->data['Information']['picture'] = $upload_avatar_dir . $new_file_name;
$this->Information->create();
if ($this->Information->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('The information has been saved'), 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The information could not be saved. Please, try again.'), 'flash_error');
}
}
$countries = $this->Information->Country->find('list');
$this->set(compact('countries'));
}
and this is my add.ctp file:
<div class="information form">
<?php echo $this->Form->create('Information', array('class' => 'form-horizontal', 'enctype' => 'multipart/form-data'));?>
<fieldset>
<legend><?php echo __('Add Information'); ?></legend>
<ul class="nav nav-tabs">
<li class="active"><?php echo __('Personal') ?></li>
<li><?php echo __('Other Information') ?></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="personal">
<div class="row">
<div class="span4">
<?php
echo $this->Form->input('name', array('label' => __('Name')));
echo $this->Form->input('lastname');
echo $this->Form->input('email');
echo $this->Form->input('countries_id');
echo $this->Form->input('mobile_phone');
echo $this->Form->input('home_phone');
?>
</div><!--./span4-->
<div class="span4">
<?php
echo $this->Form->input('address', array('cols' => 50, 'rows' => 5));
echo $this->Form->input('picture', array('type' => 'file'));
echo $this->Form->input('recruitment_status', array('label' => __('Status'),'options'=>array('1'=>__('Call for Interview'),'2'=>__('Rejected'),'3'=>__('Pending for Upcoming Oportunities'))));
?>
</div><!--./span4-->
</div><!--./row-->
</div>
<div class="tab-pane" id="extra">
<?php
echo $this->Form->input('Education.0.education_content');
echo $this->Form->input('Experience.0.experience_content');
//echo $this->Form->input('Attachment.attachment_route', array('type' => 'file', 'multiple'));
echo $this->Form->input('other_information');
?>
</div>
</div>
</fieldset>
<?php
$options = array(
'value' => __('Save!'),
'class' => 'btn btn-inverse'
);
?>
<div class="paginator-footer"> <?php echo $this->Form->end($options);?> </div>
</div>
but something is wrong there because the associated data never is saved and can't find what is wrong? Can any help me?

Make sure your relations are correctly created in the models and use saveAll instead of saveAssociated, as the saveAssociated can't handle saving multiple entries at one time. What saveAll does is basically combining saveMany and saveAssociated into one single save method.

Related

Form doesn't validate and submit in yii

I try load form via ajax in CJuiDialog. The form was success loaded but when I submitted form or write text, form not validate and not submit.I tried set "true" fourth parameter in renderPartialbut after then dialog window didn't open. In console, I got error
$(...).dialog is not a function
In view I have this:
Yii::app()->clientScript->registerScript(
"test",
"jQuery.ajax({
type: 'POST',
url: '".$this->createUrl("/Site/ShowForm")."',
success: function(html){
$('#form-test').html(html);
});
",
CClientScript::POS_READY); ?>
<div id="form-test"></div>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');
My actions in controller:
public function actionShowForm()
{
$model = new RegistrationForm;
if(Yii::app()->request->isAjaxRequest )
return $this->renderPartial('register', array('model' => $model),false,false);
}
public function actionRegister()
{
$model = new RegistrationForm;
$this->ajaxValidate($model);
$model->attributes =$_POST['RegistrationForm'];
if($model->validate())
{
$user = new User;
$user->attributes = $model->attributes;
if($user->save())
echo 1;
}
}
and my form (register.php)
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'register-form',
//'enableClientValidation'=>true,
'enableAjaxValidation' => true,
'clientOptions' => array(
//'validateOnSubmit' => true,
'validateOnChange' => true
),
'action' => array('site/Register'),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model, 'first_name'); ?>
<?php echo $form->textField($model, 'first_name'); ?>
<?php echo $form->error($model, 'first_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'last_name'); ?>
<?php echo $form->textField($model, 'last_name'); ?>
<?php echo $form->error($model, 'last_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'email'); ?>
<?php echo $form->emailField($model, 'email'); ?>
<?php echo $form->error($model, 'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'password'); ?>
<?php echo $form->textField($model, 'password'); ?>
<?php echo $form->error($model, 'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'Repeat password'); ?>
<?php echo $form->textField($model, 'repeat_password'); ?>
<?php echo $form->error($model, 'repeat_password'); ?>
</div>
<div>
<?php echo $form->textField($model, 'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->error($model, 'verifyCode'); ?>
</div>
<div class="row buttons">
<?php
echo CHtml::ajaxSubmitButton('Register', $this->createUrl("/Site/Register"), array(
'type' => 'POST',
'dataType' => 'json',
'success' => 'js:function(data){
if(data == 1){
window.location ="' . $this->createUrl('site/index') . '"
}
}',
));
?>
</div>
<?php $this->endWidget(); ?>
How Can I fix this problem?
In your controller, where you check if the request is Ajax, you should be doing the Ajax validation in there.
I found solution! I added
Yii::app()->clientScript->scriptMap = array(
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.yiiactiveform.js' => false,
);
in my actionShowForm.

how to get value from previous view in Yii

I'm not sure how to describe my question. First I added a button at my CCGridview:
array(
'class'=>'CButtonColumn',
'template' => '{view}{update}{delete}{upload_image}',
'buttons' => array(
'upload_image' => array(
'label' => 'upload foto',
'url' => 'Yii::app()->createUrl("/image/create",
array("product_id" => $data->product_id))',
),
),
),
when I clicked it will bring me to the /image/create view which has a product_id value. For example on that gridview I clicked record number 7, so the url would be:
(webApp)/index.php/image/create?product_id=7
Since it rendering a partial _form so the form has the attribute according to the image table which has this attributes: id, title, filename, product_id.
So the view will be something like:
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'filename'); ?>
<?php echo $form->fileField($model,'filename',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'filename'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
My question is, how do we use the value from the url which I mentioned before is 7 (../create?product_id=7) into the product_id attribute without have to type it at provided textField?
In other word I will remove this from the view:
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
But when i submitted, the form the value (7) should have been passed/saved at product_id field.
Added:
My controller actionCreate is
//...
public function actionCreate()
{
$dir = Yii::app()->basePath . '/../productimages/';
$uploaded = false;
$model=new Image();
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}
That's it. Many thanks..
modify your controller this way:
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
} else {
//initialize defaults
$model->product_id=intval($_GET['product_id']);
}

Updating Fields on a form with ajax and json

I want to update some fields in my form, after retrieving data from a db using ajax & json.
This is the code:
In my form:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'anagrafica-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'codicefiscale'); ?>
<?php echo $form->textField($model,'codicefiscale',array('size'=>20,'maxlength'=>16)); ?>
<?php echo $form->error($model,'codicefiscale'); ?>
<div id="bottone_ricerca" style="display:inline;">
<?php
echo CHtml::ajaxButton( 'Ricerca',
$this->createUrl('anagrafica/popolaAnagrafica'),
array(
'type' => 'POST',
'datatype' => 'json',
'data' => array('codfisc' => 'js:$(\'#AnagraficaForm_codicefiscale\').val()'),
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
$("#'.CHTML::activeId($model,'nome').'").val(response.nome);
$("#'.CHTML::activeId($model,'email').'").val(response.email);
}'
),
array()
);
?>
</div>
<div id="cand">
</div>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cognome'); ?>
<?php echo $form->textField($model,'cognome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'cognome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nome'); ?>
<?php echo $form->textField($model,'nome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'indirizzo'); ?>
<?php echo $form->textField($model,'indirizzo',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'indirizzo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cap'); ?>
<?php echo $form->textField($model,'cap',array('size'=>10,'maxlength'=>5)); ?>
<?php echo $form->error($model,'cap'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'comune'); ?>
<?php echo $form->textField($model,'comune',array('size'=>25,'maxlength'=>20)); ?>
<?php echo $form->error($model,'comune'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'provincia'); ?>
<?php echo $form->textField($model,'provincia',array('size'=>5,'maxlength'=>2)); ?>
<?php echo $form->error($model,'provincia'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'telefono'); ?>
<?php echo $form->textField($model,'telefono',array('size'=>20,'maxlength'=>15)); ?>
<?php echo $form->error($model,'telefono'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Inserisci'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
In my controller:
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
echo $codfisc;
if (Yii::app()->request->isAjaxRequest) {
if ($codfisc == '') {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Richiesta non valida.'
));
Yii::app()->end();
} else {
//$sql = "SELECT * FROM user WHERE username = ':codfisc'";
$sql = "SELECT * FROM user WHERE username = '".$codfisc . "'";
$cmd = Yii::app()->db->createCommand($sql);
//$cmd->bindParam(":codfisc", $codfisc, PDO::PARAM_STR);
$result = $cmd->queryRow();
$sql2 = $cmd->text;
if($result) {
echo CJSON::encode(array(
'error' => 'false',
'status' => 'Codice Fiscale esistente',
'username' => $result['username'],
'cognome' => $result['cognome'],
'nome' => $result['nome'],
'email' => $result['email']
)
);
Yii::app()->end();
} else {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Il codice fiscale ' . $codfisc . ' non esiste. SQL = ' . $sql2 . '.'
));
Yii::app()->end();
}
}
}
I can't update fields. The response is:
xxxyyyddxdd{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
but it should be:
{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
Where's my mistake?
Thanks
You need to remove the following line:
echo $codfisc;
(second line in function actionPopolaAnagrafica)
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
//this LINE!!!!!!!!!!!!!!!!!!!!!!!
echo $codfisc;
Change :
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
With this :
'success' => 'function(response){
$("#cand").html(response);
var obj = jQuery.parseJSON( response );
console.log(obj.cognome);
$("#'.CHTML::activeId($model,'cognome').'").val(obj.cognome);
Parse JSON data before you put in HTML value.
Use console.log(obj.cognome); to debug value in chrome.

Cakephp multiple drop down list with view

I'm trying to get drop down list in Cake for below two finds by list:
function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The User has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
}
$group = $this->User->Group->find('list');
$commune = $this->User->Commune->find('list');
$this->compact('group','commune');
}
}
The model already has belongsTo defined in User model for Group and Commune models with their ids but I cannot seem to get group and commune to show up as drop down list in the add view page.
Below is what I have for add view page.
<div class="Users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('group_id', array('type' => 'select'));
echo $this->Form->input('commune_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users', true), array('action' => 'index'));?></li>
</ul>
</div>
Is there a reason why it's not working?
you need to use plurals in order to automatically load those options into the form fields.
$groups, $communes
Try this in the view:
$this->Form->input('Group');
Alternatively:
$this->Form->input('group_id', array('type' => 'select', 'options' => $group));
You're setting $group and $commune but the view is looking for $group_id and $commune_id.

Missing validation message in cakephp application

I'm trying to add a layout for a cakephp application but now my validation message is no longer being displayed. When validating a comment on a blog entry, the validation message thats suppose to be at the top is not displayed.
If you changing the layout means that you missed to add
<?php
if ($this->Session->check('Message.flash')){
echo $this->Session->flash();
}
?>
before the
Other possible place is in the current controller.
Search if you have code like:
$this->Session->setFlash('...');
The first code is responsible for displaying the message, while the second one is responsible for setting the message.
But the code definitely will help more :)
Here is my add function in comments_controller.php
function add(){
debug($this->data);
//if the user submitted a comment post
if (!empty($this->data)){
//display the 'add view'
$this->Comment->create();
if ($this->MathCaptcha->validates($this->data['Comment']['security_code'])) {
if ($this->Comment->save($this->data)){
$this->Session->setFlash(__('The Comment has been added.', true));
$this->redirect('/posts/index/'.$this->data['Comment']['post_id']);
}
//failed validation
else{
debug($this->data);
$this->Session->setFlash(__('Comment could not be saved. Please try again.', true));
}
}
else {
$this->Session->setFlash(__('Please enter the correct answer to the math question.', true));
$this->redirect('/posts/index/'.$this->data['Comment']['post_id']);
}
Here is my entry.ctp where my posts and comments reside:
<div id="article">
<h2><?php echo $entry[0]['Post']['title']; ?></h2>
<p class="date"><em>Modified:</em> <?php $date = new DateTime($entry[0]['Post']['modified']);
echo $date->format('Y-m-d');?></p>
<p class="date"><em>Author:</em> <?php echo $entry[0]['User']['username']; ?></p>
<p class="intro"><?php echo $entry[0]['Post']['content']; ?></p>
<h2>Comments:</h2>
<div id="comments_success"></div>
<!-- show the comment -->
<?php
echo $form->create('Comment', array('action' => 'add'));
echo $form->input('name', array('class' => 'validate[required] text-input'));
echo $form->input('email', array('class' => 'validate[required,custom[email]] text-input'));
echo $form->input('text', array('id' => 'commenttext', 'type' => 'textarea', 'label' => 'Comment:', 'rows' => '10', 'class' => 'validate[required] text-input'));
//captcha
echo $form->input('security_code', array('label' => 'Please Enter the Sum of ' . $mathCaptcha));
echo $form->input( 'Comment.post_id', array( 'value' => $entry[0]['Post']['id'] , 'type' => 'hidden') );
echo $form->end('Submit');
?>
<!-- comments -->
<ol>
<?php
foreach ($entry[0]['Comment'] as $comment) :
?>
<li>
<h3><?php echo $comment['name']; ?></h3>
<p class="date"><em>Date:</em> <?php echo $comment['created']; ?></p>
<p class="text"> <?php echo $comment['text']; ?></p>
</li>
<?php
endforeach;
?>
</ol>
</div>
This is the index function in my posts_controller
function index($entry_id = null) {
if (isset($entry_id)){
$entry = $this->Post->findAllById($entry_id);
$comments = $this->Post->Comment->getCommentsFromPostID($entry_id);
$this->set('entry' , $entry);
$this->set('mathCaptcha', $this->MathCaptcha->generateEquation());
$this->render('entry');
}
else{
$posts = $this->Post->find('all');
$this->set(compact('posts'));
}
}
I know this is old, but ust make sure you have the following code somewhere visible in your app/views/layouts/default.ctp (or whatever is your layout for this application)
<?php echo $this->Session->flash(); ?>
It will echo nothing if there is no message to be displayed, but if there is a message, then it will be output accordingly.

Categories