Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
beingyii

Render A Contact Form Into A View Of Another Model

Recommended Posts

I want to render comment form in the view.php of add controller

 

task is submitting comment for the particular add of things...

 

i created comment model controller and required view files

 

sql schema for comment table is--

 

CREATE TABLE IF NOT EXISTS `tbl_comment`
(
`cid` INTEGER NOT NULL AUTO_INCREMENT,
`add_id` INTEGER,
`user_id` INTEGER,
`user_name` varchar(1000),
`description` varchar(2000),
`create_time` DATETIME,
PRIMARY KEY(`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


ALTER TABLE `tbl_comment` ADD CONSTRAINT `FK_comment_add` FOREIGN KEY (`add_id`) REFERENCES `tbl_add` (`addid`) ON DELETE CASCADE ON UPDATE RESTRICT;

ALTER TABLE `tbl_comment` ADD CONSTRAINT `FK_comment_user` FOREIGN KEY (`user_id`) REFERENCES  `users` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
 

 

sql schema for add is--

 

CREATE TABLE `tbl_add` (
`username` varchar(50) NOT NULL,
`addid` int(11) NOT NULL,
`addname` varchar(100) NOT NULL,
`category` varchar(100) NOT NULL,
`description` varchar(1000) NOT NULL,
`city` varchar(50) NOT NULL,
`address` varchar(500) NOT NULL,
`mobile` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`image`  varchar(100) NOT NULL,
`price` varchar(100) NOT NULL,
`createtime` date NOT NULL DEFAULT '0000-00-00',
PRIMARY KEY(`addid`)
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 

CommentController.php

<?php

class CommentController extends Controller
{

//I Faisal Added this code.
	/**
	* @var private property containing the associated Project model instance.
	*/
	private $_add = null;
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	/**
	* Protected method to load the associated add model class
	* @add_id the primary identifier of the associated add
	* @return object the Add data model based on the primary key
	*/
	protected function loadAdd($add_id) 
	{
		//if the add property is null, create it based on input id
		if($this->_add===null)
		{
			$this->_add=Add::model()->findbyPk($add_id);
			if($this->_add===null)
			{
			throw new CHttpException(404,'The requested ADD does not exist.');
			}
		}
		return $this->_add;
	}
				
	/**
	* In-class defined filter method, configured for use in the above filters() method
	* It is called before the actionCreate() action method is run in order to ensure a 			    proper project context
	*/
	/**
	 *  added Filter class to project to filter the add so user can select     * valid projects and process its issues
	 */
	 public function filteraddContext($filterChain)
	{
		//set the project identifier based on either the GET or POST input
		//request variables, since we allow both types for our actions
		$addId = null;
		if(isset($_GET['pid']))
		$addId = $_GET['pid'];
		else
		if(isset($_POST['pid']))
		$addId = $_POST['pid'];
		$this->loadAdd($addId);
		//complete the running of other filters and execute the requested action
		$filterChain->run();
}
	
//////////////////END OF MY CODE///////////	


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
			//I Faisal Added following filter
			'addContext + create index admin', //check to ensure valid project context
		);
	}
	

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Comment;
		//I Faisal Added the project model property for the above instance of issue to assign for the perticular project
		$model->add_id = $this->_add->addid;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Comment']))
		{
			$model->attributes=$_POST['Comment'];
			$model->user_name=Yii::app()->user->name;
			$model->create_time=date("d m y G:i:s ");
			if($model->save())
				$this->redirect(array('view','id'=>$model->cid));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Comment']))
		{
			$model->attributes=$_POST['Comment'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->cid));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
	/* added to only get comment for a particular add only*/
		$dataProvider=new CActiveDataProvider('Comment', array(
'criteria'=>array(
'condition'=>'add_id=:addId',
'params'=>array(':addId'=>$this->_add->addid),
),
));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Comment('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Comment']))
			$model->attributes=$_GET['Comment'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Comment::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
}

comment/_form.php

<?php
/* @var $this CommentController */
/* @var $model Comment */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'comment-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,'add_id'); ?>
		<?php //echo $form->textField($model,'add_id'); ?>
		<?php //echo $form->error($model,'add_id'); ?>
		<?php echo $form->hiddenField($model,'add_id'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'user_id'); ?>
		<?php echo $form->textField($model,'user_id'); ?>
		<?php echo $form->error($model,'user_id'); ?>
	</div>

	<div class="row">
		<?php //echo $form->labelEx($model,'user_name'); ?>
		<?php //echo $form->textField($model,'user_name',array('size'=>60,'maxlength'=>1000)); ?>
		<?php //echo $form->error($model,'user_name'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'description'); ?>
		<?php echo $form->textArea($model,'description',array('size'=>60,'maxlength'=>2000)); ?>
		<?php echo $form->error($model,'description'); ?>
	</div>

	<div class="row">
		<?php //echo $form->labelEx($model,'create_time'); ?>
		<?php //echo $form->textField($model,'create_time'); ?>
		<?php echo $form->hiddenField($model,'create_time',array('value'=>date("d m y G:i:s "))); ?>
		<?php //echo $form->error($model,'create_time'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->

add/view.php

<?php
/* @var $this AddController */
/* @var $model Add */
$Comment = new Comment("create");
$this->breadcrumbs=array(
	'Adds'=>array('index'),
	$model->addname,
);

$this->menu=array(
	array('label'=>'List Add', 'url'=>array('index')),
	array('label'=>'Create Add', 'url'=>array('create')),
	array('label'=>'Update Add', 'url'=>array('update', 'id'=>$model->addid)),
	array('label'=>'Delete Add', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->addid),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage Add', 'url'=>array('admin')),
	array('label'=>'Create Comment', 'url'=>array('comment/create', 'pid'=>$model->addid)),
);
?>





<?php $this->widget('bootstrap.widgets.TbDetailView', array(
	'data'=>$model,
	'type'=>'condensed',
	'attributes'=>array(
		'username',
		'addname',
		'category',
		'description',
		'city',
		'address',
		'mobile',
		'email',
		'image',
		'price',
		array(
            'label'=>'imzzzage',
            'type'=>'raw',
            'value'=>CHtml::tag('img',
                array("title"=>"CollegeLogo",
                "src"=>Yii::app()->baseUrl."/images/".$model->image,
                "style"=>"height:200px")
            )
        ),
		
	),
)); 

echo CHtml::link("contact this add publisher ",array('add/contactpublisher','id'=> $model->addname));
//$this->renderPartial('/comment/create', array('model'=>$Comment));
 
?>
<br />
<h2>Comments</h2>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$commentDataProvider,
'itemView'=>'/comment/_view',
)); ?>

<?php $this->renderPartial('/comment/create',array('model'=>$Comment,)); ?>



Comment.php model code is

<?php

/**
 * This is the model class for table "tbl_comment".
 *
 * The followings are the available columns in table 'tbl_comment':
 * @property integer $cid
 * @property integer $add_id
 * @property integer $user_id
 * @property string $user_name
 * @property string $description
 * @property string $create_time
 *
 * The followings are the available model relations:
 * @property Users $user
 * @property Add $add
 */
class Comment extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Comment the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_comment';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('description', 'required'),
			array('add_id, user_id', 'numerical', 'integerOnly'=>true),
			array('user_name', 'length', 'max'=>1000),
			array('description', 'length', 'max'=>2000),
			array('create_time', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('cid, add_id, user_id, user_name, description, create_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
			'add' => array(self::BELONGS_TO, 'Add', 'add_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'cid' => 'Cid',
			'add_id' => 'Add',
			'user_id' => 'User',
			'user_name' => 'User Name',
			'description' => 'Description',
			'create_time' => 'Create Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('cid',$this->cid);
		$criteria->compare('add_id',$this->add_id);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('user_name',$this->user_name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('create_time',$this->create_time,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}

when accessing view for the add it display error Property "Comment.addname" is not defined.

 

i tried my level best but i unable to solve this problem

 

i want to display all comments for each add also at the end a comment form to submit new comments and refresh that page and display the comment..

 

i think something is going wrong in public function relations() {....} of comment model

 

please help me to solve this...

 

thanks....

Share this post


Link to post
Share on other sites

For starters, you're pretty inconsistent in your database column names. This will lead to bugs and errors. For example:

 

user_name varchar(1000),

addname varchar(100) NOT NULL,
addid int(11) NOT NULL,
add_id INTEGER,
 
But based upon your relations, you'd want to reference add.addname.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...