1. Trang chủ
  2. » Công Nghệ Thông Tin

cakephp application development phần 8 ppsx

33 279 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 33
Dung lượng 3,68 MB

Nội dung

Chapter 9 [ 215 ] Adding Forms to Add New Questions and Answers With our application, we can view all the questions, we can view all the answers to a question, and we have even added a cool layout for our application. But we still cannot do a very important task. We still cannot add a new question or add a new answer. That is exactly what we are going to do in this section. We are going to add a form to the home() action that will be able to add a new question to Quickwall. And to add a new answer, we will also be adding a new form to the show() action. So, without any delay, let's go and see how to do that. Time for Action 1. Since we will be using the home() action for both displaying all the questions and also to add a new question, add the following code to the home() action of the Questions controller: function home() { if (!empty($this->data)) { $this->Question->create(); if ($this->Question->save($this->data)) { $this->Session->setFlash('Your Question has been added'); $this->redirect(array('action'=>'home'), null, true); } else { $this->Session->setFlash('The Question could not be saved. Please, try again.'); } } $this->Question->recursive = 1; $this->set('questions', $this->Question->find('all')); } 2. To display the form that will be used to add a new question, add the following code to the top of the view le of the home() action. As we already know, the view le is /quickwall/app/views/questions/home.ctp. <?php e($form->create('Question', array('action' => 'home')));?> <fieldset> <label for="QuestionQuestion" class="questionlabel"> <span>Your Question</span></label> <?php e($form->text('question', array('class' => 'fullwidth'))); ?><span class="big">?</span> <label for="QuestionQuestioner" class="questionerlabel"><spa Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Making Quickwall: The Basics [ 216 ] n>Your Name</span></label> <?php e($form->text('questioner', array('class' => 'halfwidth'))); ?> <?php e($form->submit('Post Your Question', array('div' => false, 'class' => 'submitbutton'))); ?> </fieldset> <?php e($form->end()); ?> <?php if(empty($questions)): ?> <p class="no_answer">No Questions yet. Be the first one to post a Question!</p> <?php else: ?> <dl> <?php foreach ($questions as $question): ?> <dt><span><?php e($question['Question']['questioner']); ?></span></dt> <dd> <?php e($html->link($question['Question']['question']. '?', '/questions/show/'.$question['Question']['id'])); ?> <?php $answer_count = count($question['Answer']); if(!$answer_count) e("(no answers yet)"); else if($answer_count == 1) e("(1 answer)"); else e("(".$answer_count." answers)"); ?> </dd> <?php endforeach; ?> </dl> <?php endif; ?> 3. The show() action is used to display a question and its answers. We will also be using it to add a new answer to question. Add the following code to the show() action of the Questions controller: function show($id = null) { if (!$id) { $this->Session->setFlash('Invalid Question.'); $this->redirect(array('action'=>'home')); } if (!empty($this->data)) { $this->Question->Answer->create(); if ($this->Question->Answer->save($this->data)) { Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Chapter 9 [ 217 ] $this->Session->setFlash('The Answer has been saved'); $this->redirect(array('action' => 'show', $id), null, true); } else { $this->Session->setFlash('The Answer could not be saved. Please, try again.'); } } $this->set('question', $this->Question->read(null, $id)); } 4. To display the form to add a new answer, add the following code to the view le(/quickwall/app/views/questions/show.ctp) of the show() action: <h2><?php e($question['Question']['question']) ?>?</h2> <div id="questioner"><div><span><?php e($question['Question'] ['questioner']) ?></span></div></div> <?php e($form->create('Answer', array('url' => 'show/ '.$question['Question']['id'])));?> <fieldset> <?php e($form->hidden('question_id', array('value' => $question['Question']['id']))); ?> <label for="AnswerAnswer" class="questionlabel"><span>Your Answer</span></label> <?php e($form->text('answer', array('class' => 'fullwidth'))); ?><span class="big">!</span> <label for="AnswerAnswerer" class="questionerlabel"><span> Your Name</span></label> <?php e($form->text('answerer', array('class' => 'halfwidth'))); ?> <?php e($form->submit('Post Your Answer', array('div' => false, 'class' => 'submitbutton'))); ?> </fieldset> <?php e($form->end()); ?> <?php if(empty($question['Answer'])): ?> <p class="no_answer">No Answers yet. Be the first one to answer!</p> <?php else: ?> <dl> <?php foreach($question['Answer'] as $answer) : ?> <dt><span><?php e($answer['answerer']); ?></span></dt> <dd><?php e($answer['answer']); ?></dd> <?php endforeach; ?> </dl> <?php endif; ?> Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Making Quickwall: The Basics [ 218 ] 5. Now let's add validation rules so that users cannot enter empty questions and answers. Open the Question model in your text editor, and add the following validation rules: <?php class Question extends AppModel { var $name = 'Question'; var $hasMany = array( 'Answer' => array( 'className' => 'Answer' ) ); var $validate = array( 'question' => array( 'rule' => array('minLenght', 1), 'required' => true, 'allowEmpty' => false, 'message' => 'Question cannot be empty' ), 'questioner' => array( 'rule' => array('minLenght', 1), 'required' => true, 'allowEmpty' => false, 'message' => 'Please enter your name' ) ); } ?> 6. If there are any validation errors, we should show an error message to the user. To do so, add the following code to /quickwall/app/views/ questions/home.ctp: <?php e($form->error('Question.question', null, array('class' => 'message'))); ?> <?php e($form->error('Question.questioner', null, array('class' => 'message'))); ?> <?php e($form->create('Question', array('action' => 'home')));?> <fieldset> <label for="QuestionQuestion" class="questionlabel"><span> Your Question</span></label> Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Chapter 9 [ 219 ] <?php e($form->text('question', array('class' => 'fullwidth'))); ?><span class="big">?</span> <label for="QuestionQuestioner" class="questionerlabel"> <span>Your Name</span></label> <?php e($form->text('questioner', array('class' => 'halfwidth'))); ?> <?php e($form->submit('Post Your Question', array('div' => false, 'class' => 'submitbutton'))); ?> </fieldset> <?php e($form->end()); ?> <?php if(empty($questions)): ?> <p class="no_answer">No Questions yet. Be the first one to post a Question!</p> <?php else: ?> <dl> <?php foreach ($questions as $question): ?> <dt><span><?php e($question['Question']['questioner']); ?></span></dt> <dd> <?php e($html->link($question['Question']['question']. '?', '/questions/show/'.$question['Question']['id'])); ?> <?php $answer_count = count($question['Answer']); if(!$answer_count) e("(no answers yet)"); else if($answer_count == 1) e("(1 answer)"); else e("(".$answer_count." answers)"); ?> </dd> <?php endforeach; ?> </dl> <?php endif; ?> 7. Add validation rules to the Answer model: <?php class Answer extends AppModel { var $name = 'Answer'; var $belongsTo = array( 'Question' => array( 'className' => 'Question' ) Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Making Quickwall: The Basics [ 220 ] ); var $validate = array( 'answer' => array( 'rule' => array('minLenght', 1), 'required' => true, 'allowEmpty' => false, 'message' => 'Answer cannot be empty' ), 'answerer' => array( 'rule' => array('minLenght', 1), 'required' => true, 'allowEmpty' => false, 'message' => 'Please enter your name' ) ); } ?> 8. Add similar code as step 6 to /quickwall/app/views/show.ctp, to show validation errors: <?php e($form->error('Answer.answer', null, array('class' => 'message'))); ?> <?php e($form->error('Answer.answerer', null, array('class' => 'message'))); ?> <h2><?php e($question['Question']['question']) ?>?</h2> <div id="questioner"><div><span><?php e($question['Question'] ['questioner']) ?></span></div></div> <?php e($form->create('Answer', array('url' => 'show/ '.$question['Question']['id'])));?> <fieldset> <?php e($form->hidden('question_id', array('value' => $question['Question']['id']))); ?> <label for="AnswerAnswer" class="questionlabel"><span> Your Answer</span></label> <?php e($form->text('answer', array('class' => 'fullwidth'))); ?><span class="big">!</span> <label for="AnswerAnswerer" class="questionerlabel"><span> Your Name</span></label> <?php e($form->text('answerer', array('class' => 'halfwidth'))); ?> <?php e($form->submit('Post Your Answer', array('div' => false, 'class' => 'submitbutton'))); ?> Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Chapter 9 [ 221 ] </fieldset> <?php e($form->end()); ?> <?php if(empty($question['Answer'])): ?> <p class="no_answer">No Answers yet. Be the first one to answer!</p> <?php else: ?> <dl> <?php foreach($question['Answer'] as $answer) : ?> <dt><span><?php e($answer['answerer']); ?></span></dt> <dd><?php e($answer['answer']); ?></dd> <?php endforeach; ?> </dl> <?php endif; ?> 9. Point your web browser to http://localhost/quickwall/ to see the newly created form for adding question. This is how our page should look like: Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Making Quickwall: The Basics [ 222 ] What Just Happened? In step 1 of this section, we changed the home() action of the Questions controller, to add the functionality to save a new question if submitted to it. If any data is submitted to the request, Cake will store the POST data into $this->data. So, if $this->data is not empty, the rst thing that is done is to call the create() method of the Question model. This prepares the model to save new data. Then the save() method is called and $this->data is passed to it. This saves the data into the database. If the operation is successful, a message is saved into the session, and redirected to the home() action. The message is then showed to the user. Next, in step 2, we change the view of the home() action, to add the form. This form will be used to insert new question, so it is related to the Question model. To bind the form with the Question model, we use the Form helper of CakePHP. A form is created by calling the create() function of the Form helper. Two parameters are passed to it: the name of the model to bind, and the name of the action to post the data to. Note that the action name is passed in an array; any other required parameter can be passed through this array. To create a text input that will be used to insert the question, we use the text() method of the Form helper. Two parameters are passed to it, the name of the eld that will be inserted through it, and an array that contains other options. In this case, we passed the name of the class that this text input should use for styling. Similarly, we use another call, the text() function of the Form helper to create the text input to insert the questioner. To create a submit button, we use the submit() function of the Form helper. Lastly, we call $form->end() to close the form. Similarly, in step 3 and 4, we create a form in the show() action to insert a new answer. To get a more clearer idea of what the Form helper creates, check out the source of the HTML that is generated. An important thing to understand here is how we access the Answer model. By default, a controller only loads the model that has the singular name of the controller. So, the Questions controller will load the Question model by default. But we can also access other models that are related to the loaded model. For example, since the Question model is loaded, and it has hasMany relationship with the Answer model, we can access the Answer model by the call $this->Question->Answer. Next in step 5, we add validation rules for the Question model. If no validation rules are added, users can submit the form empty, and the empty data will be saved as a new question. This is something that we do not want. To make sure the user cannot enter empty question or name, we add two validation rules to the Question model. All validation rules for a model must be added in an array named $validate. In the validation array of Question model, we add two validation rules, one for each eld: question and questioner. Both have similar rules applied. The minimum length of both must be 1, they both are required elds, and none of them can be empty. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Chapter 9 [ 223 ] The validation rule dened above will not allow to save data that will not pass the validation rule. To show the error messages, in step 6, we added two lines to the view of the action. Again, we use the Form helper to do so. The error() function of the Form helper shows the error message of a particular eld if there is any. We use this function to show an error message if an error is present. Similarly in step 7 and 8, we add validation rules for the Answers model. Summary This was the rst chapter of section C, which took us through all the effort that it takes to make a complete CakePHP application. Through out this section we saw how to enhance and build an application that we called Quickwall. We started the chapter by understanding what Quickwall is all about. After quickly setting up Cake for Quickwall, we went through the process of creating and connecting the Quickwall database with the application. We then created two models, and dened relationship between them. After that, we created the controller actions and their corresponding views. Adding custom layout was the natural next step. We saw how we can add our own layout and styles to Cake applications. We discussed the basics of how to add layouts and how views get rendered into them. Also discussed was how we can add CSS les to Cake applications. We ended the chapter, by adding forms to insert new data. The Form helper was used extensively, and we saw how it helped to bind models with forms. Adding validation rules to models were also discussed, along with how to show error messages if there is a validation error. All in all, this chapter went through the creation of a simple but functional web application. In the following chapters, we will extend this application by adding more useful functionalities to it. And, in the process, we learn how easy and quick it is to make a web application using CakePHP. Read on! Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... component is a built-in component of CakePHP that makes it very easy to authenticate users in a CakePHP application As we go along, you will find out just how Another thing to note is that we added the Auth component to the Users controller only But to make the whole application use the Auth component, we need to add the Auth component to all the controllers in the application But for the time being,... have to spend time to make sure the user authentication system is working properly It is also one of the most important aspect of any web application, because a lot of other functionalities depend on it We will see in this chapter, that adding user authentication in CakePHP, like many other stuff, is very easy and quick So without any delay, let's see the things that we are going to do in this chapter:... into the application • Remembering user with cookie Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Quickwall: User Authentication Creating the User Model and the Users Controller The first thing that we need to do is create the User model, with its corresponding users table in the database The users table will store data about each user who will sign up in our web application. .. simple version of Quickwall Though it was simple, it was a working web application that made it quite usable More importantly, it will be the base from where we can add more functionalities to it In this chapter, we are going to add user authentication to our Quickwall User authentication is something that is needed in almost all web applications And whether you like it or not, you have to spend time... confirmation message Integrating Authentication: Database and Models Now, we have a working sign-up process for our application But we have not yet created a process for logging in, authentication or logging out To have a good authentication process and to integrate the User model with the whole application, we need to make some minor changes into the database, models, controllers, and also the views This... such as to check if the username is unique, and the re-entered password is similar to the first one This section will also see the use of the Auth component The Auth component is a built-in component of CakePHP that makes the process of authenticating very simple and easy Lastly, we will configure the Cake router to make more meaningful URL for the sign-up process Time for Action 1 First, let's remove... => array( 'rule' => array('checkUnique', 'username'), 'message' => 'User name taken Use another' ) ), 'password' => array( ), 'email' => array( ) ); function checkUnique($data, $fieldName) { } } ?> 8 Next, to show the error, if there is any, we add the following line to the view of the signup action: . step 7 and 8, we add validation rules for the Answers model. Summary This was the rst chapter of section C, which took us through all the effort that it takes to make a complete CakePHP application. . application. In the following chapters, we will extend this application by adding more useful functionalities to it. And, in the process, we learn how easy and quick it is to make a web application. layout and styles to Cake applications. We discussed the basics of how to add layouts and how views get rendered into them. Also discussed was how we can add CSS les to Cake applications. We ended

Ngày đăng: 12/08/2014, 10:22

TỪ KHÓA LIÊN QUAN