Phalcon PHP post link with JavaScript confirmation dialog - post

I am developing a CRUD system in Phalcon PHP (version 1.3.4).
My goal is to create a link (delete row), that asks for confirmation on click (JavaScript confirmation box) and then goes (request type POST) to the link.
So lets say a user clicks on the "delete row" button.
JavaScript confirmation "Are you sure you want to delete this row?"
User clicks "yes"
Webpage does a POST to "/users/delete/1"
I know CakePHP has a function (FormHelper::postLink()) that does exactly that.
I was wondering if Phalcon PHP also had a function like this.

I see three possibilities to achieve what you want. One is to create a macro in Volt template, second is to add a function to your View. Third and closest to - what I understand is your wish - is to extend Phalcons tag helper and this is part I will describe here.
Phalcon has its own Tag helper to allow you to easily create some elements. postLink is not a part that is implemented there, but you can easily achieve it. In my example I have namespace of Application with class of Tag that extends from \Phalcon\Tag. This is my base for this tutorial.
// Tag.php
namespace Application;
class Tag extends \Phalcon\Tag
{
static public function postLink() {
return '<strong>TEST TAG</strong>';
}
}
To force Phalcon DI to use this class, it is necessary to override it's standard declaration from engine by declaring it by hand as a new DI service:
// services.php
$di['tag'] = function() {
return new \Application\Tag();
};
You can test if it is working properly by typing {{ tag.postLink() }} in Volt template or with $this->tag->postLink() if using phtml template.
Now you can fill your Tag::postLink() method with HTML and parameters you wish it will produce:
namespace Application;
class Tag extends \Phalcon\Tag
{
static $forms = [];
static public function postLink($title, $url, $options = array()) {
// random & unique form ID
while ($randId = 'f_' . mt_rand(9000, 999999)) {
if (!isset(self::$forms[$randId])) {
self::$forms[$randId] = true;
break;
}
}
// dialog message
$dialogMessage = isset($options['message']) && $options['message'] ? $options['message'] : 'Are you sure you want to go on?';
$html = <<<HTML
<form action="{$url}" method="post" id="{$randId}">
<!-- maybe not necessary part -->
<input type="hidden" name="confirmed" value="1" />
</form>
{$title}
HTML;
return $html;
}
}
Now you can run it like this:
{{ tag.postLink('delete', '/users/delete/1') }}
{% set formOptions = ['message' : 'Are you sure you want to delete user Kialia Kuliambro?'] %}
{{ tag.postLink('delete', '/users/delete/1', formOptions) }}
{{ tag.postLink('delete', '/users/delete/1', ['message' : 'Are you sure you want to delete user Kialia Kuliambro?']) }}
Have fun extending :)

