// 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')); ?>
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);
});
Im having this weird problem that causes my model to double insert into the database when ajaxvalidation is on for my form. I dont understand why this happens, but this keeps on conflicting with my custom validation and I cannot move on. Can someone enlighten me on the problem.
Model:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('category, ppmp_id', 'numerical', 'integerOnly'=>true),
array('category','required'),
array('q1, q2, q3, q4', 'numerical'),
array('category', 'myTestUniqueMethod'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('item_id, category, q1, q2, q3, q4, ppmp_id', 'safe', 'on'=>'search'),
);
}
public function myTestUniqueMethod($attribute,$params)
{
$sql = 'SELECT *
FROM ppmp_item
WHERE ppmp_id='.$this->ppmp_id.'and category='.$this->category;
$unique = Yii::app()->db->createCommand($sql)->queryRow();
if ($unique)
{
$this->addError('category', "Category already added to PPMP");
}
}
View:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'ppmp-item-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'category'); ?>
<?php
$data=PhilgepsCategory::model()->findAll();
$data=CHtml::listData($data,'id','class_name');
echo $form->dropDownList($model,'category',$data,array('options' => array('1'=>array('selected'=>true))));
?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q1'); ?>
<?php echo $form->textField($model,'q1'); ?>
<?php echo $form->error($model,'q1'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q2'); ?>
<?php echo $form->textField($model,'q2'); ?>
<?php echo $form->error($model,'q2'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q3'); ?>
<?php echo $form->textField($model,'q3'); ?>
<?php echo $form->error($model,'q3'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q4'); ?>
<?php echo $form->textField($model,'q4'); ?>
<?php echo $form->error($model,'q4'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
Controller:
public function actionCreate($ppmp,$bal)
{
$model=new PpmpItem;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PpmpItem']))
{
$model->attributes=$_POST['PpmpItem'];
$model->ppmp_id = $ppmp;
$valid=$model->validate();
if($valid)
if($model->save())
$this->redirect(array('ppmp/view','id'=>$ppmp));
}
$this->render('create',array(
'model'=>$model,
'ppmp'=>$ppmp,
'bal'=>$bal,
));
}
The problem is that you shouldn't execute save() method when validating, because it will save when doing the ajax validation and when sending the data trough the form, so, you should do something like this:
...
...
if(isset($_POST['ajax']) && $_POST['ajax']==='ppmp-item-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$valid=$model->validate();
if($valid)
if($model->save())
...
...
This is the same that gii uses to validate using ajax.
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
i am trying to make a dropdown , but i don't want i to be visible for now , here is the code.
<div class="row">
<?php echo $form->labelEx($model,'lang_id'); ?>
<?php echo $form->dropdownlist($model,'lang_id',CHtml::listData(Lang::model()->findAll(), 'id', 'name')); ?>
<?php echo $form->error($model,'lang_id'); ?>
</div>
How do i make this type = 'hidden' or something like that ?
In other words , i want to keep the field but i don't want it to be shown.
try this..
<div class='row' style='display:none'>
Also, you can define style attribute of your dropDownList.
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))
You can try with:
<div class="row">
<?php echo $form->labelEx($model,'lang_id'); ?>
<?php echo $form->dropDownList($model,'lang_id',CHtml::listData(Lang::model()->findAll(), 'id', 'name'), array('style' => 'display: none'); ?>
<?php echo $form->error($model,'lang_id'); ?>
</div>
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();
}
}