CakePHP form submits the "array" - mysql

I am trying to create a form "Movie" as follows and my database accepts movie_id, title, year, and description. When I run the code it tries to store the "array" as the year input. This is the error I get => movie_id, title, year, description) VALUES (NULL, 'Movie1', Array, 'some text')
THE VIEW:
<?php
echo $this->Form->create('Movie'); ?>
<?php echo __('Add Movie'); ?>
<?php
echo $this->Form->hidden('movie_id');
echo $this->Form->input('title');
echo $this->Form->input('year', array(
'type'=>'date',
'dateFormat'=>'Y',
'minYear'=>'1990',
'maxYear'=>date('Y'),
));
echo $this->Form->input('description');
?>
<?php echo $this->Form->end(__('Submit'));
?>
THE CONTROLLER:
public function add() {
if ($this->request->is('post')) {
$this->Movie->create();
if ($this->Movie->save($this->request->data)) {
$this->Session->setFlash(__('The movie has been created'));
$this->redirect (array('action'=>'index'));
}
else {
$this->Session->setFlash(__('The movie could not be created. Please, try again.'));
}
}
}

I believe your problem is here:
$this->Form->input('year', array(
'type'=>'date',
'dateFormat'=>'Y',
'minYear'=>'1990',
'maxYear'=>date('Y'),
));
Instead of it you should use
$this->Form->input('Movie.year', array(
'type'=>'text',
'name' => 'data[Movie][year]',
));
If you don't want to use 'text' type input, then use 'select' with your options array. Here main concern is, Movie.year and overwrite the default CakePHP's naming procedure to 'name' => 'data[Movie][year]'. Check here.

The best thing to do is to debug your $this->request->data.
I'm not sure myself, but I once have this problem. What happen is, when you define an input as a date, it will be behave as an array.
It will become $this->request->data['Movie']['year']['year'];
You can modify the data by doing the following
$this->request->data['Movie']['year'] = $this->request->data['Movie']['year']['year'];

Related

Getting field value in controller

I want to get value of field in controller.
could you please help me?
here is my form code:
<?php
$form = ActiveForm::begin([
'id' => 'request-form',
'action' => 'site/request_page',
'method' => 'post',
'fieldConfig' => ['autoPlaceholder' => false]
]);
?>
<?= $form->field($model, 'workroom_id')->label(FALSE) ?>
and this is my controller code:
public function actionRequest_page() {
echo Yii::$app->request->post('workroom_id');
die();
}
But I got nothing in result.
write workroom_id in safe rule like this-
public function rules()
{
return [
[['workroom_id'],'safe']
];
}
Use bellow code -
echo Yii::$app->request->post('MODEL_NAME')['workroom_id'];
You should expand your action form-attribute. By using Url::to() for instance. As in echo \yii\helpers\Url::to(['site/request_page']);
And access your post data differently. Try var_dump(Yii::$app->request->post()); to see what your form data looks like. The other answer shows how to access it correctly.
The docs have an excellent starting place for working with forms.

Storing datetime in mysql using yii framework

I have created datetime field in mysql. I want to store it in the db when i pick the date by using datepicker.
This is my part of code in controller
public function actionCreate()
{
$model=new EmpDetails;
$model->created = date("Y-m-d H:i");
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['EmpDetails']))
{
$model->attributes=$_POST['EmpDetails'];
if($model->save())
$this->redirect(array('view ','id'=>$model->emp_id));
}
$this->render('create',array(
'model'=>$model,
));
}
The part of my form.php is:
<div class="row">
<?php echo $form->labelEx($model,'dateof_leave'); ?>
<?php $model->created=new CDbExpression('NOW()');
$sqldate = date('Y-m-d H:i:s',strtotime($textFieldValue));?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'dateof_leave',
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength
),
));
?>
<?php // echo $form->textField($model,'dateof_leave'); ?>
<?php echo $form->error($model,'dateof_leave'); ?>
</div>
am facing the error Property "EmpLeave.created" is not defined.
Please clarify my doubts and explain me how can i overcome this issue?
Replace
$model->created=new CDbExpression('NOW()');
On
$model->created=date("Y-m-d H:i:s");
Because CJuiDatePicker needs string on input.
In yout Controller you add line
$model->created = date("Y-m-d H:i");
In your _form.php you add input form for dateof_leave. So when posting form the $model->created is EMPTY. If i am understand right In controller u must add
$var= $_POST['EmpDetails']['dateof_leave'];
$model->created = date("Y-m-d H:i", $var);

