Sylius New Field on Taxon Forms not Saving - taxonomy

I've added a new field to the Taxon entity, and have the new field showing up on the form on the edit Taxon page in the admin panel. My problem is that I can't get my new field to save to the Taxon. I receive a success message, but only existing Taxon fields save, while my new field clears. Here's my code (note I'm making changes to Sylius core rather than extending, as proof of concept. Once I have this working, I'll extend properly):
src/Sylius/Bundle/TaxonomyBundle/Form/Type/TaxonType.php:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('translations', 'sylius_translations', [
'type' => 'sylius_taxon_translation',
'label' => 'sylius.form.taxon.name',
])
->add('my_new_field', 'text', [
'label' => 'My New Field',
'required' => false
])
->addEventSubscriber(new AddCodeFormSubscriber())
->addEventSubscriber(new BuildTaxonFormSubscriber($builder->getFormFactory())
);
}
src/Sylius/Component/Core/Model/Taxon.php:
protected $my_new_field;
and
public function getMyNewField() {
return $this->my_new_field;
}
public function setMyNewField($myNewField) {
$this->my_new_field = $myNewField;
}
After updating the Taxon model, I ran doctrine:diff and then ran the migration to add my new field to the model. I can confirm, the field was added to the database.
The field also shows up on Taxons now, on the edit screen. I can input text into the field and it posts correctly, but does not ever save to the taxon.
I would think I'm missing some controller logic, but it seems that taxons go through the standard ResourceController's updateAction() and I haven't been able to figure out how to make this aware of the new field which needs to be saved.

You're probably missing ORM mapping in Taxon.orm.xml file.
Remember:
if you've added your properties on Sylius\Component\Taxonomy\Model\Taxon you have to update src/Sylius/Bundle/TaxonomyBundle/Resources/config/doctrine/model/Taxon.orm.xml.
if you've added your properties on Sylius\Component\Core\Model\Taxon you have to update src/Sylius/Bundle/CoreBundle/Resources/config/doctrine/model/Taxon.orm.xml
It's also probably better to extend Taxon model from Core component.

Related

Accessing to the `latest` record stored in DB table right after recording it

In Laravel After recording last row to a DB table, can I safely access same recorded data right after recording it by calling latest() queries? Because transactions by other users may occur at the same time, and it may not really be the last record anymore?
Edit:
For example:
Public function StoreNotif($data){
auth()->user()->Notif()->create(store $data here..)
}
Public function SendNotif(){
$data="123";
$this->StoreNotif($data)
event(new Notification(stored Notif instance?));
}
No, you cannot rely on the database to return the record from your current script.
The ->latest() method will always sort the records with the most recent created_at date first.
https://laravel.com/docs/6.x/queries#ordering-grouping-limit-and-offset
But you haven't provided any code or explanation as to why this is a concern. If you just created a new record, why do you need to query it again? You should already have access to an instance of the model.
EDIT: I've made a few edits to demonstrate how you would pass the model from a controller to an event as referenced in the comments. Please post your code if you want more specific help.
SomeController.php
function store()
{
$model = Model::create([
'some_data' => 1
]);
// fire an event with the newly created model
event(new SomeEvent($model));
dd($model);
}
------------------------
Model {
// ...
attributes: [
'id' => 101,
'some_data' => 1
'created_at' => '2019-10-06 12:48:01',
'updated_at' => '2019-10-06 12:48:01',
]
// ...
}
SomeEvent.php
<?php
namespace App\Events;
use App\Model;
use Illuminate\Queue\SerializesModels;
class SomeEvent
{
use SerializesModels;
public $model;
public function __construct(Model $model)
{
$this->model = $model;
// ...
}
}
EDIT: Per your newly added code, you just need to pass the new model back to the original method. You could do something like this.
Public function StoreNotif($data)
{
// add a return statement
return auth()->user()->Notif()->create(store $data here..);
}
Public function SendNotif()
{
$data="123";
// store the returned data to a variable
$model = $this->StoreNotif($data);
// call the event with the model instance
event(new Notification(model));
}
I'm not sure what 'latest' is but I do know that MySQL uses SELECT LAST_INSERT_ID as the query to get the 'per-connection' id of the last inserted item. Under the covers it's using mysql_insert_id so if you are in a language that supports it, you could use that too.

