Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\models;
- use Yii;
- use app\models\db\Category as CategoryModel;
- use app\helpers\Basehelp;
- use yii\helpers\ArrayHelper;
- /**
- * Category model
- */
- class Category extends CategoryModel
- {
- /**
- * Create new category item.
- * @return bool
- */
- public function createCategory() {
- if ($this->validate()) {
- $this->save();
- return true;
- }
- return false;
- }
- /**
- * Update current category
- * @return boolean
- */
- public function updateCategory() {
- if ($this->validate()) {
- $posted = Yii::$app->request->post(ucfirst($this->tableName()));
- $this->name = $posted['name'];
- $this->link = $posted['link'];
- $this->parent = $posted['parent'];
- $this->update();
- return true;
- }
- return false;
- }
- /**
- * remove Current category
- * @return bool
- */
- public function deleteCategory($id) {
- $status = false;
- $this->id = $id;
- if ($this->id > 0) {
- $categories = $this->getChildsTree();
- $status = self::deleteAll(['in', 'id', $categories]);
- }
- return $status;
- }
- /**
- * get childs list
- * @return array ids list
- */
- public function getChildsTree() {
- $childs[] = $this->id;
- while ($child = $this->getChilds()) {
- $haveChild = [];
- foreach ($child as $item) {
- $this->id = $item['id'];
- $childs[] = $item['id'];
- }
- if (sizeof($child) > 1) {
- foreach ($child as $item) {
- $haveChild = $this->getChilds($item['id']);
- if (sizeof($haveChild) > 0) {
- $this->id = $item['id'];
- }
- }
- }
- }
- return $childs;
- }
- /**
- * Get all items
- * @return array
- */
- private function getCategoryQuery() {
- return parent::find()->orderBy(['parent' => SORT_ASC])->asArray()->all();
- }
- /**
- * Get current menu
- * @return array
- */
- public function getCategory() {
- $list = $this->getCategoryQuery();
- $list = Basehelp::formatTree($list, 0);
- return $list;
- }
- /**
- * Get all menu links with format tree view
- * @return array
- */
- public function getCategorySelect() {
- $menu_list = $this->getCategoryQuery();
- $list = ArrayHelper::map($menu_list, 'id', 'name');
- $list[0] = 'Without parent';
- ksort($list);
- return $list;
- }
- /**
- * Get menu name
- * @return string
- */
- public function getCategoryName() {
- return $this->name;
- }
- /**
- * Get menu link
- * @return string
- */
- public function getCategoryLink() {
- return $this->link;
- }
- /**
- * Get menu parent
- * @return integer
- */
- public function getCategoryParent() {
- return (int)$this->parent;
- }
- /**
- * Get child category
- * @return object
- */
- public function getChilds($parent = 0) {
- if ($parent < 1) {
- $parent = $this->id;
- }
- return self::find()->where(['=', 'parent', $parent])->orderBy(['parent' => SORT_DESC])->all();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment