Blog thumb image help

Hi people!

I’m new to yii framework so i need your help.

I’m working on my blog website using yii demo blog and i like to know how can i create post with thumbnail

image, this is my live site www.flametongue.com so you know what i talking about, you can see how i have thumb image for each post.

Thank you!!

Not sure if someone can write you a whole tutorial to do what you want, I suggest go through the tutorials and other learning resources and you’ll know how you can do it.

If you just want to have some image manipulation functions like resizing, cropping try the wideimage class.

Thanks.

Thank you for takeing you time to respond to my post =).

I got some work done got so close but so far at the same time uploading image with form works find, so far only problem i have is displaying image on my blog post i got name of the image instead image i dont know whats the problem, if some can help me plz =)

Table structure for table tbl_post




CREATE TABLE IF NOT EXISTS `tbl_post` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `title` varchar(128) COLLATE utf8_unicode_ci NOT NULL,

  `image` varchar(128) COLLATE utf8_unicode_ci NOT NULL,

  `content` text COLLATE utf8_unicode_ci NOT NULL,

  `tags` text COLLATE utf8_unicode_ci,

  `status` int(11) NOT NULL,

  `create_time` int(11) DEFAULT NULL,

  `update_time` int(11) DEFAULT NULL,

  `author_id` int(11) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `FK_post_author` (`author_id`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;



Model: Post.php




<?php

class Post extends CActiveRecord

{

	/**

	 * The followings are the available columns in table 'tbl_post':

	 * @var integer $id

	 * @var string $title

	 * @var string $content

	 * @var integer $status

	 * @var integer $create_time

	 * @var integer $update_time

	 * @var integer $author_id

	 */

	const STATUS_DRAFT=1;

	const STATUS_PUBLISHED=2;

	const STATUS_ARCHIVED=3;

	public $image;

	/**

	 * Returns the static model of the specified AR class.

	 * @return CActiveRecord 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 '{{post}}';

	}

	/**

	 * @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('title, content, status', 'required'),

			array('status', 'in', 'range'=>array(1,2,3)),

			array('title', 'length', 'max'=>128),

			array('image', 'file', 'types'=>'jpg, gif, png'),

			array('title, status', '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(

			'author' => array(self::BELONGS_TO, 'User', 'author_id'),

			'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'condition'=>'comments.status='.Comment::STATUS_APPROVED, 'order'=>'comments.create_time DESC'),

			'commentCount' => array(self::STAT, 'Comment', 'post_id', 'condition'=>'status='.Comment::STATUS_APPROVED),

		);

	}

	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'Id',

			'title' => 'Title',

			'content' => 'Content',

			'status' => 'Status',

			'create_time' => 'Create Time',

			'update_time' => 'Update Time',

			'author_id' => 'Author',

		);

	}

	/**

	 * @return string the URL that shows the detail of the post

	 */

	public function getUrl()

	{

		return Yii::app()->createUrl('post/view', array(

			'id'=>$this->id,

			'title'=>$this->title,

		));

	}

	/**

	 * Adds a new comment to this post.

	 * This method will set status and post_id of the comment accordingly.

	 * @param Comment the comment to be added

	 * @return boolean whether the comment is saved successfully

	 */

	public function addComment($comment)

	{

		if(Yii::app()->params['commentNeedApproval'])

			$comment->status=Comment::STATUS_PENDING;

		else

			$comment->status=Comment::STATUS_APPROVED;

		$comment->post_id=$this->id;

		return $comment->save();

	}

	/**

	 * This is invoked before the record is saved.

	 * @return boolean whether the record should be saved.

	 */

	protected function beforeSave()

	{

		if(parent::beforeSave())

		{

			if($this->isNewRecord)

			{

				$this->create_time=$this->update_time=time();

				$this->author_id=Yii::app()->user->id;

			}

			else

				$this->update_time=time();

			return true;

		}

		else

			return false;

	}

	/**

	 * This is invoked after the record is saved.

	 */

	protected function afterSave()

	{

		parent::afterSave();

	}


	/**

	 * This is invoked after the record is deleted.

	 */

	protected function afterDelete()

	{

		parent::afterDelete();

		Comment::model()->deleteAll('post_id='.$this->id);

	}

	/**

	 * Retrieves the list of posts based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the needed posts.

	 */

	public function search()

	{

		$criteria=new CDbCriteria;


		$criteria->compare('title',$this->title,true);


		$criteria->compare('status',$this->status);


		return new CActiveDataProvider('Post', array(

			'criteria'=>$criteria,

			'sort'=>array(

				'defaultOrder'=>'status, update_time DESC',

			),

		));

	}

}



Controller: PostController.php




<?php


class PostController extends Controller

{

	public $layout='column2';


	/**

	 * @var CActiveRecord the currently loaded data model instance.

	 */

	private $_model;


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}


	/**

	 * 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 access 'index' and 'view' actions.

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated users to access all actions

				'users'=>array('@'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 */

	public function actionView()

	{

		$post=$this->loadModel();

		$comment=$this->newComment($post);


		$this->render('view',array(

			'model'=>$post,

			'comment'=>$comment,

		));

	}	

	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Post;

		if(isset($_POST['Post']))

		{

			$model->attributes=$_POST['Post'];

			$model->image=CUploadedFile::getInstance($model,'image');

			if($model->save())

			    $model->image->saveAs(Yii::app()->basePath . '/../images/' . $model->image);

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}

	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionUpdate()

	{

		$model=$this->loadModel();

		if(isset($_POST['Post']))

		{

			$model->attributes=$_POST['Post'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'index' page.

	 */

	public function actionDelete()

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel()->delete();


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(array('index'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}

 	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$criteria=new CDbCriteria(array(

			'condition'=>'status='.Post::STATUS_PUBLISHED,

			'order'=>'create_time DESC',

			'with'=>'commentCount',

		));

		if(isset($_GET['tag']))

			$criteria->addSearchCondition('tags',$_GET['tag']);


		$dataProvider=new CActiveDataProvider('Post', array(

			'pagination'=>array(

				'pageSize'=>Yii::app()->params['postsPerPage'],

			),

			'criteria'=>$criteria,

		));


		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Post('search');

		if(isset($_GET['Post']))

			$model->attributes=$_GET['Post'];

		$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.

	 */

	public function loadModel()

	{

		if($this->_model===null)

		{

			if(isset($_GET['id']))

			{

				if(Yii::app()->user->isGuest)

					$condition='status='.Post::STATUS_PUBLISHED.' OR status='.Post::STATUS_ARCHIVED;

				else

					$condition='';

				$this->_model=Post::model()->findByPk($_GET['id'], $condition);

			}

			if($this->_model===null)

				throw new CHttpException(404,'The requested page does not exist.');

		}

		return $this->_model;

	}


	/**

	 * Creates a new comment.

	 * This method attempts to create a new comment based on the user input.

	 * If the comment is successfully created, the browser will be redirected

	 * to show the created comment.

	 * @param Post the post that the new comment belongs to

	 * @return Comment the comment instance

	 */

	protected function newComment($post)

	{

		$comment=new Comment;

		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')

		{

			echo CActiveForm::validate($comment);

			Yii::app()->end();

		}

		if(isset($_POST['Comment']))

		{

			$comment->attributes=$_POST['Comment'];

			if($post->addComment($comment))

			{

				if($comment->status==Comment::STATUS_PENDING)

					Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');

				$this->refresh();

			}

		}

		return $comment;

	}

}



Form: _form.php




<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

        'id'=>'producto-form',

        'enableAjaxValidation'=>false,

        'htmlOptions'=>array('enctype'=>'multipart/form-data'),

)); 


?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo CHtml::errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'title'); ?>

		<?php echo $form->textField($model,'title',array('size'=>80,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'title'); ?>

	</div>

        

		<div class="row">

		<?php echo CHtml::activeFileField($model, 'image'); ?>

		</div>

		

	<div class="row">

		<?php echo $form->labelEx($model,'content'); ?>

		<?php echo CHtml::activeTextArea($model,'content',array('rows'=>10, 'cols'=>70)); ?>

		<?php echo $form->error($model,'content'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'status'); ?>

		<?php echo $form->dropDownList($model,'status',Lookup::items('PostStatus')); ?>

		<?php echo $form->error($model,'status'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


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


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



View: _view.php




<div class="post">

	<div class="title">

		<?php echo CHtml::link(CHtml::encode($data->title), $data->url); ?>

	</div>

	<div class="author">

		posted by <?php echo $data->author->username . ' on ' . date('F j, Y',$data->create_time); ?>

		<?php echo CHtml::link("Comments ({$data->commentCount})",$data->url.'#comments'); ?>

	</div>

    <div class="blog-thumb">

		<?php echo CHtml::link(CHtml::encode($data->image), $data->url); ?>

	</div>

	<div class="content-post">

	    <?php

    		$this->beginWidget('application.extensions.EReadMore', array(

            'linkUrl'=>$data->url

            ));?>

        <?php

			$this->beginWidget('CMarkdown', array('purifyOutput'=>true));

			echo $data->content;

			$this->endWidget();

		?>

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

    </div>

</div>

Sorry for long post =(

Thanks!!

Hi,

Try this in your view instead (given that the “image” field in your database really holds a valid url or filename). You simply encode the $data->image property and don’t render any image in your example, so it can’t work




<div class="post">

        <div class="title">

                <?php echo CHtml::link(CHtml::encode($data->title), $data->url); ?>

        </div>

        <div class="author">

                posted by <?php echo $data->author->username . ' on ' . date('F j, Y',$data->create_time); ?>

                <?php echo CHtml::link("Comments ({$data->commentCount})",$data->url.'#comments'); ?>

        </div>

    <div class="blog-thumb">

                <?php echo CHtml::link(CHtml::image($data->image,'thumbnail'), $data->url); ?>  ///USE THIS LINE IF YOU USE FULL PATHS 

                <?php echo CHtml::link(CHtml::image((Yii::app()->request->baseUrl.'/images/'.$data->image,'thumbnail'), $data->url); ?>  ///USE THIS LINE IF YOU USE RELATIVE PATHS IN THE IMAGE DB FIELD 

        </div>

        <div class="content-post">

            <?php

                $this->beginWidget('application.extensions.EReadMore', array(

            'linkUrl'=>$data->url

            ));?>

        <?php

                        $this->beginWidget('CMarkdown', array('purifyOutput'=>true));

                        echo $data->content;

                        $this->endWidget();

                ?>

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

    </div>

</div>



Thank you so much for your help everything works fine now, i had to mod little bit and add one more bracket that was missing.

this is working _view.php




<div class="post">

	<div class="title">

		<?php echo CHtml::link(CHtml::encode($data->title), $data->url); ?>

	</div>

	<div class="author">

		posted by <?php echo $data->author->username . ' on ' . date('F j, Y',$data->create_time); ?>

		<?php echo CHtml::link("Comments ({$data->commentCount})",$data->url.'#comments'); ?>

	</div>

    <div class="blog-thumb">

		<?php echo CHtml::link(CHtml::image((Yii::app()->request->baseUrl.'./images/thumb/' .$data->image)), $data->url); ?>

	</div>

	<div class="content-post">

	    <?php

    		$this->beginWidget('application.extensions.EReadMore', array(

            'linkUrl'=>$data->url

            ));?>

        <?php

			$this->beginWidget('CMarkdown', array('purifyOutput'=>true));

			echo $data->content;

			$this->endWidget();

		?>

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

    </div>

</div>



this is how it looks like, blog with thumbnail image =)

WOW this is what im looking for as a nubie.thx all