Skip to content

Instantly share code, notes, and snippets.

@vojtech-dobes
Created February 8, 2011 21:42
Show Gist options
  • Save vojtech-dobes/817320 to your computer and use it in GitHub Desktop.
Save vojtech-dobes/817320 to your computer and use it in GitHub Desktop.
Nette AJAX example (requires jQuery & jquery.nette.js)
{block content}
{control questions}
<ul n:snippet="questions" n:if="$questions" n:inner-foreach="$questions as $key => $question">
<li>
{$question}<br>
{if $answered->$key}
Děkuju, odpovězeno.
{else}
<a class="ajax" n:href="answer!, $key, TRUE">ano</a> / <a class="ajax" n:href="answer!, $key, FALSE">ne</a>
{/if}
</li>
</ul>
<a class="ajax" n:href="refresh!">znovu</a>
<script type="text/javascript">
$("a.ajax").live("click", function (event) {
event.preventDefault();
$.get(this.href);
});
</script>
<?php
use Nette\Application\AppForm;
use Nette\Application\Control;
use Nette\Environment;
class Questions extends Control
{
const YES = 'yes';
const NO = 'no';
/** @var array */
private $questions;
public function setQuestions(array $questions)
{
$this->questions = $questions;
}
public function render()
{
$template = $this->getTemplate();
$template->setFile(__DIR__ . '/questions.latte');
$template->questions = $this->questions;
$template->answered = Environment::getSession('questions');
$template->render();
}
public function handleAnswer($question, $response)
{
$storage = Environment::getSession('questions');
$storage->$question = $response ? self::YES : self::NO;
$this->invalidateControl('questions');
}
public function handleRefresh()
{
Environment::getSession('questions')->remove();
$this->invalidateControl('questions');
}
}
<?php
class QuestionsPresenter extends BasePresenter
{
public function actionDefault()
{
$questions = array(
'What is your name?',
'How old are you?',
'Where are you from?',
);
$this['questions']->setQuestions($questions);
}
protected function createComponentQuestions()
{
return new Questions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment