Доброго времени суток!
Стоит задача сделать в админке добавление пунктов меню, меню должно быть многоуровневое, и привязка их к страницам.
Короче говоря что то вроде CMS подскажите как лучше это организовать, или хотя бы где почитать про это!
Заранее спасибо!
Динамическое меню
- ShalimovDE
- Сообщения: 10
- Зарегистрирован: 2014.02.14, 03:31
- Контактная информация:
Re: Динамическое меню
Сколько денег?
- ShalimovDE
- Сообщения: 10
- Зарегистрирован: 2014.02.14, 03:31
- Контактная информация:
Re: Динамическое меню
Что неужеле все такие алчные, что не можете подсказать начинающему кодеру.
Я уже понял что надо смотреть в сторону Nested Sets, но как и куда его подключать пока догнать не могу!
Плииииз, помогите!!!!
Я уже понял что надо смотреть в сторону Nested Sets, но как и куда его подключать пока догнать не могу!
Плииииз, помогите!!!!
Re: Динамическое меню
Давай конкректные вопросы, что именно не получается?
Nested Sets уже хорошо. С ним разобрались, умеете добавлять/удалять/редактировать пункты?
Самое простое для связки этого дерева с контентом - указывать тип раздела, а в модели контента прописать id раздела из дерева.
Потом при разборе урл смотреть тип раздела и водить нужный шаблон.
Nested Sets уже хорошо. С ним разобрались, умеете добавлять/удалять/редактировать пункты?
Самое простое для связки этого дерева с контентом - указывать тип раздела, а в модели контента прописать id раздела из дерева.
Потом при разборе урл смотреть тип раздела и водить нужный шаблон.
Re: Динамическое меню
Одно дело когда человек пробовал, у него не получилось и совсем другое, когда он просит рассказать ему от А до Я что и как делать, а это труд, который должен быть оплачен.ShalimovDE писал(а):Что неужеле все такие алчные, что не можете подсказать начинающему кодеру.
В твоем случае я рекомендую взять http://yupe.ru или найти в расширениях готовый модуль и не загружать голову изобретением велосипеда. Лучше явно не сделаешь, а только потеряешь время.
- ShalimovDE
- Сообщения: 10
- Зарегистрирован: 2014.02.14, 03:31
- Контактная информация:
Re: Динамическое меню
Хочется самому разобраться, как работать с behaviors, если я правильно понял, они просто расширяют модель!
У меня есть таблица
В модель добавил behaviors
Виды и контролер по умолчанию из gii
Пробую создать ошибка
У NestedSetBehavior метод ни чего не делает
Что мне теперь куда допиливать не пойму!
В контроллере пишу
Ни чего не происходит!
У меня есть таблица
Код: Выделить всё
CREATE TABLE `category` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`root` INT(10) NOT NULL,
`lft` INT(10) NOT NULL,
`rgt` INT(10) NOT NULL,
`level` SMALLINT(5) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`alias` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
INDEX `lft` (`lft`),
INDEX `rgt` (`rgt`),
INDEX `level` (`level`),
INDEX `category_gorod` (`root`),
CONSTRAINT `category_gorod` FOREIGN KEY (`root`) REFERENCES `goroda` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2;
Код: Выделить всё
<?php
/**
* This is the model class for table "category".
*
* The followings are the available columns in table 'category':
* @property integer $id
* @property integer $lft
* @property integer $rgt
* @property integer $level
* @property integer $root
* @property string $title
* @property string $alias
*
* The followings are the available model relations:
* @property Goroda $root0
*/
class Category extends CActiveRecord{
public function behaviors()
{
return array(
'nestedSetBehavior'=>array(
'class'=>'ext.NestedSetBehavior',
'hasManyRoots'=>true,
),
);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'category';
}
/**
* @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, alias', 'required'),
//array('lft, rgt, level, root', 'numerical', 'integerOnly'=>true),
array('title, alias', 'length', 'max'=>255),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
//array('id, lft, rgt, level, root, title, alias', 'safe', 'on'=>'search'),
array('title, alias', '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(
'root0' => array(self::BELONGS_TO, 'Goroda', 'root'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'lft' => 'Lft',
'rgt' => 'Rgt',
'level' => 'Level',
'root' => 'Root',
'title' => 'Title',
'alias' => 'Alias',
);
}
/**
* 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('lft',$this->lft);
$criteria->compare('rgt',$this->rgt);
$criteria->compare('level',$this->level);
$criteria->compare('root',$this->root);
$criteria->compare('title',$this->title,true);
$criteria->compare('alias',$this->alias,true);
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 Category the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Пробую создать ошибка
У NestedSetBehavior метод ни чего не делает
Код: Выделить всё
public function beforeSave($event)
{
if($this->_ignoreEvent)
return true;
else
throw new CDbException(Yii::t('yiiext','You should not use CActiveRecord::save() method when NestedSetBehavior attached.'));
}
В контроллере пишу
Код: Выделить всё
public function actionIndex()
{
$root=new Category;
$root->title='bratsk';
$root->saveNode();
$root=new Category;
$root->title='zheleznogorsk';
$root->saveNode();
$root=new Category;
$root->title='ust-ilim';
$root->saveNode();
/*
$dataProvider=new CActiveDataProvider('Category');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));*/
}