예제 #1
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Book();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Book'])) {
         $authordetails = Author::model()->findByAttributes(array('author_name' => $_POST['Book']['author']));
         $publication = Publication::model()->findByAttributes(array('name' => $_POST['Book']['publisher']));
         $model->attributes = $_POST['Book'];
         if ($publication == NULL) {
             $publisher = new Publication();
             $publisher->name = $_POST['Book']['publisher'];
             $publisher->save();
             $model->publisher = $publisher->publication_id;
         } else {
             $model->publisher = $publication->publication_id;
         }
         if ($model->save()) {
             //echo count($authordetails).$authordetails->auth_id; exit;
             if ($authordetails) {
                 $model->author = $authordetails->auth_id;
                 $model->save();
             } else {
                 $author = new Author();
                 $author->author_name = $_POST['Book']['author'];
                 $author->save();
                 $model->author = $author->auth_id;
                 $model->save();
             }
             $model->status = 'C';
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
예제 #2
0
 public function testTicket2()
 {
     $obj = new Book();
     $obj->set('name', 'yes2');
     $obj->save();
     $this->assertEqual($obj->get('name'), 'yes2');
     $obj->save();
 }
예제 #3
0
 function bookInsertion($title, $ISBN, $author)
 {
     $book = new \Book(['title' => $title, 'isbn' => $ISBN]);
     $book->link('author', $author);
     $book->save();
     return $book;
 }
예제 #4
0
 public function add()
 {
     $rules = array('name' => 'required|unique:books,name', 'author' => 'required', 'date' => 'required', 'file' => 'mimes:jpeg,bmp,png');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         Session::put('msgfail', 'Invalid input.');
         return Redirect::back()->withErrors($validator)->withInput();
     } else {
         $destinationPath = '';
         $filename = '';
         if (Input::hasFile('file')) {
             $file = Input::file('file');
             $destinationPath = public_path() . '/uploads/book/';
             $filename = str_random(6) . '_' . $file->getClientOriginalName();
             $uploadSuccess = $file->move($destinationPath, $filename);
         }
         $book_save = new Book();
         $book_save->name = strip_tags(Input::get('name'));
         $book_save->author = strip_tags(Input::get('author'));
         $book_save->date = Input::get('date');
         $book_save->file = $filename;
         $book_save->save();
         Session::put('msgsuccess', 'Successfully added book.');
         return Redirect::back();
     }
 }
 public function testFormatALotOfResults()
 {
     $nbBooks = 50;
     $con = Propel::getConnection(BookPeer::DATABASE_NAME);
     Propel::disableInstancePooling();
     $book = new Book();
     for ($i = 0; $i < $nbBooks; $i++) {
         $book->clear();
         $book->setTitle('BookTest' . $i);
         $book->save($con);
     }
     $stmt = $con->query('SELECT * FROM book');
     $formatter = new PropelOnDemandFormatter();
     $formatter->init(new ModelCriteria('bookstore', 'Book'));
     $books = $formatter->format($stmt);
     $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
     $this->assertEquals($nbBooks, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
     $i = 0;
     foreach ($books as $book) {
         $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects');
         $this->assertEquals('BookTest' . $i, $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query');
         $i++;
     }
     Propel::enableInstancePooling();
 }
예제 #6
0
 /**
  * Show the form for creating a new resource.
  *
  * @return Response
  */
 public function create()
 {
     // Fetch all request data.
     $data = Input::only('title', 'genre', 'book_cover', 'book_public_state');
     // Build the validation constraint set.
     $rules = array('title' => array('required', 'min:3', 'max:100', 'unique:books'), 'genre' => array('alpha'), 'book_cover' => array('image'), 'book_public_state' => array('integer'));
     // Create a new validator instance.
     $validator = Validator::make($data, $rules);
     if ($validator->passes()) {
         $book = new Book();
         $title = Input::get('title');
         $book->title = $title;
         //  $date = new DateTime();
         //	$time = $date->format('Y-m-d-H-i-s');
         //$book->slug = $time.'-'.Str::slug($title, '-');
         $uniqid = str_shuffle(uniqid());
         $book->slug = Str::slug($title, '-') . '-' . $uniqid;
         $book->author_id = Sentry::getUser()->id;
         $book->genre = Input::get('genre');
         $book->secret_link = str_shuffle(uniqid());
         $book->public_state = Input::get('book_public_state') ? 1 : 0;
         //Book cover file handle
         /*$file = Input::file('book_cover');
         		$destinationPath = 'uploads/';
         		$extension = $file->getClientOriginalExtension(); 
         		$filename = $title.'.'.$extension;
         		Input::file('book_cover')->move($destinationPath, $filename);*/
         $book->save();
         return Redirect::to('/dashboard')->with('global_success', 'Book added successfuly!');
     }
     return Redirect::to('/dashboard')->withInput()->withErrors($validator)->with('message', 'Validation Errors!');
 }
예제 #7
0
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      PropelPDO $con
  * @return     int The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws     PropelException
  * @see        save()
  */
 protected function doSave(PropelPDO $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their coresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aCategory !== null) {
             if ($this->aCategory->isModified() || $this->aCategory->isNew()) {
                 $affectedRows += $this->aCategory->save($con);
             }
             $this->setCategory($this->aCategory);
         }
         if ($this->aBook !== null) {
             if ($this->aBook->isModified() || $this->aBook->isNew()) {
                 $affectedRows += $this->aBook->save($con);
             }
             $this->setBook($this->aBook);
         }
         if ($this->isNew()) {
             $this->modifiedColumns[] = ArticlePeer::ID;
         }
         // If this object has been modified, then save it to the database.
         if ($this->isModified()) {
             if ($this->isNew()) {
                 $pk = ArticlePeer::doInsert($this, $con);
                 $affectedRows += 1;
                 // we are assuming that there is only 1 row per doInsert() which
                 // should always be true here (even though technically
                 // BasePeer::doInsert() can insert multiple rows).
                 $this->setId($pk);
                 //[IMV] update autoincrement primary key
                 $this->setNew(false);
             } else {
                 $affectedRows += ArticlePeer::doUpdate($this, $con);
             }
             $this->resetModified();
             // [HL] After being saved an object is no longer 'modified'
         }
         if ($this->collAuthorArticles !== null) {
             foreach ($this->collAuthorArticles as $referrerFK) {
                 if (!$referrerFK->isDeleted()) {
                     $affectedRows += $referrerFK->save($con);
                 }
             }
         }
         if ($this->collAttachments !== null) {
             foreach ($this->collAttachments as $referrerFK) {
                 if (!$referrerFK->isDeleted()) {
                     $affectedRows += $referrerFK->save($con);
                 }
             }
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }
예제 #8
0
 public function createNewBook()
 {
     $book = new Book();
     $book->Titel = Input::get("titel");
     $book->User = Input::get("user_ID");
     $book->save();
     return View::make('createBook');
 }
예제 #9
0
 function bookInsertion($title, $ISBN, $author)
 {
     $book = new \Book();
     $book->title = $title;
     $book->isbn = $ISBN;
     $book->author()->associate($author);
     $book->save();
     return $book;
 }
예제 #10
0
파일: Set.php 프로젝트: alfytu/booklibrary
 /**
  * @return bool
  * @throws Exception
  */
 public function process()
 {
     $bookModel = new Book();
     if ($bookModel->load($this->data) && $bookModel->validate()) {
         $bookModel->save();
         return (array) $bookModel;
     }
     throw new Exception('Invalid data!');
 }
예제 #11
0
 function bookInsertion($title, $ISBN, $author)
 {
     $book = new \Book();
     $book->setTitle($title);
     $book->setISBN($ISBN);
     $book->setAuthor($author);
     $book->save();
     return $book;
 }
예제 #12
0
 function testUpdate()
 {
     $book_name = "Siddhartha";
     $test_book = new Book($book_name);
     $test_book->save();
     $test_book->setTitle("Peace Train");
     $test_book->update();
     $result = Book::getAll();
     $this->assertEquals($test_book, $result[0]);
 }
 function runBookInsertion($i)
 {
     $book = new Book();
     $book->title = 'Hello' . $i;
     $book->isbn = '1234';
     $book->price = $i;
     $book->author = $this->authors[array_rand($this->authors)];
     $book->save(false);
     $this->books[] = $book;
 }
예제 #14
0
 function save()
 {
     $params = $this->input->post();
     $obj = new Book();
     foreach ($params as $key => $val) {
         $obj->{$key} = $val;
     }
     $obj->save();
     echo $this->db->insert_id();
 }
 function runBookInsertion($i)
 {
     $book = new Book();
     $book->setTitle('Hello' . $i);
     $book->setAuthorId($this->authors[array_rand($this->authors)]);
     $book->setISBN('1234');
     $book->setPrice($i);
     $book->save($this->con);
     $this->books[] = $book->getId();
 }
예제 #16
0
 function testRemoveCopies()
 {
     $book_name = "Marakami";
     $new_book = new Book($book_name);
     $new_book->save();
     Copies::setCopies($new_book, 8);
     Copies::removeCopies($new_book, 5);
     $result = Copies::getCopies($new_book);
     $this->assertEquals(3, $result);
 }
 public function saveBook($book, $inputFormat = 'jsons', $outputFormat = 'dbs')
 {
     //$book = stripslashes($book);
     $newBook = new Book();
     switch ($inputFormat) {
         case 'json':
         default:
             $json_obj = json_decode($book);
             if (!isset($json_obj)) {
                 $error = new GsError(401, "Ups!!! Sorry, Book has not received properly to server. Be aware you are running an alpha version.");
                 if ($error->isDebugging()) {
                     $error->addContentElement("Recieved data", $book);
                 }
                 throw $error;
             }
             //TODO: Remove when user functionalities added
             $json_obj->userId = 0;
             $newBook->fromJson($json_obj);
             break;
     }
     if ($outputFormat == 'db') {
         // Permission check
         if (is_numeric($newBook->bookId)) {
             $this->security->checkWrite($newBook->bookId);
         } else {
             $this->security->checkCreate();
         }
         $newBook->save();
     } else {
         $controller = new ExportController();
         switch ($outputFormat) {
             case 'xls':
                 $controller->generateBook($newBook, $outputFormat);
                 break;
             case 'xlsx':
                 $controller->generateBook($newBook, $outputFormat);
                 break;
             case 'pdf':
                 $controller->generateBook($newBook, $outputFormat);
                 break;
             case 'ods':
                 $controller->generateBook($newBook, $outputFormat);
                 break;
             default:
                 $errors = $newBook->save();
                 if (!$errors) {
                     throw new Success('Book saved succesfully', "{'BookId':" . $newBook->getId() . "}");
                 } else {
                     $error = new GsError(302, "Error saving book.");
                     throw $error;
                 }
                 break;
         }
     }
 }
예제 #18
0
 public function getAdd()
 {
     $book = new Book();
     $book->name = '算法导论';
     $book->author = '张济';
     $book->press = '科学出版社';
     $book->detail = '这是一本介绍算法的书';
     $book->image_url = 'http://img5.douban.com/lpic/s1959967.jpg';
     $book->save();
     $this->layout->result = 'success';
 }
예제 #19
0
 function testGetBook()
 {
     $title = "Carrie";
     $test_book = new Book($title);
     $test_book->save();
     $book_id = $test_book->getId();
     $test_copy = new Copy($book_id);
     $test_copy->save();
     $result = $test_copy->getBook();
     $this->assertEquals($test_book, $result);
 }
예제 #20
0
 /**
  * @test
  */
 public function saveSingleWithoutSuffix()
 {
     $book = new Book();
     $book->id = 1;
     Yii::app()->language = 'sv';
     $book->title = 'Alkemisten';
     $saveResult = $book->save();
     $this->assertTrue($saveResult);
     $this->assertEquals($book->title, $book->title_sv);
     $this->assertEquals($book->title, 'Alkemisten');
     $this->assertEquals($book->title_sv, 'Alkemisten');
     Yii::app()->language = 'en';
     $book->title = 'The Alchemist';
     $saveResult = $book->save();
     $this->assertTrue($saveResult);
     $this->assertEquals($book->title, $book->title_en);
     $this->assertEquals($book->title, 'The Alchemist');
     $this->assertEquals($book->title_en, 'The Alchemist');
     $books = Book::model()->findAll();
     $this->assertEquals(1, count($books));
 }
예제 #21
0
 public function actionIndex()
 {
     $b = new Book();
     /*$b->id = 1;
             $b->title = 'Анна Каренина';
             $b->year = '1914';
             $b->author = 'Л.Н. Толстой';
     
             $b->save(false);
             */
     $b->id = false;
     $b->isNewRecord = true;
     $b->id = 3;
     $b->title = 'Это бало под Ровно';
     $b->year = '1960';
     $b->author = 'Медведев';
     $b->save(false);
     /*$arr[] = 0;
             $arr[] = 1;
             $arr[] = 2;
             $num = 'Анна каренина';
     
             //$a = Book::model()->findByPk(2);
             //$a = Book::model()->findAllByPk($arr);
             //$a = Book::model()->findAll('id<:num', array(':num' => $num));
             //$a = Book::model()->findAllByAttributes(array('id' => array(0,1,2), 'title' => array('Анна Каренина','Тихий Дон')));
             //$a = Book::model()->findBySql('SELECT title FROM book WHERE id = :num', array(':num' => $num));
             //$a = Book::model()->findAllBySql('SELECT title FROM book WHERE year = :num', array(':num' => $num));
             //$a = Book::model()->count('year = :num', array(':num' => $num));
             //$a = Book::model()->countBySql('SELECT count(title) From book WHERE year <= :num', array(':num' => $num));
             //$a = Book::model()->exists('year > :num', array(':num' => $num));
             //$a = Book::model()->updateByPk($arr, array('author' => 'М. Шолохов'));
             //$a = Book::model()->updateAll(array('author' => 'М. Шолохов'), 'author = "Шолохов"');
             //$a = Book::model()->updateAll(array('author' => 'Шолохов новый'), 'author =:author', array(':author' => "Шолохов"));
             //$a = Book::model()->deleteByPk(1);
             $a = Book::model()->deleteAll('title = :title', array(':title' => $num));
     
     
     
             if($a){
                 echo 'Есть';
             } else {
                 echo 'Нет';
             }
             */
     /*
     foreach ($a as $ar){
         echo $ar->title . "<hr />";
     }
     */
     //echo $a->title;
 }
예제 #22
0
 public static function store()
 {
     $params = filter_input_array(INPUT_POST);
     $attributes = array('name' => $params['name'], 'author' => $params['author'], 'publishyear' => $params['publishyear'], 'pages' => $params['pages'], 'description' => $params['description']);
     $book = new Book($attributes);
     $errors = $book->errors();
     if (count($errors) == 0) {
         $book->save();
         Redirect::to('/allbooks/' . $book->id, array('message' => 'Kirja on lisätty listalle!'));
     } else {
         View::make('/book/add_new.html', array('errors' => $errors, 'attributes' => $attributes));
     }
 }
 /**
  * Process the "Add a book form"
  * @return Redirect
  */
 public function postCreate()
 {
     # Instantiate the book model
     $book = new Book();
     $book->fill(Input::except('tags'));
     # Note this save happens before we enter any tags (next step)
     $book->save();
     foreach (Input::get('tags') as $tag) {
         # This enters a new row in the book_tag table
         $book->tags()->save(Tag::find($tag));
     }
     return Redirect::action('BookController@getIndex')->with('flash_message', 'Your book has been added.');
 }
 public function crudCreate()
 {
     # Instantiate the book model
     $book = new Book();
     $book->title = 'The Great Gatsby';
     $book->author = 'F. Scott Fitzgerald';
     $book->published = 1925;
     $book->cover = 'http://imagesbn.com....';
     $book->purchase_link = 'http://amazon...';
     # Magic: Eloquent
     $book->save();
     return "Added a new row";
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Book();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Book'])) {
         $model->attributes = $_POST['Book'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
예제 #26
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Book();
     $modelCustomer = new Customer();
     if ($_GET["id"] != "" && $_GET["d"] != "") {
         $model->RoomID = $_GET["id"];
         $model->Start = date("Y-m-d", $_GET["d"]);
     }
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Book'])) {
         $model->attributes = $_POST['Book'];
         // Check if the Room is booked
         if (strtotime($model->Finish) - strtotime($model->Start) > 86400) {
             // More than 1 day
             $j = (strtotime($model->Finish) - strtotime($model->Start)) / 86400;
             for ($i = 0; $i < $j; $i++) {
                 $theDate = strtotime($model->Start) + $i * 86400;
                 $criteria = new CDbCriteria();
                 $criteria->condition = "(:start BETWEEN Start AND Finish) AND RoomID = :roomid AND UserID = :userid";
                 $criteria->params = array(':start' => date("Y-m-d", $theDate), ':roomid' => $model->RoomID, ':userid' => Yii::app()->user->ID);
                 if (count(Book::model()->find($criteria)) > 0) {
                     $model->addError('Name', 'Ya existe una reserva para el rango de fechas en esta misma habitaci&oacute;n.');
                     $this->render('create', array('model' => $model, 'modelCustomer' => $modelCustomer));
                     exit;
                 }
             }
         } else {
             // One day booking
         }
         // Room is not booked then...
         // Si creamos un nuevo Customer hay que guardarlo
         if (strlen($model->CustomerID) == 0) {
             $modelCustomer->attributes = $_POST['Customer'];
             $modelCustomer->UserID = Yii::app()->user->ID;
             if ($modelCustomer->save()) {
                 $model->CustomerID = $modelCustomer->ID;
             }
         } else {
             $modelCustomer = Customer::model()->findByPK($model->CustomerID);
             $modelCustomer->attributes = $_POST['Customer'];
             $modelCustomer->UserID = Yii::app()->user->ID;
             $modelCustomer->save();
         }
         $model->SeasonID = Book::model()->getSeason($model->Start);
         if ($model->save()) {
             $this->redirect(array('update', 'id' => $model->ID));
         }
     }
     $this->render('create', array('model' => $model, 'modelCustomer' => $modelCustomer));
 }
예제 #27
0
 private function members_invite($user_list)
 {
     $user = Yii::app()->user;
     if ($this->book->n_invites <= 0) {
         $user->setFlash("error", "Сегодня вы больше не можете приглашать людей в этот перевод.");
         return false;
     }
     $U = explode(",", $user_list);
     foreach ($U as $k => $v) {
         $v = trim(mb_strtolower($v));
         if ($v == "") {
             continue;
         }
         $U[$k] = trim($v);
     }
     // Список юзеров, у которых ещё нет инвайта
     $c = new CDbCriteria(array());
     $c->addInCondition("LOWER(login)", $U);
     $c->join = "LEFT JOIN invites ON invites.book_id = '{$this->book->id}' AND invites.to_uid = t.id";
     $c->addCondition("invites.to_uid IS NULL");
     $users = User::model()->membership($this->book->id)->findAll($c);
     $sql = "INSERT INTO invites (from_uid, to_uid, book_id) VALUES ";
     $invited = "";
     $cnt = 0;
     foreach ($users as $u) {
         if ($u->membership->status == GroupMember::MEMBER || $u->membership->status == GroupMember::MODERATOR || $u->membership->status == GroupMember::BANNED) {
             continue;
         }
         if ($this->book->n_invites - $cnt <= 0) {
             break;
         }
         if ($cnt) {
             $sql .= ", ";
             $invited .= ", ";
         }
         $sql .= "('{$user->id}', '{$u->id}', '{$this->book->id}')";
         $invited .= $u->login;
         // "{$this->book->id}\n{$this->book->fullTitle}\n{$user->id}\n{$user->login}"
         $u->Notify(Notice::INVITE, $this->book);
         $cnt++;
     }
     if ($cnt) {
         $n = Yii::app()->db->createCommand($sql)->execute();
         $this->book->n_invites -= $n;
         $this->book->save(array("n_invites"));
         $user->setFlash("success", Yii::t("app", "Отправлено {n} приглашение|Отправлено {n} приглашения|Отправлено {n} приглашений", $n) . ": {$invited}");
     } else {
         $user->setFlash("error", "Ни одного приглашения не отправлено. Возможно, вы неправильно написали ники пользователей, или им уже было отправлено приглашение, или они уже участвуют в переводе.");
     }
     return true;
 }
예제 #28
0
 function testAddBook()
 {
     //Arrange
     $name = "Ben";
     $test_author = new Author($name);
     $test_author->save();
     $book_name = "Intro to Art";
     $test_book = new Book($book_name);
     $test_book->save();
     //Act
     $test_author->addBook($test_book);
     //Assert
     $this->assertEquals($test_author->getBooks(), [$test_book]);
 }
 public function testSerializeObjectWithRelations()
 {
     $author = new Author();
     $author->setFirstName('John');
     $book = new Book();
     $book->setTitle('Foo4');
     $book->setISBN('1234');
     $book->setAuthor($author);
     $book->save();
     $b = clone $book;
     $sb = serialize($b);
     $book->clearAllReferences();
     $this->assertEquals($book, unserialize($sb));
 }
예제 #30
0
 /** set up */
 public function setUp()
 {
     Registry::put($configurator = new MockConfigurator(), '__configurator');
     Registry::put(new Logger($configurator), '__logger');
     ActiveRecord::close_connection();
     $author = new Author();
     $author->name = 'Andrei Cristescu';
     $author->email = '*****@*****.**';
     $id = $author->save();
     $book = new Book();
     $book->author_id = $id;
     $book->title = 'The End is NEAR!';
     $book->save();
 }