new Model fills updated_at - lumen

I am using Lumen and I just found an issue. When creating a new model, the code also fills 'updated_at' despite the model is new and it wasn't updated yet (since it was just created). Since this is a crucial flaw and would be strange that it wasn't noticed till now, I presume I am doing something wrong.
App\User.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
const CREATED_AT = 'date_created';
const UPDATED_AT = 'date_updated';
protected $fillable = [
'name',
'email',
'role_id',
'password'
];
protected $hidden = [
'token',
'password',
'date_password_reset',
'token_password_reset'
];
protected $casts = [
'date_created' => 'datetime:Uv',
'date_updated' => 'datetime:Uv',
'date_password_reset' => 'datetime:Uv'
];
protected $with = ['userRoles'];
protected $validationRules = [...];
}
App\Http\Controllers\UsersController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use Illuminate\Validation\ValidationException;
use Exception;
class UsersController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
...
// first attempt
public function create(Request $request) {
$this->validate($request, (new User)->rules('create'));
$user = new User;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
$user->role_id = $request->input('role_id');
$user->active = $request->boolean('active');
$user->save();
return response()->json(
[
'success' => true,
'message' => 'User successfully created',
'data' => User::query()->find($user->id)
], 200);
}
// second attempt
public function create(Request $request) {
$this->validate($request, (new User)->rules('create'));
$user = new User;
$user->update($request->input());
$user->password = Hash::make($request->input('password'));
$user->active = $request->boolean('active');
$user->save();
return response()->json(
[
'success' => true,
'message' => 'User successfully created',
'data' => User::query()->find($user->id)
], 200);
}
// third attempt
public function create(Request $request) {
$this->validate($request, (new User)->rules('create'));
$user = new User($request->input());
$user->password = Hash::make($request->input('password'));
$user->active = $request->boolean('active');
$user->save();
return response()->json(
[
'success' => true,
'message' => 'User successfully created',
'data' => User::query()->find($user->id)
], 200);
}
}
DB migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Hash;
class CreateUsersTable extends Migration
{
protected $initialUsers = [
[
'name' => 'Administrator',
'email' => 'admin#localhost.local',
'password' => null,
'role_id' => null,
'active' => 1
]
];
protected $initialRoles = [
[
'name' => 'Administrator'
],
[
'name' => 'User'
]
];
protected $initialUserRoles = [];
public function up()
{
DB::beginTransaction();;
Schema::create('users_roles', function (Blueprint $table) {
$table->id();
$table->string('name', 50);
$table->timestamp('date_created')->useCurrent();
$table->timestamp('date_updated')->nullable()->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
});
foreach ($this->initialRoles as $data) {
DB::table('user_roles')->insert($data);
}
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name', 100);
$table->string('email', 255)->unique();
$table->string('password');
$table->unsignedBigInteger('role_id')->nullable();
$table->string('token', 255)->nullable();
$table->tinyInteger('active');
$table->timestamp('date_password_reset')->nullable();
$table->string('token_password_reset')->nullable();
$table->timestamp('date_created')->useCurrent();
$table->timestamp('date_updated')->nullable()->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
$table->foreign('role_id')->references('id')->on('users_roles')->onDelete('set null')->onUpdate('cascade');
});
$password = Hash::make('xxx#x');
$role_id = DB::table('users_roles')->where('name', 'Administrator')->value('id');
foreach ($this->initialUsers as $data) {
$data['password'] = $password;
$data['role_id'] = $role_id;
$user_id = DB::table('users')->insertGetId($data);
$this->initialUserRoles[] = [
'user_id' => $user_id,
'role_id' => $role_id
];
}
DB::commit();
}
}
Query created by Eloquent:
array (size=3)
'query' => string 'insert into `users` (`name`, `email`, `password`, `role_id`, `active`, `date_updated`, `date_created`) values (?, ?, ?, ?, ?, ?, ?)' (length=131)
'bindings' =>
array (size=7)
0 => string 'Test User 5' (length=11)
1 => string 'test6#test.net' (length=14)
2 => string '$2y$10$lvRGKuznotd8lqwCj2diIONGjyiAkhaNthWGjQyFWbBqiyuf20wpG' (length=60)
3 => string '1' (length=1)
4 => boolean true
5 => string '2020-06-17 10:30:07' (length=19)
6 => string '2020-06-17 10:30:07' (length=19)
'time' => float 5.5
All three create() attempts are filling up 'updated_at' despite that one should stay NULL until an actual update is done on this model. Can you guys give me any indication what am I doing wrong? Would also like to keep the $model->update($request->input()) functionality if possible, so that I do not need too assign each field manually.

Because Lumen/Laravel is handling the "created_at" and "updated_at" fields on it's own and it sets both to the same timestamp when a record is created (which I do not like), I created my own solution.
First is already in place when creating a migration. I created my own timestamp fields and those are already properly updated by MySQL:
$table->timestamp('date_created')->useCurrent();
$table->timestamp('date_updated')->nullable()->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
And of course, disable timestamp handling for Lumen in User.php model:
public $timestamps = false;
But in case that this is not possible for any reason or if you want Lumen/Laravel to handle those, this is the code I wrote in User.php model:
const CREATED_AT = 'date_created';
const UPDATED_AT = 'date_updated';
public $timestamps = false;
public static function boot() {
parent::boot();
static::creating(function ($model) {
$model->{self::CREATED_AT} = $model->freshTimestamp();
});
static::updating(function ($model) {
$model->{self::UPDATED_AT} = $model->freshTimestamp();
});
}

Related

Exclude fields from a Resource template Laravel 7 and 8

I have come across a solution that filters fields from a resource collection in the Controller CompanyController.php
E.g The code below returns all the values except company_logo
CompanyResource::collection($companies)->hide(['company_logo']);
CompanyResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CompanyResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected $withoutFields = [];
public static function collection($resource)
{
return tap(new CompanyResourceCollection($resource), function ($collection) {
$collection->collects = __CLASS__;
});
}
// Set the keys that are supposed to be filtered out
public function hide(array $fields)
{
$this->withoutFields = $fields;
return $this;
}
// Remove the filtered keys.
protected function filterFields($array)
{
return collect($array)->forget($this->withoutFields)->toArray();
}
public function toArray($request)
{
return $this->filterFields([
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'telephone' => $this->telephone,
'company_logo' => $this->company_logo,
'social_links' => $this->social_links,
]);
}
}
Now from my UserResource I still want to specify fields I don't want returned from the same CompanyResource but it's not a collection anymore in the UserResource
UserResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'email' => $this->email,
'status' => $this->status,
'timezone' => $this->timezone,
'last_name' => $this->last_name,
'first_name' => $this->first_name,
'tags' => TagResource::collection($this->whenLoaded('tags')),
'company' => new CompanyResource($this->whenLoaded('company')),
];
}
So my idea is to be able to specify excluded fields on 'company' => new CompanyResource($this->whenLoaded('company')), Been stuck here for some time.
After researching I found a working solution for my problem
'company' => CompanyResource::make($this->whenLoaded('company'))->hide(['company_logo']),
Instead of the below which I could not use flexibly use:
'company' => new CompanyResource($this->whenLoaded('company')),

Prestashop 1.7 renderform by admincontroller error

for my module i need to generate a form with helper. I found nothing with my error on the web so... I post again something...
Here my AdminYoutubeHomeController
<?php
class AdminYoutubeHomeController extends ModuleAdminController
{
public function __construct()
{
$this->bootstrap = true;
$this->display = 'view';
parent::__construct();
$this->meta_title = $this->l('Youtube');
if (!$this->module->active) {
Tools::redirectAdmin($this->context->link->getAdminLink('AdminHome'));
}
}
public function renderView()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitYoutubeHomeModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign([
'youtube_dir', _PS_MODULE_DIR_.'youtubehome',
'youtube_embeded' => "https://www.youtube.com/embed/",
'youtubeLink' => Configuration::get('YOUTUBEHOME_LINK_VIDEO')
]);
return $this->context->smarty->fetch(_PS_MODULE_DIR_.'youtubehome/views/templates/admin/youtubehome.tpl').$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
public function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->name_controller = $this->module->name;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitYoutubeHomeModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->module->name.'&tab_module='.$this->module->tab.'&module_name='.$this->module->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
public function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-youtube-play"></i>',
'desc' => $this->l('Enter your youtube end link'),
'name' => 'YOUTUBEHOME_LINK_VIDEO',
'label' => $this->l('Link'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
public function getConfigFormValues()
{
return array(
'YOUTUBEHOME_LINK_VIDEO' => Configuration::get('YOUTUBEHOME_LINK_VIDEO'),
);
}
/**
* Save form data.
*/
public function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
}
}
}
And here the error
My tpl file is in modules/youtubehome/views/templates/admin/youtubehome.tpl
I don't want to override the default form. Do you think i have doing something wrong ?
EDIT POST
Here it's the error with ps_version
try with :
$this->setTemplate('module:youtubehome/views/templates/admin/youtubehome.tpl');
Regards

