Posts Tagged with yii

Displaying 41-50 of 110 results.
Resolved: Yii 1: Uncaught TypeError: jQuery(...).yiiactiveform is not a function
posted by admin on October 10, 2016
In form pages I have got an error like this

Yii 1: Uncaught TypeError: jQuery(...).yiiactiveform is not a function

Form:

<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
...
<?php $this->endWidget(); ?>

head:

...
<?php Yii::app()->clientScript->registerScriptFile(app::baseUrl(false, "/js/", "jquery-1.9.1.min.js"), CClientScript::POS_HEAD);?>
...

Warning:
app::baseUrl(false, "/js/", "jquery-1.9.1.min.js") - it is my function and class, repace it by Yii baseURL propertyRead more
Wiki: Yii 1: Как задавать стили css (class, id) для CMenu, пунктов меню и ссылок в менюwiki
posted by admin on October 10, 2016
Часто хочется задать свои стили css, своё оформление для меню CMenu. Это сводится к добавлению классов и идентификаторов id в html (виджет Cmenu формирует ненумерованный список <ul>, <li>;). В Yii для этих целей предусмотрены htmlOptions, itemOptions, and linkOptions.
1. Добавление названий id и class к CMenu.
Используются id и htmlOptions для добавления своих идентификаторов и классов.

//in your view
$this->widget('zii.widgets.CMenu', array(
'id'=>'myMenu',
'items'=>$this->myMenu,
'htmlOptions'=>array('class'=>'span-24 last'),
'encodeLabel'=>false, // чтобы можно было в label использовать html-теги (жирность, наклон, цвет и т.д.)
));

Это сформирует следующий html:

<ul class="span-24 last" id="myMenu">
...
</ul>

2. Добавление названий классов (class names) к пунктам CMenu (CMenu items) и ссылкам в пунктах меню (CMenu item links).
Используем itemOptions и linkOptions. Например:

//in your controller
$this->myMenu = array(
'id'=>'myMenu',
'items'=>array(
array(
'label'=>'Home',
'url'=>array('site/index'),
'itemOptions'=>array('class'=>'visited'),
'linkOptions'=>array('class'=>'bar'),
),
array('label'=>'Sign Out', 'url'=>array('site/signout')),
),
);

Эти команды позволят Yii сгенерировать следующий кусочек меню:

...
<ul id="myMenu">
<li class="visited">
<a class="bar" href="/site/index">Home</a>
</li>
...

Установив таким образом идентификаторы и классы в шаблоне html, далее расписывайте в файле стилей .css соответствующее оформление для них.Read more
Wiki: Yii 1.1 Minimizing Script Files by clientScript - scriptMap. CGoogleApi - initwiki
posted by admin on October 6, 2016
Complex pages often need to include many external JavaScript and CSS files. Because each file would cause one extra round trip to the server and back, we should minimize the number of script files by merging them into fewer ones. We should also consider reducing the size of each script file to reduce the network transmission time. There are many tools around to help on these two aspects.

For a page generated by Yii, chances are that some script files are rendered by components that we do not want to modify (e.g. Yii core components, third-party components). In order to minimizing these script files, we need two steps.

First, we declare the scripts to be minimized by configuring the scriptMap property of the clientScript application component. This can be done either in the application configuration or in code. For example,

$cs=Yii::app()->clientScript;
$cs->scriptMap=array(
'jquery.js'=>'/js/all.js',
'jquery.ajaxqueue.js'=>'/js/all.js',
'jquery.metadata.js'=>'/js/all.js',
......
);

What the above code does is that it maps those JavaScript files to the URL /js/all.js. If any of these JavaScript files need to be included by some components, Yii will include the URL (once) instead of the individual script files.

Second, we need to use some tools to merge (and perhaps compress) the JavaScript files into a single one and save it as js/all.js.

The same trick also applies to CSS files.

We can also improve page loading speed with the help of Google AJAX Libraries API. For example, we can include jquery.js from Google servers instead of our own server. To do so, we first configure the scriptMap as follows,

$cs=Yii::app()->clientScript;
$cs->scriptMap=array(
'jquery.js'=>false,
'jquery.ajaxqueue.js'=>false,
'jquery.metadata.js'=>false,
......
);

By mapping these script files to false, we prevent Yii from generating the code to include these files. Instead, we write the following code in our pages to explicitly include the script files from Google,

<head>
<?php echo CGoogleApi::init(); ?>

<?php echo CHtml::script(
CGoogleApi::load('jquery','1.3.2') . "\n" .
CGoogleApi::load('jquery.ajaxqueue.js') . "\n" .
CGoogleApi::load('jquery.metadata.js')
); ?>
......
</head>
Read more
Resolved: Yii cactiverecord not saving model
posted by admin on September 6, 2016
My model:

<?php

/**
* This is the model class for table "tbl_test".
*
* The followings are the available columns in table 'tbl_test':
* @property integer $id
* @property string $name
* @property integer $status_id
*
* The followings are the available model relations:
* @property TblQuestion[] $tblQuestions
* @property TblStatus $status
*/
class Test extends CActiveRecord
{
public $status_list;
public $status_listdata;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_test';
}

