PUT /admin/categories/:id
767699
def admin_update
      return unless user_is_allowed('categories', 'edit')
      
      # Define category and initialize response
      category = Category.find(params[:id])
      response = { attributes: Hash.new }
      
      # Iterate over params and update relevant attributes
      params.each do |key, value|
        case key
        when 'name' then category.name = value
        when 'slug' then category.slug = value
        when 'status' then category.status = value
        when 'image' then category.image = value
        end
      end
      
      # Try and save category
      response[:success] = category.save
      
      # If an image is passed, return the url
      response[:attributes][:image] = { value: category.image.url(:medium) } if params[:image]
      
      # Respond to update request
      render :json => response
    end
318605
def admin_add_to_category
      return if !user_is_allowed('products', 'edit')
      cat_id = params[:category_id]
      product_id = params[:id]
      
      if !CategoryMembership.exists?(:category_id => cat_id, :product_id => product_id)
        CategoryMembership.create(:category_id => cat_id, :product_id => product_id)
      end    
      render :json => true
    end
717733
def add_category(self, category):
        
        self._categories = self._ensure_append(category, self._categories)
15067
def new
      @categories = Category.discussions
      @category = Category.find(params[:cat]) if params[:cat]
      @discussion = Discussion.new
      @discussion.category_id = @category.id if @category
      @discussion.posts.build
      respond_with(@discussion)
    end
1358807
public function ManageCategories() {
      // Check permission
      $this->Permission('Garden.Settings.Manage');
      
      $this->AddSideMenu('vanilla/settings/managecategories');
      
      // Nested sortable always breaks when we update jQuery so we give it it's own old version of jquery.
      $this->RemoveJsFile('jquery.js');
      $this->AddJsFile('js/library/nestedSortable.1.3.4/jquery-1.7.2.min.js', '', array('Sort' => 0));
      
      $this->AddJsFile('categories.js');
      $this->AddJsFile('js/library/jquery.alphanumeric.js');
      $this->AddJsFile('js/library/nestedSortable.1.3.4/jquery-ui-1.8.11.custom.min.js');
      $this->AddJsFile('js/library/nestedSortable.1.3.4/jquery.ui.nestedSortable.js');
      $this->Title(T('Categories'));
      
      // Get category data
      $this->SetData('CategoryData', $this->CategoryModel->GetAll('TreeLeft'), TRUE);
      
      // Enable/Disable Categories
      if (Gdn::Session()->ValidateTransientKey(GetValue(1, $this->RequestArgs))) {
         $Toggle = GetValue(0, $this->RequestArgs, '');
         if ($Toggle == 'enable') {
            SaveToConfig('Vanilla.Categories.Use', TRUE);
         } else if ($Toggle == 'disable') {
            SaveToConfig('Vanilla.Categories.Use', FALSE);
         }
         Redirect('vanilla/settings/managecategories');
      }
      
      // Setup & save forms
      $Validation = new Gdn_Validation();
      $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
      $ConfigurationModel->SetField(array(
         'Vanilla.Categories.MaxDisplayDepth',
         'Vanilla.Categories.DoHeadings',
         'Vanilla.Categories.HideModule'
      ));
      
      // Set the model on the form.
      $this->Form->SetModel($ConfigurationModel);
      
      // Define MaxDepthOptions
      $DepthData = array();
      $DepthData['2'] = sprintf(T('more than %s deep'), Plural(1, '%s level', '%s levels'));
      $DepthData['3'] = sprintf(T('more than %s deep'), Plural(2, '%s level', '%s levels'));
      $DepthData['4'] = sprintf(T('more than %s deep'), Plural(3, '%s level', '%s levels')) ;
      $DepthData['0'] = T('never');
      $this->SetData('MaxDepthData', $DepthData);
      
      // If seeing the form for the first time...
      if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Apply the config settings to the form.
         $this->Form->SetData($ConfigurationModel->Data);
      } else {
         if ($this->Form->Save() !== FALSE)
            $this->InformMessage(T("Your settings have been saved."));
      }
      
      // Render default view
      $this->Render();
   }
