In Symfony 3 it's no longer possible to re-validate whole entity with dynamic groups in a callback, like this:
$executionContext->validate($this, '', 'someGroup', true);
How to do it in version 3?
There is a need to get validator and set it context to current one
public function validatePrice(ExecutionContextInterface $executionContext)
{
if($this->type !== self::TYPE_FREE){
$executionContext
->getValidator()
->inContext($executionContext)
->validate($this, null, ['payableTask'] );
}
}
Related
I have a custom field type that contains a small validator. It is used all over the place on the Frontend, so for convenience we also use it in the CMS.
class MyTextField extends TextField {
public function Type() {
return 'text';
}
public function getAttributes() {
return array_merge(
parent::getAttributes(),
array(
'type' => 'text'
)
);
}
public function validate($validator) {
$this->value = trim($this->value);
$maxLength = empty($this->getMaxLength())?50:$this->getMaxLength();
if(strlen($this->value)>$maxLength) {
$validator->validationError(
$this->name,
'Exceeded max length '.$maxLength,
"validation"
);
return false;
}else{
return true;
}
}
}
}
Field works fine. If a create a new instance using it, and that constructor doesn't include a maxlength property, it defaults to 50.
The issue I am having is that a change to a frontend field "MyText" was set to 100, while the version of this field in getCMSFields was not, and thus defaulted to a max length of 50. Obviously validation failure.
Of course this should and has been rectified, but the issue came up as a CMS user could not delete a record. And I don't really disagree with the user in that validation should be ignored when you discarding the data anyway. It would make sense for add/edit, but not really delete.
Anyone know of a way of disabling validation for a delete operation inside getCMSFields? Here is an excerpt of my getCMSFields in case a refactor is required.
function getCMSFields() {
$detailBlock = CompositeField::create(
MyTextField::create('MyTextField','CustomField', '', 255),
);
// Build the fieldlist for the form.
$fields = FieldList::create (
TabSet::create (
"Root",
Tab::create (
"Main Content",
$detailBlock
)
)
);
return $fields;
}
EDIT: I have just discovered that I need a way to bypass getCMSValidator for delete operations too. There are required fields set in here that can trigger a validation error on delete too. It doesn't really make sense that you would need to put a record in a valid state just to delete it.
in my project I have some forms with choice types with a lot of options.
So I decided to build an autocomplete choice type based on jquery autocomplete, which adds new <option> HTML elements to the original <select> on runtime. When selected they are submitted correctly, but can't be handled within the default ChoicesToValuesTransformer, since the don't exist in my form when I create it.
How can I make symfony accept my dynamically added values?
I found this answer Validating dynamically loaded choices in Symfony 2 , where the submitted values are used to modify the form on the PRE_SUBMIT form event, but couldn't get it running for my situation. I need to change choices known to the current type instead of adding a new widget to the form
To deal with dynamically added values use 'choice_loader' option of choice type. It's new in symfony 2.7 and sadly doesn't have any documentaion at all.
Basically it's a service implementing ChoiceLoaderInterface which defines three functions:
loadValuesForChoices(array $choices, $value = null)
is called on build form and receives the preset values of object bound into the form
loadChoiceList($value = null)
is called on build view and should return the full list of choices in general
loadChoicesForValues(array $values, $value = null)
is called on form submit and receives the submitted data
Now the idea is to keep a ArrayChoiceList as private property within the choice loader. On build form loadValuesForChoices(...) is called, here we add all preset choices into our choice list so they can be displayed to the user. On build view loadChoiceList(...) is called, but we don't load anything, we just return our private choice list created before.
Now the user interacts with the form, some additional choices are loaded via an autocomplete and put into th HTML. On submit of the form the selected values are submitted and in our controller action first the form is created and afterwards on $form->handleRequest(..) loadChoicesForValues(...) is called, but the submitted values might be completly different from those which where included in the beginning. So we replace our internal choice list with a new one containing only the submitted values.
Our form now perfectly holds the data added by autocompletion.
The tricky part is, that we need a new instance of our choice loader whenever we use the form type, otherwise the internal choice list would hold a mixture of all choices.
Since the goal is to write a new autocomplete choice type, you usually would use dependency injection to pass your choice loader into the type service.
But for types this is not possible if you always need a new instance, instead we have to include it via options. Setting the choice loader in the default options does not work, since they are cached too. To solve that problem you have to write a anonymous function which needs to take the options as parameters:
$resolver->setDefaults(array(
'choice_loader' => function (Options $options) {
return AutocompleteFactory::createChoiceLoader();
},
));
Edit:
Here is a reduced version of the choice loader class:
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
class AutocompleteChoiceLoader implements ChoiceLoaderInterface
{
/** #var ChoiceListInterface */
private $choiceList;
public function loadValuesForChoices(array $choices, $value = null)
{
// is called on form creat with $choices containing the preset of the bound entity
$values = array();
foreach ($choices as $key => $choice) {
// we use a DataTransformer, thus only plain values arrive as choices which can be used directly as value
if (is_callable($value)) {
$values[$key] = (string)call_user_func($value, $choice, $key);
}
else {
$values[$key] = $choice;
}
}
// this has to be done by yourself: array( label => value )
$labeledValues = MyLabelService::getLabels($values);
// create internal choice list from loaded values
$this->choiceList = new ArrayChoiceList($labeledValues, $value);
return $values;
}
public function loadChoiceList($value = null)
{
// is called on form view create after loadValuesForChoices of form create
if ($this->choiceList instanceof ChoiceListInterface) {
return $this->choiceList;
}
// if no values preset yet return empty list
$this->choiceList = new ArrayChoiceList(array(), $value);
return $this->choiceList;
}
public function loadChoicesForValues(array $values, $value = null)
{
// is called on form submit after loadValuesForChoices of form create and loadChoiceList of form view create
$choices = array();
foreach ($values as $key => $val) {
// we use a DataTransformer, thus only plain values arrive as choices which can be used directly as value
if (is_callable($value)) {
$choices[$key] = (string)call_user_func($value, $val, $key);
}
else {
$choices[$key] = $val;
}
}
// this has to be done by yourself: array( label => value )
$labeledValues = MyLabelService::getLabels($values);
// reset internal choice list
$this->choiceList = new ArrayChoiceList($labeledValues, $value);
return $choices;
}
}
A basic (and probably not the best) option would be to unmap the field in your form like :
->add('field', choiceType::class, array(
...
'mapped' => false
))
In the controller, after validation, get the data and send them to the entity like this :
$data = request->request->get('field');
// OR
$data = $form->get('field')->getData();
// and finish with :
$entity = setField($data);
I have been looking for hours for a way of setting a condition on the list of items that an APYDataGridBundle grid should return but could not find an answer.
Is there a way to set a DQL Query and pass it to the grid to display the exact query results I want to fetch?
This is the code:
public function filteredlistAction(){
// Create simple grid based on the entity
$source = new Entity('ACMEBundle:MyEntity');
// Get a grid instance
$grid = $this->get('grid');
// Attach the source to the grid
$grid->setSource($source);
...
...
**$grid->getColumns()->getColumnById('myentity_filter_column')->setData('the exact value I tried to match');**
// Manage the grid redirection, exports and the response of the controller
return $grid->getGridResponse('ACMEBundle:MyEntity:index_filteredlist.html.twig');
}
You can add a callback (closure or callable) to run before QueryBuilder execution - its done like this :
$source->manipulateQuery(
function ($query)
{
$query->resetDQLPart('orderBy');
}
);
$grid->setSource($source);
$query is an instance of QueryBuilder so you can change whatever you need to
Example taken from docs here
A more "complicated" query.
$estaActivo = 'ACTIVO';
$tableAlias = $source->getTableAlias();
$source->manipulateQuery(
function ($query) use ($tableAlias, $estaActivo)
{
$query->andWhere($tableAlias . '.estado = :estaActivo')
->andWhere($tableAlias . '.tipoUsuario IN (:rol)')
->setParameter('estaActivo', $estaActivo)
->setParameter('rol', array('VENDEDOR','SUPERVISOR'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
}
);
Cheers!
A simple task: before displaying the form, if $data->getRole() starts with "ROLE_", remove this string and display only the rest. When user submit the form, do the opposite: add "ROLE_" before the name.
What's the best place to do this? Actually i'm using PRE_SET_DATA and POST_BIND. Are these the right events to perform this operation?
$builder->addEventListener(FormEvents::PRE_SET_DATA,
function(DataEvent $event){
if(is_null($data = $event->getData()) || !$data->getId()) return;
$data->setRole(strtoupper(preg_replace('/^ROLE_/i', '',
$data->getRole())));
});
$builder->addEventListener(FormEvents::POST_BIND,
function(DataEvent $event) {
if(is_null($data = $event->getData()) || !$data->getId()) return;
$data->setRole('ROLE_' . strtoupper($data->getRole()));
});
Well reading the role without the prefix "ROLE" is not something I would do using events. As they obsfusicate your workflow, events should be used with care! Working with symfony for some time, I used them once or twice when there was really no other way. All the other times there was a better way.
I would tend to simply add a function getShortRole and setShortRole and use shortRole within your Entity:
class MyEntity {
private $role;
public function setShortRole($role) {
$this->role = 'ROLE_' . strtoupper($role);
}
public function getShortRole() {
return strtoupper(preg_replace('/^ROLE_/i', '', $this->role));
}
}
You are saving yourself a lot of trouble working with models instead of events!
A second, more complicated way would be to use a Model which represents the form instead of the Entity and maps the form to the entity. Here is a good article about this here!
I use it myself and it works nice.
Seems doesn't works:
<?php
$collection = Mage::getModel('catalog/product')->getCollection();
foreach($collection->getItems() as $key => $_product){
//product
$collection->removeItemByKey($key);
}
?>
$collection is still populated
If you'd like to work with an empty collection, the best approach would be to load it with a filter that would always produce an empty set. Here's an example:
$collection = Mage::getModel('catalog/product')->getCollection()
->addFieldToFilter('entity_id', 0);
Because Magento product ids start at 1, this collection would remain empty, until you add items to it with the addItem() method.
clear() and removeItemByKey(), on the other hand, will only trigger a second run to the database to refetch the data you don't want in there.
You question doesn't make sense. Running the following code
$c = Mage::getModel('catalog/product')->getCollection();
foreach($c->getItems() as $key=>$item)
{
$c->removeItemByKey($key);
}
foreach($c->getItems() as $key=>$item)
{
var_dump($key);
}
var_dump( "Done" );
results in only the word "done" being output (Magento 1.6.1).
My guess it something about your installation of Magento is making the call to $c->getItems(); trigger a reload of the collection. So, you remove all the items, but then when you call your second getItems, the collection is refetched.
There's clear() method in Varien_Data_Collection class which clears the collection.
I'm not sure if the method exists in the time the question was asked, but it exists in Magento 1.7
There's also a possibility to remove all the items without "fake loading" (in opposite to Shay Acrich's answer):
class MyCollection extends SomeCollection {
// ...
public function setEmpty()
{
$this->clear();
$this->_totalRecords = 0;
$this->_setIsLoaded(true);
return $this;
}
// ...
}
Setting _totalRecords to 0 is required in order not to allow getSize() method to reload the collection.
Nevertheless, one needs to extend / modify a collection's code, because both the field _totalRecords and the method _setIsLoaded() are protected.
There should be noted, that if a particular collection ignores flags like _totalRecords and _isCollectionLoaded the above solution may not work as expected.
$collection->clear()
should do the work.