how to post checkbox to action in Yii? - php

I want to post a checkbox to action and print alert if the checkbox is checked, here is my code:
view:
echo CHtml::checkBox('hi');
echo CHtml::button('Search', array('onclick' => 'js:document.location.href="index"'));
controller:
public function actionIndex()
{
$model = Jobs::model()->findAll();
$model2 = Tags::model()->findAll();
if(isset($_POST['hi']))
echo "<script>alert('hello');</script>";
$this->render('index', array('model'=>$model, 'model2'=>$model2));
}
when I check the checkbox and click the button nothing is happened, where is the error in my code?

You just redirect your page to actionIndex. You must SUBMIT your form instead of redirecting it. Take a look:
echo CHtml::beginForm(Yii::app()->createUrl('index'), 'POST');
echo CHtml::checkBox('hi');
echo CHtml::submitButton('Search');
echo CHtml::endForm();
If you try:
CVarDumper::dump($_POST,56789,true);
You can see the POST value after submitting the form.
Or you can do it via java-script in your button:
//if you have created a form
echo CHtml::button('Search', array('onclick' => 'this.submit();'));

Related

Pass Form dropdown value to controller CakePHP

can i pass form dropdown value in my controller and after this, i can send the value in my DB table....please help me i m new in cakephp here is my job_content.ctp
echo'<div class="AcceptButtonFormData">';
echo $this->Form->create('Job' ,array('action' => 'view'));
$ipr_value=array('0'=>0.0,'1'=>.1,'2'=>.2,'3'=>.3);
echo $this->Form->input('IPR_teeth_pair12',array('type' => 'select','name'=>'drop12', 'options' => $ipr_value,'default'=>0));
echo $this->Form->input('IPR_teeth_pair23',array('type' => 'select','name'=>'drop23', 'options' => $ipr_value,'default'=>0));
echo $this->Form->input('IPR_teeth_pair34',array('type' => 'select','name'=>'drop34', 'options' => $ipr_value,'default'=>0));
echo $this->Form->end();
echo '</div>'
yes you can save it. As per above form this will post to you controller action in view
public function view() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Job->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('JobSaved!');
$this->redirect('/jobs');
}
}
// If no form data, find the recipe to be edited
// and hand it to the view.
$this->set('jobs', $this->Job->findAll());
}
below is just sudo code you can change as per you need and for more understanding you can visit cakephp.org

Edit page has to be submitted twice for changes to be saved

I have an edit page set up for editing blog posts. Here's the controller action...
public function edit($id = null) {
$post = $this->Post->findById($id);
if(!$post) {
throw new NotFoundException('Post not found');
}
if($this->request->is('post')) {
$this->Post->id = $id;
if($this->Post->save($this->request->data)) {
$this->Session->setFlash('Post updated!');
$this->redirect('/');
} else {
$this->Session->setFlash('Unable to update post!');
}
}
if (!$this->request->data) {
$this->request->data = $post;
}
$this->set('tags', $this->Post->Tag->find('list'));
$this->set('pageTitle', 'Edit blog post');
}
And the edit pages view...
<h1>Edit blog post</h1>
<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)', 'value' => $tags)); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Save Changes'); ?>
For some reason when I make changes and click "save changes", the page just refreshes and although the changes are reflected in the form after the refresh, I have to click "save changes" again for them to get saved to the database and for Cake to redirect me to /.
What could be causing that?
Because there is no Post.id in your form, CakePHP sends a PUT request (instead of a POST request) to create (or "put") a new row into your database the first time. This doesn't pass your request check:
if($this->request->is('post'))
Now, at this point your logic gets the entire row for the corresponding post, with this code:
$this->request->data = $post;
This will include the ID of the given post, since it's in your find() result and hence the second time you submit it, it has an id and therefor sends a POST request instead of a PUT request.
Assuming you only want to edit existing posts, add an id field to your form (the FormHelper automagic should make a hidden field of it, but you can always explicitly tell it to, like in the example below):
echo $this->Form->input('Post.id', array('type' => 'hidden');
This should pass along the id and hence trigger a POST request rather than a PUT request and make your submission pass at once.

edit function creates a new user, and wont update the current user in the database

I'm currently using CAKEPHP 2.3 and I'm trying to edit the user's information. but when I submit the information, it does not update the information in to the database. it instead creates a new user with the new information i inserted. i want it to update the user, not create a new one.
My code for the edit.ctp is:
<h1>Edit Account information</h1>
<?php
echo $this->Form->create('User', array('action' => 'edit'));
echo $this->Form->input('username', array('value' => $this->Session->read('Auth.User.username')));
echo $this->Form->input('name', array('value' => $this->Session->read('Auth.User.name')));
echo $this->Form->end('Submit');
?>
And then my edit function in the users controller is:
public function edit() {
// debug($this->User->save($this->request->data));
$this->User->id = $this->Session->read('Auth.User.id');
$this->request->data['User']['id'];
if ($this->request->is('post')) {
if ($this->User->save($this->request->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));
}
} else {
$this->request->data = $this->User->read(null);
isset($this->request->data['User']['password']);
}
}
Here is the index to get to the edit user page.
<h1>Users Home</h1>
<p>Welcome <?php print $this->Session->read('Auth.User.name');?> <br/></p>
<table border="0" width="200" text-align="center">
<tr>
<td width="50"><?php echo $this->Html->link('Log out', array('action' => 'logout')); ?></td>
<td width="50"><?php echo $this->Html->link('Edit', array('action' => 'edit')); ?></td>
<td width="50"><?php echo $this->Html->link('Add User', array('action' => 'add')); ?></td><!-- should only show for admin -->
<td width="50"><?php echo $this->html->link('Manage Users', array('action' => 'usermanage')); ?></td><!-- should only show for admin -->
</tr>
</table>
Many Thanks.
lose the $id in your edit method. usually a user can only - and only himself - edit his own record.
public function edit() {
if ($this->request->is('post')) {
$this->request->data['User']['id'] = $this->Session->read('Auth.User.id');
if ($this->User->save($this->request->data)) {
...
and value is wrong for your forms. never use that. it breaks your form on post and validation errors (see http://www.dereuromark.de/2010/06/23/working-with-forms/ for the "why" - you will also find how you can set default values if you really need to).
since you pass down data via $this->request->data you need to leave them as they were:
echo $this->Form->input('username');
also lose the action. the form will automatically post to itself!
last but not least dont use read(), use find(first)
You have to specify the $id of the User you want to edit. In this case, as only one user can edit his own profile, we do it at the controller:
public function edit() {
$this->User->id = this->Session->read('Auth.User.id');
//whatever...
}
If you are on the edit view and the $id is passed by param, you don't even need to do it, just create the form like this and CakePHP will automatically generate the form for the edit action:
echo $this->Form->create('User');
Also, your inputs seems to be wrong, you don't need the options variable:
echo $this->Form->input('username', array('value' => $this->Session->read('Auth.User.username')));
echo $this->Form->input('name', array('value' => $this->Session->read('Auth.User.name')));
You can also include it in the form. By default, the id field will be hidden in the form. Doing it with session is more secure but you can do it this way for admin functions or verify it before a save.
echo $this->Form->input('User.id');

Infinite loop trying to validate/save

I'm using Yii framework to create a really simple 1 text-area field and 2 hidden inputs with predefined values sent from the server.
The way it should work is as expected, I mean, you write something on that text-area and you click on the send button. An ajax validation is made (only requisite for the text-area is that is shouldn't be empty) and if validated, save the data and redirect to some other page.
The problem is that it won't save any data if validation error was triggered.
I mean, if I go to the page, write something and hit on the send button, data will be saved and I'll be redirected correctly. But if I go to the page, hit the send button (without typing anything in the text-area), wait for the error to appear (note that this is done via ajax, so no page-reload here), write something and hit send again Yii is going to start making a request after a request in an infinite loop.
I already have checked the data being sent, and everything is fine (both data and action-url).
Here is my Controller code
public function actionView($id)
{
$user = Usuario::model()->findByAttributes(
array(
'nick'=>Yii::app()->user->getId()
)
);
$dataProvider=new CActiveDataProvider('Mensaje', array(
'criteria'=>array(
'with'=>array('usuario', 'usuario.detallesusuario'),
'condition'=>'Tema_idtema='.$id
),
'pagination'=>array(
'pageSize'=>1000,
),
));
$this->render('view',array(
'model'=>$this->loadModel($id),
'usuario_id'=>$user->idusuario,
'tema_id'=>$id,
'dataProvider'=>$dataProvider,
));
}
public function actionCreateMessage(){
$model=new Mensaje;
$this->performAjaxValidation($model);
if(isset($_POST['Mensaje']))
{
$model->attributes=$_POST['Mensaje'];
$model->fecha_hora=new CDbExpression('NOW()');
$model->save();
$this->redirect(array('view', 'id'=>$model->Tema_idtema));
}
}
And the code from the View
<?php
$model = new Mensaje();
echo $this->renderPartial('_mensaje_form', array(
'model'=>$model,
'usuario_id'=>$usuario_id,
'tema_id'=>$tema_id,
),
false, //return instead of echo
true //post-process
);
?>
Here is the "_mensaje_form" code
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'mensaje-form',
'action'=>CHtml::normalizeUrl(array('tema/createMessage')),
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>false,
'validateOnType'=>false,
),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row" style="margin:20px 5px 0 176px;">
<?php echo $form->labelEx($model,'mensaje'); ?>
<?php echo $form->textArea($model,'mensaje',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'mensaje'); ?>
<?php echo $form->hiddenField($model, 'Tema_idtema', array('value'=>$tema_id)); ?>
<?php echo $form->hiddenField($model, 'Usuario_idusuario', array('value'=>$usuario_id)); ?>
</div>
<div class="row buttons" style="margin:-3px 0 -8px 176px;">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Responder' : 'Guardar'); ?>
</div>
<?php $this->endWidget(); ?>
Any idea why I'm getting that loop?
This might help you,
http://www.yiiframework.com/forum/index.php/topic/10427-ajax-clientscript/
in your view, the last parameter "true" in renderPartial may be the problem.
My guess (a bit long shot) that form id in your preformAjaxValidation() might be wrong, so it causes the loop! since it won't get in the body of the if and hence executes Yii::app()->end(); !!
Check it in your controller:
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='exact-form-id')//should be mensaje-form
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}

Accessing Text Input Field Data

Using CodeIgniter, how do I access and display text entered into an input field on a view file (see code below) from my controller file?
// input_view.php
<?php
echo form_open('search/submit');
$input_data = array('name' => 'search_field', 'size' => '70');
echo form_input($input_data);
form_submit('submit','Submit');
form_close();
?>
When text is entered into an input field, it is impossible to access until the form has been posted back to the server. In other words, the form must be submit for your controller to see it.
Let's say you have a form in the file called input_view.php:
<?php echo form_open('my_controller/my_method'); ?>
<?php echo form_input('search'); ?>
<?php echo form_submit('submit', 'Search'); ?>
When this form is submit, it will be sent to the 'my_controller' controller.
Now, Here's what the my_method should look like if you want to simply print the contents of the search field:
public function my_method() {
if ($this->input->post()) {
$name = $this->input->post('search');
echo $name;
}
}
I hope this helps.

Categories