There's a few ways to implement such behavior in phalcon. Before anything, we need to understand how views and view helpers work in phalcon. And if you pay close attention, you'll notice, both .volt and .phtml have direct access to the DI.
In volt, for example, you can access the flash service, and output its messages by calling:
{{ flash.output() }}
which gets converted to the phtml: <?php echo $this->flash->output(); ?>
Thus my solution focuses on defining a new service in the DI which volt can access. In CakePHP, the syntax for postLink(), looks something like: echo $this->Form->postLink() while the function is actually defined in a class named FormHelper. So my solution will do the same thing, define a class FormHelper, then inject it into the view under the name Form.
Create an app/helpers/ directory.
Update your app/config/config.php file adding a reference to our new directory: 'helpersDir'=> APP_PATH . '/app/helpers/'
Update your app/config/loader.php file adding $config->application->helpersDir to the registered directories.
Create a new file app/helpers/FormHelper.php
Copy-paste the following code into the file:
<?php
use Phalcon\Tag;
class FormHelper extends Tag
{
protected $_lastAction = '';
public function dottedNameToBracketNotation($name)
{
$parts=explode('.',$name);
$first = array_shift($parts);
$name=$first . ($parts ? '[' . implode('][', $parts) . ']' : '');
return $name;
}
protected function flatten(array $data, $separator = '.')
{
$result = [];
$stack = [];
$path = null;
reset($data);
while (!empty($data)) {
$key = key($data);
$element = $data[$key];
unset($data[$key]);
if (is_array($element) && !empty($element)) {
if (!empty($data)) {
$stack[] = [$data, $path];
}
$data = $element;
reset($data);
$path .= $key . $separator;
} else {
$result[$path . $key] = $element;
}
if (empty($data) && !empty($stack)) {
list($data, $path) = array_pop($stack);
reset($data);
}
}
return $result;
}
protected function _confirm($message, $okCode, $cancelCode = '', $options = [])
{
$message = json_encode($message);
$confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
if (isset($options['escape']) && $options['escape'] === false) {
$confirm = $this->h($confirm);
}
return $confirm;
}
public function h($text, $double = true, $charset = 'UTF-8')
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset, $double);
}
protected function _lastAction($url)
{
$action = $url;//Router::url($url, true);
$query = parse_url($action, PHP_URL_QUERY);
$query = $query ? '?' . $query : '';
$this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
}
public function postLink($title, $url = null, array $options = [])
{
$out='';
$options += ['block' => null, 'confirm' => null];
$requestMethod = 'POST';
if (!empty($options['method'])) {
$requestMethod = strtoupper($options['method']);
unset($options['method']);
}
$confirmMessage = $options['confirm'];
unset($options['confirm']);
$formName = str_replace('.', '', uniqid('post_', true));
$formOptions = [
'name' => $formName,
'style' => 'display:none;',
'method' => 'post',
];
if (isset($options['target'])) {
$formOptions['target'] = $options['target'];
unset($options['target']);
}
$formOptions[0]=$url;
$out.=$this->form($formOptions);
$out .= $this->hiddenField(['_method','value' => $requestMethod]);
$fields = [];
if (isset($options['data']) && is_array($options['data'])) {
foreach ($this->flatten($options['data']) as $key => $value) {
$out .= $this->hiddenField([$this->dottedNameToBracketNotation($key),'value' => $value]);
}
unset($options['data']);
}
$out .= $this->endForm();
//This is currently unsupported
if ($options['block']) {
if ($options['block'] === true) {
$options['block'] = __FUNCTION__;
}
//$this->_View->append($options['block'], $out);
$out = '';
}
unset($options['block']);
$url = '#';
$onClick = 'document.' . $formName . '.submit();';
if ($confirmMessage) {
$options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
} else {
$options['onclick'] = $onClick . ' ';
}
$options['onclick'] .= 'event.returnValue = false; return false;';
$options[0]=$url;
$options[1]=$title;
$options[2]=false;
$out .= $this->linkTo($options);
return $out;
}
}
Edit your app/config/services.php file and add in:
$di->set('Form',function () {
return new FormHelper();
});
(you could make "Form" lowercase if you want, both work. I made it capital to closer resemble CakePHP's syntax. Do note that Volt is case sensitive when trying to access services but phtml will lowercase it.)
Edit the template you want to test the code on, such as app/views/index/test.volt
Copy-paste the following code into there:
{{ Form.postLink(' Delete','',['confirm':'Are you sure you want to delete #4?','data':['a':['b','c']]]) }}
Alternatively for phtml, use: <?php echo $this->form->postLink(' Delete', '', array('confirm' => 'Are you sure you want to delete #4?', 'data' => array('a' => array('b', 'c')))); ?>
Run it, and watch it work its magic, just render your index/test.volt template by visiting /index/test in your address bar. (Make sure you defined such an action in your index controller)
In terms, of other solutions, you could also use $compiler->addFunction() to make functions available to volt, one at time. The page in the manual gives the example of $compiler->addFunction('shuffle', 'str_shuffle');. You can attempt to override the factoryDefault for "tag" in the DI, and use the helper we already defined which extends tag. So you'd just change it from "form" to "tag" like so: $di->set('tag',function () {return new FormHelper();}); but, as you can see, it won't make the function postLink() available to volt as a function, you'll notice you still need to access it as tag.postLink(). Rather, all the \Phalcon\Tag functions are actually hard-coded into the volt engine. You can see this clearly by viewing the zephir source code of the \Phalcon\Mvc\View\Engine\Volt\Compiler class available over here. For your convenience, and in case the link ever gets broken, I have posted a snippet here which shows the "tag" functions in volt are actually hard-coded into it:
if method_exists(className, method) {
let arrayHelpers = this->_arrayHelpers;
if typeof arrayHelpers != "array" {
let arrayHelpers = [
"link_to": true,
"image": true,
"form": true,
"select": true,
"select_static": true,
"submit_button": true,
"radio_field": true,
"check_field": true,
"file_field": true,
"hidden_field": true,
"password_field": true,
"text_area": true,
"text_field": true,
"email_field": true,
"date_field": true,
"tel_field": true,
"numeric_field": true,
"image_input": true
];
let this->_arrayHelpers = arrayHelpers;
}
if isset arrayHelpers[name] {
return "$this->tag->" . method . "(array(" . arguments . "))";
}
return "$this->tag->" . method . "(" . arguments . ")";
}
So, if you'd like to "hack" in a few more methods by extending the \Phalcon\Tags class, you're out of luck. However, as demonstrated on the volt documentation page, there exists the concept of registering custom extensions to work with volt. The documentation gives the example of: $compiler->addExtension(new PhpFunctionExtension());
Where the source of the class is:
<?php
class PhpFunctionExtension
{
/**
* This method is called on any attempt to compile a function call
*/
public function compileFunction($name, $arguments)
{
if (function_exists($name)) {
return $name . '('. $arguments . ')';
}
}
}
This would allow volt access to any function you'd like, without having to manually register every possible function you could possibly ever need. You can test this by trying to access str_shuffle in volt, like we did before with $compiler->addFunction('shuffle', 'str_shuffle'); but this time without having to register it.
In terms of other solutions, you could also try to integrate CakePHP and PhalconPHP together, and attempt to call CakePHP's view helpers from PhalconPHP, but then you'd run into a problem of CakePHP not understanding your router setup you have configured in Phalcon. But, if you're determined, you could code all the routes and config for CakePHP and run it alongside PhalconPHP, but I'd highly discourage such a desperate workaround. And, finally, if you understand how the function works, and you barely use it, you could get away with just hard-coding the HTML in the first place. Honestly, CakePHP's logic doesn't look so sound to me in the first place because it has to corrupt your HTML document with a form inserted which can bother your layout. I think it would make more sense to generate a form dynamically with JavaScript, if we're using JavaScript already, and append it to the <body> when the button is clicked, then submit the form we just created dynamically. But, you wanted a CakePHP implementation, so I coded it as close to the logic they used as possible. It's not perfect, in terms of supporting all their features, such as block, but it should suit most of your needs.
I can always revise my implementation, but I think it demonstrates how to work with Phalcon pretty well for those migrating from CakePHP.

Related

How to integrate the element label into the validation error message in ZF2?

I have a form, where the error messages have to be displayed bundled at one place. The default messages are general, so the user sometimes doesn't know, which message is for which form field:
A record matching the input was found
Value is required and can't be empty
The input is not a valid email address...
I could write a custom message for every field, but is much effort and copy&paste.
So, I'd like to display the messages like this:
My element Foo label: A record matching the input was found
My element Bar label: Value is required and can't be empty
My element Buz label: The input is not a valid email address...
How to achieve this?
ZF2 seems not to provide a solution for this requirement. My solution/workaround is to override the Zend\Form\View\Helper\FormElementErrors replacing these lines of the FormElementErrors#render(...) by
$this->prepareMessagesToPrint($messages, $messagesToPrint, $element, $escapeHtml);
and add a method, that process the $messages as desired:
protected function prepareMessagesToPrint($messages, &$messagesToPrint, $element, $escapeHtml) {
foreach ($messages as $nameOrType => $elementOrError) {
if (is_string($elementOrError)) {
$elementLabel = $element->getLabel()
? '<b>' . $this->view->translate($element->getLabel()) . '</b>' . ': '
: null
;
$message = $escapeHtml($elementOrError);
$messagesToPrint[] = $elementLabel ? $elementLabel . $message : $message;
} elseif (is_array($elementOrError)) {
$newElement = $element->get($nameOrType);
$this->prepareMessagesToPrint(
$elementOrError, $messagesToPrint, $newElement, $escapeHtml
);
}
}
}

How to modify an URL in a view in CakePHP 2.x

It seems quite simple but there is something I am not able to figure out. I hope someone can help me fast.
I have an url, something like http://host/controller/action/argument/named:1/?query1=1. I want to add another query param to look it like http://host/controller/action/argument1/argument2/named:1/?query1=1&query2=2. I fact I want to add query2=2 to all URLs on a particular page, through some callback or something.
An URL may or may not have query params in the existing page URL.
How do I do it?
Example url : http://www.example.com/myController/myAction/param1:val1/param2:val2
You can use :
$this->redirect(array("controller" => "myController",
"action" => "myAction",
"param1" => "val1",
"param2" => "val2",
$data_can_be_passed_here),
$status,
$exit);
Hope it helps you.
May be I am thinking too much of it but here is how it came out. I put it in a UtilityHelper.
function urlmodify($params = array(), $baseurl = true) {
$top_level_1 = array('plugin', 'controller', 'action'); //top level vars
$top_level_2 = array('pass', 'named'); //top level vars
//for integrated use
$top_level = array_merge($top_level_1, $top_level_2);
$urlparams = array();
//get top level vars
foreach($top_level as $k) {
if(in_array($k, $top_level_1)) {
$urlparams[$k] = $this->request->params[$k];
}
if(in_array($k, $top_level_2)) {
$$k = $this->request->params[$k]; //create $pass & $named
}
}
//get query vars
if($this->request->query) {
$urlparams['?'] = $this->request->query;
}
//check for custom pass vars
if(isset($params['pass'])) {
$pass = array_merge($pass, $params['pass']);
}
//pass var has to be in numarical index
foreach($pass as $v) {
array_push($urlparams, $v);
}
//check for custom named vars
if(isset($params['named'])) {
$named = array_merge($named, $params['named']);
}
//pass var has to be in key=>value pair
foreach($named as $k=>$v) {
$urlparams[$k] = $v;
}
//check for custom query vars
if(isset($params['?'])) {
$urlparams['?'] = array_merge($urlparams['?'], $params['?']);
}
return Router::url($urlparams, $baseurl);
}
}
I have an URL: http://localhost/project/exlplugin/logs/manage_columns/1/a:1/n:1/?b=1. On some links I want to add some certain parameters. Here is the result when i call
echo $this->Utility->urlmodify(array('pass'=>array(2), 'named'=>array('m'=>2), '?'=>array('c'=>2)));*
It gives: http://localhost/thecontrolist/spreadsheet/logs/manage_columns/1/2/a:1/n:1/m:2?b=1&c=2
I just wanted to add just a query parameter to all my listing urls deleted=0 or deleted=1 for the SoftDelete thing :)
Thank you #u2460470 for the answer but it's just about modifying (not removing or creating anything but just adding some params to) current URL on a view page.

