/ Gists / Nette-Tricks

Gists - Nette-Tricks

On gists

Nette form - vlastní pravidlo

Nette Nette-Tricks

nette.php #

<?php

$cnew->addText("input1", "Jméno 1")->addRule(

    function ($item, $arg){

         return $item->value == "ano";
    }

    , 'Číslo musí být dělitelné %d.', 8);

On gists

Nette - multiplier kontrolka - přístup v presenteru - způsoby

Nette Nette-Controls Nette-Tricks

nette-multiplier #

<?php

	public function handleTime()
	{
		$this['time'][1]->invalidateControl();
		$this['time-2']->invalidateControl();
	}




// LATTE

		{control time-1}
		{control time-2}

On gists

Nette - Neon - vlastní proměnné / own variables

Nette Nette-Tricks

presenter.php #

<?php

declare(strict_types = 1);

namespace Fp\Presenters;

use Fp\Template\TemplateHelpers;
use Nette\Application\UI\Presenter;
use Nette\Application\Helpers;
use Nette\Http\Url;
use Nette\Utils\Strings;

abstract class BasePresenter extends Presenter
{

	/** @var string */
	public $appDir;

	/** @var string */
	public $wwwDir;

	/** @var bool */
	public $productionMode;

	/** @var string */
	public $googleAnalyticsAccount;

	/** @var string */
	public $disqusShortname;

	/** @var string */
	public $twitterHandle;

	/** @var string */
	public $gplusAccountId;

	/** @var string */
	public $facebookUsername;

	/** @var string */
	public $facebookProfileId;

	/** @var string */
	public $githubRepository;

	/** @var \Fp\FaviconsLoader @inject */
	public $faviconsLoader;

	protected function startup()
	{
		parent::startup();
		if ($this->appDir === null) {
			throw new \Exception('%appDir% was not provided');
		}
	}

	protected function beforeRender()
	{
		parent::beforeRender();

		$this->template->wwwDir = $this->wwwDir;
		$this->template->productionMode = $this->productionMode;

		$this->template->faviconMetas = $this->faviconsLoader->getMetadata();

		$this->template->googleAnalyticsAccount = $this->googleAnalyticsAccount;
		$this->template->disqusShortname = $this->disqusShortname;
		$this->template->twitterHandle = $this->twitterHandle;
		$this->template->gplusAccountId = $this->gplusAccountId;
		$this->template->facebookUsername = $this->facebookUsername;
		$this->template->facebookProfileId = $this->facebookProfileId;
		$this->template->githubRepository = $this->githubRepository;

		$this->template->now = new \DateTimeImmutable();

		$canonicalUrlQuery = $this->getHttpRequest()->getUrl()->getQueryParameters();
		foreach ($canonicalUrlQuery as $queryParameter => $_) {
			if (Strings::startsWith($queryParameter, 'utm_')) {
				unset($canonicalUrlQuery[$queryParameter]);
			}
		}
		$this->template->canonicalUrl = (new Url($this->getHttpRequest()->getUrl()))->setQuery($canonicalUrlQuery);
	}

	protected function createTemplate()
	{
		/** @var \Nette\Bridges\ApplicationLatte\Template $template */
		$template = parent::createTemplate();
		$template->getLatte()->addFilter('filectime', 'filectime');
		$template->getLatte()->addFilter('timeAgo', TemplateHelpers::class . '::timeAgoInWords');
		return $template;
	}

	/**
	 * Formats layout template file names.
	 *
	 * @return string[]
	 */
	public function formatLayoutTemplateFiles(): array
	{
		if (is_string($this->layout) && preg_match('#/|\\\\#', $this->layout)) {
			return [$this->layout];
		}

		return [
			sprintf('%s/templates/@%s.latte', $this->appDir, $this->layout ?: 'layout'),
		];
	}

	/**
	 * Formats view template file names.
	 *
	 * @return string[]
	 */
	public function formatTemplateFiles(): array
	{
		list(, $presenter) = Helpers::splitName($this->getName());

		return [
			sprintf('%s/templates/%s/%s.latte', $this->appDir, $presenter, $this->view),
		];
	}

}

On gists

Nette CSV response

Nette Nette-Tricks

NetteCsvResponse.php #

<?php

namespace Nette\Application\Responses;

use Nette;

/**
 * CSV download response.
 * Under New BSD license.
 *
 * @property-read string $name
 * @property-read string $contentType
 * @package Nette\Application\Responses
 */
class CsvResponse extends Nette\Object implements Nette\Application\IResponse
{
	/** @var array */
	private $data;

	/** @var string */
	private $name;

	/** @var bool */
	public $addHeading;

	/** @var string */
	public $glue;

	/** @var string */
	private $charset;

	/** @var string */
	private $contentType;