cakephp Image escape false not working

I am making a Image link to user profile, but it is not working as it should be
this is my code.with this i want to add contoroller,function and id. How i can do it.
<?php
$pic = $User['User']['url'];
if(!$pic){
echo $this->Html->link($this->Html->image('pro.jpg'), array('alt'=>$User['User']['handle'],'title' => $User['User']['handle']),array('escape'=>false) ,array('class'=>'inner_image'));
}else{
echo $this->Html->link($this->Html->image($User['User']['url']),array('alt' => $User['User']['handle']),array('escape'=>false),array('class'=>'inner_image'));
}
?>
This code is making image a link but i can't define a link and it is not accepting the class
.I want to pass this url
$this->Html->link('', array('controller'=>'User','action'=>'view','id'=>$User['User']['id']));
This is how I did it
echo $this->Html->link($this->Html->image($pic, array('class'=>'inner_image')), $url_array, array('alt' => $User['User']['handle'], 'escape'=>false));
What cake version are you using? You don't seem to be following the documentation for Html::link.
HtmlHelper::link(string $title, mixed $url = null, array $options =
array(), string $confirmMessage = false)
alt, escape and class should be indexes in the options array, but you're not defininf the url parameter anywhere.
It should be something like this
if(!$pic){
echo $this->Html->link($this->Html->image('pro.jpg'), $url_array, array('alt'=>$User['User']['handle'],'title' => $User['User']['handle'],'escape'=>false,'class'=>'inner_image'));
} else {
echo $this->Html->link($this->Html->image($User['User']['url']), $url_array, array('alt' => $User['User']['handle'], 'escape'=>false, 'class'=>'inner_image'));
(don't know what url you want to point this at, so replace $url_array to your convenience.

Google Map V3 Cakephp helper and multiple markers

I am using the Cakephp Google Map V3 Helper. I can get the google map to show up but the markers do not. Here is my view code:
<?php
echo $this->GoogleMapV3->map();
foreach ($allcondos as $condo) {
$options = array(
'lat' => $condo['Unit']['lat'],
'lng' => $condo['Unit']['lon']
);
$this->GoogleMapV3->addMarker($options);
}
?>
I know that if I just tell the app to echo out my $condo['Unit']['lat'] or ['lon'] it will do so in the foreach loop (so it is pulling my data). What I don't know how to do is how to write the code for the $options array. I have also tried this:
foreach ($allcondos as $condo) {
$lat=$condo['Unit']['lat'];
$lon=$condo['Unit']['lon'];
$options = array(
'lat' => $lat,
'lng' => $lon
);
$this->GoogleMapV3->addMarker($options);
}
How do I write this correctly?
A couple easy steps to get this to work:
Download
Download from https://github.com/dereuromark/cakephp-google-map-v3-helper and place the GoogleMapV3Helper.php file in /app/view/helper/GoogleMapV3Helper.php.
Load Helper
Either modify your appcontroller so that the top of it reads like the following:
<?php
class AppController extends Contoller{
public $helpers = array('Html','Javascript','GoogleMapV3');
}
?>
Or load it in a single controller by adding it to the helpers array as such:
<?php
class DemoController extends AppContoller{
function map() {
$this->helpers[] = 'GoogleMapV3';
# rest of your code
}
}
?
Include Scripts
Include Jquery in your header. Include the following as well:
<?php
echo '<script type="text/javascript" src="'.$this->GoogleMapV3->apiUrl().'"></script>';
?>
Create Map Container
Put this in your view where you want your map to appear. Feel free to modify the properties of the div.
<?php echo $this->GoogleMapV3->map(array('div'=>array('id'=>'my_map', 'height'=>'400', 'width'=>'100%'))); ?>
Note: you can change the default position of the map by including more options than just 'div':
<?php echo $this->GoogleMapV3->map(array('map'=>array(
'defaultLat' => 40, # only last fallback, use Configure::write('Google.lat', ...); to define own one
'defaultLng' => -74, # only last fallback, use Configure::write('Google.lng', ...); to define own one
'defaultZoom' => 5,
),'div'=>array('id'=>'my_map', 'height'=>'400', 'width'=>'100%'))); ?>
Add markers
Can be in a loop or whatever, but this is done in the view after your container is created.
<?php
$options = array(
'lat'=>40.770272,
'lng'=>-73.974037,
'title' => 'Some title', # optional
'content' => '<b>HTML</b> Content for the Bubble/InfoWindow' # optional
);
$this->GoogleMapV3->addMarker($options);
?>
note: only set the 'icon' key in the array if you want to use a custom image. Otherwise, they will not show up.
Include the script for the markers
<?php echo $this->GoogleMapV3->script() ?>
All done!
Alternately, you can use finalize() instead of script() if you do not want to echo the javascript right away, but write it to the buffer for later output in your layout:
<?php $this->GoogleMapV3->finalize(); ?>
See http://www.dereuromark.de/2010/12/21/googlemapsv3-cakephp-helper/ for details.

updating multiple rows with codeigniter

Im having some trouble getting on with my first codeigniter project, and i have a feeling the answer is really near...
Im populating a form of inputfields from a database, and when the user submits the form, it should run through the rows of the database, and update the content based on the 'id' of each row.
My form (in the view 'admin.php') looks something like this:
<?php echo form_open('admin/update'); ?>
<?php foreach($content as $row) : ?>
<?php echo form_input('id['. $row->id .'][id]', $row->id); ?>
<?php echo form_input('id['. $row->id .'][order]', $row->order); ?>
<?php echo form_input('id['. $row->id .'][title_text]', $row->title_text); ?>
<?php echo form_textarea('id['. $row->id .'][body_text]', $row->body_text); ?>
<?php
if ($row->visibility == 'visible') {
echo form_checkbox('id['. $row->id .'][visibility]', 'visibility', TRUE);
} else {
echo form_checkbox('id['. $row->id .'][visibility]', 'visibility', FALSE);
}
?>
<?php endforeach;?>
<?php echo form_submit('Save Changes', 'Save Changes'); ?>
<?php echo form_close(); ?>
Now, most of this is based on a mix of tutorials and help documents. Here's the code from the controller 'admin', that i call when people click 'Save changes':
function update()
{
$this->load->model('admin_model');
$this->admin_model->updateRecords($_POST['id']);
$this->index();
}
The data is then passed on to the model, wherein the function looks like this:
function updateRecords($data)
{
$this->db->insert_batch('content', $data);
}
This is the only way i have gotten it to somehow work. It inserts the data fine, but adds it in new rows instead of updating the ones already there, according to their unique 'id's.
For good orders sake, here's the columns i have in my mySQL database:
id (PRIMARY and AUTOINCREMENT)
order
title_text
body_text
visibility
origin_date
Thanks alot in advance :)
Here's how I might do it, I added in some basic error handling; Hope this explains itself:
Model
function updateRecords($records)
{
// Method 1
// If you want to proceed if there is an error
$errors = array();
// Method 2
// If you want to rollback if there is an error
$this->db->trans_start();
foreach ($records as $id => $values):
// Your form fields conveniently match the column names
// No need to create the data array, we already have it
// If you want to update `origin_date` just do this:
// $values['origin_date'] = time();
// See if checkbox values were sent
// Assumes visibility is integer
if (empty($values['visibility']))
{
$values['visibility'] = 0;
}
else
{
$values['visibility'] = 1;
}
// Using method 1, store the error id in an array
$this->db
->where('id', $id)
->update('content', $values) OR $errors[] = $id;
// If using method 2, stop the loop
$this->db
->where('id', $id)
->update('content', $values) OR break;
endforeach;
// Method 1
// Return the array of failed updates
// Controller will check if the array is empty
// You can tell the user which updates failed or just how many
return $errors;
// Method 2
// This will return TRUE or FALSE
$this->db->trans_complete();
return $this->db->trans_status();
}
Controller
function update()
{
$records = $this->input->post('id');
$this->load->model('admin_model');
// Make sure to return errors here if they occur
// Using method 1
$errors = $this->admin_model->updateRecords($records);
$num_errors = count($errors);
if ($num_errors > 0)
{
echo "There were {$num_errors} errors!";
// You can optionally print which records had errors
echo "There were errors updating these rows: ".implode(', ', $errors);
}
// Using method 2
$success = $this->admin_model->updateRecords($records);
if ( ! $success)
{
echo "Error performing update, no records were saved.";
}
$this->index();
}
Don't just echo the errors of course, use some kind of message library, session data, or send variables to the view. Some references:
http://codeigniter.com/user_guide/database/transactions.html
http://codeigniter.com/user_guide/database/active_record.html#update