for each element with behat or codeception

I want to test a website which has a dynamic menustructure. I want to loop through all menuitems and run the same series of test on every page. We're talking about 100+ pages that change reguraly.
I would like to do this with either behat or codeception.
Does anybody have an idea about how to do this?
When using Behat with Mink, you can grab your menu items with findAll() and then iterate over it:
/**
* #When /^I run my test series for all menu items$/
*/
public function iRunMyTestSeriesForAllMenuItems() {
$result = TRUE;
$this->getSession()->visit('http://www.example.com/');
$links = $this->getSession()->getPage()->findAll('css', '#menu ul li a');
foreach ($links as $link) {
$url = $link->getAttribute('href');
if (FALSE === $this->yourTestHere($url)) {
$result = FALSE;
}
}
return $result;
}
I had a similar use case where I wanted to visit all pages of a given site map making sure there isn't any dead links. I had the approach to dynamically generate an array of steps which is then returned and processed by Behat. I had to add an artificial step "I print out page" to make sure I can see on the console what page is currently tested.
/**
* #Then /^I should access all pages of site map "([^"]*)"$/
*/
public function iShouldAccessAllPagesOfSiteMap($selector) {
$page = $this->getSession()->getPage();
$locator = sprintf('#%s a', $selector);
$elements = $page->findAll('css', $locator);
$steps = array();
foreach ($elements as $element) {
/** #var \Behat\Mink\Element\NodeElement $element */
$steps[] = new Behat\Behat\Context\Step\When(sprintf('I print out page "%s"', $element->getAttribute('href')));
$steps[] = new Behat\Behat\Context\Step\When(sprintf('I go to "%s"', $element->getAttribute('href')));
$steps[] = new Behat\Behat\Context\Step\Then('the response status code should be 200');
}
return $steps;
}
/**
* #When /^I print out page "([^"]*)"$/
*/
public function iPrintOutThePage($page) {
$string = sprintf('Visiting page ' . $page);
echo "\033[36m -> " . strtr($string, array("\n" => "\n| ")) . "\033[0m\n";
}
Then my scenario looks as follows:
Scenario: my website has no "dead" pages
Given I am on "/examples/site-map/"
Then I should access all pages of site map "c118"
The whole Gist is here https://gist.github.com/fudriot/6028678