874501
protected function setCategory($category_id)
    {
        $options = array(
            'category_id' => $category_id,
            'language' => $this->langcode,
            'store_id' => $this->store_id
        );

        $this->data_category = $this->category->get($options);

        if (empty($this->data_category['status'])) {
            $this->outputHttpStatus(404);
        }

        $this->prepareCategory($this->data_category);
    }
607834
public function EditCategory($CategoryID = '') {
      // Check permission
      $this->Permission('Garden.Settings.Manage');
      
      // Set up models
      $RoleModel = new RoleModel();
      $PermissionModel = Gdn::PermissionModel();
      $this->Form->SetModel($this->CategoryModel);
      
      if (!$CategoryID && $this->Form->IsPostBack()) {
         if ($ID = $this->Form->GetFormValue('CategoryID'))
            $CategoryID = $ID;
      }
      
      // Get category data
      $this->Category = $this->CategoryModel->GetID($CategoryID);
      $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID;
      
      // Set up head
      $this->AddJsFile('jquery.alphanumeric.js');
      $this->AddJsFile('categories.js');
      $this->AddJsFile('jquery.gardencheckboxgrid.js');
      $this->Title(T('Edit Category'));
         
      $this->AddSideMenu('vanilla/settings/managecategories');
      
      // Make sure the form knows which item we are editing.
      $this->Form->AddHidden('CategoryID', $CategoryID);
      $this->SetData('CategoryID', $CategoryID);
      
      // Load all roles with editable permissions
      $this->RoleArray = $RoleModel->GetArray();
      
      $this->FireEvent('AddEditCategory');
      
      if ($this->Form->IsPostBack() == FALSE) {
         $this->Form->SetData($this->Category);
         $this->Form->SetValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID);
      } else {
         $Upload = new Gdn_Upload();
         $TmpImage = $Upload->ValidateUpload('PhotoUpload', FALSE);
         if ($TmpImage) {
            
            // Generate the target image name
            $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS);
            $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);

            // Save the uploaded image
            $Parts = $Upload->SaveAs(
               $TmpImage,
               $ImageBaseName
            );
            $this->Form->SetFormValue('Photo', $Parts['SaveName']);
         }
         $this->Form->SetFormValue('CustomPoints', (bool)$this->Form->GetFormValue('CustomPoints'));
         
         if ($this->Form->Save()) {
            $Category = CategoryModel::Categories($CategoryID);
            $this->SetData('Category', $Category);
            
            if ($this->DeliveryType() == DELIVERY_TYPE_ALL)
               Redirect('vanilla/settings/managecategories');
         }
      }
       
      // Get all of the currently selected role/permission combinations for this junction.
      $Permissions = $PermissionModel->GetJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions));
      $Permissions = $PermissionModel->UnpivotPermissions($Permissions, TRUE);
      
      if ($this->DeliveryType() == DELIVERY_TYPE_ALL)
         $this->SetData('PermissionData', $Permissions, TRUE);
      
      // Render default view
      $this->Render();
   }
182472
def __remove_category(self, id):
        """"""

        affected_query = """
            SELECT id
              FROM facts
             WHERE activity_id in (SELECT id FROM activities where category_id=?)
        """
        affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))]

        update = "update activities set category_id = -1 where category_id = ?"
        self.execute(update, (id, ))

        self.execute("delete from categories where id = ?", (id, ))

        self.__remove_index(affected_ids)
882360
def update
      @record = Post.find(params[:id])
      @record.additional_data(params[:additional_data]) if defined?(params[:additional_data]) && !params[:additional_data].blank?
      @record.deal_with_cover(params[:has_cover_image])
      respond_to do |format|

        if @record.update_attributes(post_params)

          # assigns and unassigns categories and tags to an individual posts
          Post.deal_with_categories @record, params[:category_ids], params[:tag_ids], true
          format.html { redirect_to edit_admin_article_path(@record), notice: I18n.t("controllers.admin.articles.update.flash.success") }

        else
          format.html {
            # add breadcrumb and set title
            add_breadcrumb I18n.t("controllers.admin.articles.edit.breadcrumb")
            @action = 'update'
            flash[:error] = I18n.t('generic.validation.no_passed')
            render action: "edit"
          }
        end

      end
    end
