I just started working with yii and I stumbled upon a problem.
I have a table called "users" and a table called "messages".
I basically want to have a page where I can view a user's details but also send him a message that would be saved in the message table.
I have a view called "user/view.php" which consists of:
<h1>View User #<?php echo $model->id; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'username',
'first_name',
'last_name',
),
)); ?>
<?php $message=new Message;
echo $this->renderPartial('_messagesend', array('model'=>$message)); ?>
the _messagesend form (created using gii) looks like:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'message-_messagesend-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
//for the sake of simplicity lets just insert the id's manually for now
<div class="row">
<?php echo $form->labelEx($model,'idFrom'); ?>
<?php echo $form->textField($model,'idFrom'); ?>
<?php echo $form->error($model,'idFrom'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'idTo'); ?>
<?php echo $form->textField($model,'idTo'); ?>
<?php echo $form->error($model,'idTo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'msg'); ?>
<?php echo $form->textField($model,'msg'); ?>
<?php echo $form->error($model,'msg'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Send'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I have a simple view in my UserController to display the details info:
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id)
));
}
And now I want to figure out how i can add the controller to save the message. After gii creation I get a code which I tried to use and modify a little bit:
public function actionMessagesend()
{
$model=new Message;
if(isset($_POST['Message']))
{
$model->attributes=$_POST['Message'];
if($model->save()){
$this->redirect(array('admin'));
}
}
$this->render('_messagesend',array('model'=>$model));
}
I tried to add this controller function in the UserController.php but it doesn't seem to work, I tried to add the same function to MessageController.php but it also doesn't seem to work. I tried to remove all the code and only add a redirect to show if the controllercode actually hits but it doesn't redirect (i tried it both in usercontroller and messagecontroller). So I have a feeling my code isn't reached. You guys have any idea what I'm missing here?
Maybe a little extra question: Is there a better suggestion to do what I want to do?
Thanks a lot!
Best regards,
WtFudgE
Your message sending action isn't reached because by default the CActiveForm submits to the current page, so you will have to add the message processing to the view action, or you will need to set the action property for your CActiveForm.
Here is the link to the property documentation: http://www.yiiframework.com/doc/api/1.1/CActiveForm#action-detail
So the form widget in the view should be something like:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'message-_messagesend-form',
'enableAjaxValidation'=>false,
'action' => array( '/message/messageSend' ), // change depending on your project
)); ?>
You can also achieve this by editing the submit button in the view page like this:
<?php echo CHtml::button('Send', array('submit' => array('message/messageSend')));?>
Related
I am working on a small project in which users create accounts in it and then they can add projects, edit projects, see projects. When user adds projects his/her id (available in the session) is also added into the project table. I want to add projects using dynamic codeigniter form. When the create_project_view is loaded and the user is logged in the form is visible on the page, but when I click for its source code on the source code the form is not visible, however if user logs out the form is visible on screen as well as on the source code. I don't know why the form is not visible on the source code. and this could be the possible reason the I am not able to add data as there is no form though shown on the page. and this could also be the reason that when I click on the submit button and I am logged in, it logs me out.
I was using PHP version:7.2.1, but then downgraded to PHP version:5.6.3 still I have that problems. Could you please help me in this issue?
Below I am sharing my code and the screenshots in both condition when user is logged in and logged out
screenshot when user is logged in:
1- (View) Index.php
Here is a button code which takes me to the (create) controller
<h1>Projects</h1>
<table class="table table-hover">
<thead class="bg-warning">
<a class="btn btn-primary pull-right" href="<?php echo base_url();?>projects/create">Create Project</a><br>
<tr>
<th>Project Name</th>
<th>Project Created</th>
</tr>
</thead>
<tbody>
<?php foreach($projects as $project): ?>
<tr>
<?php echo"<td><a href='".base_url()."projects/display/".$project->id."'>".$project->project_name."</a></td>" ?>
<?php echo"<td>".$project->created_date."</td>" ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
2-(Controller) projects.php :
which contains the 'create' project function
class Projects extends CI_Controller
{
public function create()
{
$this->form_validation->set_rules('project_name','Project
Name','trim|required');
$this->form_validation->set_rules('project_body','Project
Body','trim|required');
if($this->form_validation->run()==false)
{
$data['main_view']="projects/create_project_view";
$this->load->view('Layouts/main',$data);
}
else
{
$user_data= array(
'user_project_id' =>$this->session->userdata('user_id'),
'project_name' =>$this->input->post('project_name'),
'project_body' =>$this->input->post('project_body'));
if($this->project_model->create_project($user_data))
{redirect("projects/index");}
}
}
}
?>
3- (Modal) porject_model.php
<?php
class project_model extends CI_Model
{
public function create_project($data)
{
$insert_query=$this->db->insert('projects', $data);
return $insert_query;
}
}
?>
4. (View): Create_project_view.php:
Through this form I send data to "projects" controller
<h1>Registration Form</h1>
<?php $attributes=array('Id'=>'reg_form','class'=>'form-vertical');?>
<?php echo form_open('projects/create',$attributes);?>
<div class="form-group">
<?php echo form_label('Project title:'); ?>
<?php $data=array(
'Name'=>'project_name',
'class'=>'form-control',
'placeholder'=>'Enter Your First Name:');?>
<?php echo form_input($data); ?>
</div>
<div class="form-group">
<?php echo form_label('project body:'); ?>
<?php $data=array(
'Name' =>'project_body',
'class' =>'form-control',
'placeholder' =>'Enter Your User Name:');?>
<?php echo form_textarea($data); ?>
</div>
<div class="form-group">
<?php $data=array(
'Name'=>'reg_button',
'class'=>'btn btn-primary',
'value'=>'Register');?>
<?php echo form_submit($data); ?>
</div>
<?php echo form_close(); ?>
You may have two forms in the same page that are conflicting. If you have your logout function inside a form (which is not necessary, you can make it a direct link by giving onClick event to your button), your "Submit" action of creating a project may trigger that action, instead of its own. It looks that's why you are logging out.
Otherwise, I can see no other issues in your forms. As you develop more applications, you will adopt a better structure and that way, you won't get into traps like this.
Jamshid Hashimi's answer was correct. I am just sharing the code here so others may also benefit and don't get into similar trap as I got into. Actually the problem was in other view called (login_view) which I had not post it. I had two forms in one page. I opened the first page and then without closing the first form I opened the second form. On line 10th I commented the line I forgot.
<!--When user is logged in -->
<?php if($this->session->userdata('loged_in')): ?>
<h2>Logout</h2>
<?php echo"You are loged in as " . $this->session->userdata('user_name');?>
<?php echo form_open('users/logout');?>
<?php $data=array(
'name'=>'lgout',
'class'=>'btn btn-primary',
'value'=>'Log out');?>
<?php echo form_submit($data); ?>
<?php echo form_close(); ?> **<!--I forgot this line -->**
<?php else: ?>
<!--When user is not logged in -->
<h2>login</h2>
<?php $attributes=array('id'=>'regform','class'=>'form-horizontal'); ?>
<?php if($this->session->flashdata('errors')): ?>
<?php echo $this->session->flashdata('errors'); ?>
<?php endif; ?>
<!--form starts here-->
<?php echo form_open('users/login',$attributes); ?>
<div class="form-group">
<?php echo form_label('User Name:');?>
<?php $data=array(
'name'=>'username',
'class'=>'form-control',
'placeholder'=>'Enter Your Name'); ?>
<?php echo form_input($data); ?>
</div>
<div class="form-group">
<?php echo form_label('User Password:');?>
<?php $data=array(
'name'=>'userpass',
'class'=>'form-control',
'placeholder'=>'Enter Your Name'); ?>
<?php echo form_password($data); ?>
</div>
<div class="form-group">
<?php $data=array(
'name'=>'sbmt',
'class'=>'btn btn-primary',
'value'=>'Login'); ?>
<?php echo form_submit($data); ?>
</div>
<?php echo form_close(); ?> <!--form ends here-->
In a Yii project passed to me, there's a function that creates (or shows?) a textbox when the button/link Comment is clicked. From there, the user can create Comments, which will be displayed in a row.
I'm trying to see if I can create an edit comment function, so I thought I could go about this by copying the Comment function - it'll show a textbox, and the user can input the new text in there. And instead of adding a new comment, it will edit the existing one.
But I hit a snag, as apparently the view.php makes use of a variable that I couldn't for the life of me figure out how to use in _comments.php - the file responsible for displaying the individual comments, afaik.
Here's the code for view.php:
</script>
<?php
$this->breadcrumbs=array('Forums'=>array('index'),$model->title,);
?>
<?php
if(Yii::app()->user->hasFlash('message')):
echo '<script>alert("'.Yii::app()->user->getFlash('message').'");</script>';
endif;
?>
<?php $starter = Persons::model()->findByAttributes(array('party_id'=>$model->party_id));?>
<div id="forum_main_box">
<div class="comment-icon-textbox">
<?php echo CHtml::ajaxLink('Comment',array('forum/callcommentform'),
array(
'update' => '#render_div'.$model->id,
'data'=>array('id'=>$model->id),
)); ?>
</div>
<?php endif; ?>
<div id="forum_comment_headerbox">
</div>
<div>
<?php
$this->widget('zii.widgets.CListView',
array(
'dataProvider'=>$dataProvider,
'itemView'=>'_comments',
'summaryText'=>'',
));
?>
<div id="render_div<?=$model->id?>" class="comment-form">
</div>
</div>
</div>
Of that code, below is the Comment link I spoke of:
<?php echo CHtml::ajaxLink('Comment',array('forum/callcommentform'),
array(
'update' => '#render_div'.$model->id,
'data'=>array('id'=>$model->id),
)); ?>
<?php } ?>
This block displays the list of comments, and what (I assume to be) the space where the textbox will pop up when the above Comment is clicked:
<?php
$this->widget('zii.widgets.CListView',
array(
'dataProvider'=>$dataProvider,
'itemView'=>'_comments',
'summaryText'=>'',
));
?>
<div id="render_div<?=$model->id?>" class="comment-form">
</div>
Notice that both makes use of $model. It first appeared in the code as $model->title.
And here's a shortened version of the _comments.php, which is used for the comment rows and the comment box.
<?php $comment = $data; ?>
<div class="other-member-comment-box">
<?php $person=Persons::model()->findByAttributes(array('party_id'=>$comment->party_id)); ?>
<?php
$country=Lookup_codes::model()->findByAttributes(array('id'=>$person->country));
$location = empty($country) ? '' : ' - '.$country->name;
// $model->title;
?>
<?php if (Yii::app()->user->id == $person->party_id || Yii::app()->partyroles->isAdmin()) {
?>
<p class="admin-commands">
<?php echo CHtml::link(CHtml::encode('Edit'),array('forum/editcomment','reply'=>$data->id,'topic'=>$data->content_id)); ?>
<?php echo CHtml::ajaxLink('EditTestComment',array('forum/callcommentform'),array('update' => '#render_div'.$model->id,'data'=>array('id'=>$model->content_id),)); ?>
<?php echo CHtml::link(CHtml::encode('Delete'),array('forum/delete','reply'=>$data->id,'topic'=>$data->content_id),array('confirm'=>'Are you sure you want to delete this item?')); ?>
<div id="render_div<?=$model->id?>" class="comment-form">
</div>
</p>
<?php } ?>
</div>
Under <p class="admin-commands">, there's a EditTestComment link which is a straight up copy of the Comment code from the view.php. This doesn't work, of course, because of this:
2016/04/07 10:24:03 [error] [php] Undefined variable: model
Where'd $model come from in view.php? Because putting in the same line ($model->title) anywhere in _comments.php just breaks it further.
EDIT: Here's the CallComment part of the controller:
public function actionCallCommentForm($id='')
{
$topic=Forum::model()->findByPk($id);
$this->renderPartial('_commentform', array(
'forum'=>$topic,
'model'=>new Comment,
//'view'=>array('view','id'=>$id),
'view'=>'view',
));
}
$model variable is coming from your controller initially. It is an instance of a Comment class which gets passed to the view via $this->render('view', array('model'=>$whatever)). This line will make $whatever available in the forum/view.php file under the name of $model. Now since you are dealing with partial views you have to track it because it is possible that the same $model variable will be passed to another partial view with $this->renderPartial('_comment', array('whatever'=>$model)) and now this will be accessible in partial view as $whatever.
I would like to avoid redirecting after error validation.
I display a list of post and for each post the user can give a comment after clicking on a button.
This display the comment form under the choosen post.
If there is an error in validation of the comment I want to stay on the page and display errors beside the field in error (as default).
Here is My controller action for the comment
public function actionCreate()
{
$model=new Comment;
if(isset($_POST['Comment']))
{
$model->attributes=$_POST['Comment'];
if($model->save()) {
$this->redirect(Yii::app()->request->urlReferrer);
} else {
Yii::app()->end();
}
}
$this->render('create',array(
'model'=>$model,
));
}
and the view
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'enableClientValidation'=>true,
)); ?>
<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,'comment'); ?>
<?php echo $form->textField($model,'comment',array('size'=>60,'maxlength'=>140)); ?>
<?php echo $form->error($model,'comment'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
For the moment, with Yii::app()->end(); it shows a blank page, if I dont do nothing in the else part , then it continues and displays the create view (loosing some decoration)
---Adding some more information
Actually, what I have in my page is this
Post 1
(Comment form)
Commment : ........
Save
Post 2
Post 3
when I click on save without comment, I want to stay in this page, giving the user the possibility to see where the error is (comment is missing) and save it again.
Can you tell me where is my mistake?
Thank you for your help
in the else block you have to tell yii to render the same page again. After calling $model->save() you get errors back in the model. So before Yii::app()->end(); call rendering of your page $this->render('create',array('model'=>$model,));
I have a problem with captcha in my YII project. I included a captcha in popup form. It's showing correctly, but there's a problem with the validation. The validation is true sometimes, if we entered the correct word in first attempt, the validation says it is wrong, after generating another code the validation succeeds. Why?
In model-> rules:
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=> 'signup')
In controller -> calling the signup form via renderPartial
$this->renderPartial('signUp',array('model'=>$model),false,true);
In view :
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'sign-up-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
-----------------------
-----------------------
<?php if(CCaptcha::checkRequirements()): ?>
<?php echo $form->labelEx($model, 'verifyCode', array('for'=>'User_security_code')); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode',array('class'=>'txt-style width-289')); ?>
Please enter the letters as they are shown in the image above. Letters are not case-sensitive.
<?php echo $form->error($model,'verifyCode',array('class'=>'error_msg')); ?>
<?php endif; ?>
i added this in view
<?php
Yii::app()->clientScript->registerScript(
'initCaptcha',
'$("#yw0_button").trigger("click");',
CClientScript::POS_READY);
?>
and in
`CCaptchaAction.php` updated `$testLimit = 0;` //for unlimted test`
and the problem solved. I'm not sure about this is the right way, but for my current scenario it helped.
i have already the comment form bellow my post view , but the problem is that it can not be store the data by comment form to the database which is bellow post view.
My code for comment form....
<h5>Add your Comment</h5>
<?php if(Yii::app()->user->hasFlash('commentSubmitted')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('commentSubmitted'); ?>
<?php else: ?>
<?php $comment= new Comment();
$this->renderPartial('/comment/_form',array('model'=>$comment,
)); ?>
and my code of _form is
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'enableAjaxValidation'=>true,
)); ?>
<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,'content'); ?>
<?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'content'); ?>
</div>
i want to store data from the comment form which is in the post view.
I'm not 100% sure what you are asking here, but I think you are asking how to save the data from the form submit? In you controller, in the action that renders the comment form, use:
$model = new Comment;
if(isset($_POST['Comment'])){
$model->attributes=$_POST['Comment'];
$model->save();
}
You should check out the gii tool (http://yiitutorials.net/easy/using-yiis-gii-tool), it will help you generate your models, forms and action to save the form data. Hope that answered your question, apologies if it didn't!
On the downloaded source code you can find blog demo, and it has great example howto use comments :D