
Woody Allen
Blogger: aarkerio

Este artículo ha sido consultado en 2,515 ocasiones.
I am implementing a polling ajax system on CakePHP, I have two Postgresql tables:
CREATE TABLE polls (
id serial PRIMARY KEY,
question varchar(130) NOT NULL,
created timestamp(0) with time zone DEFAULT now() NOT NULL,
user_id integer NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status integer DEFAULT 0 NOT NULL -- defines if poll is published = 1 or not = 0
);
CREATE TABLE pollrows (
id serial PRIMARY KEY,
poll_id integer NOT NULL REFERENCES polls(id) ON DELETE CASCADE,
answer varchar(130) NOT NULL,
color varchar(15) DEFAULT 'green' NOT NULL,
vote integer DEFAULT 0 NOT NULL
);
Note "users" table must exist, if you don't have the table just delete the column user_id in "polls" table. Poll keeps the questions and Pollrows the answers and votes. (Is easy migrate the tables to->MySQL just use "date" instead "timestamp"). So the model Poll is:
<?php
//File: /app/models/poll.php
class Poll extends AppModel
{
public $name = 'Poll';
public $hasMany = array('Pollrow' =>
array('className' => 'Pollrow',
'conditions' => null,
'order' => 'answer',
'limit' => null,
'foreignKey' => 'poll_id',
'dependent' => true,
'exclusive' => false,
'finderQuery' => ''
)
);
}
?>
The Pollrow model:
<?php
class Pollrow extends AppModel
{
public $name = 'Pollrow';
public $belongsTo = array('Poll' =>
array('className' => 'Poll',
'conditions' => '',
'order' => '',
'foreignKey' => 'poll_id'
)
);
}
?>
I inserted manually the first poll:
INSERT INTO polls ("question", "user_id", "status") VALUES ('Who is your favourite Renaissance Artist?', 1, 1);
INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Michelangelo', 'green', 0);
INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Raphael', 'orange', 0);
INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Leonardo Davinci', 'red', 0);
INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Other', 'blue', 0);
INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'None', 'yellow', 0);
The colors column correspond to images in app/webroot/images/static/poll directory, every images is 10x10 pixels and .png (and only .png) format.
I am putting the poll inside the div add_pollrow in app/views/users/general.thtml (my homepage site defined in routes.php), this view correspond to /users/general (controller/action). Surely you have another controller/action as your home page, just set DIV add_pollrow in the view and load the model Poll on the controller.
The steps:
- Set a form with the question and the options to answer in add_pollrow div in the view app/views/users/general.thtml
- Send and add the vote to Pollrows model (table) in app/controllers/pollrows.php, method "vote()" and after this, select the new values
- Render app/views/pollrows/results.thml and set the new values of poll in add_pollrow
So we need to load the Poll model in app/controllers/users_controller.php:
loadModel('Poll');
And inside "general" method:
/********** Poll ****/
$this->Poll = new Poll; //Instantiate the model
$conditions = array("status"=>1); // only polls published
$fields = array("id", "question");
$order = "Poll.id DESC"; // the most recent poll
$limit = 1;
$this->set('poll', $this->Poll->findAll($conditions, $fields, $order, $limit, null, 2));
After set "poll" array in app/views/users/general.thtml, I process the array "poll" in this view (you will need a loading.gif image):
<div class="tiny_title">Well, the poll</div>
<div id="loading" style="display: none;">
<?php echo $html->image("static/loading.gif", array("alt"=>"Loading")); ?>
</div>
<div id="add_pollrow">
<?php
if ( !isset( $_SESSION["poll"] ) ) // the user has not voted, so, set the form
{
echo $html->formTag('#','post', array("onsubmit"=>"return false;")); // do nothing
$array = array();
echo "<p><b>" . $poll[0]['Poll']['question'] ."</b></p>";
echo $html->hiddenTag('Pollrow/poll_id', $poll[0]['Poll']['id']); // Poll_id
foreach ($poll[0]['Pollrow'] as $key=>$val)
{
$array[$val['id']] = $val['answer']; // construct id->value array
}
echo $html->radio('Pollrow/id', $array, '<br /><br />'); //print the answers
echo '<br /><br />';
echo $ajax->submit('Vote', array("url" => "/pollrows/vote",
"update"=>"add_pollrow", // add_pollrow wil be updated with app/views/pollrows/results.thtml render
"loading" => "Element.hide('add_pollrow');Element.show('loading')",
"complete" => "Element.hide('loading');Effect.Appear('add_pollrow')"
));
echo '</form>';
}
else // the user has voted, so just print the poll results
{
$total_votes = 0;
foreach ($poll[0]["Pollrow"] as $key => $val)
{
$total_votes += $val["vote"]; // the total votes
}
foreach ($poll[0]["Pollrow"] as $key => $val)
{
$percent = ($val["vote"] * 100) / $total_votes; // % = votes * 100 / total
$width = number_format($percent, 0);
echo '<p><b>'.$val['answer'].'</b> '.number_format($percent, 2).'% <br />';
echo $html->image('static/poll/'.$val["color"].'.png', array("height"=>"10", "width"=>$width,"alt"=>$val["answer"], "title"=>$val["answer"]) );
echo " ". $val['vote'];
}
echo "<p class='negrita'>Total votes:" . $total_votes . "</p>";
}
?>
</div>
Note $ajax->submit send the vote to app/controllers/pollrows/vote:
public function vote() {
// adds new vote to database
if (!empty($this->params['data']))
{
$vote = $this->Pollrow->field('vote', array("Pollrow.id" => $this->params['data']['Pollrow']['id']) );
$vote += 1;
$this->params['data']['Pollrow']['vote'] = $vote; // add vote
//die(print_r($this->params['data']));
if ( $this->Pollrow->save($this->params['data']) ) // add the Poll vote
{
$_SESSION["poll"] = true; //set session, only one vote per session
$conditions = array("Pollrow.poll_id" => $this->params['data']['Pollrow']['poll_id']);
$fields = array("Pollrow.answer", "Pollrow.color", "Pollrow.vote", "Pollrow.poll_id");
$order = "Pollrow.answer DESC";
$this->set('poll', $this->Pollrow->findAll($conditions, $fields, $order, null, null, 2));
$this->render('results', 'ajax');
}
else
{
echo "Ajax error, check with the company's computer guy...";
}
}
}
Note, after add the vote and set 'poll' array, the view app/views/pollrows/results.thtml is rendered:
<?php
//die(print_r( $poll ));
$total_votes = 0;
foreach ($poll as $key => $val)
{
$total_votes += $poll[$key]["Pollrow"]["vote"]; // the total votes
}
foreach ($poll as $key => $val)
{
$percent = ($poll[$key]["Pollrow"]["vote"] * 100) / $total_votes; // % = votes * 100 / total
$width = number_format($percent, 0);
echo '<p><b>' . $poll[$key]["Pollrow"]["answer"] . '</b> '.number_format($percent, 2).'% <br />';
echo $html->image('static/poll/'.$poll[$key]["Pollrow"]["color"].'.png',
array("height"=>"10", "width"=>$width,"alt"=>$poll[$key]["Pollrow"]["answer"], "title"=>$poll[$key]["Pollrow"]["answer"]) );
echo " ". $poll[$key]["Pollrow"]['vote'];
}
echo "<p>Total votes:" . $total_votes . "</p>";
?>
this view is settled inside add_pollrow div as we indicated in $ajax->submit.
And that is it!! You can see the Poll in action here.
aarkerio
Notice (8): Undefined index: email [APP/View/Pages/display.ctp, line 26]Code Contextecho $this->Html->div('cv');echo "Ficha del autor:<br /><span class=\"login\">".$data['User']['username'].'</span><br />';echo "<b>". str_replace('@', '_ARRROBA_', $data['User']['email'])."</b><br />".$data['User']['cv'].'<br />';$___viewFn = "/var/chipotle/sites/cakephp/centauro/View/Pages/display.ctp" $___dataForView = array( "data" => array( "Page" => array(), "User" => array(), "Section" => array(), "Discution" => array() ) ) $data = array( "Page" => array( "id" => 753, "section_id" => 26, "title" => "Ajax Poll CakePHP", "body" => " <p>I am implementing a polling ajax system on CakePHP, I have two Postgresql tables:</p><p><font color="#003366">CREATE TABLE polls (<br /> id serial PRIMARY KEY,<br /> question varchar(130) NOT NULL,<br /> created timestamp(0) with time zone DEFAULT now() NOT NULL,<br /> user_id integer NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br /> status integer DEFAULT 0 NOT NULL -- defines if poll is published = 1 or not = 0<br /> );<br /><br /> CREATE TABLE pollrows (<br /> id serial PRIMARY KEY,<br /> poll_id integer NOT NULL REFERENCES polls(id) ON DELETE CASCADE,<br /> answer varchar(130) NOT NULL,<br /> color varchar(15) DEFAULT 'green' NOT NULL,<br /> vote integer DEFAULT 0 NOT NULL<br /> );</font> <br /> </p><p>Note "users" table must exist, if you don't have the table just delete the column <em>user_id</em> in "polls" table. Poll keeps the questions and Pollrows the answers and votes. (Is easy migrate the tables to->MySQL just use "date" instead "timestamp"). So the model Poll is:<br /> </p><p><font color="#336600"><?php <br />//File: /app/models/poll.php<br />class Poll extends AppModel<br />{<br /> public $name = 'Poll';<br /> <br /> public $hasMany = array('Pollrow' =><br /> array('className' => 'Pollrow',<br /> 'conditions' => null,<br /> 'order' => 'answer',<br /> 'limit' => null,<br /> 'foreignKey' => 'poll_id',<br /> 'dependent' => true,<br /> 'exclusive' => false,<br /> 'finderQuery' => ''<br /> )<br /> );<br />}<br />?></font> <br /></p><p>The Pollrow model:</p><p><font color="#336600"><?php <br />class Pollrow extends AppModel<br />{<br /> public $name = 'Pollrow';<br /> <br /> public $belongsTo = array('Poll' =><br /> array('className' => 'Poll',<br /> 'conditions' => '',<br /> 'order' => '',<br /> 'foreignKey' => 'poll_id'<br /> )<br /> );<br />}<br />?> </font><br /></p><p>I inserted manually the first poll:</p><p>INSERT INTO polls ("question", "user_id", "status") VALUES ('Who is your favourite Renaissance Artist?', 1, 1);<br /> <br /> INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Michelangelo', 'green', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Raphael', 'orange', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Leonardo Davinci', 'red', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Other', 'blue', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'None', 'yellow', 0);<br /> </p><p>The colors column correspond to images in app/webroot/images/static/poll directory, every images is 10x10 pixels and .png (and only .png) format. </p><p>I am putting the poll inside the div <strong>add_pollrow</strong> in app/views/users/general.thtml (my homepage site defined in routes.php), this view correspond to /users/general (controller/action). Surely you have another controller/action as your home page, just set DIV <strong>add_pollrow</strong> in the view and load the model Poll on the controller.</p><p> The steps:<br /></p><ol><li>Set a form with the question and the options to answer in add_pollrow div in the view app/views/users/general.thtml</li><li>Send and add the vote to Pollrows model (table) in app/controllers/pollrows.php, method "vote()" and after this, select the new values<br /></li><li>Render app/views/pollrows/results.thml and set the new values of poll in add_pollrow<br /></li></ol><p>So we need to load the Poll model in app/controllers/users_controller.php:</p><p><strong>loadModel('Poll');</strong></p><p>And inside "general" method:</p><p> <font color="#990000"> /********** Poll ****/<br /> <br /> $this->Poll = new Poll; //Instantiate the model<br /> <br /> $conditions = array("status"=>1); // only polls published<br /> $fields = array("id", "question");<br /> $order = "Poll.id DESC"; // the most recent poll<br /> $limit = 1;<br /> <br /> $this->set('poll', $this->Poll->findAll($conditions, $fields, $order, $limit, null, 2));<br /></font><br /></p><p>After set "poll" array in app/views/users/general.thtml, I process the array "poll" in this view (you will need a <a href="http://www.ajaxload.info/">loading.gif</a> image):</p><p><font color="#990000"><div class="tiny_title">Well, the poll</div><br /><br /><div id="loading" style="display: none;"><br /> <?php echo $html->image("static/loading.gif", array("alt"=>"Loading")); ?><br /></div><br /><br /><div id="add_pollrow"><br /> <?php </font></p><p><font color="#990000"> if ( !isset( $_SESSION["poll"] ) ) // the user has not voted, so, set the form<br /> {<br /> </font><font color="#990000">echo $html->formTag('#','post', array("onsubmit"=>"return false;")); // do nothing<br /></font><br /><font color="#990000"> $array = array();<br /> <br /> echo "<p><b>" . $poll[0]['Poll']['question'] ."</b></p>";<br /> <br /> echo $html->hiddenTag('Pollrow/poll_id', $poll[0]['Poll']['id']); // Poll_id<br /> <br /> foreach ($poll[0]['Pollrow'] as $key=>$val)<br /> {<br /> $array[$val['id']] = $val['answer']; // construct id->value array<br /> }<br /> <br /> echo $html->radio('Pollrow/id', $array, '<br /><br />'); //print the answers<br /> <br /> echo '<br /><br />';<br /> <br /> echo $ajax->submit('Vote', array("url" => "/pollrows/vote", <br /> "update"=>"add_pollrow", // add_pollrow wil be updated with app/views/pollrows/results.thtml render<br /> "loading" => "Element.hide('add_pollrow');Element.show('loading')",<br /> "complete" => "Element.hide('loading');Effect.Appear('add_pollrow')"<br /> ));<br /> echo '</form>';<br /> }<br /> else // the user has voted, so just print the poll results<br /> {<br /> <br /> $total_votes = 0;<br /> <br /> foreach ($poll[0]["Pollrow"] as $key => $val) <br /> {<br /> $total_votes += $val["vote"]; // the total votes<br /> }<br /> <br /> foreach ($poll[0]["Pollrow"] as $key => $val) <br /> {<br /> $percent = ($val["vote"] * 100) / $total_votes; // % = votes * 100 / total<br /> $width = number_format($percent, 0);<br /> echo '<p><b>'.$val['answer'].'</b> '.number_format($percent, 2).'% <br />'; <br /> echo $html->image('static/poll/'.$val["color"].'.png', array("height"=>"10", "width"=>$width,"alt"=>$val["answer"], "title"=>$val["answer"]) );<br /> echo " ". $val['vote'];<br /> }<br /> <br /> echo "<p class='negrita'>Total votes:" . $total_votes . "</p>"; <br />}<br />?><br /></div></font><br /></p><p>Note $ajax->submit send the vote to app/controllers/pollrows/vote:<br /><br /> <font color="#990000"> public function vote() {<br /> // adds new vote to database<br /> if (!empty($this->params['data']))<br /> { <br /> $vote = $this->Pollrow->field('vote', array("Pollrow.id" => $this->params['data']['Pollrow']['id']) );<br /> <br /> $vote += 1;<br /> <br /> $this->params['data']['Pollrow']['vote'] = $vote; // add vote<br /> <br /> //die(print_r($this->params['data']));<br /> <br /> if ( $this->Pollrow->save($this->params['data']) ) // add the Poll vote<br /> { <br /> $_SESSION["poll"] = true; //set session, only one vote per session<br /> <br /> $conditions = array("Pollrow.poll_id" => $this->params['data']['Pollrow']['poll_id']);<br /> $fields = array("Pollrow.answer", "Pollrow.color", "Pollrow.vote", "Pollrow.poll_id");<br /> $order = "Pollrow.answer DESC";<br /> <br /> $this->set('poll', $this->Pollrow->findAll($conditions, $fields, $order, null, null, 2));<br /> <br /> $this->render('results', 'ajax');<br /> }<br /> else<br /> {<br /> echo "Ajax error, check with the company's computer guy...";<br /> }<br /> }<br /> }</font><br /> </p><p>Note, after add the vote and set 'poll' array, the view app/views/pollrows/results.thtml is rendered:</p><p><font color="#990000"><?php<br /> //die(print_r( $poll ));<br /> $total_votes = 0;<br /> <br /> foreach ($poll as $key => $val) <br /> {<br /> $total_votes += $poll[$key]["Pollrow"]["vote"]; // the total votes<br /> }<br /> <br /> foreach ($poll as $key => $val) <br /> {<br /> $percent = ($poll[$key]["Pollrow"]["vote"] * 100) / $total_votes; // % = votes * 100 / total<br /> $width = number_format($percent, 0);<br /> echo '<p><b>' . $poll[$key]["Pollrow"]["answer"] . '</b> '.number_format($percent, 2).'% <br />'; <br /> echo $html->image('static/poll/'.$poll[$key]["Pollrow"]["color"].'.png', <br /> array("height"=>"10", "width"=>$width,"alt"=>$poll[$key]["Pollrow"]["answer"], "title"=>$poll[$key]["Pollrow"]["answer"]) );<br /> echo " ". $poll[$key]["Pollrow"]['vote'];<br /> }<br /> <br /> echo "<p>Total votes:" . $total_votes . "</p>"; <br />?></font> </p><p>this view is settled inside add_pollrow div as we indicated in $ajax->submit.</p><p>And that is it!! You can see the Poll in action <a href="http://karamelo.mononeurona.org/users/general">here</a>. <br /></p>", "created" => "2007-04-29 10:57:00-05", "discution" => 1, "display" => 2, "status" => 1, "user_id" => 1, "cv" => 1, "visits" => 160, "rank" => 2515, "editor" => 1, "updated" => "2009-08-20 00:32:14-05" ), "User" => array( "id" => 1, "username" => "aarkerio", "avatar" => "aarkerio_avatar.png" ), "Section" => array( "id" => 26, "description" => "WWW", "img" => "gimp-sec.png" ), "Discution" => array( array(), array() ) )include - APP/View/Pages/display.ctp, line 26 View::_render() - CORE/Cake/View/View.php, line 598 View::render() - CORE/Cake/View/View.php, line 365 Controller::render() - CORE/Cake/Controller/Controller.php, line 900 Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 114 Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 89 [main] - APP/webroot/index.php, line 81
Notice (8): Undefined index: cv [APP/View/Pages/display.ctp, line 26]Code Contextecho $this->Html->div('cv');echo "Ficha del autor:<br /><span class=\"login\">".$data['User']['username'].'</span><br />';echo "<b>". str_replace('@', '_ARRROBA_', $data['User']['email'])."</b><br />".$data['User']['cv'].'<br />';$___viewFn = "/var/chipotle/sites/cakephp/centauro/View/Pages/display.ctp" $___dataForView = array( "data" => array( "Page" => array(), "User" => array(), "Section" => array(), "Discution" => array() ) ) $data = array( "Page" => array( "id" => 753, "section_id" => 26, "title" => "Ajax Poll CakePHP", "body" => " <p>I am implementing a polling ajax system on CakePHP, I have two Postgresql tables:</p><p><font color="#003366">CREATE TABLE polls (<br /> id serial PRIMARY KEY,<br /> question varchar(130) NOT NULL,<br /> created timestamp(0) with time zone DEFAULT now() NOT NULL,<br /> user_id integer NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br /> status integer DEFAULT 0 NOT NULL -- defines if poll is published = 1 or not = 0<br /> );<br /><br /> CREATE TABLE pollrows (<br /> id serial PRIMARY KEY,<br /> poll_id integer NOT NULL REFERENCES polls(id) ON DELETE CASCADE,<br /> answer varchar(130) NOT NULL,<br /> color varchar(15) DEFAULT 'green' NOT NULL,<br /> vote integer DEFAULT 0 NOT NULL<br /> );</font> <br /> </p><p>Note "users" table must exist, if you don't have the table just delete the column <em>user_id</em> in "polls" table. Poll keeps the questions and Pollrows the answers and votes. (Is easy migrate the tables to->MySQL just use "date" instead "timestamp"). So the model Poll is:<br /> </p><p><font color="#336600"><?php <br />//File: /app/models/poll.php<br />class Poll extends AppModel<br />{<br /> public $name = 'Poll';<br /> <br /> public $hasMany = array('Pollrow' =><br /> array('className' => 'Pollrow',<br /> 'conditions' => null,<br /> 'order' => 'answer',<br /> 'limit' => null,<br /> 'foreignKey' => 'poll_id',<br /> 'dependent' => true,<br /> 'exclusive' => false,<br /> 'finderQuery' => ''<br /> )<br /> );<br />}<br />?></font> <br /></p><p>The Pollrow model:</p><p><font color="#336600"><?php <br />class Pollrow extends AppModel<br />{<br /> public $name = 'Pollrow';<br /> <br /> public $belongsTo = array('Poll' =><br /> array('className' => 'Poll',<br /> 'conditions' => '',<br /> 'order' => '',<br /> 'foreignKey' => 'poll_id'<br /> )<br /> );<br />}<br />?> </font><br /></p><p>I inserted manually the first poll:</p><p>INSERT INTO polls ("question", "user_id", "status") VALUES ('Who is your favourite Renaissance Artist?', 1, 1);<br /> <br /> INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Michelangelo', 'green', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Raphael', 'orange', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Leonardo Davinci', 'red', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Other', 'blue', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'None', 'yellow', 0);<br /> </p><p>The colors column correspond to images in app/webroot/images/static/poll directory, every images is 10x10 pixels and .png (and only .png) format. </p><p>I am putting the poll inside the div <strong>add_pollrow</strong> in app/views/users/general.thtml (my homepage site defined in routes.php), this view correspond to /users/general (controller/action). Surely you have another controller/action as your home page, just set DIV <strong>add_pollrow</strong> in the view and load the model Poll on the controller.</p><p> The steps:<br /></p><ol><li>Set a form with the question and the options to answer in add_pollrow div in the view app/views/users/general.thtml</li><li>Send and add the vote to Pollrows model (table) in app/controllers/pollrows.php, method "vote()" and after this, select the new values<br /></li><li>Render app/views/pollrows/results.thml and set the new values of poll in add_pollrow<br /></li></ol><p>So we need to load the Poll model in app/controllers/users_controller.php:</p><p><strong>loadModel('Poll');</strong></p><p>And inside "general" method:</p><p> <font color="#990000"> /********** Poll ****/<br /> <br /> $this->Poll = new Poll; //Instantiate the model<br /> <br /> $conditions = array("status"=>1); // only polls published<br /> $fields = array("id", "question");<br /> $order = "Poll.id DESC"; // the most recent poll<br /> $limit = 1;<br /> <br /> $this->set('poll', $this->Poll->findAll($conditions, $fields, $order, $limit, null, 2));<br /></font><br /></p><p>After set "poll" array in app/views/users/general.thtml, I process the array "poll" in this view (you will need a <a href="http://www.ajaxload.info/">loading.gif</a> image):</p><p><font color="#990000"><div class="tiny_title">Well, the poll</div><br /><br /><div id="loading" style="display: none;"><br /> <?php echo $html->image("static/loading.gif", array("alt"=>"Loading")); ?><br /></div><br /><br /><div id="add_pollrow"><br /> <?php </font></p><p><font color="#990000"> if ( !isset( $_SESSION["poll"] ) ) // the user has not voted, so, set the form<br /> {<br /> </font><font color="#990000">echo $html->formTag('#','post', array("onsubmit"=>"return false;")); // do nothing<br /></font><br /><font color="#990000"> $array = array();<br /> <br /> echo "<p><b>" . $poll[0]['Poll']['question'] ."</b></p>";<br /> <br /> echo $html->hiddenTag('Pollrow/poll_id', $poll[0]['Poll']['id']); // Poll_id<br /> <br /> foreach ($poll[0]['Pollrow'] as $key=>$val)<br /> {<br /> $array[$val['id']] = $val['answer']; // construct id->value array<br /> }<br /> <br /> echo $html->radio('Pollrow/id', $array, '<br /><br />'); //print the answers<br /> <br /> echo '<br /><br />';<br /> <br /> echo $ajax->submit('Vote', array("url" => "/pollrows/vote", <br /> "update"=>"add_pollrow", // add_pollrow wil be updated with app/views/pollrows/results.thtml render<br /> "loading" => "Element.hide('add_pollrow');Element.show('loading')",<br /> "complete" => "Element.hide('loading');Effect.Appear('add_pollrow')"<br /> ));<br /> echo '</form>';<br /> }<br /> else // the user has voted, so just print the poll results<br /> {<br /> <br /> $total_votes = 0;<br /> <br /> foreach ($poll[0]["Pollrow"] as $key => $val) <br /> {<br /> $total_votes += $val["vote"]; // the total votes<br /> }<br /> <br /> foreach ($poll[0]["Pollrow"] as $key => $val) <br /> {<br /> $percent = ($val["vote"] * 100) / $total_votes; // % = votes * 100 / total<br /> $width = number_format($percent, 0);<br /> echo '<p><b>'.$val['answer'].'</b> '.number_format($percent, 2).'% <br />'; <br /> echo $html->image('static/poll/'.$val["color"].'.png', array("height"=>"10", "width"=>$width,"alt"=>$val["answer"], "title"=>$val["answer"]) );<br /> echo " ". $val['vote'];<br /> }<br /> <br /> echo "<p class='negrita'>Total votes:" . $total_votes . "</p>"; <br />}<br />?><br /></div></font><br /></p><p>Note $ajax->submit send the vote to app/controllers/pollrows/vote:<br /><br /> <font color="#990000"> public function vote() {<br /> // adds new vote to database<br /> if (!empty($this->params['data']))<br /> { <br /> $vote = $this->Pollrow->field('vote', array("Pollrow.id" => $this->params['data']['Pollrow']['id']) );<br /> <br /> $vote += 1;<br /> <br /> $this->params['data']['Pollrow']['vote'] = $vote; // add vote<br /> <br /> //die(print_r($this->params['data']));<br /> <br /> if ( $this->Pollrow->save($this->params['data']) ) // add the Poll vote<br /> { <br /> $_SESSION["poll"] = true; //set session, only one vote per session<br /> <br /> $conditions = array("Pollrow.poll_id" => $this->params['data']['Pollrow']['poll_id']);<br /> $fields = array("Pollrow.answer", "Pollrow.color", "Pollrow.vote", "Pollrow.poll_id");<br /> $order = "Pollrow.answer DESC";<br /> <br /> $this->set('poll', $this->Pollrow->findAll($conditions, $fields, $order, null, null, 2));<br /> <br /> $this->render('results', 'ajax');<br /> }<br /> else<br /> {<br /> echo "Ajax error, check with the company's computer guy...";<br /> }<br /> }<br /> }</font><br /> </p><p>Note, after add the vote and set 'poll' array, the view app/views/pollrows/results.thtml is rendered:</p><p><font color="#990000"><?php<br /> //die(print_r( $poll ));<br /> $total_votes = 0;<br /> <br /> foreach ($poll as $key => $val) <br /> {<br /> $total_votes += $poll[$key]["Pollrow"]["vote"]; // the total votes<br /> }<br /> <br /> foreach ($poll as $key => $val) <br /> {<br /> $percent = ($poll[$key]["Pollrow"]["vote"] * 100) / $total_votes; // % = votes * 100 / total<br /> $width = number_format($percent, 0);<br /> echo '<p><b>' . $poll[$key]["Pollrow"]["answer"] . '</b> '.number_format($percent, 2).'% <br />'; <br /> echo $html->image('static/poll/'.$poll[$key]["Pollrow"]["color"].'.png', <br /> array("height"=>"10", "width"=>$width,"alt"=>$poll[$key]["Pollrow"]["answer"], "title"=>$poll[$key]["Pollrow"]["answer"]) );<br /> echo " ". $poll[$key]["Pollrow"]['vote'];<br /> }<br /> <br /> echo "<p>Total votes:" . $total_votes . "</p>"; <br />?></font> </p><p>this view is settled inside add_pollrow div as we indicated in $ajax->submit.</p><p>And that is it!! You can see the Poll in action <a href="http://karamelo.mononeurona.org/users/general">here</a>. <br /></p>", "created" => "2007-04-29 10:57:00-05", "discution" => 1, "display" => 2, "status" => 1, "user_id" => 1, "cv" => 1, "visits" => 160, "rank" => 2515, "editor" => 1, "updated" => "2009-08-20 00:32:14-05" ), "User" => array( "id" => 1, "username" => "aarkerio", "avatar" => "aarkerio_avatar.png" ), "Section" => array( "id" => 26, "description" => "WWW", "img" => "gimp-sec.png" ), "Discution" => array( array(), array() ) )include - APP/View/Pages/display.ctp, line 26 View::_render() - CORE/Cake/View/View.php, line 598 View::render() - CORE/Cake/View/View.php, line 365 Controller::render() - CORE/Cake/Controller/Controller.php, line 900 Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 114 Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 89 [main] - APP/webroot/index.php, line 81
Notice (8): Undefined index: quote [APP/View/Pages/display.ctp, line 30]Code Contextecho $this->Html->link($this->Html->image('avatars/'.$data['User']['avatar'], array('class'=>'imgborder', 'alt'=>$data['User']['username'], 'title'=>$data['User']['username'])), '/blog/'.$data['User']['username'], array('escape'=>False)) . "<br />";echo '<i>'.$data['User']['quote'].'</i><br />';$___viewFn = "/var/chipotle/sites/cakephp/centauro/View/Pages/display.ctp" $___dataForView = array( "data" => array( "Page" => array(), "User" => array(), "Section" => array(), "Discution" => array() ) ) $data = array( "Page" => array( "id" => 753, "section_id" => 26, "title" => "Ajax Poll CakePHP", "body" => " <p>I am implementing a polling ajax system on CakePHP, I have two Postgresql tables:</p><p><font color="#003366">CREATE TABLE polls (<br /> id serial PRIMARY KEY,<br /> question varchar(130) NOT NULL,<br /> created timestamp(0) with time zone DEFAULT now() NOT NULL,<br /> user_id integer NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br /> status integer DEFAULT 0 NOT NULL -- defines if poll is published = 1 or not = 0<br /> );<br /><br /> CREATE TABLE pollrows (<br /> id serial PRIMARY KEY,<br /> poll_id integer NOT NULL REFERENCES polls(id) ON DELETE CASCADE,<br /> answer varchar(130) NOT NULL,<br /> color varchar(15) DEFAULT 'green' NOT NULL,<br /> vote integer DEFAULT 0 NOT NULL<br /> );</font> <br /> </p><p>Note "users" table must exist, if you don't have the table just delete the column <em>user_id</em> in "polls" table. Poll keeps the questions and Pollrows the answers and votes. (Is easy migrate the tables to->MySQL just use "date" instead "timestamp"). So the model Poll is:<br /> </p><p><font color="#336600"><?php <br />//File: /app/models/poll.php<br />class Poll extends AppModel<br />{<br /> public $name = 'Poll';<br /> <br /> public $hasMany = array('Pollrow' =><br /> array('className' => 'Pollrow',<br /> 'conditions' => null,<br /> 'order' => 'answer',<br /> 'limit' => null,<br /> 'foreignKey' => 'poll_id',<br /> 'dependent' => true,<br /> 'exclusive' => false,<br /> 'finderQuery' => ''<br /> )<br /> );<br />}<br />?></font> <br /></p><p>The Pollrow model:</p><p><font color="#336600"><?php <br />class Pollrow extends AppModel<br />{<br /> public $name = 'Pollrow';<br /> <br /> public $belongsTo = array('Poll' =><br /> array('className' => 'Poll',<br /> 'conditions' => '',<br /> 'order' => '',<br /> 'foreignKey' => 'poll_id'<br /> )<br /> );<br />}<br />?> </font><br /></p><p>I inserted manually the first poll:</p><p>INSERT INTO polls ("question", "user_id", "status") VALUES ('Who is your favourite Renaissance Artist?', 1, 1);<br /> <br /> INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Michelangelo', 'green', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Raphael', 'orange', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Leonardo Davinci', 'red', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'Other', 'blue', 0);<br />INSERT INTO pollrows ("poll_id", "answer", "color", "vote") VALUES (1, 'None', 'yellow', 0);<br /> </p><p>The colors column correspond to images in app/webroot/images/static/poll directory, every images is 10x10 pixels and .png (and only .png) format. </p><p>I am putting the poll inside the div <strong>add_pollrow</strong> in app/views/users/general.thtml (my homepage site defined in routes.php), this view correspond to /users/general (controller/action). Surely you have another controller/action as your home page, just set DIV <strong>add_pollrow</strong> in the view and load the model Poll on the controller.</p><p> The steps:<br /></p><ol><li>Set a form with the question and the options to answer in add_pollrow div in the view app/views/users/general.thtml</li><li>Send and add the vote to Pollrows model (table) in app/controllers/pollrows.php, method "vote()" and after this, select the new values<br /></li><li>Render app/views/pollrows/results.thml and set the new values of poll in add_pollrow<br /></li></ol><p>So we need to load the Poll model in app/controllers/users_controller.php:</p><p><strong>loadModel('Poll');</strong></p><p>And inside "general" method:</p><p> <font color="#990000"> /********** Poll ****/<br /> <br /> $this->Poll = new Poll; //Instantiate the model<br /> <br /> $conditions = array("status"=>1); // only polls published<br /> $fields = array("id", "question");<br /> $order = "Poll.id DESC"; // the most recent poll<br /> $limit = 1;<br /> <br /> $this->set('poll', $this->Poll->findAll($conditions, $fields, $order, $limit, null, 2));<br /></font><br /></p><p>After set "poll" array in app/views/users/general.thtml, I process the array "poll" in this view (you will need a <a href="http://www.ajaxload.info/">loading.gif</a> image):</p><p><font color="#990000"><div class="tiny_title">Well, the poll</div><br /><br /><div id="loading" style="display: none;"><br /> <?php echo $html->image("static/loading.gif", array("alt"=>"Loading")); ?><br /></div><br /><br /><div id="add_pollrow"><br /> <?php </font></p><p><font color="#990000"> if ( !isset( $_SESSION["poll"] ) ) // the user has not voted, so, set the form<br /> {<br /> </font><font color="#990000">echo $html->formTag('#','post', array("onsubmit"=>"return false;")); // do nothing<br /></font><br /><font color="#990000"> $array = array();<br /> <br /> echo "<p><b>" . $poll[0]['Poll']['question'] ."</b></p>";<br /> <br /> echo $html->hiddenTag('Pollrow/poll_id', $poll[0]['Poll']['id']); // Poll_id<br /> <br /> foreach ($poll[0]['Pollrow'] as $key=>$val)<br /> {<br /> $array[$val['id']] = $val['answer']; // construct id->value array<br /> }<br /> <br /> echo $html->radio('Pollrow/id', $array, '<br /><br />'); //print the answers<br /> <br /> echo '<br /><br />';<br /> <br /> echo $ajax->submit('Vote', array("url" => "/pollrows/vote", <br /> "update"=>"add_pollrow", // add_pollrow wil be updated with app/views/pollrows/results.thtml render<br /> "loading" => "Element.hide('add_pollrow');Element.show('loading')",<br /> "complete" => "Element.hide('loading');Effect.Appear('add_pollrow')"<br /> ));<br /> echo '</form>';<br /> }<br /> else // the user has voted, so just print the poll results<br /> {<br /> <br /> $total_votes = 0;<br /> <br /> foreach ($poll[0]["Pollrow"] as $key => $val) <br /> {<br /> $total_votes += $val["vote"]; // the total votes<br /> }<br /> <br /> foreach ($poll[0]["Pollrow"] as $key => $val) <br /> {<br /> $percent = ($val["vote"] * 100) / $total_votes; // % = votes * 100 / total<br /> $width = number_format($percent, 0);<br /> echo '<p><b>'.$val['answer'].'</b> '.number_format($percent, 2).'% <br />'; <br /> echo $html->image('static/poll/'.$val["color"].'.png', array("height"=>"10", "width"=>$width,"alt"=>$val["answer"], "title"=>$val["answer"]) );<br /> echo " ". $val['vote'];<br /> }<br /> <br /> echo "<p class='negrita'>Total votes:" . $total_votes . "</p>"; <br />}<br />?><br /></div></font><br /></p><p>Note $ajax->submit send the vote to app/controllers/pollrows/vote:<br /><br /> <font color="#990000"> public function vote() {<br /> // adds new vote to database<br /> if (!empty($this->params['data']))<br /> { <br /> $vote = $this->Pollrow->field('vote', array("Pollrow.id" => $this->params['data']['Pollrow']['id']) );<br /> <br /> $vote += 1;<br /> <br /> $this->params['data']['Pollrow']['vote'] = $vote; // add vote<br /> <br /> //die(print_r($this->params['data']));<br /> <br /> if ( $this->Pollrow->save($this->params['data']) ) // add the Poll vote<br /> { <br /> $_SESSION["poll"] = true; //set session, only one vote per session<br /> <br /> $conditions = array("Pollrow.poll_id" => $this->params['data']['Pollrow']['poll_id']);<br /> $fields = array("Pollrow.answer", "Pollrow.color", "Pollrow.vote", "Pollrow.poll_id");<br /> $order = "Pollrow.answer DESC";<br /> <br /> $this->set('poll', $this->Pollrow->findAll($conditions, $fields, $order, null, null, 2));<br /> <br /> $this->render('results', 'ajax');<br /> }<br /> else<br /> {<br /> echo "Ajax error, check with the company's computer guy...";<br /> }<br /> }<br /> }</font><br /> </p><p>Note, after add the vote and set 'poll' array, the view app/views/pollrows/results.thtml is rendered:</p><p><font color="#990000"><?php<br /> //die(print_r( $poll ));<br /> $total_votes = 0;<br /> <br /> foreach ($poll as $key => $val) <br /> {<br /> $total_votes += $poll[$key]["Pollrow"]["vote"]; // the total votes<br /> }<br /> <br /> foreach ($poll as $key => $val) <br /> {<br /> $percent = ($poll[$key]["Pollrow"]["vote"] * 100) / $total_votes; // % = votes * 100 / total<br /> $width = number_format($percent, 0);<br /> echo '<p><b>' . $poll[$key]["Pollrow"]["answer"] . '</b> '.number_format($percent, 2).'% <br />'; <br /> echo $html->image('static/poll/'.$poll[$key]["Pollrow"]["color"].'.png', <br /> array("height"=>"10", "width"=>$width,"alt"=>$poll[$key]["Pollrow"]["answer"], "title"=>$poll[$key]["Pollrow"]["answer"]) );<br /> echo " ". $poll[$key]["Pollrow"]['vote'];<br /> }<br /> <br /> echo "<p>Total votes:" . $total_votes . "</p>"; <br />?></font> </p><p>this view is settled inside add_pollrow div as we indicated in $ajax->submit.</p><p>And that is it!! You can see the Poll in action <a href="http://karamelo.mononeurona.org/users/general">here</a>. <br /></p>", "created" => "2007-04-29 10:57:00-05", "discution" => 1, "display" => 2, "status" => 1, "user_id" => 1, "cv" => 1, "visits" => 160, "rank" => 2515, "editor" => 1, "updated" => "2009-08-20 00:32:14-05" ), "User" => array( "id" => 1, "username" => "aarkerio", "avatar" => "aarkerio_avatar.png" ), "Section" => array( "id" => 26, "description" => "WWW", "img" => "gimp-sec.png" ), "Discution" => array( array(), array() ) )include - APP/View/Pages/display.ctp, line 30 View::_render() - CORE/Cake/View/View.php, line 598 View::render() - CORE/Cake/View/View.php, line 365 Controller::render() - CORE/Cake/Controller/Controller.php, line 900 Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 114 Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 89 [main] - APP/webroot/index.php, line 81
Ver todos los articulos de aarkerio
Última actualización: 2009-08-20 00:32:14-05
blog comments powered by Disqus




























