Schlagwort-Archive: Twig

ZF2: Custom ZfcTwig Extension unter Zend 2

Notizen zu einer exemplarischen Twig Extension unter ZF2 &ZfcTwig:

Klasse anlegen z.B. unter Application/src/Application/View/CustomTwigExtension.php

<?php

// http://stackoverflow.com/questions/28254666/twig-add-filter

namespace Application\View;

use Twig_Extension;
use Twig_SimpleFilter;
use Twig_SimpleFunction;

class CustomTwigExtension extends Twig_Extension
{
    public function getFilters() {
        return [new Twig_SimpleFilter('ucfirst', 'ucfirst') ];
    }
    public function getName() {
        return "CustomTwigExtension";
    }
    public function getFunctions() {
        return [new Twig_SimpleFunction('renderimg', function ($picture, $width = 100, $height = 100) {
            $filename = basename($picture);
            
            return '<img src="' . $filename . '" width="' . $width . '" height="' . $height . '" />';
        }
        , array(
            'is_safe' => array(
                'html'
            )
        )) ];
    }
}

Custom Extension in config/autoload/global.php registieren:

<?php
/**
 * Global Configuration Override
 *
 * You can use this file for overriding configuration values from modules, etc.
 * You would place values in here that are agnostic to the environment and not
 * sensitive to security.
 *
 * @NOTE: In practice, this file will typically be INCLUDED in your source
 * control, so do not include passwords or other sensitive information in this
 * file.
 */

return array(
	'zfctwig' => [
	      'extensions' => [
	            'Twig_Extension_Debug',

	            // Custom Twig Extension registrieren
	            \Application\View\CustomTwigExtension::class,
	      ],
	      'environment_options' => array(
	            'debug'         => false
	      )
	],
);

Verwendung im Twig Template

{{ renderimg('test.jpg', 100, 100) }}

 

 

ZF2: Twig Templateengine installieren und aktivieren

Notizen zur Installation von Twig unter Zend 2.

Composer Beispielkonfiguration:

{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.3.*",
        "zendframework/zftool": "dev-master",
        "zf-commons/zfc-twig": "dev-master",
        "zendframework/zend-modulemanager": "2.3.*@dev"
    }
}

Mit Composer  installieren:

composer require zf-commons/zfc-twig:dev-master

Twig Modul in application.config.php aktivieren:

<?php
/**
 * Configuration file generated by ZFTool
 * The previous configuration file is stored in application.config.old
 *
 * @see https://github.com/zendframework/ZFTool
 */
return array(
    'modules' => array(
        'Application',
		'ZfcTwig'
    ),
    'module_listener_options' => array(
        'module_paths' => array(
            './module',
            './vendor'
        ),
        'config_glob_paths' => array(
            'config/autoload/{,*.}{global,local}.php'
        )
    )
);

Die Twig Example Templates ersetzen dann die Templates der ZF2 Skeleton Application.

Zu finden sind diese unter:

vendor/zf-commons/zfc-twig/examples

und ersetzen die Templates in diesem Ordner:

module/Application/view

 

ZF2: Zend Form in Twig Templates ausgeben

Einige Notizen zur Umsetzung einer Zend Form mit Ausgabe in einem Twig Template.

Form Klasse:

<?php

namespace Application\Form;

use Zend\Captcha;
use Zend\Form\Element;
use Zend\Form\Form;

class ContactForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('contact');

        $this->setAttribute('method', 'post');
        $this->setAttribute('class', 'zf2');


        $this->add(array(
            'name' => 'name',
            'type' => 'Zend\Form\Element\Text',
            'attributes' => array(
                'required' => 'required',
            ),
            'options' => array(
                'label' => 'Name',
                'label_attributes' => array(
                    'class' => 'required',
                ),
            ),
        ));

        $this->add(array(
            'name' => 'email',
            'type' => 'Zend\Form\Element\Email',
            'attributes' => array(
                'required' => 'required',
            ),
            'options' => array(
                'label' => 'Email',
                'label_attributes' => array(
                    'class' => 'required',
                ),
            ),
        ));

        $this->add(array(
            'name' => 'comment',
            'type' => 'Zend\Form\Element\Textarea',
            'attributes' => array(
                'required' => 'required',
            ),
            'options' => array(
                'label' => 'Kommentar',
                'label_attributes' => array(
                    'class' => 'required',
                ),
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'class' => 'gradient-button',
                'value' => 'Abschicken',
                'id' => 'submit',
            ),
        ));


        $this->add(array(
            'name' => 'csrf',
            'type' => 'Zend\Form\Element\Csrf',
            'options' => array(
                'csrf_options' => array(
                    'timeout' => 600
                )
            )
        ));
    }
}

Form Validieren:

<?php
namespace Application\Model\Form;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Contact implements InputFilterAwareInterface
{
    protected $inputFilter;

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter()
    {
        if (!$this->inputFilter)
        {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();


            $inputFilter->add($factory->createInput([
                'name' => 'name',
                'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array (
                        'name' => 'NotEmpty',
                        'options' => array(
                            'messages' => array(
                                'isEmpty' => 'Bitte geben Sie Ihren Namen ein.',
                            )
                        ),
                        'break_chain_on_failure' => true,
                    ),
                ),
            ]));

            $inputFilter->add($factory->createInput([
                'name' => 'email',
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array (
                        'name' => 'Regex',
                        'options' => array (
                            'pattern' => '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/',
                            'message' => array (
                                'regexNotMatch' => 'Bitte geben Sie eine gültige E-Mailadresse ein.',
                            )
                        ),
                        'break_chain_on_failure' => true,
                    ),
                    array (
                        'name' => 'EmailAddress',
                        'options' => array(
                            'messages' => array(
                                'emailAddressInvalidFormat' => 'Bitte geben Sie eine gültige E-Mailadresse ein.',
                            )
                        ),
                        'break_chain_on_failure' => true,
                    ),
                    array (
                        'name' => 'NotEmpty',
                        'options' => array(
                            'messages' => array(
                                'isEmpty' => 'Bitte geben Sie eine E-Mailadresse ein.',
                            )
                        ),
                        'break_chain_on_failure' => true,
                    ),
                ),
            ]));

            $inputFilter->add($factory->createInput([
                'name' => 'comment',
                'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array (
                        'name' => 'NotEmpty',
                        'options' => array(
                            'messages' => array(
                                'isEmpty' => 'Bitte geben Sie einen Kommentar ein.',
                            )
                        ),
                        'break_chain_on_failure' => true,
                    ),
                ),
            ]));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}

From in Controller an View übergeben:

        $formValidator = new Contact();
        $form = new ContactForm();
        $form->setInputFilter($formValidator->getInputFilter());
        $form->setAttribute('action', $this->url()->fromRoute('kontakt'));


        $view->setVariables(
            array(
                'form' => $form,
            )
        );

Form in Controller verarbeiten:

        $request = $this->getRequest();

        if ($request->isPost()) {

                $form->setData($request->getPost());


            if ($form->isValid()) {
                {

                    $view->setVariables(
                        array(
                            'formValid' => TRUE,
                            'formData' => $form->getData()
                        )
                    );

                    // send mail
                    $this->sendMail($form->getData());

                    return $view;
                }
            }
        }

Form in Twig Template ausgeben.

        {{ form().prepare() }}
        {{ form().openTag(form)|raw }}
        {{ formRow().setInputErrorClass('error').render(form.get('name'))|raw }}
        {{ formRow().setInputErrorClass('error').render(form.get('email'))|raw }}
        {{ formRow().setInputErrorClass('error').render(form.get('comment'))|raw }}
        {{ formRow(form.get('submit'))|raw }}
        {{ formRow(form.get('csrf'))|raw }}
        {{ form().closeTag(form)|raw }}