	/**
	 * @param array[]|\Traversable $data
	 * @param string $name
	 * @param bool $addHeading
	 * @param string $glue
	 * @param string $charset
	 * @param string $contentType
	 * @throws \InvalidArgumentException
	 */
	public function __construct($data, $name = NULL, $addHeading = TRUE, $glue = ';', $charset = 'utf-8', $contentType = NULL)
	{
		if (is_array($data)) {
			if (count($data) && !is_array(reset($data))) {
				$invalid = TRUE;
			}
		} elseif (!$data instanceof \Traversable) {
			$invalid = TRUE;
		}
		if (isset($invalid)) {
			throw new \InvalidArgumentException(__CLASS__.": data must be array of arrays or instance of Traversable.");
		}
		if (empty($glue) || preg_match('/^[\n\r]+$/s', $glue) || $glue === '"') {
			throw new \InvalidArgumentException(__CLASS__.": glue cannot be an empty or reserved character.");
		}

		$this->data = $data;
		$this->name = $name;
		$this->addHeading = $addHeading;
		$this->glue = $glue;
		$this->charset = $charset;
		$this->contentType = $contentType ? $contentType : 'text/csv';
	}


	/**
	 * Returns the file name.
	 * @return string
	 */
	final public function getName()
	{
		return $this->name;
	}


	/**
	 * Returns the MIME content type of a downloaded content.
	 * @return string
	 */
	final public function getContentType()
	{
		return $this->contentType;
	}


	/**
	 * Sends response to output.
	 * @param Nette\Http\IRequest $httpRequest
	 * @param Nette\Http\IResponse $httpResponse
	 */
	public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
	{
		$httpResponse->setContentType($this->contentType, $this->charset);

		if (empty($this->name)) {
			$httpResponse->setHeader('Content-Disposition', 'attachment');
		} else {
			$httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"');
		}

		$data = $this->formatCsv();

		$httpResponse->setHeader('Content-Length', strlen($data));
		print $data;
	}


	protected function formatCsv()
	{
		if (empty($this->data)) {
			return '';
		}

		$csv = array();

		if (!is_array($this->data)) {
			$this->data = iterator_to_array($this->data);
		}
		$firstRow = reset($this->data);

		if ($this->addHeading) {
			if (!is_array($firstRow)) {
				$firstRow = iterator_to_array($firstRow);
			}

			$labels = array();
			foreach (array_keys($firstRow) as $key) {
				$labels[] = ucfirst(str_replace(array("_", '"'), array(' ', '""'), $key));
			}
			$csv[] = '"'.join('"'.$this->glue.'"', $labels).'"';
		}

		foreach ($this->data as $row) {
			if (!is_array($row)) {
				$row = iterator_to_array($row);
			}
			foreach ($row as &$value) {
				$value = str_replace(array('"'), array('""'), $value);
			}
			$csv[] = '"'.join('"'.$this->glue.'"', $row).'"';
		}

		return join("\r\n", $csv);
	}
}

On gists

From https://forum.nette.org/cs/24327-jak-ve-formulari-vypnout-editaci-pole-ale-zobrazit-data#p162878

Nette Nette-Forms Nette-Tricks

nette-readonly.php #

$input = $form->addInput('text');
$input->setDisabled(true); // nejdřív vypnout editaci
$input->setOmitted(false); // potom vypnout neodesílání

On gists

From https://forum.nette.org/cs/20267-jde-nejak-zmenit-data-v-active-row-kdyz-jsou-ted-read-only#p139460 Wrapper nad ActiveRow, Nette

Nette Nette-Tricks

nette-wrapper-active-row.php #

class RowWrapper extends Nette\Object
{
    protected $row;

    protected $data;

    public function __construct(Nette\Database\Table\ActiveRow $row)
    {
        $this->row = $row;
    }

    public function &__get($key)
    {
        if(isset($this->data[$key]) {
            $value = $this->data[$key];
        }
        $value = $this->row->$key;

        return $value;
    }

    public function __set($key, $value)
    {
        $this->data[$key] = $value;
    }

    //pripadne jeste related a ref

}

On gists

Ruční vykreslení formuláře v Nette (skoro ruční)

Nette Nette-Forms Nette-Tricks Nette-Latte

semi-manual-form-renderning.latt #

{form $form}
<ul class=error n:if="$form->ownErrors">
	<li n:foreach="$form->ownErrors as $error">{$error}</li>
</ul>

<table>
<tr n:foreach="$form->controls as $input" n:class="$input->required ? required">
	<th>{label $input /}</th>
	<td>{input $input} <span class=error n:ifcontent>{$input->error}</span></td>
</tr>
</table>
{/form}

On gists

Povolení načtení webu ve Frames, Nette

Nette Nette-Neon Nette-Tricks

example.neon #

common:
	security:
		debugger: true
		frames: SAMEORIGIN

On gists

Automatické přihlášení - NETTE

Nette Nette-Tricks

RegisterPresenter.php #

		$this->user->login(new Nette\Security\Identity($row["id"], array(), $row));
		$this->redirectUrl($this->link('@homepage'));

On gists

Partial rendering - nette, latte, formuláře

Nette-Tricks

Partial rendering.latte #

{foreach $form[gender]->items as $key => $label}
    <label n:name="gender:$key"><input n:name="gender:$key"> {$label}</label>
{/foreach}