I am using Yii Framework.
Purpose: Get user input and insert data into Order and OrderDetail tables on one form. The problem is data is inserted only into the Order table. I have tried to follow the wiki tutorial, but I can't fix this problem.
Why can't I insert data into both tables, Order and OrderDetail?
I have five models:
Customers(customer_id, customer_name, phone, email, lat, lng, ...)
Products(product_id, product_name,price, ...)
Order(order_id,customer_id, order_status, staff_id, ...)
OrderDetail(order_detail_id, order_id,product_id, qty, ...)
Staff(staff_id, staff_name, ...)
OrderController.php
public function actionCreate()
{
$model=new Order;
$orderdetail=new OrderDetail();
$product=new Products();
$date=date('y-m-d');
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation(array($model,$orderdetail));
if(isset($_POST['Order']))
{
$model->attributes=$_POST['Order'];
$model->lat='12.53';
$model->lng='13.2';
$model->completed_date=$date;
$model->received_date=$date;
$model->created_date=$date;
$model->upated_date=$date;
if($model->save())
if(isset($_POST['OrderDetail'])){
$orderdetail->attributes=$_POST['OrderDetail'];
$orderdetail->order_id= $model->order_id;
$orderdetail->order_item_status=1;
$orderdetail->created_date=$date;
$orderdetail->updated_date=$date;
if($orderdetail->save())
$this->redirect(array('view','id'=>$model->order_id));
}
//$OrderDetailController=new OrderDetail();
//$this->redirect(array('OrderDetail/create'));
}
$this->render('create',array(
'model'=>$model,
'orderdetail'=>$orderdetail,
'product'=>$product,
));
}
views/order/create.php
<?php
$this->breadcrumbs=array(
'Orders'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List Order', 'url'=>array('index')),
array('label'=>'Manage Order', 'url'=>array('admin')),
);
?>
<h1>Create Order</h1>
<?php echo $this->renderPartial('_form', array('model'=>$model,'orderdetail'=>$orderdetail,'product'=>$product)); ?>
views/order/_form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'order-form',
'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,'customer_id'); ?>
<?php //echo $form->textField($model,'customer_id'); ?>
<?php echo $form->dropDownList($model,'customer_id',CHtml::listData(Customers::model()->findAll(),'customer_id','fullname'),
array('empty' => '--- Choose---')); ?>
<?php echo $form->error($model,'customer_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'order_status'); ?>
<?php echo $form->textField($model,'order_status'); ?>
<?php //echo $form->dropDownList($model,'order_id', array(1=>'Pending', 2=>'Processing',3=>'Completed'));?>
<?php echo $form->error($model,'order_status'); ?>
</div>
<?php /*?>
<div class="row">
<?php echo $form->labelEx($model,'lat'); ?>
<?php echo $form->textField($model,'lat'); ?>
<?php echo $form->error($model,'lat'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lng'); ?>
<?php echo $form->textField($model,'lng'); ?>
<?php echo $form->error($model,'lng'); ?>
</div>
<?php */?>
<div class="row">
<?php echo $form->labelEx($model,'address'); ?>
<?php echo $form->textField($model,'address',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx(Products::model(),'product_id'); ?>
<?php //echo $form->textField($model,'product_id'); ?>
<?php echo $form->dropDownList(Products::model(),'product_id',CHtml::listData(Products::model()->findAll(),'product_id','product_name'),
array('empty' => '--- Choose---')); ?>
<?php echo $form->error(Products::model(),'product_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx(OrderDetail::model(),'qty'); ?>
<?php echo $form->textField(OrderDetail::model(),'qty'); ?>
<?php echo $form->error(OrderDetail::model(),'qty'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'received_date'); ?>
<?php echo $form->textField($model,'received_date'); ?>
<?php echo $form->error($model,'received_date'); ?>
</div>
<?php /*?>
<div class="row">
<?php echo $form->labelEx($model,'completed_date'); ?>
<?php echo $form->textField($model,'completed_date'); ?>
<?php echo $form->error($model,'completed_date'); ?>
</div>
<?php */?>
<div class="row">
<?php echo $form->labelEx($model,'staff_id'); ?>
<?php //echo $form->textField($model,'staff_id'); ?>
<?php echo $form->dropDownList($model,'staff_id',CHtml::listData(Staff::model()->findAll(),'staff_id','fullname'),
array('empty' => '--- Choose---')); ?>
<?php echo $form->error($model,'staff_id'); ?>
</div>
<?php /*?>
<div class="row">
<?php echo $form->labelEx($model,'created_date'); ?>
<?php echo $form->textField($model,'created_date'); ?>
<?php echo $form->error($model,'created_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'upated_date'); ?>
<?php echo $form->textField($model,'upated_date'); ?>
<?php echo $form->error($model,'upated_date'); ?>
</div>
<?php */?>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
A form which handles two models... Create a form which has all the attributes for the two models and then in the view when the form is posted and valid save the attributes into two the models.
if(isset($_POST['ModelOneAndModelTwoForm']))
{
$form->attributes=$_POST['ModelOneAndModelTwoForm'];
if($form->validate())
{
$modelOne = new ModelOne();
$modelOne->save();
$modelTwo = new ModelTwo();
$modelTwo->save();
}
}
Related
I am able to send simple email to receiver.Now i have to be able to select a email format from existing different formats and this template must appear in my message box.i should also be able to change the content of the template that appears in message box before sending to receiver.How to do this?
My code for view form
<div class="form wide">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'mail-form',
'enableAjaxValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data'), // ADD THIS
)); ?>
<div class="row col2">
<?php echo $form->labelEx($model,'email_from'); ?>
<?php echo $form->textField($model,'email_from',array('size'=>50,'maxlength'=>50,'readonly'=>'readonly')); ?>
<?php echo $form->error($model,'email_from'); ?>
</div>
<div class="row col2">
<?php echo $form->labelEx($model,'email_to'); ?>
<?php echo $form->textField($model,'email_to',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'email_to'); ?>
</div>
<div style="clear:both"></div>
<div class="row col2">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>250)); ?>
<?php echo $form->error($model,'subject'); ?>
</div>
<div style="clear:both"></div>
<div class="row col2">
<?php echo $form->labelEx($model,'message'); ?>
<?php echo $form->textArea($model,'message',array('style'=>'width: 680px; height: 300px;')); ?>
<?php echo $form->error($model,'message'); ?>
</div>
<div style="clear:both"></div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord ? 'Send' : 'Send',array('class' => 'btn'));
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Try below code:
public function actionContact() {
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$status = Yii::$app->mailer->compose()
->setTo($model->email_to)
->setFrom([$model->email_from => $model->email_from])
->setSubject($model->subject)
->setTextBody($model->message)
->send();
if ($status) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
You can also create a email_template directory under views folder and create template file in which you can set email template content.
you can use js or ajax to do the same.
1: Use jQuery:
I assume that you are using jQuery. So use ajax.
.......JS Cod........
/*I assume that you have your template data in an attribute like data-template-data=""*/
$('#select_template_id').chang(function(){
template=$(this).attr('data-template-data');
$('#template_edit_box').val(template);
});
I have used ajaxSubmitButton in my form.On click of button i am trying to open dialog When i click the button ,the dialog opens and it displays entire code written for that form . How to resolve this?
my code for button is :
<div class="btnalign" style="margin-top: 20px;margin-left:20px;">
<?=CHtml::ajaxSubmitButton('Mail to Client', Yii::app()->createUrl('reply/composeMail'),
array('type'=>'POST',
'data'=> 'js:{"data1":callData()}',
//'success' => 'function(response){afterSubmitForm(response);}'
'success'=>'js:function(string){ alert(string);$.fn.yiiGridView.update("my-grid"); }'
),
array('class' => 'btn btn-primary'));
?>
</div>
my controller code:
public function actionComposeMail()
{
if(Yii::app()->request->isAjaxRequest){
print_r($_POST['data1']);
if(isset($_POST['data1'])){
$model=new Reply;
$model->scenario = 'compose';
EQuickDlgs::render('_compose',array(
'model'=>$model,
));
}else{
echo "Please select row to Mail.";
}
}
else
{
echo "The request is invalid.";
}
}
my dialog form code is:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'reply-form',
'enableAjaxValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.For multiple recipients please seperate by comma</p>
<?php echo $form->errorSummary($model); ?>
<div class="row col2">
<?php echo $form->labelEx($model,'email_from'); ?>
<?php echo $form->textField($model,'email_from',array('size'=>50,'maxlength'=>50,'readonly'=>'readonly')); ?>
<?php echo $form->error($model,'email_from'); ?>
</div>
<div class="row col2">
<?php echo $form->labelEx($model,'email_to'); ?>
<?php echo $form->textField($model,'email_to',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'email_to'); ?>
</div>
<div style="clear:both"></div>
<div class="row col2">
<?php echo $form->labelEx($model,'email_cc'); ?>
<?php echo $form->textField($model,'email_cc',array('size'=>60,'maxlength'=>250)); ?>
<?php echo $form->error($model,'email_cc'); ?>
</div>
<div class="row col2">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>250)); ?>
<?php echo $form->error($model,'subject'); ?>
</div>
<div style="clear:both"></div>
<div class="row">
<?php echo $form->labelEx($model,'message'); ?>
<?php echo $form->textArea($model,'message',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'message'); ?>
</div>
<div style="clear:both"></div>
<div style="clear:both"></div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Send' : 'Send',array('class' => 'btn')); ?>
</div>
<?php $this->endWidget(); ?>
Image of dialog
You must use renderPartial() instead of render() and try to call Yii::app()->end() at the end in your mail form view
public function actionComposeMail()
{
if(Yii::app()->request->isAjaxRequest){
print_r($_POST['data1']);
if(isset($_POST['data1'])){
$model=new Reply;
$model->scenario = 'compose';
$this->renderPartial('_compose',array(
'model'=>$model,
));
}else{
echo "Please select row to Mail.";
}
}
else
{
echo "The request is invalid.";
}
}
I've went through this tutorial http://www.yiiframework.com/wiki/561/ajax-login-form-with-validation-errors-inside-jquery-modal-dialog/ It appears to be functioning properly, but instead of the form being in the modal dialog, it just renders it right on the page like zii.widgets.jui.CJuiDialog isn't even there.
<?php $this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'login-dialog',
'options'=>array(
'title'=>'Login',
'autoOpen'=>false,
),
));?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user_login_form',
'enableAjaxValidation'=>false,
'enableClientValidation'=>true,
'method' => 'POST',
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
)); ?>
<h1>
Login</h1>
<p>
Please fill out the following form with your login credentials:</p>
<p class="note">
Fields with <span class="required">*</span> are required.</p>
<div id="login-error-div" class="errorMessage" style="display: none;">
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array("onfocus"=>"$('#login-error- div').hide();")); ?>
<?php //echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array("onfocus"=>"$('#login-error- div').hide();")); ?>
<?php //echo $form->error($model,'password'); ?>
<p class="hint">
Hint: You may login with <tt>demo/demo</tt>.
</p>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
<div class="row submit">
<?php echo CHtml::ajaxSubmitButton(
'Sign In',
array('/site/login.GetLogin'),
array(
'beforeSend' => 'function(){
$("#login").attr("disabled",true);
}',
'complete' => 'function(){
$("#user_login_form").each(function(){ this.reset();});
$("#login").attr("disabled",false);
}',
'success'=>'function(data){
var obj = jQuery.parseJSON(data);
// View login errors!
// alert(data);
if(obj.login == "success"){
$("#user_login_form").html("<h4>
Login Successful! Please Wait...</h4>
");
parent.location.href = "/";
}
else{
$("#login-error-div").show();
$("#login-error-div").html("Login failed! Try again.");$("#login-error-div").append("
");
}
}'
),
array("id"=>"login","class" => "btn btn-primary")
); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<!-- form -->
<?php $this->endWidget('zii.widgets.jui.CJuiDialog'); ?>
Its suppose to render like this above so when i click the link below it opens
echo CHtml::link('Login', array('/site/login.GetLogin'), array('onclick'=>'$("#login-dialog").dialog("open"); return false;'));
Its built in a widget, if you have a look at the tutorial. Here's the complete widget
<?php
class loginProvider extends CWidget{
public static function actions(){
return array(
'GetLogin'=>'application.components.actions.getLogin',
);
}
public function run(){
$this->renderContent();
}
protected function renderContent(){
echo '<span style="float:right;">';
if(Yii::app()->user->isGuest){
echo CHtml::link('Login', array('/site/login.GetLogin'), array('onclick'=>'$("#login-dialog").dialog("open"); return false;'));
echo '</span>';
$this->getController()- >renderPartial('application.components.views.login',array('model'=>new LoginForm));
}
else
echo CHtml::link('Logout ('.Yii::app()->user->name.')', array('site/logout'), array('visible'=>!Yii::app()->user->isGuest));
echo '</span>';
}
}
I have created two models :User and UserProfile , Now I want display in some fields of UserProfile in User view (_form) , on create action in user table I have done this :
public function actionCreate() {
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$user_form= new TblUser;
$profile_form = new TblUserProfile;
if(isset($_POST['user_form'], $_POST['profile_form'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['user_form'];
$profile_form->attributes=$_POST['profile_form'];
// validate BOTH $a and $b
$valid=$user_form->validate();
$valid=$profile_form->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$user_form->save(false);
$profile_form->save(false);
// ...redirect to another page
}
}
$this->render('create', array(
'user_form'=>$user_form,
'profile_form'=>$profile_form,
));
}
Then ,
This is my _form class of user table
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo Chtml::errorSummary($user_form,$profile_form); ?>
<div class="row">
<?php //echo $form->labelEx($model,'id'); ?>
<?php echo $form->hiddenField($user_form,'id'); ?>
<?php //echo $form->error($model,'id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user_form,'password'); ?>
<?php echo $form->passwordField($user_form,'password',array('size'=>40,'maxlength'=>40)); ?>
<?php echo $form->error($user_form,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user_form,'username'); ?>
<?php echo $form->textField($user_form,'username',array('size'=>45,'maxlength'=>45)); ?>
<?php // echo $form->error($user_form,'username'); ?>
</div>
<div class="row">
<?php //echo $form->labelEx($model,'Is_active'); ?>
<?php echo $form->HiddenField($user_form,'Is_active'); ?>
<?php //echo $form->error($model,'Is_active'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($profile_form,'user_first_name '); ?>
<?php echo $form->textField($profile_form,'user_first_name ',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($profile_form,'user_first_name '); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($user_form->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php echo CHtml::endForm(); ?>
<!-- form -->
Now , I have render both models in same view like this ,
<?php echo $this->renderPartial('_form',
array('user_form'=>$user_form,'profile_form'=>$profile_form)); ?>
Problem which I am facing after doing all this is :
Undefined variable: form
C:\wamp\www\topicoll\protected\views\tblUser\_form.php(9)
01
02
03 <?php echo CHtml::beginForm(); ?>
04
05
06
07 <p class="note">Fields with <span class="required">*</span> are required.</p>
08
09 <?php echo CHtml::errorSummary($user_form,$profile_form); ?>
10
11 <div class="row">
12 <?php //echo $form->labelEx($model,'id'); ?>
13 <?php echo $form->hiddenField($user_form,'id'); ?>
14 <?php //echo $form->error($model,'id'); ?>
15 </div>
16
17 <div class="row">
18 <?php echo $form->labelEx($user_form,'password'); ?>
19 <?php echo $form->passwordField($user_form,'password',array('size'=>40,'maxlength'=>40)); ?>
20 <?php echo $form->error($user_form,'password'); ?>
21 </div>
Please tell me what I am missing !
oh.. you are using CHtml to start a form CHtml::beginForm() and to end CHtml::endForm()
if you do so, you have to use CHtml to generate form elements as well i.e. CHtml::activeTextfield($model, 'field', array()) and CHtml::activeLabelEx($model, 'field') in all all places in your _form
other way is...
add this code instead of CHtml::beginForm().
$form=$this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>false,
'clientOptions'=>array(
),
));
and add this code in place of CHtml::endForm()
$this->endWidget();
it will fix your problem.
In your _form.php replace <?php echo CHtml::beginForm(); ?> with
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'profile-form',
'type'=>'horizontal',
'enableAjaxValidation'=>false,
)); ?>
and <?php echo CHtml::endForm(); ?> with
<?php $this->endWidget(); ?>
And in your controller change the code block
if(isset($_POST['user_form'], $_POST['profile_form'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['user_form'];
$profile_form->attributes=$_POST['profile_form'];
with
if(isset($_POST['TblUserProfile'], $_POST['TblUser'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['TblUser'];
$profile_form->attributes=$_POST['TblUserProfile'];
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'profile-form',
'type'=>'horizontal',
'enableAjaxValidation'=>false,
)); ?>
and <?php echo CHtml::endForm(); ?> with
<?php $this->endWidget(); ?>
And in your controller change the code block
if(isset($_POST['user_form'], $_POST['profile_form'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['user_form'];`enter code here`
$profile_form->attributes=$_POST['profile_form'];
with
// Post model
return array(
'categories' => array(self::MANY_MANY, 'Category', 'categories_posts(post_id, category_id)')
);
I already have the setup of tables
posts
id, title, content
categories
id, name
categories_posts
post_id, category_i
The problem I have is that I am getting an error when creating this form:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'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,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'uri'); ?>
<?php echo $form->textField($model,'uri',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'uri'); ?>
</div>
<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>
<div class="row">
<?php // echo $form->labelEx($model,'content'); ?>
<?php echo CHtml::activeDropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>
<?php // echo $form->error($model,'content'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
The error is:
Property "Post.category_id" is not defined.
I am quite confused. What should I be doing to correct this?
I use the CAdvancedArBehavior to make this easier. I wouldn't be surprised if something like this gets rolled into the Yii core eventually either:
http://www.yiiframework.com/extension/cadvancedarbehavior/
It lets you write code like this in your controller:
$model->categories = $_POST['Post']['categories'];
I use this with the more-bugggy-than-I-would-like "Relation" widget/extension. You might need to use that to get the POST variables to structure correctly, I'm not sure.
I honestly thought that Yii has something like Kohana or Cake in their AR anyway. I guess I have to manually add them.
foreach ($_POST['category_id'] as $category_id)
{
$categoryPost = new CategoryPost;
$categoryPost->category_id = $category_id;
$categoryPost->post_id = $model->id;
$categoryPost->save();
}
Use in this way:
In controller
create object for category: $modelCat= new Category;
then in
<?php echo CHtml::activeDropDownList(**$modelCat**,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>