InputFilter "setRequired" not working for html5 multiple

I'm having hard time with a weird behaviour of fileinput.
This is my form:
namespace Frontend\Form;
use NW\Form\Form;
use Zend\InputFilter;
use Zend\Form\Element;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class EnrollStructure extends Form implements ServiceManagerAwareInterface
{
protected $sm;
public function __construct($name=null) {
parent::__construct("frmEnrollStructure");
$this->setAttribute("action", "/registrazione_struttura/submit")
->setAttribute('method', 'post')
->setAttribute("id", "iscrizione_struttura")
->setAttribute("class", "form fullpage");
$this->addInputFilter();
}
public function init()
{
$structureFs = $this->sm->get('Structure\Form\Fieldsets\Structure');
$structureFs->setUseAsBaseFieldset(true);
$structureFs->remove("id")
->remove("creationTime")
->remove("latLon");
$file = new Element\File("images");
$file->setAttribute('multiple', true);
$this->add($structureFs)->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Iscriviti',
'id' => 'sbmtEnrollStructure',
'class' => 'submit_btn'
),
));
$this->setValidationGroup(
array(
'structure' =>
array(
'companyname',
'vatNumber',
'addressStreet',
'addressZip',
'addressCity',
'addressRegion',
'fax',
'publicPhone',
'publicEmail',
'website',
'status',
'ownerNotes',
'category',
'subcategory',
"facilities",
"agreeOnPolicy",
"agreeOnPrivacy",
"subscribeNewsletter",
"contact" => array("name", "surname", "email", "role", "phone"),
),
"images"
));
}
/**
* Set service manager
*
* #param ServiceManager $serviceManager
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->sm = $serviceManager;
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$fileInput = new InputFilter\FileInput('images');
$fileInput->setRequired(true);
$fileInput->getValidatorChain()
->attachByName('filesize', array('max' => "2MB"))
->attachByName('filemimetype', array('mimeType' => 'image/png,image/x-png,image/jpg,image/jpeg'))
->attachByName('fileimagesize', array('maxWidth' => 2048, 'maxHeight' => 2048));
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
Basically, I mainly use a fieldset which contains most of the data I request to the user, plus a File input field.
This is the Fieldset Structure: (most important parts..)
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Validator\Identical;
use Zend\Validator\NotEmpty;
use Zend\Validator\Regex;
use Zend\Validator\StringLength;
class Structure extends Fieldset implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
protected $sm;
public function __construct()
{
parent::__construct('structure');
}
public function init()
{
$this->setHydrator(new DoctrineHydrator($this->_entityManager(),'Structure\Entity\Structure'));
$this->setObject($this->sm->getServiceLocator()->get("Structure_Structure"));
$id = new Element\Hidden("id");
$name = new Element\Text("companyname");
$name->setLabel("Ragione Sociale");
...........
}
public function getInputFilterSpecification()
{
return array
(
"id" => array(
"required" => false,
),
"companyname" => array(
"required" => true,
"validators" => array(
array('name' => "NotEmpty", 'options' => array("messages" => array( NotEmpty::IS_EMPTY => "Inserire la ragione sociale")))
),
),
.....
}
}
This is my controller:
public function submitAction()
{
try {
$this->layout("layout/json");
$form = $this->getForm('Frontend\Form\EnrollStructure');
//$form->addInputFilter();
$structure = $this->getServiceLocator()->get("Structure_Structure");
$viewModel = new ViewModel();
$request = $this->getRequest();
if ($request->isPost())
{
$post = array_merge_recursive
(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid())
{
$structure = $form->getObject();
$contact = $structure->getContact();
$this->getServiceLocator()->get('Structure_ContactService')->save($contact);
$files = $request->getFiles()->toArray();
if(isset($files['images']))
{
$count = 3;
foreach($files['images'] as $pos => $file)
{
$fpath = $this->getServiceLocator()->get('RdnUpload\Container')->upload($file);
if(!empty($fpath))
{
if(--$count ==0) break;
$asset = $this->getServiceLocator()->get("Application_AssetService")->fromDisk($fpath, $file['name']);
$this->getServiceLocator()->get("Application_AssetService")->save($asset);
$structure->addImage($asset);
}
}
}
$this->getServiceLocator()->get('Structure_StructureService')->save($structure);
$retCode = RetCode::success(array("iscrizione_struttura!" => array("form_submit_successfull")), true);
}
else
{
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
}
$viewModel->setVariable("retcode", $retCode);
return $viewModel;
}
} catch(Exception $e)
{
throw $e;
}
}
The strange thing is that if i remove from the field "images" the "multiple" attribute everything works fine, causing the form not to validate and i get this message:
[images] => Array
(
[fileUploadFileErrorFileNotFound] => File was not found
)
While, if i set the attribute multiple, and the user does not upload a file i get no error, but the form gets invalidated (this is the reason for this "bad" code in my controller:)
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
I found the problem was caused by the Jquery form plugin, without it it works fine. :( In case somebody needs, I think the correct action code can be found here (I haven't tryied it anyway)
https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Controller/ProgressExamples.php

$form->isValid says it is invalid, but my form does not show any error message - Zend Framework 2

Im having a problem with the addAction in my CRUD application. On the controller the logic does not pass the $form->isValid() verification but the form does not show any error message.
I tried with this (Thanks Sam):
foreach($form->get('product')->getElements() as $el)
{
echo $el->getName()." = ".$el->getValue()." > ".$el->getMessages()." <br/>";
}
That only show the name and value of the field, but not the error message.
I've tried letting the form totally blank and it fire "Value is required and can't be empty" error messages, but then, i fill each field one by one until i don't get more error messages but the form still invalid.
My form has a Product Fieldset as a base fieldset and a submit button. Inside Product Fieldset i have an ID field, a name field, a price field and a Brand Fieldset. Inside my Brand Fieldset i have a id field. Like this:
ProductForm:
class ProductForm extends Form
{
public function init()
{
// we want to ignore the name passed
parent::__construct('product');
$this->setName('product');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'product',
'type' => 'Administrador\Form\ProductFieldset',
'options' => array(
'use_as_base_fieldset' => true
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Add',
'id' => 'submitbutton',
),
));
}
}
ProductFieldset:
class ProductFieldset extends Fieldset implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
function __construct($name = null)
{
parent::__construct('product_fieldset');
$this->setHydrator(new ArraySerializableHydrator());
$this->setObject(new Product());
}
public function init()
{
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'name',
'type' => 'Text',
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'name' => 'price',
'type' => 'Text',
'options' => array(
'label' => 'Price',
),
));
$this->add(array(
'name' => 'brand',
'type' => 'BrandFieldset',
));
}
public function setServiceLocator(ServiceLocatorInterface $sl)
{
$this->serviceLocator = $sl;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
BrandFieldset:
class BrandFieldset extends Fieldset
{
function __construct(BrandTable $brandTable)
{
parent::__construct('brand_fieldset');
//$this->setHydrator(new ClassMethodsHydrator(false))->setObject(new Brand());
$this->setHydrator(new ArraySerializableHydrator());
$this->setObject(new Brand());
$brandSelectOptionsArray = $brandTable->populateSelectBrand();
$this->add(array(
'name' => 'id',
'type' => 'Select',
'options' => array(
'label' => 'Brand',
'empty_option' => 'Please select a brand',
'value_options' => $brandSelectOptionsArray,
),
));
}
}
This is my new Form statement in the addAction:
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Administrador\Form\ProductForm');
Inside my model 'Product' i have the inputFilters, required filter for 'id' field, required filter for 'name' field. And for the Brand field i created other inputFilter and added it to the main inputFilter:
$brandFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($brandFilter, 'brand');
The weird behavior is that my editAction works fine and has the same logic.
Is it there any form of echoing an internal error message from the form, something that helps me to understand WHY the form is not valid.
EDIT 2013-06-01
Here is my full Controller:
class ProductController extends AbstractActionController
{
protected $productTable;
protected $brandTable;
public function indexAction()
{
return new ViewModel(array(
'products' => $this->getProductTable()->fetchAll(),
));
}
public function addAction()
{
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Administrador\Form\ProductForm');
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$product = new Product();
$product->brand = new Brand();
$form->setInputFilter($product->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$this->getProductTable()->saveProduct($product);
// Redirect to list of products
return $this->redirect()->toRoute('product');
}
}
return new ViewModel(array(
'form' => $form,
));
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('product', array(
'action' => 'add'
));
}
// Get the Product with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try {
$product = $this->getProductTable()->getProduct($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('product', array(
'action' => 'index'
));
}
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Administrador\Form\ProductForm');
$brand = $this->getBrandTable()->getBrand($product->brand);
$product->brand = $brand;
$form->bind($product);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($product->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getProductTable()->saveProduct($form->getData());
// Redirect to list of products
return $this->redirect()->toRoute('product');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
public function deleteAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('product');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Yes') {
$id = (int) $request->getPost('id');
$this->getProductTable()->deleteProduct($id);
}
// Redirect to list of products
return $this->redirect()->toRoute('product');
}
return array(
'id' => $id,
'product' => $this->getProductTable()->getProduct($id)
);
}
public function getProductTable()
{
if (!$this->productTable) {
$sm = $this->getServiceLocator();
$this->productTable = $sm->get('Administrador\Model\ProductTable');
}
return $this->productTable;
}
public function getBrandTable()
{
if (!$this->brandTable) {
$sm = $this->getServiceLocator();
$this->brandTable = $sm->get('Administrador\Model\BrandTable');
}
return $this->brandTable;
}
}
My case was I passed wrong input filter. isValid returns false, but $form->getMessages() is empty. Form OrderForm had the following:
$form->setInputFilter(new \Application\Form\UserInputFilter($er));
When I changed UserInputFilter to OrderInputFilter it works.
Well, I got the answer :D
This is how the addAction should be:
public function addAction()
{
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Administrador\Form\ProductForm');
$form->get('submit')->setValue('Add');
$product = new Product();
$product->brand = new Brand();
$form->bind($product); // I need to bind the product to the form to pass the isValid() validation
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($product->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$product = $form->getData();
$this->getProductTable()->saveProduct($product);
// Redirect to list of products
return $this->redirect()->toRoute('product');
}
}
return new ViewModel(array(
'form' => $form,
));
}
Apparently i needed to bind and empty product object to the form to be able to pass the isValid() validation. After that i retrieve a product object from the $form->getData().
You can also do: $form->setBindOnValidate(false);

Zend Form : pass var from controller to form

i have this problem : i want to pass to my form a param because i need it to complete a select.
Here's my code
Controller :
$p1 = $this->getRequest()->getParam ( '1' );
$p2 = $this->getRequest()->getParam ( '2' );
$utentepost = new Application_Model_myMapper();
$data = $utentepost->populateFormInsert($p1, $p2);
$form = new Application_Form_myForm();
$form->populate($data);
...
Form
public function init()
{
$this->setMethod('post');
$this->addElement('text', 'p1', array());
$this->addElement('text', 'p2', array());
$this->addElement('select', 'sede_id', array(
'label' => 'Sede',
'required' => true,
'multiOptions' => $this->_setSelect($p1),
));
.... ....
protected function _setSelect($p1) {
... call model/mapper to execute sql query
}
Thanks
You could do the following:
if you have an Constructor defined in your form add "parent::..":
public function __construct($options = null)
{
parent::__construct($options);
}
now pass the attribs as array to your form:
$form = new Application_Form_myForm(array('p1' => $p1, 'p2' => $p2));
inside your form:
protected function _setSelect() {
$p1 = $this->getAttrib('p1');
... call model/mapper to execute sql query
}