/ Gists / Nette-Controls

Gists - Nette-Controls

On gists

Auto komponenty (Parent -> Children)

Nette Nette-Controls Nette-Tricks

ParentControl.php #

<?php

class OrderAction extends FrontControl 
{
  
  	public function __construct(, 
		Order $order, 
		Model\OrderAction $orderAction,
		Container $container
	) 
	{
		parent::__construct();

		$this->order = $order;
		$this->orderAction = $orderAction;
		$this->actions = $this->orderAction->getActions($this->pageByState);
	}
	
	
	
	public function render(array $config = [])
	{
		$config = $this->getCurrentConfig($config);

		$this->template->order = $this->order;
		$this->template->actions = $this->actions;

		$this->vueRender($config);
	}

	public function createComponent(string $name): ?Nette\ComponentModel\IComponent
	{
		if (!Strings::startsWith($name, 'action')) {
			return parent::createComponent($name);
		}

		return $this->container->createInstance('App\\FrontModule\\Components\\' . $this->actions[Strings::after($name, 'action')]->action, [
			'orderAction' => $this->actions[Strings::after($name, 'action')],
			'order' => $this->order
		]);
	}
	

}

On gists

Nette find template file if not exists

Nette Nette-Controls

findTemplate.php #

<?php

 if (!$this->template->getFile()) {
		$files = $this->formatTemplateFiles();
		foreach ($files as $file) {
			if (is_file($file)) {
				$this->template->setFile($file);
				break;
			}
		}
 }

On gists

Automatické vytvoření komponenty s @autowiringem // AW

Nette-Controls Nette-Tricks AW

auto-create.php #

<?php

	public function createComponentOrderReview()
	{
		return $this->getPresenter()->getControlFactory()->create($this, 'orderReview', [
			'order' => $this->getOrder()
		]);
	}
	
	
	    // from same category
    public function createComponentSameCategoryProducts()
    {
        $config = $this->getCurrentConfig();
        $product = $this->getProduct();
        $component = parent::createComponent($config['category_list_component']);
        $component->setConfig([
            'except_ids' => [
                $product::INHERITED ? $product->product_id : $product->id,
                $product->item__product_id,
                $product->inherit__product_id
            ],
            'navigation_id' => $product->getMainCat()->id,
            'default_filter' => []
        ]);
        return $component;
    }

On gists

Dohledani dat z jine kontrolky (template)

Nette-Controls Nette-Tricks Nette-Latte

some-file.latte #

{var $mailData = $control->lookup('App\FrontModule\Components\MailTemplateWrapper')->template}
{var $settings = $presenter->getContext()->getByType(App\EshopModule\Model\Settings::class)->getSetting()}



On gists

MatchResult component

Nette Nette-Controls PHP

MatchResultControl.php #

<?php


class MatchResult extends Control{

	const TEMPLATE_FULL = 'full';
	const TEMPLATE_INLINE = 'inline';

	public function renderFull($match){
		$this->render($match, self::TEMPLATE_FULL);
	}

	public function renderInline($match){
		$this->render($match, self::TEMPLATE_INLINE);
	}

	private function render($match, $templateName){
		$template = $this->createTemplate();
		$template->setFile(__DIR__.'/'.$templateName.'.latte');
		$template->match = $this->evaluateResult($match);
		$template->render();
	}

	private function evaluateResult($match){
		return //...
	}
}

On gists

ProductDeliveryDateInfo component

Nette Nette-Controls AW

ProductDeliveryDateInfo.php #

<?php

namespace FrontModule\Components;

use Nette,
	Andweb,
	Model;

class ProductDeliveryDateInfo extends Andweb\Application\UI\FrontControl 
{


	const HOUR = 13;



	protected $items = array(
				
			'Praha' => array(
			
				'Osobní odběr Praha'              => 0,
				'Expresní večerní doručení Praha' => 0,
			
			),
			
			'Česká republika' => array(
			
				'Česká pošta'    => 1,
				'Zásilkovna'     => 1,
				'Kurýrní služba' => 1,
			),			
			
			
			'Slovensko' => array(
			
				'Česká pošta'    => 2,
				'Zásilkovna'     => 2,
				'Kurýrní služba' => 2,
			),

	);


	public function __construct() 
	{

	}


	public function renderDefault() 
	{

		$template        = $this->template;
		$template->items = $this->items;

		// Fucking php5.3 on production
		$that = $this;

		$template->registerHelper('formatDate', function($s) use ($that) {
			return $that->formatDate($s);
		});
		
	}	



	public function renderNotAvailable() 
	{
		$template   = $this->template;
		$this->view = 'default';

		$template->notAvailable = TRUE;
		
		$template->items = $this->items;

		// Fucking php5.3 on production
		$that = $this;

		$template->registerHelper('formatDate', function($s) use ($that) {
			return $that->formatDate($s);
		});


		$this->render();
		
	}



	public function formatDate($s)
	{
		$today = new \DateTime();
		$tomorrow = clone $today;
		$tomorrow->modify('+ 1 day');

		if ($today->format('j.n.Y') == $s)
			return $this->presenter->translator->translate('dnes');			

		if ($tomorrow->format('j.n.Y') == $s)
			return $this->presenter->translator->translate( 'zítra');

		return $s;
	}


	// ukaze na velikonocni nedeli, napric vsemi casovymi pasmy, jinak funkce easter_day se chova obcas divne, viz php.net
	public function getEasterDateTime($year) 
	{
		$base = new \DateTime("$year-03-21");
		$days = easter_days($year);
	    return $base->add(new \DateInterval("P{$days}D"));
	}


	public function isNotHoliday(\Datetime $date)
	{
		// statni svatky
		$holidays = array('01-01', '05-01', '05-08', '07-05', '07-06', '09-28', '10-28', '11-17', '12-24', '12-25', '12-26');
		
		// velikonocni pondeli
		$holidays[] = $this->getEasterDateTime(date('Y'))->modify('+1day')->format('m-d');
		
		// velky patek, (pred velikonocnim pondelim)
		$holidays[] = $this->getEasterDateTime(date('Y'))->modify('-2day')->format('m-d');
		
		$day        = $date->format('w');

		if ($day == 0 || $day == 6) 
			return FALSE;

		if (in_array($date->format('m-d'), $holidays)) 
			return FALSE;

		return TRUE;
	}


	function getDeliveryDate($actualDate, $dayDelay = 0)
	{
		$actualDate = new \DateTime($actualDate);
		$actualDate->modify("+$dayDelay day");

		while (!$this->isNotHoliday($actualDate))
		{	
			$actualDate->modify('+1 day');
		}

		return $actualDate;
	}


	public function formatter($dayDelay)
	{
		// 13h a vic + 1 day
		if (date('H') >= self::HOUR)
			$dayDelay += 1;

		return $this->getDeliveryDate(date('Y-m-d'), $dayDelay);
	}





}

On gists

Control Poll - ajax, multiplier

Nette Nette-Controls Nette-Tricks

polls.latte #

{foreach $polls as $id => $poll}
    <h2>Anketa {$poll->name}</h2>
    {control poll-$id}
{/foreach}

On gists

Nette - kontrolka - dynamicke view / pohledy

Nette Nette-Controls Nette-Tricks

control.php #

<?php

namespace App\FrontModule\Components;

use Nette\Application\UI,
	Nette,
	Nette\Mail\Message,
	Nette\Mail\SendmailMailer,
	App,
	CardBook;


interface IContactUsFormFactory
{
	/** @return ContactUsForm */
	public function create ();
}


class ContactUsForm extends UI\Control 
{
	protected $userModel;
	protected $mailer;
	protected $messageFactory;
	
	/** @persistent */
	public $view;


	public function __construct (App\Model\User $user, Nette\Mail\IMailer $mailer, App\FrontModule\Factory\MessageFactory $messageFactory)
	{
		parent::__construct();

		$this->userModel = $user;
		$this->mailer    = $mailer;
		$this->messageFactory   = $messageFactory;
	}


	public function render() 
	{
		
		if (!$this->view)
			$this->template->setFile(__DIR__ . '/../templates/components/ContactUsForm/form.latte');
		else
			$this->template->setFile(__DIR__ . '/../templates/components/ContactUsForm/'.$this->view.'.latte');
		
		$this->template->render();
	}


	public function createComponentForm()
	{
		$form = new UI\Form;

		$form->addText("name", "Vaše jméno")
			 ->addRule($form::FILLED, "Vyplňte prosím jméno");

		
		$form->addText("email", "E-mail")
			 ->addRule($form::FILLED, "Vyplňte prosím email")
			 ->addRule($form::EMAIL, "Email není ve správném formátu");
		
		$form->addTextArea("message", "Vaše zpráva")
		     ->addRule($form::FILLED, "Vyplňte prosím Váš dotaz");

		$form->addSubmit("send", "Odeslat");

		$form->onSuccess[] = array($this, 'submitted');

		return $form;
	}


	public function submitted($form)
	{

		$values = $form->getValues();
	
	    $template = $this->createTemplate();
	    $template->setFile(__DIR__ . '/../templates/emails/contactus.latte');
		$template->title  = 'Napište nám';
		$template->values = $values;
	

		$mail = $this->messageFactory->create();
	

		//$mail = new Message;
		$mail->setFrom($values->email)
		     ->addTo(CardBook\Settings::ADMIN_EMAIL)
		     ->setSubject('Cardbook - napište nám')
		     ->setHtmlBody($template);
		
		$this->mailer->send($mail);


		// $mailer = new SendmailMailer;  1)

		// $mailer = new Nette\Mail\SmtpMailer(array(  2)
		// 		'host'     => 'smtp.savana.cz',
		// 		'username' => 'podpora@cardbook.cz',
		// 		'password' => 'uL$g4GHl6AR'
		// ));
		// $mailer->send($mail);

		// 3)
		// 
		
		//  arguments: [..., ..., %foo%, %bar%] #ano, opravdu dvojtecky

		// nebo:
		// arguments: [foo: %foo%, bar: %bar%]

		// nebo:
		// arguments: [2: %foo%, 3: %bar%]
 
		
        if ($this->presenter->isAjax()) 
        {
           	$this->view = 'save';
    		$this->redrawControl('contactUsForm');
     
        }
        else
        {
        	$this->redirect("this", array('view' => 'save'));
        }
		
	}


}

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

Ukázková komponenta

Nette-Controls

Open Graph Component.php #

<? 

class OpenGraphControl extends Nette\Application\UI\Control
{

    /** @var Nette\Utils\Html[] */
    private $tags = [];


    public function addOgTag($property, $content)
    {
        $this->tags[] = Nette\Utils\Html::el('meta', [
            'property' => $property,
            'content' => $content,
        ]);
        return $this;
    }


    public function render()
    {
        $el = Nette\Utils\Html::el();

        foreach ($this->tags as $tag) {
            $el->add($tag);
        }

        echo $el;
    }

}

$this['openGraph']->addOgTag('og:video', 'http://www.youtube.com/watch?v=' . $this->content->url);