Magento 1.9 add custom column to associated products grid

We have an existing customization that appears to have broken when we upgraded from 1.7 to 1.9 community.
The customization adds a column to the associated products grid.
The customization is a local override of
app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
This was done before I started on the project
$this->addColumn('breakdown_part_no', array(
'header' => Mage::helper('catalog')->__('Part No'),
'name' => 'breakdown_part_no',
'type' => 'varchar',
'index' => 'breakdown_part_no',
'width' => '120px',
'editable' => true,
));
This was added to _prepareColumns()
Another customization was added to method getSelectedGroupedProducts()
public function getSelectedGroupedProducts()
{
$associatedProducts = Mage::registry('current_product')->getTypeInstance(true)
->getAssociatedProducts(Mage::registry('current_product'));
$products = array();
foreach ($associatedProducts as $product) {
$products[$product->getId()] = array(
'qty' => $product->getQty(),
'position' => $product->getPosition(),
'breakdown_part_no' => $product->getBreakdownPartNo(),
);
}
return $products;
}
The behavior is that the column appears in the admin and can be edited, however when saved, it does not save any value.
If I modify the getSelectedGroupedProducts part and set a hard coded value, it displays still no value (blank field), but interestingly if I click save with no value, it saves the value that was hard coded. If I enter any value in the field, it saves as a blank. This is really strange behavior that makes no sense to me.
If I change one of the other fields, such as position to be a hard coded value, it appears instantly and works as expected. Please let me know the proper way for this to work.
There are several posts on various forums about how to do the above and the modification mentioned is true, but what all of the other posts left out was the adminhtml layout input. When a user edits product data in Magento Admin (Associated Products), the data is serialized and sent to the controller save action. I noticed that the fields were not present when a value was entered. This is because the value wasn't in the layout so it was being stripped off of the request before it was posted to the controller.
Add input field in adminhtml/default/default/layout/catalog.xml
adminhtml_catalog_product_supergroup
addColumnInputName

Insert a field with value whenever new instance of modal is created

I want to insert a field with value whenever new row is created for a modal.
Ex: Suppose this is my user.php modal
class User extends Authenticatable
{
protected $guarded = ['id'];
}
What i want is in my application anywhere when i insert a row in user table, then i want to insert an extra column code with its value in user table.
Ex: If i do below in my application
User::create(['name'=>'xyz', 'password' => 'kajsndjk']);
then it should insert an extra column code =>'Qwedf' also in my table.
In my application there are many places where i am creating the users, so i don't want to remember every time to insert code column.
Please suggest how can i achieve it.
Overriding the static create function on the User class is the only thing that will work in my opinion.
public static function create(array $attributes = [])
{
$object = parent::create($attributes);
$object->code = 'some text';
$object->save();
return $object;
}
I've tested and like I expected, oseintow's answer will not work, because it would work only if you directly modified code variable, which you obviously are not doing.
Add this mutator to your User model
public function setCodeAttribute($value)
{
$this->attributes['code'] = "Qwedf";
}
Anytime you are saving a record code will be assigned the Qwedf value

Preventing malicious users update data at add action

Here is a basic add action:
public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
$this->Flash->success('Success.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('Fail.');
}
}
$this->set(compact('article'));
}
If a malicious user injects at form a field with name id and set the value of this field to 2. Since the user do that the id value will be in $this->request->data so at $this->Articles->patchEntity($article, $this->request->data) this id will be patched and at $this->Articles->save($article) the record 2 will be updated instead of create a new record??
Depends.
Entity::$_accessible
If you baked your models, then this shouldn't happen, as the primary key field will not be included in the entities _accessible property, which defines the fields that can be mass assigned when creating/patching entities. (this behavior changed lately)
If you baked your models, then this shouldn't happen, as the primary key field(s) will be set to be non-assignable in the entities _accessible property, which means that these the fields cannot be set via mass assignment when creating/patching entities.
If you didn't baked your models and haven't defined the _accessible property, or added the primary key field to it, then yes, in case the posted data makes it to the patching mechanism, then that is what will happen, you'll be left with an UPDATE instead of an INSERT.
The Security component
The Security component will prevent form tampering, and reject requests with modified forms. If you'd use it, then the form data wouldn't make it to the add() method in the first place.
There's also the fieldList option
The fieldList option can be used when creating/patching entities in order to specifiy the fields that are allowed to be set on the entity. Sparse out the id field, and it cannot be injected anymore.
$article = $this->Articles->patchEntity($article, $this->request->data, [
'fieldList' => [
'title',
'body',
//...
]
]);
And finally, validation
Validation can prevent injections too, however that might be considered a little wonky. A custom rule that simply returns false would for example do it, you could create an additional validator, something like
public function validationAdd(Validator $validator) {
return
$this->validationDefault($validator)
->add('id', 'mustNotBePresent', ['rule' => function() {
return false;
}]);
}
which could then be used when patching the entity like
$article = $this->Articles->patchEntity($article, $this->request->data, [
'validate' => 'add'
]);

How to do Kohana Validation of $_serialize_column inside ORM

The validation on Kohana ORM is done using rules
function rules()
{
return array(
'username' => array(
array('not_empty'),
array(array($this, 'availability')),
)
);
}
I'm struggling to validate a JSON encoded column using $_serialize_columns.
class Model_Admin extends ORM {
protected $_belongs_to = array();
protected $_has_many = array(
'plans' => array(),
'groups' => array(),
'transactions' => array(),
'logins' => array()
);
protected $_serialize_columns = array('data');
/**
* #param array $data
* #param Validation $validation
*
* #return bool
*/
public function data($data, $validation)
{
return
Validation::factory(json_decode($data, TRUE))
// ... rules ...
->check();
}
public function rules()
{
return array(
'data' => array(
array(array($this, 'data'), array(':value',':validation')
)
);
}
}
the array that gets encoded is:
array(
'name' => '',
'address' => '',
'phone' => '',
'postalcode' => ''
);
the data method receives the json encoded data, because the ORM runs the filters before doing the validation, so I need to convert it back to an associative array, then create a new validation object to check specifically for the content of that array. Because I can't merge Validation rules from another Validation instance
Updated Answer
The use of a second validation object is necessary since save() causes the internal model validation object to be checked. This means that rules added to the validation object being checked from a validation rule will be ignored (Validation->check() imports the rules into local scope before looping).
Since the data itself is technically another object (in the sense of object relationships, it has its own dataset that needs validation) the ideal solution would be to find a way to create a real model that saves the data.
There are numerous other benefits to saving data with proper database column definitions, not least if you need to perform data property lookups, make in-situ changes etc. (which would otherwise require unserializing the data column, potetnailly in all rows).
There are some alternatives, but they feel like kludges to me:
Create a model that represents the data object and add rules to it, using check() to validate the data (problem: will require a lot of maintenance, no real-world table means columns must be manually defined).
Set the data as real columns in the Admin model, and use a filter that will convert it into the data column on set (problem: again, must manually define the columns and exclude the additional columns from the save operation).
I hope this is of some use.
Original Answer
The Kohana ORM save() method permits the inclusion of an "extra" validation object, which is merged into the main ORM validation object namespace.
This is documented briefly here.
If I have understood correctly, I think you are looking to do something like this:
// another script, e.g., a controller
// Create the model
$admin = ORM::factory('Admin');
// $data = the data as an array, before serialization ...
$extra_validation = Validation::factory($data)
// add ->rule() calls here, but DO NOT chain ->check()
;
// Set $data in the model if it is going to be saved, e.g., $admin->data = $data;
// Set other data... e.g., $admin->foo = 'bar';
// Save the model
try {
$admin->save($extra_validation);
}
catch (ORM_Validation_Exception $e)
{
// Manipulate the exception result
}
While in this example you must still create another validation object, you are now able to catch all exceptions in a single block. I would recommend using var_dump() or similar on $e->errors() to check the namespace if you are using i18n messages to provide a human-readable error message. You should find that a namespace called "_external" has been created in the response.