Missing validation message in cakephp application - php

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.

Related

"Message: Undefined property: stdClass" codeigniter controller issue

First of all, I inherited the code for this site so I'm having trouble figuring out some of it. The problem is with our blog page creation. When I try to create a new blog page (using an admin site) I get an error before each element. It only appears on the create side and works fine on the edit side. I'm also still able to create the new post, it just has the notices. It was working as of about 24 hours ago and nothing was changed in any of the code.
The errors I'm getting are :
> A PHP Error was encountered
>Severity: Notice
>Message: Undefined property: stdClass::$keywords
>Filename: admin/form.php
>Line Number: 94
as well as:
> $title, Line Number: 28
> $comments_enabled, line 122
>$slug, line 33
>$status, line 38
>$body, line 53
>$preview_hash, line 58
I've narrowed it down to the $extra array code that doesn't seem to be getting read (maybe?). Here is my create function:
public function create()
{
// They are trying to put this live
if ($this->input->post('status') == 'live')
{
role_or_die('blog', 'put_live');
$hash = "";
}
else
{
$hash = $this->_preview_hash();
}
$post = new stdClass();
// Get the blog stream.
$this->load->driver('Streams');
$stream = $this->streams->streams->get_stream('blog', 'blogs');
$stream_fields = $this->streams_m->get_stream_fields($stream->id, $stream->stream_namespace);
// Get the validation for our custom blog fields.
$blog_validation = $this->streams->streams->validation_array($stream->stream_slug, $stream->stream_namespace, 'new');
// Combine our validation rules.
$rules = array_merge($this->validation_rules, $blog_validation);
// Set our validation rules
$this->form_validation->set_rules($rules);
if ($this->input->post('created_on'))
{
$created_on = strtotime(sprintf('%s %s:%s', $this->input->post('created_on'), $this->input->post('created_on_hour'), $this->input->post('created_on_minute')));
}
else
{
$created_on = now();
}
if ($this->form_validation->run())
{
// Insert a new blog entry.
// These are the values that we don't pass through streams processing.
$extra = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'category_id' => $this->input->post('category_id'),
'keywords' => Keywords::process($this->input->post('keywords')),
'body' => $this->input->post('body'),
'status' => $this->input->post('status'),
'created_on' => $created_on,
'created' => date('Y-m-d H:i:s', $created_on),
'comments_enabled' => $this->input->post('comments_enabled'),
'author_id' => $this->current_user->id,
'type' => $this->input->post('type'),
'parsed' => ($this->input->post('type') == 'markdown') ? parse_markdown($this->input->post('body')) : '',
'preview_hash' => $hash
);
if ($id = $this->streams->entries->insert_entry($_POST, 'blog', 'blogs', array('created'), $extra))
{
$this->pyrocache->delete_all('blog_m');
$this->session->set_flashdata('success', sprintf($this->lang->line('blog:post_add_success'), $this->input->post('title')));
// Blog article has been updated, may not be anything to do with publishing though
Events::trigger('post_created', $id);
// They are trying to put this live
if ($this->input->post('status') == 'live')
{
// Fire an event, we're posting a new blog!
Events::trigger('post_published', $id);
}
}
else
{
$this->session->set_flashdata('error', lang('blog:post_add_error'));
}
// Redirect back to the form or main page
($this->input->post('btnAction') == 'save_exit') ? redirect('admin/blog') : redirect('admin/blog/edit/'.$id);
}
else
{
// Go through all the known fields and get the post values
$post = new stdClass;
/*
---------Gives array to string error without the if statement-------
foreach ($this->validation_rules as $key => $field)
{
$post->$field['field'] = set_value($field['field']);
}*/
foreach ($this->validation_rules as $key => $field)
{
if (isset($_POST[$field['field']]))
{
$post->$field['field'] = set_value($field['field']);
}
}
$post->created_on = $created_on;
// if it's a fresh new article lets show them the advanced editor
$post->type or $post->type = 'wysiwyg-advanced';
}
// Set Values
$values = $this->fields->set_values($stream_fields, null, 'new');
// Run stream field events
$this->fields->run_field_events($stream_fields, array(), $values);
$this->template
->title($this->module_details['name'], lang('blog:create_title'))
->append_metadata($this->load->view('fragments/wysiwyg', array(), true))
->append_js('jquery/jquery.tagsinput.js')
->append_js('module::blog_form.js')
->append_js('module::blog_category_form.js')
->append_css('jquery/jquery.tagsinput.css')
->set('stream_fields', $this->streams->fields->get_stream_fields($stream->stream_slug, $stream->stream_namespace, $values))
->set('post', $post)
->build('admin/form');
}
The $extra array doesn't seem to be getting read. These errors also came about at the same time as an array to string error. I was hoping the fix for that would fix both but so far no good. The errors are coming from two sources as well. I was thinking it might be the if statement not being read? Or maybe it has something to do with the $validation_rules at the beginning of the file?
This bit of code is the first one to fail (for $type) and the only one through the actual controller.php file and the rest (keywords, title, slug, etc) fail under the form.php file.
$post->type or $post->type = 'wysiwyg-advanced';
Any advice or help is appreciated. I'm still fairly new to PHP and CodeIgniter but it looks like it'll be to much work to overhaul the website.
Thank you.
Edit: I've added my edit function below, maybe someone else can see why it works but not my create function.
public function edit($id = 0)
{
$id or redirect('admin/blog');
$post = $this->blog_m->get($id);
// They are trying to put this live
if ($post->status != 'live' and $this->input->post('status') == 'live')
{
role_or_die('blog', 'put_live');
}
// If we have keywords before the update, we'll want to remove them from keywords_applied
$old_keywords_hash = (trim($post->keywords) != '') ? $post->keywords : null;
$post->keywords = Keywords::get_string($post->keywords);
// If we have a useful date, use it
if ($this->input->post('created_on'))
{
$created_on = strtotime(sprintf('%s %s:%s', $this->input->post('created_on'), $this->input->post('created_on_hour'), $this->input->post('created_on_minute')));
}
else
{
$created_on = $post->created_on;
}
// Load up streams
$this->load->driver('Streams');
$stream = $this->streams->streams->get_stream('blog', 'blogs');
$stream_fields = $this->streams_m->get_stream_fields($stream->id, $stream->stream_namespace);
// Get the validation for our custom blog fields.
$blog_validation = $this->streams->streams->validation_array($stream->stream_slug, $stream->stream_namespace, 'new');
$blog_validation = array_merge($this->validation_rules, array(
'title' => array(
'field' => 'title',
'label' => 'lang:global:title',
'rules' => 'trim|htmlspecialchars|required|max_length[100]|callback__check_title['.$id.']'
),
'slug' => array(
'field' => 'slug',
'label' => 'lang:global:slug',
'rules' => 'trim|required|alpha_dot_dash|max_length[100]|callback__check_slug['.$id.']'
),
));
// Merge and set our validation rules
$this->form_validation->set_rules(array_merge($this->validation_rules, $blog_validation));
$hash = $this->input->post('preview_hash');
if ($this->input->post('status') == 'draft' and $this->input->post('preview_hash') == '')
{
$hash = $this->_preview_hash();
}
//it is going to be published we don't need the hash
elseif ($this->input->post('status') == 'live')
{
$hash = '';
}
if ($this->form_validation->run())
{
$author_id = empty($post->display_name) ? $this->current_user->id : $post->author_id;
$extra = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'category_id' => $this->input->post('category_id'),
'keywords' => Keywords::process($this->input->post('keywords'), $old_keywords_hash),
'body' => $this->input->post('body'),
'status' => $this->input->post('status'),
'created_on' => $created_on,
'updated_on' => $created_on,
'created' => date('Y-m-d H:i:s', $created_on),
'updated' => date('Y-m-d H:i:s', $created_on),
'comments_enabled' => $this->input->post('comments_enabled'),
'author_id' => $author_id,
'type' => $this->input->post('type'),
'parsed' => ($this->input->post('type') == 'markdown') ? parse_markdown($this->input->post('body')) : '',
'preview_hash' => $hash,
);
if ($this->streams->entries->update_entry($id, $_POST, 'blog', 'blogs', array('updated'), $extra))
{
$this->session->set_flashdata(array('success' => sprintf(lang('blog:edit_success'), $this->input->post('title'))));
// Blog article has been updated, may not be anything to do with publishing though
Events::trigger('post_updated', $id);
// They are trying to put this live
if ($post->status != 'live' and $this->input->post('status') == 'live')
{
// Fire an event, we're posting a new blog!
Events::trigger('post_published', $id);
}
}
else
{
$this->session->set_flashdata('error', lang('blog:edit_error'));
}
// Redirect back to the form or main page
($this->input->post('btnAction') == 'save_exit') ? redirect('admin/blog') : redirect('admin/blog/edit/'.$id);
}
// Go through all the known fields and get the post values
foreach ($this->validation_rules as $key => $field)
{
if (isset($_POST[$field['field']]))
{
$post->$field['field'] = set_value($field['field']);
}
}
$post->created_on = $created_on;
// Set Values
$values = $this->fields->set_values($stream_fields, $post, 'edit');
// Run stream field events
$this->fields->run_field_events($stream_fields, array(), $values);
$this->template
->title($this->module_details['name'], sprintf(lang('blog:edit_title'), $post->title))
->append_metadata($this->load->view('fragments/wysiwyg', array(), true))
->append_js('jquery/jquery.tagsinput.js')
->append_js('module::blog_form.js')
->set('stream_fields', $this->streams->fields->get_stream_fields($stream->stream_slug, $stream->stream_namespace, $values, $post->id))
->append_css('jquery/jquery.tagsinput.css')
->set('post', $post)
->build('admin/form');
}
Edit2: I've added the whole form.php that is sending most of the errors.
<section class="title">
<?php if ($this->method == 'create'): ?>
<h4><?php echo lang('blog:create_title') ?></h4>
<?php else: ?>
<h4><?php echo sprintf(lang('blog:edit_title'), $post->title) ?></h4>
<?php endif ?>
</section>
<section class="item">
<div class="content">
<?php echo form_open_multipart() ?>
<div class="tabs">
<ul class="tab-menu">
<li><span><?php echo lang('blog:content_label') ?></span></li>
<?php if ($stream_fields): ?><li><span><?php echo lang('global:custom_fields') ?></span></li><?php endif; ?>
<li><span><?php echo lang('blog:options_label') ?></span></li>
</ul>
<!-- Content tab -->
<div class="form_inputs" id="blog-content-tab">
<fieldset>
<ul>
<li>
<label for="title"><?php echo lang('global:title') ?> <span>*</span></label>
<div class="input"><?php echo form_input('title', htmlspecialchars_decode($post->title), 'maxlength="100" id="title"') ?></div>
</li>
<li>
<label for="slug"><?php echo lang('global:slug') ?> <span>*</span></label>
<div class="input"><?php echo form_input('slug', $post->slug, 'maxlength="100" class="width-20"') ?></div>
</li>
<li>
<label for="status"><?php echo lang('blog:status_label') ?></label>
<div class="input"><?php echo form_dropdown('status', array('draft' => lang('blog:draft_label'), 'live' => lang('blog:live_label')), $post->status) ?></div>
</li>
<li class="editor">
<label for="body"><?php echo lang('blog:content_label') ?> <span>*</span></label><br>
<div class="input small-side">
<?php echo form_dropdown('type', array(
'html' => 'html',
'markdown' => 'markdown',
'wysiwyg-simple' => 'wysiwyg-simple',
'wysiwyg-advanced' => 'wysiwyg-advanced',
), $post->type) ?>
</div>
<div class="edit-content">
<?php echo form_textarea(array('id' => 'body', 'name' => 'body', 'value' => $post->body, 'rows' => 30, 'class' => $post->type)) ?>
</div>
</li>
</ul>
<?php echo form_hidden('preview_hash', $post->preview_hash)?>
</fieldset>
</div>
<?php if ($stream_fields): ?>
<div class="form_inputs" id="blog-custom-fields">
<fieldset>
<ul>
<?php foreach ($stream_fields as $field) echo $this->load->view('admin/partials/streams/form_single_display', array('field' => $field), true) ?>
</ul>
</fieldset>
</div>
<?php endif; ?>
<!-- Options tab -->
<div class="form_inputs" id="blog-options-tab">
<fieldset>
<ul>
<li>
<label for="category_id"><?php echo lang('blog:category_label') ?></label>
<div class="input">
<?php echo form_dropdown('category_id', array(lang('blog:no_category_select_label')) + $categories, #$post->category_id) ?>
[ <?php echo anchor('admin/blog/categories/create', lang('blog:new_category_label'), 'target="_blank"') ?> ]
</div>
</li>
<?php if ( !module_enabled('keywords')): ?>
<?php echo form_hidden('keywords'); ?>
<?php else: ?>
<li>
<label for="keywords"><?php echo lang('global:keywords') ?></label>
<div class="input"><?php echo form_input('keywords', $post->keywords, 'id="keywords"') ?></div>
</li>
<?php endif; ?>
<li class="date-meta">
<label><?php echo lang('blog:date_label') ?></label>
<div class="input datetime_input">
<?php echo form_input('created_on', date('Y-m-d', $post->created_on), 'maxlength="10" id="datepicker" class="text width-20"') ?>
<?php echo form_dropdown('created_on_hour', $hours, date('H', $post->created_on)) ?> :
<?php echo form_dropdown('created_on_minute', $minutes, date('i', ltrim($post->created_on, '0'))) ?>
</div>
</li>
<?php if ( ! module_enabled('comments')): ?>
<?php echo form_hidden('comments_enabled', 'no'); ?>
<?php else: ?>
<li>
<label for="comments_enabled"><?php echo lang('blog:comments_enabled_label');?></label>
<div class="input">
<?php echo form_dropdown('comments_enabled', array(
'no' => lang('global:no'),
'1 day' => lang('global:duration:1-day'),
'1 week' => lang('global:duration:1-week'),
'2 weeks' => lang('global:duration:2-weeks'),
'1 month' => lang('global:duration:1-month'),
'3 months' => lang('global:duration:3-months'),
'always' => lang('global:duration:always'),
), $post->comments_enabled ? $post->comments_enabled : '3 months') ?>
</div>
</li>
<?php endif; ?>
</ul>
</fieldset>
</div>
</div>
<input type="hidden" name="row_edit_id" value="<?php if ($this->method != 'create'): echo $post->id; endif; ?>" />
<div class="buttons">
<?php $this->load->view('admin/partials/buttons', array('buttons' => array('save', 'save_exit', 'cancel'))) ?>
</div>
<?php echo form_close() ?>
</div>
</section>
In your code:
$post->type or $post->type = 'wysiwyg-advanced';
PHP will first evaluate $post->type, and if that returns false, the second part of your or statement will be run. Since PHP has to evaluate it, it will attempt to access the property, and since it's not set, the interpreter throws a notice and assumes it's false.
The proper way to do this is:
if (!isset($post->type)) {
$post->type = 'wysiwyg-advanced';
}
// Or in PHP 7:
$post->type = $post->type ?? 'nobody';
Replace
$post->type or $post->type = 'wysiwyg-advanced';
with
$post->type = 'wysiwyg-advanced';
hope it works..

php - ajax update textfield after dropdownlist is selected not working (yii)

Hello I have dropdownlist dependant textfield. The value of the textfield should be updated via ajax request when dropdownlist is selected (I'm using Yii's CHTML textfield).
Here is my code :
view _form.php
<div class="row">
<?php echo $form->labelEx($model,'kode_rincian'); ?>
<?php
echo $form->dropDownList($model, 'kode_rincian', array(), array(
'empty'=>'--Pilih--',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('OPS/calculateRealisasi'),
//'update'=>'#OPS_contrealisasi',
'dataType'=>'json',
'data'=>array(
'kode_program' => 'js:$(\'#OPS_kode_program option:selected\').val()',
'kode_kegiatan' => 'js:$(\'#OPS_kode_kegiatan option:selected\').val()',
'kode_output' => 'js:$(\'#OPS_kode_output option:selected\').val()',
'kode_komponen' => 'js:$(\'#OPS_kode_komponen option:selected\').val()',
'kode_akun' => 'js:$(\'#OPS_kode_akun option:selected\').val()',
'kode_rincian'=>'js:this.value',
),
'success'=>"function(data)
{
$('#OPS_realisasi_at').html(data.sumrealisasi);
$('#OPS_sisa_at').html(data.sumsisa);
} ",
)
));
?>
<?php echo $form->error($model,'kode_rincian'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'realisasi_at'); ?>
<?php
echo $form->textField($model,'realisasi_at');
?>
<?php echo $form->error($model,'realisasi_at'); ?>
</div class="row">
<?php echo $form->labelEx($model,'sisa_at'); ?>
<?php echo $form->textField($model,'sisa_at'); ?>
<?php echo $form->error($model,'sisa_at'); ?>
</div>
And controller OPSController.php:
public function actionCalculateRealisasi(){
$kode_rincian = $_POST["kode_rincian"];
$kode_program = $_POST["kode_program"];
$kode_kegiatan = $_POST["kode_kegiatan"];
$kode_komponen = $_POST["kode_komponen"];
$kode_akun = $_POST["kode_akun"];
$kode_output = $_POST["kode_output"];
$modelkode= KodePOK::model()->findByAttributes(array(
'kode_program'=>$kode_program,
'kode_komponen'=>$kode_komponen,
'kode_kegiatan'=>$kode_kegiatan,
'kode_akun'=>$kode_akun,
'kode_output'=>$kode_output,
'kode_rincian'=>$kode_rincian,
));
if($modelkode!=NULL){
$idpok=$modelkode->id_pok;
}
else{
$idpok=0;
}
$criteria = new CDbCriteria;
$criteria->select='SUM(jumlah_pengajuan) as realisasi';
$criteria->condition="id_pok='".$idpok."'";
$sum = OPS::model()->find($criteria);
$sumrealisasi=$sum->realisasi;
$sumrealisasi=(int)$sumrealisasi;
$calcsisa=POK::model()->findByPk($idpok);
$getjumlah=$calcsisa->jumlah_pagu;
$sumsisa=$getjumlah-$sumrealisasi;
echo CJSON::encode(array(
'sumrealisasi'=>$sumrealisasi,
'sumsisa'=>$sumsisa,
));
Yii::app()->end();
}
The code didn't show any error but the textfield wasn't updated. Please help me. Here is the result when I tried to inspect the page element :
I've solved the problem.
I changed
'success'=>"function(data)
{ $('#OPS_realisasi_at').html(data.sumrealisasi);
$('#OPS_sisa_at').html(data.sumsisa);
} ",
to :
'success'=>"function(data)
{ $('#OPS_realisasi_at').val(data.sumrealisasi);
$('#OPS_sisa_at').val(data.sumsisa);
} ",

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']);
}

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

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.

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.

Categories