ManyToOneAssociationField not working in shopware6 - symfony

I have category_id column in exclude_categories table.
And in exclude_categories entities, I want to add category entity. So, in Exclude categories definition ExcludeCategoryDefinition, I have
protected function defineFields(): FieldCollection
{
return new FieldCollection([
(new IdField('id','id'))->addFlags(new Required(), new PrimaryKey()),
(new FkField('category_id', 'categoryId', CategoryDefinition::class, 'id'))->addFlags(new PrimaryKey(), new ApiAware(), new Required()),
new ManyToOneAssociationField('category', 'category_id', CategoryDefinition::class, 'id', false ),
]);
}
But the category shows null.
#categoryId: "a515ae260223466f8e37471d279e6406"
#category: null
#_uniqueIdentifier: "04bb7ecb26394f5face052f8dc6bf143"
#versionId: null
#translated: []
#createdAt: DateTimeImmutable #1661737483 {#5871 ▶}
#updatedAt: null
-_entityName: "customer_specific_prices_exclude_categories"
-_fieldVisibility: Shopware\Core\Framework\DataAbstractionLayer\FieldVisibility {#5874 ▶}
#extensions: array:1 [▶]
#id: "04bb7ecb26394f5face052f8dc6bf143"

You have to add the association to the criteria you are using to fetch the data:
$criteria = new Criteria();
$criteria->addAssociation('category');
Alternatively you can also set the association to autoload, if you don't want to add the association manually every time:
new ManyToOneAssociationField('category', 'category_id', CategoryDefinition::class, 'id', true)

Related

How to validate array of arrays in Symfony 4

I want to know how can I validate array of arrays in symfony.
My validation rules are:
User - NotBlank
Date - Date and NotBlank
Present - NotBlank
So far I have done this:
$validator = Validation::createValidator();
$constraint = new Assert\Collection(array(
'user' => new Assert\NotBlank(),
'date' => new Assert\Date(),
'present' => new Assert\NotBlank()
));
$violations = $validator->validate($request->request->get('absences')[0], $constraint);
But the problem is that it only allows to validate single array eg.
$request->request->get('absences')[0].
Here is how the array looks like:
You have to put the Collection constraint inside All constraint:
When applied to an array (or Traversable object), this constraint allows you to apply a collection of constraints to each element of the array.
So, your code will probably look like this:
$constraint = new Assert\All(['constraints' => [
new Assert\Collection([
'user' => new Assert\NotBlank(),
'date' => new Assert\Date(),
'present' => new Assert\NotBlank()
])
]]);
Update: if you want to use annotations for this, it'll look something like this:
#Assert\All(
constraints={
#Assert\Collection(
fields={
"user"=#Assert\NotBlank(),
"date"=#Assert\Date(),
"present"=#Assert\NotBlank()
}
)
}
)

Adding Sort to Group Members

I have a Page that displays a list of Members in a group, but I need to change the sort of the group members. I though the esiest way would be to add a relation editor to the pagetype with the sort order added via a Data Extension
Here is my extension on Group
class MyGroup extends DataExtension {
static $many_many_extraFields = array(
'Members' => array(
'SortOrder' => "Int"
)
);
}
On the Page I have the following:
if($this->GroupID != 0 && Permission::check("APPLY_ROLES")) {
$group = Group::get()->byID($this->GroupID);
$fields->addFieldsToTab("Root.Members", array(
GridField::create(
"Members",
"Members",
$group->DirectMembers(),
GridFieldConfig_RelationEditor::create()->addComponents(
new GridFieldSortableRows('SortOrder')
)
)
));
}
When I try to sort the Members I get an error
Uncaught SS_DatabaseException: Couldn't run query:
UPDATE "" SET "SortOrder" = 1 WHERE "" = 12 AND "" = 18
I'm not sure why GridField isn't getting the Columns
You can define the sort order on the list you use for the gridfield
$group->DirectMembers()->sort('Whatever')
If you want to sort them manually, have a look at https://github.com/silverstripe-australia/silverstripe-gridfieldextensions or https://github.com/UndefinedOffset/SortableGridField.
Both modules give you the possibility to sort the entries with drag and drop.

How to add / update a field collection without updating parent node/entity drupal 7

I needed to to add / update field collections to node entities without updating the node entities. I tried two ways listed in https://www.drupal.org/node/1842304 and http://alexrayu.com/blog/saveupdate-field-collection-without-nodesave but none of them seems to be working exactly the way I want.
I tried as follows:
$node = node_load($nid);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_college_rating_data'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_text1['und'][0]['tid'] = $form_state['input']['field_text1']['und'];
$field_collection_item->field_text2['und'][0]['value'] = $form_state['input']['field_text2']['und'];
$field_collection_item->save();
It added a field collection but it updates the node.
I also tried to alter the field collection form submit and used custom submit handler as follows:
function own_custom_field_collection_submit($form,$form_state) {
$field_collection_item = field_collection_item_form_submit_build_field_collection($form, $form_state);
$field_collection_item->save(TRUE);
drupal_set_message(t('The changes have been saved.'));
$form_state['redirect'] = $field_collection_item->path();
}
I have copied this code from core field collection module to change the default argument to "TRUE" in the save function. It added the field collection but didn't associated with the parent node.
I need to save the field collection separately since my node entity form is very large with 50 to 60 fields and field collections and I don't want to update it as many times as I add / update any field collections to the node.
Any help will be much appreciated.
Thanks
You have to pragmatically relate your field collection to the host entity by the following code.
$field_collection_item = field_collection_item_form_submit_build_field_collection($form, $form_state);
$field_collection_item->save(TRUE);
$host_entity = $field_collection_item->hostEntity();
$lang = 'und';
if (isset($host_entity->nid) && isset($host_entity->vid) && isset($lang) && isset($field_collection_item->item_id) && isset($field_collection_item->revision_id)) {
$query = db_select('field_data_field_text1', 'fd');
$query->addExpression('max(fd.delta)', 'total_row');
$query->condition('fd.entity_id', $host_entity->nid);
$max_delta = $query->execute()->fetchField();
if (isset($max_delta)) {
$max_delta = $max_delta + 1;
} else {
$max_delta = 0;
}
db_insert('field_data_{field_collection}')->fields(array(
'entity_type' => 'node',
'bundle' => '{node_type}',
'entity_id' => $host_entity->nid,
'revision_id' => $host_entity->vid,
'language' => $lang,
'delta' => $max_delta,
'field_text' => $field_collection_item->item_id,
'field_text_revision_id' => $field_collection_item->revision_id
))
->execute();
}
Replace your content type and field type in { } and then you just have your field collection relate to your host entity.
Thanks

Sorting Versioned ModelAdmin

I'm trying to do a custom sort in ModelAdmin on SiteTree object
public function getList() {
$list = parent::getList();
if($this->modelClass == 'Listing') {
$list = $list->sort(array('Status' => 'ASC','Street' => 'ASC'));
}
return $list;
}
The sort works but when you try to edit a record I get the following error:
[User Error] Couldn't run query: SELECT DISTINCT "SiteTree_Live"."ID", "Status", "Street" FROM "SiteTree_Live" WHERE ("SiteTree_Live"."ClassName" IN ('Listing','UnavailableListing')) ORDER BY "Status" ASC, "Street" ASC LIMIT 30 Unknown column 'Status' in 'field list'
Obviously Status doesn't exist on SiteTree, it exists on Listing.
You've kind of answered your own question. You can't order by Status when querying SiteTree if the column doesn't exist on that table.
You need to change your model class to Listing or add the Status column to your SiteTree table.

Choice Multiple = true, create new Entries

My Entity
/**
* Set friend
*
* #param \Frontend\ChancesBundle\Entity\UserFriends $friend
* #return ChanceRequest
*/
public function setFriend(\Frontend\ChancesBundle\Entity\UserFriends $friend = null)
{
$this->friend = $friend;
return $this;
}
My Action
$task = new ChanceRequest();
$form = $this->createFormBuilder($task)
->add('friend', 'choice', array(
'required' => true,
'expanded' => true,
'choices' => $fb_friends,
'multiple' => true,
'mapped' => true
))
->getForm();
Because setFriend is expecting a scalar, I cannot validate this or save it to db. It is an array from how many friends the user want to send a message to somebody. How can I change it?
I have seen here a post:
Symfony2 Choice : Expected argument of type "scalar", "array" given
but this don't work that I put an array in front of \Frontend or $friend. I guess because of the related table.
What do I have to do in Entity to get it work?
If friends could be found in your database (for example it is a User entity), you should declare ManyToMany relationship for these two tables. If not, make friend property to be a doctrine array type. if friends is not a valid entity class, all the rest you have is to make a custom validator and datatransformer. Otherwise you have nothing left to do. All this information you can find in the official symfony and doctrine documentation.
How to create a Custom Validation Constraint
How to use Data Transformers
Association Mapping
Working with Associations

Resources