Skip to content

Instantly share code, notes, and snippets.

@gpfiel
Created August 27, 2013 16:19
Show Gist options
  • Save gpfiel/6355711 to your computer and use it in GitHub Desktop.
Save gpfiel/6355711 to your computer and use it in GitHub Desktop.
I got a problem while using fieldset and collection, i created a view wich has 3 fieldsets and inside the fieldsets i have 1 file input for each, the problem is when i create the object Http() (Zend\File\Transfer\Adapter\Http), the constructor get $_FILES and pass it to an array of files inside the object, but when it does the array format the a…
<div class="span12">
<?php
$title = 'Adicionar banner';
$this->ztbForm($this->form);
$form = $this->form;
$form->setAttribute('action', $this->url('banner', array('action' => 'adicionar')));
$form->setAttribute('class', 'form-horizontal');
$form->setAttribute('class', 'pull-left');
$form->setAttribute('class', 'span12');
$form->prepare();
echo $this->form()->openTag($form);
// echo $this->formCollection($form->get('banners'));
?>
<div class="page-header">
<h1><?php echo $this->escapeHtml($title); ?></h1>
</div>
<?php
echo $this->ztbFormElement($form->get('banners')->get(0)->get('nom_banner'));
?>
<?php
$idiomas_temp = array();
if(count($idiomas)):
echo '<ul class="nav nav-tabs">';
foreach ($idiomas as $idioma) :
?>
<li <?php echo (count($idiomas_temp) == 0) ? "class='active'" : "" ?>>
<a href="#idioma<?php echo $idioma->cod_idioma ?>" data-toggle="tab">
<img src="<?php echo $this->basePath().'/assets/idioma/original/'.$this->escapeHtml($idioma->url_imagem) ?>" >
<?php echo $idioma->nom_idioma ?>
</a>
</li>
<?php
$idiomas_temp[] = $idioma;
endforeach;
echo '</ul>';
endif;
?>
<?php
if(count($idiomas_temp)) :
?>
<div class="tab-content">
<?php
$cont = 0;
foreach ($idiomas_temp as $idioma):
?>
<div class="tab-pane <?php echo ($cont == 0) ? "active" : "" ?>" id="idioma<?php echo $idioma->cod_idioma ?>">
<?php
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('cod_banner'));
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('cod_banner_pai'));
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('cod_idioma'));
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('des_banner'));
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('url_imagem'));
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('url_banner'));
echo $this->ztbFormElement($form->get('banners')->get($cont)->get('ind_status'));
?>
</div>
<?php
$cont++;
endforeach;
?>
</div>
<hr/>
<?php
echo $this->formElement($form->get('submit'));
echo $this->form()->closeTag();
?>
<?php
$controller = ucfirst($this -> parametros() -> getController(true));
echo $this->headScript()->appendFile($this->basePath() . "/public_admin/js/validation/Admin/{$controller}Form.js");
endif;
?>
</div>
<?php
/**
* @author Gabriel P. Fiel <gpfiel@hotmail.com>
* @package Banner
*/
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Form\CriarBanner;
use Admin\Model\Banner;
use Admin\Form\BannerForm;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Zend\File\Transfer\Adapter\Http;
use Zend\Validator\File\Size;
class BannerController extends AbstractActionController
{
protected $bannerTable;
public function indexAction()
{
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$busca = $this->params()->fromPost('busca') ? $this->params()->fromPost('busca') : null;
$itemsPerPage = 10;
$banners = $this -> getBannerTable()->fetchAll(null, $busca);
if(!$banners -> count() and $busca != null)
{
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'erro', 'Não foi encontrado nenhum registro.');
return $this -> redirect() -> toRoute("banner");
}
$paginator = new Paginator(new paginatorIterator($banners));
$paginator -> setCurrentPageNumber($page)
-> setItemCountPerPage($itemsPerPage)
-> setPageRange(10);
return new ViewModel(array(
'flashMessages' => $this->flashMessenger()->getMessages(),
'page' => $page,
'paginator' => $paginator,
));
}
public function adicionarAction()
{
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$form = new CriarBanner();
$idiomas = $this -> pluginFuncoes() -> getIdiomas();
$form->get('banners')->setCount($idiomas->count())->prepareFieldset();
$form->get('banners')->get(0)->get('ind_status')->setAttribute("value","1");
$form->get('submit')->setValue('Adicionar');
$request = $this->getRequest();
if ($request->isPost())
{
$data = $request->getPost()->toArray();
$files = $this->params()->fromFiles();
$cont = 0;
foreach ($files['banners'] as $file) {
$data['banners'][$cont]['url_imagem'] = $file['url_imagem'];
$cont++;
}
$form->setData($data);
$form->setValidationGroup(array('banners' => array('url_imagem','nom_banner')));
foreach ($data['banners'] as $chave => $h)
{
if($h['ind_status'] == 2 and $chave > 0)
{
$form->getInputFilter()->get('banners')->get($chave)->get('url_imagem')->setRequired(false);
}
if($chave > 0)
{
$form->getInputFilter()->get('banners')->get($chave)->get('nom_banner')->setRequired(false);
}
}
if ($form->isValid())
{
$codigos_dos_idiomas = array();
foreach ($idiomas as $idioma)
{
$codigos_dos_idiomas[] = $idioma->cod_idioma;
}
self::uploadImageAndResize($files);
foreach ($data['banners'] as $chave => $h)
{
if($chave != 0)
{
$h['cod_banner_pai'] = $cod_banner_pai;
$h['nom_banner'] = $nom_banner_pai;
}
$h['cod_idioma'] = $codigos_dos_idiomas[$chave];
$banner = new Banner();
$banner->exchangeArray($h);
if($chave == 0)
{
$cod_banner_pai = $this->getBannerTable()->cadastrarBanner($banner);
$nom_banner_pai = $banner ->nom_banner;
}
else
{
$this->getBannerTable()->cadastrarBanner($banner);
}
}
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'ok');
return $this->redirect()->toRoute('banner', array('page' => $page));
}
else
{
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'erro',"Necessário o preenchimento do banner em {$idiomas -> current() -> nom_idioma} e os idiomas que estão ativos.");
}
}
$viewmodel = new ViewModel(array(
'form' => $form,
'page' => $page,
'flashMessages' => $this->flashMessenger()->getCurrentMessages(),
'idiomas' => $idiomas
));
return $viewmodel;
}
public function deletarAction()
{
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$cod_banner = $this->getEvent()
->getRouteMatch()
->getParam('cod_banner');
$banner = $this->getBannerTable()->getBanner($cod_banner);
$retorno = $this->getBannerTable()->deletarBanner($cod_banner, $this -> pluginFuncoes());
if(!$retorno)
{
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'ok');
}
else
{
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'erro', $retorno);
}
return $this->redirect()->toRoute('banner', array('page' => $page));
}
public function editarAction()
{
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$cod_banner = ((int) $this->params('cod_banner') ? (int) $this->params('cod_banner') : (int) $this->params('cod_banner'));
$banner = $this->getBannerTable()->getBanner($cod_banner);
$form = new CriarBanner();
$idiomas = $this -> pluginFuncoes() -> getIdiomas();
if($banner -> count() != $idiomas -> count())
{
foreach ($banner as $ha)
{
$idiomas_da_banner[] = $ha -> cod_idioma;
}
foreach ($idiomas as $idioma)
{
$idiomas_existentes[] = $idioma -> cod_idioma;
}
$idiomas_novos = array_diff($idiomas_existentes, $idiomas_da_banner);
foreach ($idiomas_novos as $in)
{
$banner = new Banner();
$banner -> cod_banner_pai = $cod_banner;
$banner -> cod_idioma = $in;
$banner -> ind_status = 2;
$banner -> nom_banner = "";
$this->getBannerTable()->cadastrarBanner($banner);
}
$banner = $this->getBannerTable()->getBanner($cod_banner);
$idiomas = $this -> pluginFuncoes() -> getIdiomas();
}
$form->get('banners')->setCount($idiomas->count())->prepareFieldset();
foreach ($banner as $ha) {
$banners_lista[] = (array) $ha;
}
$banners_lista[] = array();
$form->setData(array("banners" => $banners_lista));
$form->get('submit')->setValue('Editar');
$request = $this->getRequest();
if ($request->isPost()) {
$banner = new Banner();
$form->setInputFilter($banner->getInputFilter());
$data = $request->getPost()->toArray();
$form->setValidationGroup(array('banners' => array('nom_banner')));
$form->setData($data);
foreach ($data['banners'] as $chave => $h)
{
if($h['ind_status'] == 2 and $chave > 0)
{
$form->getInputFilter()->get('banners')->get($chave)->get('nom_banner')->setRequired(false);
}
}
if ($form->isValid())
{
foreach ($data['banners'] as $h)
{
$banner->exchangeArray($h);
$this->getBannerTable()->editarBanner($banner);
}
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'ok');
return $this->redirect()->toRoute('banner', array('page' => $page));
}
else
{
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'erro',"Necessário o preenchimento do banner em {$idiomas -> current() -> nom_idioma} e os idiomas ativos.");
}
}
$viewmodel = new ViewModel(array(
'form' => $form,
'page' => $page,
'flashMessages' => $this->flashMessenger()->getCurrentMessages(),
'idiomas' => $idiomas
));
return $viewmodel;
}
public function uploadImageAndResize($files)
{
$adapter = new Http();
$files = $adapter->getFileInfo();
echo '<pre>';
print_r($files);
if (!$adapter->isUploaded($files['banners_0_'])) {
print "Why havn't you uploaded the file ?";
}
exit;
$adapter->setDestination($this -> pluginFuncoes() -> getBasePath() . '/assets');
foreach ($files['banners'] as $file)
{
$size = new Size(array(
'min' => 100
)); // minimum bytes filesize
$adapter->setValidators(array(
$size
), $file['url_imagem']['name']);
if(!empty($file['url_imagem']['name']))
{
if($adapter->isValid())
{
$novo_nome = date("d-m-Y_H-i-s").'.jpg';
$adapter->addFilter('File\Rename', array(
'target' => $adapter->getDestination() . "/banner/original/{$novo_nome}",
'overwrite' => true
));
if ($adapter->receive($file['url_imagem']['name']))
{
$thumbnailer = $this->getServiceLocator()->get('WebinoImageThumb');
$thumb = $thumbnailer->create($this -> pluginFuncoes() -> getBasePath() . "/assets/banner/original/{$novo_nome}", $options = array());
$thumb->resize(240, 240);
$thumb->save($this -> pluginFuncoes() -> getBasePath() . "/assets/banner/miniatura/{$novo_nome}");
}
else
{
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'erro', "Erro ao enviar o arquivo {$file['url_imagem']['name']}.");
}
}
else
{
$dataError = $adapter->getMessages();
$error = array();
foreach ($dataError as $key => $row) {
$error .= '<br/>' . $row;
}
if($error)
$this -> pluginMensagem() -> adicionarMensagem($this->params('action'),'erro', $error);
}
}
}
}
public function getBannerTable()
{
if (! $this->bannerTable) {
$sm = $this->getServiceLocator();
$this->bannerTable = $sm->get('Admin\Model\BannerTable');
}
return $this->bannerTable;
}
}
<?php
namespace Admin\Form;
use Admin\Model\Banner;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
use Zend\Validator\NotEmpty;
use Zend\Validator\StringLength;
class BannerFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('banner-form');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$this->setHydrator(new ClassMethodsHydrator(false))
->setObject(new Banner());
$this->setLabel('Banner');
$this->add(array(
'name' => 'cod_banner',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'cod_banner_pai',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'cod_idioma',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'nom_banner',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Nome',
),
));
$this->add(array(
'name' => 'des_banner',
'attributes' => array(
'type' => 'textarea',
'class' => 'span6',
'style' => 'height:200px; resize:none;'
),
'options' => array(
'label' => 'Descrição',
),
));
$this->add(array(
'name' => 'url_imagem',
'attributes' => array(
'id' => 'url_imagem',
'type' => 'file',
),
'options' => array(
'label' => 'Imagem',
),
));
$this->add(array(
'name' => 'url_banner',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Link',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'ind_status',
'options' => array(
'label' => 'Situação',
'value_options' => array(
'2' => 'Inativo',
'1' => 'Ativo'
),
),
'attributes' => array(
'value' => '2'
)
));
}
public function getInputFilterSpecification()
{
return array(
'nom_banner' => array(
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 250,
'messages' => array(
StringLength::TOO_SHORT => 'Deve conter no mínimo um caracter.',
StringLength::TOO_LONG => 'Não pode exceder 250 caracteres.',
),
)
),
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
NotEmpty::IS_EMPTY => 'Preenchimento obrigatório.',
),
),
),
),
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
)
),
),
'cod_banner' => array(
'required' => false,
'filters' => array(
array(
'name' => 'Int'
)
)
),
'cod_banner_pai' => array(
'required' => false,
'filters' => array(
array(
'name' => 'Int'
)
)
),
'cod_idioma' => array(
'required' => false,
'filters' => array(
array(
'name' => 'Int'
)
)
),
'des_banner' => array(
'required' => false,
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8'
)
)
),
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
)
),
),
'ind_status' => array(
'required' => false,
'filters' => array(
array(
'name' => 'Int'
)
)
),
'url_imagem' => array(
'required' => true,
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
NotEmpty::IS_EMPTY => 'É obrigatório a seleção de uma imagem.',
),
),
),
),
),
'url_banner' => array(
'required' => false,
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'max' => 250,
'messages' => array(
StringLength::TOO_LONG => 'Não pode exceder 250 caracteres.',
),
)
)
),
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
)
),
),
);
}
}
?>
<?php
namespace Admin\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;
use Zend\Validator\NotEmpty;
use Zend\Validator\StringLength;
class CriarBanner extends Form
{
public function __construct()
{
parent::__construct('banner-form');
$this->setAttribute('method', 'post')
->setAttribute('enctype','multipart/form-data')
->setHydrator(new ClassMethodsHydrator(false))
->setInputFilter(new InputFilter());
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'banners',
'options' => array(
'label' => 'Please choose banners for this product',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Admin\Form\BannerFieldset'
)
)
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Adicionar',
'id' => 'submitbutton',
'class' => 'btn btn-large btn-wtg pull-left'
),
));
}
public function getInputFilterSpecification()
{
return array(
);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment