SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'Cumque esse a adipis' for column 'tag_id' at row 1 - eloquent

I got an error like that, I've tried various ways but haven't found a solution.
App\Models\Post
public function tags()
{
return $this->belongsToMany(Tag::class);
}
App\Models\Tag
public function posts()
{
return $this->belongsToMany(Post::class);
}
PostController
public function store(Request $request)
{
//dd($request->all());
$this->validate($request, [
'title' => 'required|string|max:255',
'description' => 'required',
'category' => 'required',
'tag' => 'required',
]);
Post::create([
'title' => $request->title,
'description' => $request->description,
'category_id' => $request->category,
'user_id' => Auth()->id()
])->tags()->attach($request->tag);
return redirect()->route('blog.create')->with('status', 'Post Created Successfully');
}
Please guide me.....

Related

Magento 1.9 sending custom form - form data not found in controller

I am having trouble with a simple form. I am quite sure that I miss some critical info about this topic...
I created a custom module, I created a custom form
<?php
class modulename_History_Block_Adminhtml_History_Edit_Form extends Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'name' => 'edit_form',
'action' => $this->getUrl('*/*/history', array('id' => 'orders_export')),
'method' => 'post',
'enctype' => 'multipart/form-data',
'data' =>'somethingsomethingdarkaside'
));
$this->setForm($form);
$fieldset = $form->addFieldset('Filtrování objednávek', array('legend'=> 'Nastavte filtr pro report objednávek'));
$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('date_from', 'date', array(
'label' => 'Změna statusu objednávek od:',
'title' => 'Změna statusu objednávek od:',
'time' => true,
'name' => 'filter_date_from',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateTimeFormatIso,
'required' => true,
));
$fieldset->addField('export_history_order_status_changed', 'button', array(
'label' => 'Exportovat do souboru:',
'value' => 'Export',
'name' => 'export_history_order_status_changed',
'class' => 'form-button',
'onclick' => "setLocation('{$this->getUrl('*/*/export')}')",
));
$form->setUseContainer(true);
return parent::_prepareForm();
}
And then there is a controller. When the button is pressed, it goes to the correct controller to a correct action. However no data in post received:
<?php
class modulename_History_Adminhtml_History_HistoryController extends Mage_Adminhtml_Controller_Action {
protected function _initAction()
{
return $this;
}
/**
* A page with the form, creating the block with it.
*
*/
public function editAction()
{
$this->_title('Historie objednavky')
->loadLayout()
->_setActiveMenu('modulename/historymenu');
$this->_addContent($this->getLayout()->createBlock('modulename_history/adminhtml_history_edit'));
$this->renderLayout();
}
/**
* A main entrance - when the filter is set and the "export" button pressed then this is the function which starts.
*
* #return bool|Mage_Core_Controller_Varien_Action - either we return a downloadable file or we return false.
*/
public function exportAction()
{
if ($this->_setParameters())
{
if ($this->_setOrdersIds())
{
return $this->_getDownloadFile();
}
}
return false;
}
/**
* Try to get parameters from the admin form. If all correct then we return true. If there is something not set
* then we are unable to continue and we return false.
*
* #return bool - either we were successful with getting the parameters or not.
*/
protected function _setParameters()
{
$parameters = $this->getRequest()->getParams();
$pokus = $this->getRequest()->getPost();
$necf = $this->getRequest()->getPost('edit_form');
$neco = Mage::app()->getRequest()->getParam('edit_form');
}
}
Hellou,
so a competent colleque find an answer within minutes. I mean it was as silly as expected, just remove on click action on button and set the heading from the button to the form. And changed the button to submit. I quess the guy I copied the code from used some other spells of high magic so it worked for him. I hope this will help. Correct form below:
<?php
class modulename_History_Block_Adminhtml_History_Edit_Form extends
Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'name' => 'edit_form',
//'action' => $this->getUrl('*/*/history', array('id' => 'orders_export')),
'action' => $this->getUrl('*/*/export', array('id' => 'orders_export')),
'method' => 'post',
'enctype' => 'multipart/form-data',
'data' =>'somethingsomethingdarkaside'
));
$this->setForm($form);
$fieldset = $form->addFieldset('Filtrování objednávek', array('legend'=> 'Nastavte filtr pro report objednávek'));
$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('date_from', 'date', array(
'label' => 'Změna statusu objednávek od:',
'title' => 'Změna statusu objednávek od:',
'time' => true,
'name' => 'filter_date_from',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateTimeFormatIso,
'required' => true,
));
$fieldset->addField('export_history_order_status_changed', 'submit', array(
'label' => 'Exportovat do souboru:',
'value' => 'Export',
'name' => 'export_history_order_status_changed',
'class' => 'form-button',
//'onclick' => "setLocation('{$this->getUrl('*/*/export')}')",
));
$form->setUseContainer(true);
return parent::_prepareForm();
}

Zend - Dynamic form dropdown

I start with zend framework and I'm having trouble implementing a dynamic drop-down list.
I need to create a simple dropdown list of events select from the database.
This is my Module class :
public function getFormElementConfig()
{
return array(
"factories" => [
'participant_form' => function (ServiceManager $serviceManager) {
/** #var EntityManager $entityManager */
$entityManager = $serviceManager->get("doctrine.entitymanager.orm_default");
$events = $entityManager->getRepository('Application\Entity\Event')->findAll();
$eventForSelect = array();
foreach ($events as $event) {
$eventForSelect[$event->getId()] = $event->getName();
}
/** #var \Zend\Form\Form $form */
$form = new ParticipantForm();
$form->setHydrator(new DoctrineHydrator($entityManager));
$form->setObject(new Participant());
$form->setOption('event_for_select', $eventForSelect);
return $form;
},
]
);
}
but I do not know how to get the option 'event_for_select' in my form :
class ParticipantForm extends Form
{
public function __construct($name = null)
{
parent::__construct('user');
$this->setAttribute('class', 'form-horizontal');
$this->add([
'name' => 'id',
'type' => 'Hidden',
]);
$this->add([
'name' => 'firstname',
'type' => 'Text',
'options' => [
'label' => 'Prénom',
],
]);
$this->add([
'name' => 'event',
'type' => 'Select',
'options' => [
'label' => 'Event',
'value_options' => // ?? $event_for_select
],
]);
Thanks for your help !
Add field in your form class:
class ParticipantForm extends Form
{
protected $eventForSelect;
public function setEventForSelect($eventForSelect)
{
$this->eventForSelect = $eventForSelect;
// update field value options
$this->get('event')
->setValueOptions($this->eventForSelect);
return $this;
}
// rest of form class code
}
Then use setEventForSelect() method in your factory:
/** #var \Zend\Form\Form $form */
$form = new ParticipantForm();
$form->setHydrator(new DoctrineHydrator($entityManager));
$form->setObject(new Participant());
$form->setEventForSelect($eventForSelect);
return $form;
And then in form:
$this->add([
'name' => 'event',
'type' => 'Select',
'options' => [
'label' => 'Event',
'value_options' => $this->eventForSelect,
],
]);

Symfony 3.3 Form - EntityType field does not select option

For some unknown reason, the EntityType form field will not display the selected option on submit, even though the name of the column matches and data passes.
I've created a form that I'm using to select some values that will filter a list of products.
<?php namespace AppBundle\Filter;
use AppBundle\Entity\ProductCategory;
use AppBundle\Repository\ProductCategoryRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ProductFilterType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', null, [
'required' => false,
'label' => 'SKU'
])
->add('productCategory', EntityType::class,
array(
'class' => ProductCategory::class,
'choice_label' => 'name',
'choice_value' => 'id',
'placeholder' => '',
'label_attr' => array('title' => 'Category for this product'),
'query_builder' => function (ProductCategoryRepository $v) {
return $v->createQueryBuilder('v')
->orderBy('v.name',' ASC');
}
))
->add('name', null, [
'required' => false,
])
->add('description', null, [
'required' => false,
])
;
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'app_bundle_product_filter_type';
} }
The form renders as expected, and it submits a post to the same URL, which filters based on the value received from the request.
That works ok.
However, when the form is re-rendered, the option that was selected before the form filter submission is no longer selected. All other inputs are repopulating.
I did notice that when I'm working with a form that is bound to an Entity (ie: Editting and saving the entity) and using the ConfigureOptions method to set the data class, that the EntityType form field works as expected. However, I need it to work in this case where the overall form is not bound to an Entity.
EDIT:
Doing these steps worked for me...but it seems a bit odd.
Injected entity manager into the form constructor:
public $em;
public function __construct(EntityManager $em) {
$this->em = $em;
}
Then updated the EntityType form field to get the object based on the array value:
->add('productCategory', EntityType::class,
array(
'class' => ProductCategory::class,
'choice_label' => 'name',
'choice_value' => 'id',
'placeholder' => '',
'label_attr' => array('title' => 'Category for this product'),
'data' => $this->em->getReference("AppBundle:ProductCategory",
isset($options['data']['productCategory']) ? $options['data']['productCategory'] : 0),
'query_builder' => function (ProductCategoryRepository $v) {
return $v->createQueryBuilder('v')
->orderBy('v.name',' ASC');
}
))
...
Another solution is using a Data Transformer.
Remove the data attribute from the productCategory type, and add a data transformer to the end of the build method:
$builder->get('productCategory')
->addModelTransformer(new CallbackTransformer(
function ($id) {
if (!$id) {
return;
}
return $this->em->getRepository('AppBundle:ProductCategory')->find($id);
},
function($category) {
return $category->getId();
}
));
If you use the same transformer in multiple places, you can extract it into its own class.
My workaround was like this ...
pass data and entity manager to formType.
$form = $this->createForm(new xxxType($this->get('doctrine.orm.entity_manager')), xxxEntity, array(
'method' => 'POST',
'action' => $this->generateUrl('xxxurl', array('id' => $id)),
'selectedId' => xxxId,
));
setDefaultOptions in form Type initialize as an empty array for selectedId
$resolver->setDefaults(array(
'data_class' => 'xxx',
'selectedId' => array()
));
and in builder
->add('productCategory', EntityType::class,
array(
'class' => ProductCategory::class,
'choice_label' => 'name',
'choice_value' => 'id',
'placeholder' => '',
'label_attr' => array('title' => 'Category for this product'),
'query_builder' => function (ProductCategoryRepository $v) {
return $v->createQueryBuilder('v')
->orderBy('v.name',' ASC');
},
'data'=>$this->em->getReference("xxx",$options['selectedId'])
))
for more details, you can see this answer Symfony2 Setting a default choice field selection