/**
* @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('name, status_id', 'required'),
//array('status_id', 'numerical', 'integerOnly'=>true),
array('name', 'length', 'max'=>255),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, status_id', '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(
'question' => array(self::HAS_MANY, 'Question', 'test_id'),
'status' => array(self::BELONGS_TO, 'Status', 'status_id'),
);
}

/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Name',
'status_id' => 'Status',
);
}

/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.

$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('status_id',$this->status_id);

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

/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Test the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}

public function __construct() {
$this->status_list = Status::model()->findAll();
$this->status_listdata = CHtml::listData($this->status_list,'id','name');
}
}


My Controller actionCreate:

public function actionCreate()
{
$model=new Test;

if($model->save()){
$this->redirect(array('view','id'=>$model->id));
}else{
die("asd");
}// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);

if(isset($_POST['Test']))
{
$model->attributes=$_POST['Test'];

}

$this->render('create',array(
'model'=>$model,
));
}
Read more
Resolved: Yii 1.1 ‪Sitemap systems. Auto Generate sitemap.xml
posted by admin on August 12, 2016
I want to generate my SITEMAP.XML by controller, action, and view systems, without using any website service, which generating XML file.
I have pages, posts, and other links.
In database for example
1. tbl_pages
2. tbl_postsRead more
Resolved: Yii beforeDelete function not working
posted by admin on June 3, 2016

class Buku extends CActiveRecord
{
..
..
protected function beforedelete() {
if(parent::beforeDelete()) {
// to do
}
}
}
Read more
Resolved: Yii 1.1 dataProvider total items count
posted by admin on May 22, 2016
In controller:

$dataProvider = new CActiveDataProvider('Media');
$this->render('tag', array(
'dataProvider' => $dataProvider,
));


In view I want to get total count of $dataProviderRead more
Resolved: Yii redirect from model
posted by admin on May 22, 2016
In model I try use redirect, but it is not working

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

It working only from controller. I want to redirect from modelRead more
Resolved: Yii get renderpartial and store in value
posted by admin on May 22, 2016
I want to store renderpartial, and dont want to echo

<?php $this->renderPartial($view, $data); ?>

It echo content automatically.
I want to store it like

<?php
$value = "my value";
$value .= $this->renderPartial($view, $data);
?>
Read more
Wiki: Yii 1.1: How to work with flash messageswiki
posted by admin on May 22, 2016
Summary
Set your messages in a controller:

Yii::app()->user->setFlash('success', "Data1 saved!");
Yii::app()->user->setFlash('error', "Data2 failed!");
Yii::app()->user->setFlash('notice', "Data3 ignored.");

Display them in your view:

<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>

Setting flash messages
A flash message is used in order to keep a message in session through one or several requests of the same user. By default, it is removed from session after it has been displayed to the user. Flash messages are usually used in combination with HTTP redirections, because in this case there is no view, so messages can only be displayed in the request that follows redirection.

A flash message has a name and a content (AKA key and value). It is an entry of an associative array. The name is a string: often "notice", "success", or "error", but it can be anything. The content is usually a string. You can put HTML tags in your message if you display it raw. You can also set the message value to a number or an array: it will be serialized and kept in session like a string.

Flash messages can be set using the setFlash() Method of CWebUser. For example, if you would like to inform the user that his changes were successfully saved, you could add the following line to your Controller:

<?php
Yii::app()->user->setFlash('success', "Data saved!");
$this->redirect(array('thing/view', 'id' => 1));

In this example we used the key 'success'. If you want to define more than one flash messages, you will have to use different keys.
Displaying flash messages
To check for flash messages we use the hasFlash() Method and to obtain the flash message we use the getFlash() Method. Since Yii v1.1.3, there is also a method getFlashes() to fetch all the messages.

By default, fetching a message deletes it from the session. This means that a message is meant to be displayed only on the first page served to the user. The fetching methods have a boolean parameter that can change this behavior. See the API links in the previous paragraph.

Displaying statically
So showing of the flash message defined above in a view is done by

<?php if(Yii::app()->user->hasFlash('success')):?>
<div class="info">
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>

These few lines of code will make a flash message with the key "success" visible to the user within a div of class "info". The message will be displayed until this or another page is (re)loaded in the browser.

If you want to always display all the flash messages, then you should add a block to your layout (by default protected/views/layout/main.php). Here is a more elaborate example:

<?php
$flashMessages = Yii::app()->user->getFlashes();
if ($flashMessages) {
echo '<ul class="flashes">';
foreach($flashMessages as $key => $message) {
echo '<li><div class="flash-' . $key . '">' . $message . "</div></li>\n";
}
echo '</ul>';
}
?>

The default CSS created by the Yii script yiic webapp has directives for three classes of flash messages on a div tag: flash-error, flash-notice, flash-success.

The best way to know if some flash messages are set is to check if Yii::app()->user->getFlashes() is empty. Since v1.1.7, Yii keeps an associative array of the flash keys in the form array("key1" => 0, ...), or null if not flash message is set. You can fetch this with Yii::app()->user->getState(CWebUser::FLASH_COUNTERS) but this is not recommended, as Yii could change this internal process.

Displaying dynamically (with Javascript)
If you want the flash message to appear somewhere above the content and then automatically fade out after a few seconds, you will have to add the following lines to your view:

<?php
Yii::app()->clientScript->registerScript(
'myHideEffect',
'$(".info").animate({opacity: 1.0}, 3000).fadeOut("slow");',
CClientScript::POS_READY
);
?>

With these lines of code we register a piece of jQuery (already included with YII) javascript code, using 'myHideEffect' as ID. It will be inserted in the jQuery's ready function (CClientScript::POS_READY). Due to the chainablity of jQuery the little script will run two effects on the .info DIV sequentially:

.animate({opacity: 1.0}, 3000)

Normally this would animate the .info DIV to a full opacity within 3 seconds. But the DIV is already rendered with full opacity upon page load, so calling this effect will just cause a delay for 3 seconds.

.fadeOut("slow")

This is the fadeOut effect which will hide the .info DIV at slow speed.Read more