Advertisement
Guest User

Untitled

a guest
Jul 15th, 2017
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.38 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\controllers;
  4.  
  5. use app\models\Link;
  6. use app\models\Tag;
  7. use Yii;
  8. use yii\data\Pagination;
  9. use yii\helpers\Url;
  10. use yii\web\Controller;
  11.  
  12. class LinkController extends Controller
  13. {
  14.     public function actionCreateEdit($id)
  15.     {
  16.         $request = Yii::$app->request;
  17.  
  18.         $link = Link::find()
  19.             ->where(['id' => $id])
  20.             ->with('tags')
  21.             ->one();
  22.  
  23.         $allTags = Tag::find()->all();
  24.  
  25.         if ($link->load($request->post()) && $link->validate()) {
  26.             $givenTags = $request->getBodyParam('tags');
  27.  
  28.             $newTagNames = array_diff($givenTags, $allTags);
  29.             foreach ($newTagNames as $tagName) {
  30.                 $tag = (new Tag)->setName($tagName);
  31.                 $tag->save();
  32.                 $link->link('tags', $tag);
  33.             }
  34.  
  35.             foreach (array_diff($allTags, $link->tags) as $existedTag) {
  36.                 $link->link('tags', $existedTag);
  37.             }
  38.  
  39.             $tagsToDelete = array_diff($link->tags, $givenTags);
  40.             foreach ($tagsToDelete as $tag) {
  41.                 $link->unlink('tags', $tag, $delete = true);
  42.             }
  43.  
  44.             $link->save($runValidation = false);
  45.  
  46.             return $this->redirect(Url::to(['link/create-edit', 'id' => $link->id]));
  47.         }
  48.  
  49.         return $this->render('create_edit', compact('link', 'allTags'));
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement