Yii file CFormInputElement won't display unless explicitly marked "safe" - file-upload

I'm trying to use Form Builder to build a simple file upload prompt. I want to specify the rule for the file to be similar to
array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html'),
but something is wrong. The file upload element only appears if I explicitly mark the element as 'safe' (and remove the 'file' rule). What am I missing?
models/UploadForm.php
class UploadForm extends CFormModel
{
public $year;
public $formFile;
public function rules ()
{
return array(
array('year', 'required'),
array('year', 'date', 'format'=>'yyyy'),
// array('formFile', 'safe'),
array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html'),
);
}
static public function getYearOptions () {...}
}
views/extranet/uploadForm.php
return array(
'title' => 'Select year',
'method' => 'post',
'enctype' => 'multipart/form-data',
'elements' => array(
'year' => array(
'type' => 'dropdownlist',
'items' => UploadForm::getYearOptions(),
),
'formFile' => array(
'type' => 'file',
'label' => 'form source file',
),
),
'buttons' => array(
'upload' => array(
'type' => 'submit',
'label' => 'upload',
),
),
);
controllers/ExtranetController.php
class ExtranetController extends CController
{
public function actionIndex ()
{
$form = new CForm('application.views.extranet.uploadForm', new UploadForm());
if ($form->submitted('upload') && $form->validate()) {...}
$this->render('index', array('form' => $form));
}
}

The reason for this is very simple.
The form builder only renders input elements which are considered safe (I.E. have a validation rule). What you have done is perfectly fine, except CFileValidator isn't "safe" by default, whereas other validators are safe.
The quickest way to solve this is the following:
// In your model::rules() function
return array(
array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html', 'safe' => true),
);
Refer to these two links for more information: the CFileValidator#safe documentation, and the Github issue for a problem very similar to yours.

Related

Yiibooster TBSelect2 not displayed

In my view I have this code:
echo $form->select2Row($model, 'Zustelladresse', array(
'asDropDownList' => false,
'options' => array(
'placeholder' => "Zustelladresse",
'width' => '100%',
'closeOnSelect' => true,
'minimumInputLength'=>1,
'initSelection' => "js:function (element, callback) {
var selected_data = new Object;
selected_data.id = '123';
selected_data.text = 'Test';
callback(selected_data);
}",
'ajax' => array(
'url' => Yii::app()->createUrl('address/zustelladresse'),
'dataType' => 'json',
'data' => 'js:function(term,page) { if(term && term.length){ return { zustelladresse: term };} }',
'results' => 'js:function(data,page) { return {results: data}; }',
),
)));
Created html:
Why is created only label and hidden input?
YiiBooster widgets are quite tricky to debug, if anything is wrong they just don't show. If you still need the answer, I successfully displayed a select2 widget with this code:
$form->select2Row($model, 'attribute_name', array(
'data' => array('1'=>'value1,'2'=>'value2'),
'htmlOptions'=>array(
'style' => 'width:600px',
'multiple' => true,
),
'options'=>array('placeholder'=>'Please make a selection'),
));
I'd suggest you to start from this code and add up your options one by one, and see if anything breaks.

How can I use yii widget nested another widget?

class CommonHeaderWidget extends CWidget {
public function run() {
// I want use Another widget here,
// but it's no use like this:
$this->getController->widget('bootstrap.widgets.TbNavbar', array(
'items' => array(
array(
'class' => 'bootstrap.widgets.TbMenu',
'items' => array(
array('label' => 'mall', 'url' => '#'),
array('label' => 'Join', 'url' => #),
),
),
),
));
// end.
$this->render('commonHeader');
}
}
Then,I put the widget TbNavbar in commonHeader view ,it's no use too! How can I do?

Attach inputFilter to dynamcially created field elements

Until now I have been binding input filters to the form in the module, in other words I have been creating elements in the form, adding input filters to the elements on the module side.
For example check this example
Right now im creating text field elements dynamically depending upon the requirements, like this in my form
//Form
public function addNamesTextFieldElement($names)
{
foreach($names as $name)
{
$nameTextField = new Element\Text($name->getName());
$nameTextField->setAttribute('type', "text");
$nameTextField->setLabel($name->getName());
$this->add($nameTextField );
}
}
What would be best approach where to add/attach input filters to such dynamically generated elements.
I probably wouldn't use this approach, but something like this would work, providing you have already assigned an InputFilter to the form:
public function addNamesTextFieldElement($names)
{
$factory = new InputFactory();
foreach($names as $name)
{
$nameTextField = new Element\Text($name->getName());
$nameTextField->setAttribute('type', "text");
$nameTextField->setLabel($name->getName());
$this->add($nameTextField );
$this->getInputFilter()->add(
$factory->createInput(array(
'name' => $name->getName(),
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
))
);
}
}

ZF2: create url aliases in router

I'm new to Zend Framework 2 and i want to learn this framework. I want to create url aliases in router.
For example, I have defined something like this in module.config.php
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'node' => array(
'type' => 'Application\Controller\AliasSegment',
'options' => array(
'route' => '/node[/:id]',
'constraints' => array(
'id' => '[0-9]+'
),
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
'id' => '0'
),
),
'may_terminate' => true,
),
),
),
When i type www.myapp.local/node/1 it routes to the default action in default controller of my application. What i want is a router extension that can handle aliases for url paths. For example:
www.myapp.local/node/1 = www.myapp.local/aboutus
www.myapp.local/node/2 = www.myapp.local/company/gallery
I know that it was possible in ZF. Here is a link to tutorial how to achieve this in ZF:
friendly urls
I know that this is in Polish but code is self-explanatory i think :)
The idea is to use url helper to assembly valid url using aliases or normal segments (node/[:id])
I've already created AliasSegment class in my Application\Controller folder but it shows me an error:
Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Application\Controller\AliasSegment' in C:\xampp\htdocs\industengine\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:450 Stack trace: #0
My AliasSegment class (incomplete):
<?php
namespace Zend\Mvc\Router\Http;
use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
class AliasSegment extends Segment
{
public function match(Request $request, $pathOffset = null)
{
}
}
I was looking for an answer for hours and i couldnt find anything. Please tell me at least what I'm doing wrong, where to insert a code or maybe You know better sollution?
I'm not looking for ready application. I want to learn something but i would appreciate if You can tell me an answer in details :)
Thanks in advance and sorry for my English :)
EDITED:
My custom router is working now. At this moment aliases are hardcoded but it works.
My AliasSegment class looks now:
<?php
namespace Application\Controller;
use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Mvc\Router\Http;
class AliasSegment extends \Zend\Mvc\Router\Http\Segment
{
public function match(Request $request, $pathOffset = null)
{
$uri = $request->getUri();
$path = $uri->getPath();
//sample logic here
//for /about/gallery uri set node id to 1
//todo: get action, controller and module from navigation
if($path == '/about/gallery'){
$uri->setPath('/node/1');
$request->setUri($uri);
}
return parent::match($request, $pathOffset);
}
protected function buildPath(array $parts, array $mergedParams, $isOptional, $hasChild)
{
if(isset($mergedParams['link'])){
return $mergedParams['link'];
}
return parent::buildPath($parts, $mergedParams, $isOptional, $hasChild);
}
}
In this case /about/gallery is an alias to /node/1. Both adresses are correct. The buildPath function returns alias path correctly. Well, I hope this would be usefull for somebody :)
However i want to setup it in Zend_Navigation with additional parameter named 'link'.
I've done 50% of what i want to achieve however now I have problem to get Zend_Navigation from my router. I don't know how to pass it. I guess it should be something like this:
$sm = $this->getServiceLocator();
$auth = $sm->get('Navigation');
It works in my IndexController but doesnt work in my AliasSegment. I need to find in navigation array nodes with 'link' parameter.
EDIT
I've found solution. The answer is below.
unable to fetch or create an instance for Application\Controller\AliasSegment
if this is controller then I would expect in module.config.php to have:
'controllers' => array(
'invokables' => array(
'\Application\Controller\AliasSegment' => '\Application\Controller\AliasSegment',
)
),
also namespace of your class looks a bit weird:
namespace Zend\Mvc\Router\Http;
what about:
namespace Application\Controller;
OK, I've made it. The important thing for this Thread:
ZF2: How to get Zend\Navigation inside custom route?.
You can use any segment type route. But this may need a little modifications to match function.
If navigation's single page will have 'link' param, the url will be converted to 'link' string but other params will stay behind it. Just think of it as an overlay for default URI of current route.
I had to modify my custom route class a little bit. First of all, i had to change its namespace to Application\Router. Here is a full class:
// EDIT - file within ModuleName/src/Router/Alias.php
namespace Application\Router;
use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Mvc\Router\Http;
class Alias extends Http\Segment
{
private static $_navigation = null;
public function match(Request $request, $pathOffset = null)
{
$uri = $request->getUri();
$path = $uri->getPath();
$items = self::$_navigation->findAllBy('route', 'node');
$params = null;
if($items != null){
$t = sizeof($items);
for ($i=0; $i < $t; $i++) {
$item = $items[$i];
$params = $item->getParams();
if (isset($params['link']) && $params['link']==$path){
$uri->setPath('/'.$item->getRoute().'/'.$params['id']);
$request->setUri($uri);
break;
}
}
}
return parent::match($request, $pathOffset);
}
public function setNavigation($navigation){
self::$_navigation = $navigation;
}
protected function buildPath(array $parts,
array $mergedParams, $isOptional, $hasChild)
{
if(isset($mergedParams['link'])){
return $mergedParams['link'];
}
return parent::buildPath($parts, $mergedParams,
$isOptional, $hasChild);
}
}
here is sample part of module.config.php:
'navigation' => array(
// The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key
'default' => array(
// And finally, here is where we define our page hierarchy
'account' => array(
'label' => 'Account',
'route' => 'node',
'params' => array(
'id' => '2',
),
'pages' => array(
'home' => array(
'label' => 'Dashboard',
'route' => 'node',
'params' => array(
'id' => '8',
'link' => '/about/gallery'
),
),
'login' => array(
'label' => 'Sign In',
'route' => 'node',
'params' => array(
'id' => '6',
'link' => '/signin'
),
),
'logout' => array(
'label' => 'Sign Out',
'route' => 'node',
'params' => array(
'id' => '3',
),
),
),
),
),
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'node' => array(
'type' => 'Application\Router\Alias',
'options' => array(
'route' => '/node[/:id]',
'constraints' => array(
'id' => '[0-9]+'
),
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
'id' => '0'
),
),
'may_terminate' => true,
),
),
),
If it is just for routes like /about and /about/galery then you can simply use literal routes with child routes
'about' => array(
'type' => 'literal',
'options' => array(
'route' => '/about',
'defaults' => array(
'controller' => 'module-controller-about',
'action' => 'index'
)
),
'may_terminate' => true,
'child_routes' => array(
'galery' => array(
'type' => 'literal',
'options' => array(
'route' => '/galery',
'defaults' => array(
'controller' => 'module-controller-galery'
)
)
)
)
)
When it comes to URLs like /blog/1-my-great-seo-title you probably have to set-up a Regex route (which is the slowest, literals are fastest).
Maybe check out DASPRiDs Slides from his Router Presentation

ZF2 Select element usage

I'm using Zend Framework 2 and I need a Dependent Dropdown. When user select an category (cat_id on my example) the system fills the subcategory (sca_id) with the correct elements.
I could do that by creating an application like this:
My form looks like:
$this->add(array(
'name' => 'cat_id',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Categoria',
'value_options' => array(
'' => '',
),
),
));
$this->add(array(
'name' => 'sca_id',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Sub Categoria',
'style' => 'display:none;', // Esse campo soh eh exibido qndo uma categoria for escolhida
'value_options' => array(
'' => '',
),
),
));
Note that I don't fill the value_options there, because I choose do that in my controller, where the Service Manager is avaliable:
$form = new ProdutoForm('frm');
$form->setAttribute('action', $this->url()->fromRoute('catalogo-admin', array( ... )));
// Alimenta as comboboxes...
$form->get('cat_id')->setValueOptions($this->getCategoriaService()->listarCategoriasSelect());
On the change event of cat_id I do an $.ajax to grab the elements from an Action and fill the sca_id.
That works fine!
The problem is on my validation:
$this->add(array(
'name' => 'cat_id',
'require' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$this->add(array(
'name' => 'sca_id',
'require' => true,
'filters' => array(
array('name' => 'Int'),
),
));
When I submit my form it keeps saying : The input was not found in the haystack for both dropdowns...
What I'm doing wrong?
Extra questions : There's a better way to fill my dropdowns?
Ps.: I guess this question Disable notInArray Validator Zend Framework 2 asks something similar than me, but I wanted to detail more my problem.
Well, I realized that I should populate my select element before validate my form!
// SaveAction
$request = $this->getRequest();
if ($request->isPost())
{
$form = new ProdutoForm();
// Alimenta as comboboxes...
$form->get('cat_id')->setValueOptions($this->getCategoriaService()->listarCategoriasSelect());
$form->get('sca_id')->setValueOptions($this->getSubCategoriaService()->listarSubCategoriasSelect());
// If the form doesn't define an input filter by default, inject one.
$form->setInputFilter(new ProdutoFormFilter());
// Get the data.
$form->setData($request->getPost());
// Validate the form
if ($form->isValid())
{
// Valid!
}else{
// Invalid...
}
That code works nice. My form now validate perfectly!