Codeigniter 2 Autocomplete from Database

I am trying to set up an autocomplete input box on a form and although everything seems to work I an getting no data passed to the input box. Firebug reports a success but nothing there. I was wondering if some one could look at my code to see if there are any glaring errors that may be causing it.
Script is:
(function($){
$("#town").autocomplete({
source :"drivers/driver_gettown",
minLength : 3,
dataType:'JSON',
type:'POST'
});
})(jQuery);
Input Box is:
<div class="div">
<input name="town" id="town" type="text" class="txtSelect input required" value="<?php echo set_value('town'); ?>" />
<?php echo form_error('town'); ?>
</div>
Model is:
class Driver_model extends CI_Model
{
public function __construct() {
// Load the Database
parent::__construct();
$this->load->database();
}
function driver_get_towns($q)
{
// Get a list of Towns
// Search for row "place_name" from Table called "tbk_towns"
$this->db->select('place_name');
$this->db->like('place_name', $q);
$query = $this->db->get('tbk_towns');
if($query->num_rows > 0)
{
foreach ($query->result_array() as $row)
{
//build an array for the towns
$row_set[] = htmlentities(ucfirst($row['place_name']));
}
//format the array into json data
// header('Content-Type: application/x-json; charset=utf-8');
// echo json_encode($row_set);
$this->output
->set_content_type('application/json')
->set_output(json_encode($row_set));
}
}
}
and Finally the controller:
class Drivers extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('driver_model');
$this->load->helper('url', 'form', 'html', 'json');
}
function index()
{
// Just loads the main Page of the Drivers Area
$data['metatitle'] = "Auto Ninja | Drivers Members Area | Locally Rated Garages & Mechanics";
$data['metadescription'] = "Garages &amp Mechanics";
$data['metakeywords'] = "Car Repair, Car Service, Car MOT";
$this->load->view('drivers/header_drivers.inc.php', $data);
$this->load->view('drivers/index');
$this->load->view('drivers/footer_index.inc.php');
}
public function driver_gettown()
{
if (isset($_GET['term'])){
exit;
}
$this->load->model('driver_model');
$q = ucfirst($_GET['term']);
$this->driver_model->driver_get_towns($q);
}
}
and comments/help would be gratefully appreciated.
function driver_addjob()
{
// Loads the Add New Job Form for the Website
$this->load->helper('form');
$this->load->library(array('form_validation', 'session'));
$this->load->model('driver_model');
$this ->form_validation->set_error_delimiters('<span class="error">', '</span>');
// Validate the form fields
$this->form_validation->set_rules('town', 'Nearest Town or City', 'trim|required|xss_clean');
// Populates dropdown "town" from the database ???
if ($this->form_validation->run() == FALSE)
{
$data['metatitle'] = "Auto Ninja | Drivers - Add New Job | Locally Rated Garages & Mechanics";
$data['metadescription'] = "Garages &amp Mechanics";
$data['metakeywords'] = "Car Repair, Car Service, Car MOT";
$this->load->view('drivers/header_drivers.inc.php', $data);
$this->load->view('drivers/driver_addjob.php');
$this->load->view('drivers/footer_index.inc.php');
}
else
{
$townid = $this->input->post('town');
$work_jobtitle = $this->input->post('jobtitle');
$this->driver_model->driver_add_job ($townid);
$this->session->set_flashdata('message', 'your work request has been added to the system');
$data['metatitle'] = "Auto Ninja | Drivers - Add New Jobs Success | Locally Rated Garages & Mechanics";
$data['metadescription'] = "Garages &amp Mechanics";
$data['metakeywords'] = "Car Repair, Car Service, Car MOT";
$this->load->view('drivers/header_drivers.inc.php', $data);
$this->load->view('drivers/driver_addjob_success');
$this->load->view('drivers/footer_index.inc.php');
}
}
Ok I finally figured this one out. For some reason the response URL is coming out at
http://php.codeigniter.server/drivers/drivers/driver_gettown?term=ed
so the controller is being added twice. I updated the Java to
(function($){
$("#town").autocomplete({
source :"driver_gettown",
minLength : 3,
dataType:'JSON',
type:'POST'
});
})(jQuery);
ie not including the controller and it works!!! So a tad confused as to how it knows which controller to find the method in but who cares it works. It would be nice to know though as it will probably still annoy me... Possibly the JSON call bring it over in the URL maby?

image resize zf2

I need to implement image resize functionality (preferably with gd2 library extension) in zend framework 2.
I could not find any component/helper for the same. Any references?
If i want to create one, where should I add it. In older Zend framework, there was a concept of Action Helper, what about Zend framework 2 ?
Please suggest the best solution here.
I currently use Imagine together with Zend Framework 2 to handle this.
Install Imagine: php composer.phar require imagine/Imagine:0.3.*
Create a service factory for the Imagine service (in YourModule::getServiceConfig):
return array(
'invokables' => array(
// defining it as invokable here, any factory will do too
'my_image_service' => 'Imagine\Gd\Imagine',
),
);
Use it in your logic (hereby a small example with a controller):
public function imageAction()
{
$file = $this->params('file'); // #todo: apply STRICT validation!
$width = $this->params('width', 30); // #todo: apply validation!
$height = $this->params('height', 30); // #todo: apply validation!
$imagine = $this->getServiceLocator()->get('my_image_service');
$image = $imagine->open($file);
$transformation = new \Imagine\Filter\Transformation();
$transformation->thumbnail(new \Imagine\Image\Box($width, $height));
$transformation->apply($image);
$response = $this->getResponse();
$response->setContent($image->get('png'));
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
}
This is obviously the "quick and dirty" way, since you should do following (optional but good practice for re-usability):
probably handle image transformations in a service
retrieve images from a service
use an input filter to validate files and parameters
cache output (see http://zend-framework-community.634137.n4.nabble.com/How-to-handle-404-with-action-controller-td4659101.html eventually)
Related: Zend Framework - Returning Image/File using Controller
Use a service for this and inject it to controllers needing the functionality.
Here is a module called WebinoImageThumb in Zend Framework 2. Checkout this. It has some great feature such as -
Image Resize
Image crop, pad, rotate, show and save images
Create image reflection
For those who are unable to integrate Imagine properly like me..
I found another solution WebinoImageThumb here which worked perfectly fine with me. Here is little explanation if you don't want to read full documentation :
Run: php composer.phar require webino/webino-image-thumb:dev-develop
and add WebinoImageThumb as active module in config/application.config.php which further looks like :
<?php
return array(
// This should be an array of module namespaces used in the application.
'modules' => array(
'Application',
'WebinoImageThumb'
),
.. below remains the same
Now in your controller action use this through service locator like below :
// at top on your controller
use Zend\Validator\File\Size;
use Zend\Validator\File\ImageSize;
use Zend\Validator\File\IsImage;
use Zend\Http\Request
// in action
$file = $request->getFiles();
$fileAdapter = new \Zend\File\Transfer\Adapter\Http();
$imageValidator = new IsImage();
if ($imageValidator->isValid($file['file_url']['tmp_name'])) {
$fileParts = explode('.', $file['file_url']['name']);
$filter = new \Zend\Filter\File\Rename(array(
"target" => "file/path/to/image." . $fileParts[1],
"randomize" => true,
));
try {
$filePath = $filter->filter($file['file_url'])['tmp_name'];
$thumbnailer = $this->getServiceLocator()
->get('WebinoImageThumb');
$thumb = $thumbnailer->create($filePath, $options = [], $plugins = []);
$thumb->adaptiveResize(540, 340)->save($filePath);
} catch (\Exception $e) {
return new ViewModel(array('form' => $form,
'file_errors' => array($e->getMessage())));
}
} else {
return new ViewModel(array('form' => $form,
'file_errors' => $imageValidator->getMessages()));
}
Good luck..!!
In order to resize uploaded image on the fly you should do this:
public function imageAction()
{
// ...
$imagine = $this->getImagineService();
$size = new \Imagine\Image\Box(150, 150);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$image = $imagine->open($destinationPath);
$image->thumbnail($size, $mode)->save($destinationPath);
// ...
}
public function getImagineService()
{
if ($this->imagineService === null)
{
$this->imagineService = $this->getServiceLocator()->get('my_image_service');
}
return $this->imagineService;
}

Resources