173878
public function addCategoryToAllowedRoots($categoryId)
    {
        if (null === ($roots = $this->getUserAllowedRoots())) {
            return;
        }

        $categoryId = (int) $categoryId;
        $user = $this->getUser();

        /** @var StringUtil $stringUtil */
        $stringUtil = $this->framework->getAdapter(StringUtil::class);

        // Add the permissions on group level
        if ('custom' !== $user->inherit) {
            $groups = $this->db->fetchAll('SELECT id, newscategories, newscategories_roots FROM tl_user_group WHERE id IN('.\implode(',', \array_map('intval', $user->groups)).')');

            foreach ($groups as $group) {
                $permissions = $stringUtil->deserialize($group['newscategories'], true);

                if (\in_array('manage', $permissions, true)) {
                    $categoryIds = $stringUtil->deserialize($group['newscategories_roots'], true);
                    $categoryIds[] = $categoryId;

                    $this->db->update('tl_user_group', ['newscategories_roots' => \serialize($categoryIds)], ['id' => $group['id']]);
                }
            }
        }

        // Add the permissions on user level
        if ('group' !== $user->inherit) {
            $userData = $this->db->fetchAssoc('SELECT newscategories, newscategories_roots FROM tl_user WHERE id=?', [$user->id]);
            $permissions = $stringUtil->deserialize($userData['newscategories'], true);

            if (\in_array('manage', $permissions, true)) {
                $categoryIds = $stringUtil->deserialize($userData['newscategories_roots'], true);
                $categoryIds[] = $categoryId;

                $this->db->update('tl_user', ['newscategories_roots' => \serialize($categoryIds)], ['id' => $user->id]);
            }
        }

        // Add the new element to the user object
        $user->newscategories_roots = \array_merge($roots, [$categoryId]);
    }
1004442
protected function addCategoryGroup()
    {
        if (!$this->isError()) {
            $id = $this->category_group->add($this->getSubmitted());
            if (empty($id)) {
                $this->errorAndExit($this->text('Unexpected result'));
            }
            $this->line($id);
        }
    }
876395
def serialize_categories
      serialized = {}
      categories.each do |category|
        serialized[category.id] = category.serialize_base
      end
      serialized
    end
951963
public function insert_course_category($courseid) {
        $this->courseid    = $courseid;
        $this->fullname    = '?';
        $this->path        = null;
        $this->parent      = null;
        $this->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;

        $this->apply_default_settings();
        $this->apply_forced_settings();

        $this->timecreated = $this->timemodified = time();

        if (!parent::insert('system')) {
            debugging("Could not insert this category: " . print_r($this, true));
            return false;
        }

        // build path and depth
        $this->update('system');

        return $this->id;
    }
763453
def update
      @article = Article.find(params[:id])
      if @article.update_attributes(params[:article])
        flash[:notice] = 'Article was successfully updated.'
      else
        @categories = Category.articles
      end
      respond_with(:admin, @article)
    end
284107
def new_category(blog_id, username, password, category_struct):
    
    authenticate(username, password, 'zinnia.add_category')
    category_dict = {'title': category_struct['name'],
                     'description': category_struct['description'],
                     'slug': category_struct['slug']}
    if int(category_struct['parent_id']):
        category_dict['parent'] = Category.objects.get(
            pk=category_struct['parent_id'])
    category = Category.objects.create(**category_dict)

    return category.pk
95260
public function setCategoryId($categoryId = '')
    {
        $this->categoryId = $categoryId;
        $this->logger->info(__FUNCTION__, 'setCategoryId: ' . $this->categoryId);
    }
883143
public function addCategory($category)
    {
        if (!($category instanceof Category)) {
            $category = new Category($category);
        }
        $this->categories[] = $category;
    }