/ Gists / Nette

Gists - Nette

On gists

Nette filter helper latte

Nette Nette-Latte

config1.neon #

services:
    nette.latteFactory:
        setup:
            - addFilter(abs, @petrjirasek\Latte\AbsFilter)

    - petrjirasek\Latte\AbsFilter

On gists

Nette - error hlášky

Nette Nette-Forms

nette-form-error-msg.latte #

{$form[name]->errors} - vraci pole chyb toho inputu
{$form[name]->error} - vraci retezec s chybami spojenych mezerou (obvykle ma input jen jeden error, takze tohle je asi nejlepsi)
{inputError name} - makro, ktere vypise chybu inputu


{$form[name]->hasErrors()}


<input n:name="number">
<span class=error n:ifcontent>{inputError number}</span>

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 reset hodnot ve formuláři po odeslání

Nette Nette-Forms

nette-reset.php #

<?php

 $form->setValues(array(), TRUE);

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

Filter do Latte

Nette

predlozky.php #

<?php


	public static function predlozky($string) {
		/*

			$string = preg_replace('~ ([akosvzAKOSVZ]) ~', ' $1&nbsp;', $string);
			$string = preg_replace('~^([AKOSVZ]) ~', ' $1&nbsp;', $string);

			return $string;

		*/

		$string = preg_replace('~ ([akosvuzAKOSVZ]) ~', ' $1&nbsp;', $string);
        $string = preg_replace('~^([AKOSVZ]) ~', ' $1&nbsp;', $string);
        // predlozky, tituly, jednotky
        for($i = 1; $i <= 3; $i++)
            $string = preg_replace('~( |&nbsp;)(i|na|ve|pod|nad|od|do|před|ke|ku|ze|bez|ob|pro|při|po|skrz|za|Ing|MUDr|JUDr|Mgr|Bc|BcA|Ing. arch|MVDr|PhDr|RNDr|Pharmr|ThLic|ThDr|prof|doc|PaeDr|Dr|PhMr) ~', '$1$2&nbsp;', $string);

        $string = preg_replace('~(Na|Ve|Pod|Nad|Od|Do|Před|Ke|Ku|Ze|Bez|Ob|Pro|Při|Po|Skrz|Za) ~', '$1&nbsp;', $string);
        
        // en
        for($i = 1; $i <= 3; $i++)
            $string = preg_replace('~( |&nbsp;)(for|the|its|high-school|was|of|in|on|an|a|are|who|is|we|to|as|and|by|from|has|be|about|I) ~', '$1$2&nbsp;', $string);
        
        $string = preg_replace('~(For|The|Its|High-school|Was|Of|In|On|An|Are|Who|Is|We|To|As|And|By|From|Has|Be|About|I) ~', '$1&nbsp;', $string);
        // ru
        $string = preg_replace('~( |&nbsp;)(в|с|и|из|на|со) ~i', '$1$2&nbsp;', $string);
        
         // veliciny
        $string = preg_replace('~([0-9]{1,}) (m{1,2}|cm|dm|ml|l|dcl|dl|g|kg|%|dkg|kg|s|A|K|cd|mol|rad|sr|Hz|N|Pa|J|W|C|V|F|Ω|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat)( |\.|\,|$)~', '$1&nbsp;$2$3', $string);
        
        // procenta
        //$string = preg_replace('~([0-9]{1,}) %~', "$1&nbsp;%", $string);

        // kalendarni data
        $string = preg_replace('~(\d{1,})\. (\d{1,})\. (\d{1,})~', "$1.&nbsp;$2.&nbsp;$3", $string);

        //$string = preg_replace('^(([ ][a-zA-Z\&]{1,2})|([a-zA-Z0-9 ,\.\(][0-9]{1,5}))[ ]^','$1&nbsp;', $string);

        return $string;

	}

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

Helper když díky vazbám nejde použít spojení ...

Nette Helpers-Filters-Plugins

andweb-datatype-helper.php #

	public function helperImage($id, $size = 'original'){

		$imageDataType = new \Andweb\Datatypes\Image('image');

		$imageDataType->setValue($id);

		return $imageDataType->getImageElement($size);

	}