$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 not valid but no error messages

i have a strange Problem with one of my Zend_Forms: isValid() correctly states that my form isn't valid but i do not get any error messages. How could that happen?
Heres the code, nothing special here. $data is an array of post data. The problem occurs when no file is sended.
$form = $this->getForm('Foto');
if(!$form->isValid($data)) {
var_dump( $form->getErrors() ); die;
return false;
}
getForm() initializes the form if not allready done. The form itself is pretty straight forward.
class Media_Forms_Foto extends Zend_Form
{
/**
* Initializer function. Setup forms fields.
*/
public function init()
{
$this->setName('add Image');
$this->setAction('media/gallery/addImage');
$this->addElement('Hidden', 'gallery', array(
'filters' => array(),
'validators' => array('Digits'),
'required' => false,
'label' => '',
));
$this->addElement('File', 'foto', array(
'required' => true,
'destination' => ROOT_PATH .'public/upload/tmp/',
'label' => 'Foto',
'validators' => array(
new Zend_Validate_File_IsImage(array(
'image/jpeg', 'image/gif', 'image/png'
))
),
'maxFileSize' => 2097152,
));
$this->addElement('Submit', 'add', array(
'required' => false,
'ignore' => true,
'label' => 'add Foto',
));
$this->setAttrib('enctype', 'multipart/form-data');
}
}
Output:
array(3) {
["gallery"]=>
array(0) {
}
["foto"]=>
array(0) {
}
["add"]=>
array(0) {
}
}
Are you using the jquery form plugin by any chance? if so, try using the iframe mode to upload files:
var options = {
url: '/test/upload',
success: function(response) {
},
beforeSubmit: disableSubmitButtons,
iframe: true,
dataType : 'json'
};
$('#testForm').ajaxForm(options);