I am using the form builder to create an choice-field form an entity looking like this:
$form->add(
'existing_items','entity', array(
'label' => 'Artikel aus',
'class' => 'ProjectShoppinglistBundle:Item',
'empty_value' => 'Bitte einen Artikel auswählen',
'property' => 'name',
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('item')
->leftJoin('item.userItems', 'userItem')
->where('userItem.user = ' . $options['attr']['id'])
->orderBy('item.name', 'ASC');
},
'attr' => array(
'class' => 'form-control',
),
));
but I am using jquery to change the content of the dropdown, so I need to change the validation for the field, how can I achieve that the values in the form are valid for all elements in the items-table and not just the one's which are linked to my the userId used in the query?
This is necessary for my approach because I have a second dropdown where the user can define if he wants to see the items on his own list, of other lists or all items
I have already taken a look at this but I still don't really get it how I can use the eventListener to get the desired result.
If someone could give me a useful hint, I would appreciate this very much.
Related
Iam trying and not finding a way to load the value from a field and generate a select_from_array based on its range.
For example:
I have 2 select box
Brand -> loads -> Model (using backpack field types, and its working good)
`'type' => 'select2_from_ajax',
'name' => 'camera_model_id',
'entity' => 'camera_model',
'attribute' => 'name',
'data_source' => url('camera-brands'),
'placeholder' => 'Selecione o Modelo',
'minimum_input_length' => 0,
'dependencies' => ['camera_brand_id'],`
But, after the user selects this last selectBox, I need that another field was modified
`'name' => 'channel',
'label' => "Canal da Câmera",
'type' => 'select2_from_array',
'options' => ['' => '',
'01' => '01',
'02' => '02', ...`
So, the options could be filled with the maximum of the field I registered in the Model field database.
Is it possible? or maybe another approach to achieve the solution?
Thanks in advance!
To have an input that depends on the value of another input, you can make both your fields select2_from_ajax.
That way:
you will have the value of all inputs in the controller (the controller that returns the ajax results; then you can return a filtered set of results depending on how the form is filled so far - CategoryController::index() in the documentation example);
you can use the "dependencies" attribute on the selec2_from_ajax fields, so that when one field is reset, both are;
I hope the answer helps someone. Cheers!
I am using tinymce for to add user cover letter related to the application.
This what my post array look like:
Array
(
[cover_letter] => <p>Test Cover Letter</p>
<ol>
<li>Need to save this data</li>
</ol>
<p><strong>Thanks</strong></p>
)
Simply I have used the require validation rule for this.
'candidate_cover_letter' => array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
)
I get the validation error regarding this like Cover Letter require.
I have two main problem:
How to validate HTML post array data
Is this best practice to save data like this? if no then how should i save this data?
First of all, in Codeigniter if we want to do form validations we need to go like this :
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required',
'errors' => array(
'required' => 'You must provide a %s.',
),
)
);
$this->form_validation->set_rules($config);
You can refer here
so, your code here should be like this in the controller:
$config =array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
You can add extra fields in the $config like the example above.
Another thing that you asked, "How you should save the data ?"
I would suggest you to use a field in the database table with type "TEXT" and it should be okay for you.
After you hit submit you get redirected back to your controller somewhere. One way to utilize CI form validation is:
//look to see if you have post data
if($this->input->post('submit')){
//points to applications/config/form_validation.php (look at next chucnk to set form_validation.php)
if($this->_validate('cover_letter')){
//rest of your post logic
//get data to upload to database
$data = [
'cover_letter'=>$this->input->post('cover_letter'),
'user_id'=>$this->input->post('user_id')
];
//save data to database ..also this should be moved to a model
$this->db->insert('name of table to insert into', $data);
}
//if you post doesnt not get validated you will fall here and if you have this chucnk of code in the same place were you have the logic to set up the cover letter you will see a pink message that says what ever error message you set up
}
Set up form validation.php
<?php
$config = [
//set up cover letter validation
//$this->_validate('cover_letter') maps to here and checks this array
'cover_letter' => [
[
'field'=>'cover_letter',
'label'=>'Cover Letter Required',//error message to return back to user
'rules'=>'required'//field is required
],
//example to add additional fields to check
[
'field'=>'observations',
'label'=>'Observations',
'rules'=>'required'
],
],
]
I have the following form. Both for device and parts, I want to suppress Symfony loading all the choices into the HTML as I am already using a Select2 hook to load the choices through Ajax, and adding choices adds a lot of bloat (there are over 4000 parts).
What should I do? I tried adding 'choices' => array(), which indeed serves an empty list, bu results in an invalid form, as this means that there are no valid available choices.
<?php
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', EntityType::class, array('label' => 'Toestel', 'class' => 'AppBundle:Device', 'choice_label' => function($device) {
return $device->getBrand()->getName().' '.$device->getName();
}))
->add('parts', EntityType::class, array('label' => 'Onderdelen', 'class' => 'AppBundle:Part', 'choice_label' => 'name', 'multiple' => true))
->getForm();
}
?>
Use a querybuilder instead. This will show you a good example:
http://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities
I think you can figure it out from the above link...
OK EDIT #2 according to your comments:
Try using the 'choices' option shown below:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', EntityType::class, array(
'label' => 'Toestel',
'class' => 'AppBundle:Device',
'choices' => $device->getBrand()->getName().' '.$device->getName(),
}))
->add('parts', EntityType::class, array(
'label' => 'Onderdelen',
'class' => 'AppBundle:Part',
'choice_label' => 'name',
'multiple' => true))
->getForm();
}
Not certain that this will work for you though, but it might.
The variable $device needs be passed in as the form options, or somewhere else as a variable that represents the object AppBundle:Device.
Try this and see if it works for you!
Edit #3:
Based on your comments. I understand what you mean by loading with AJAX. What are you using? Maybe 'onload' for the body? You don't show the code.
However, maybe the best solution then is a ChoiceType with an empty array. If the empty array doesn't work, try putting something in it.
Try these suggestions. I only did it for the 'device' drop down list, since I'm not sure which one(s) you need it for:
Null array:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', ChoiceType::class, array(
'label' => 'Toestel',
'choices' => array(
//null
),
}))
->add('parts', EntityType::class, array(
'label' => 'Onderdelen',
'class' => 'AppBundle:Part',
'choice_label' => 'name',
'multiple' => true))
->getForm();
}
Array with garbage in it:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', ChoiceType::class, array(
'label' => 'Toestel',
'choices' => array(
'Something' => true,
),
}))
->add('parts', EntityType::class, array(
'label' => 'Onderdelen',
'class' => 'AppBundle:Part',
'choice_label' => 'name',
'multiple' => true))
->getForm();
}
Try them!
Found a solution of sorts. It's not excellent but it beats loading over 4000 HTML option tags.
It was harder than I think it should've been, but with the alsatian/form-bundle, it works fine. Read More info on alsatian/form-bundle from the coder himself.
You're going to want to tweak it a bit though, especially if you're not using MongoDB. E.g. in the bundle's services.yml I had to comment out:
- [setDocumentManager,["#doctrine.odm.mongodb.document_manager"]]
And in order to even install it, you have to set minimum-stability in composer.json to dev - and in order not to break everything else, you should also set prefer-stable to true.
in order for it to work on my MySQL setup. Otherwise it's also not very good at setting options for the Select2 element. I was able to tweak AbstractRoutableType.php a bit so it could also take different request methods, but there's no advanced data parsing as you would need JavaScript for that (I don't think HTML data- properties can convey functions).
So in the end, I still have all those options configured in my Twig file, between <script> tags.
I´m currently developing a custom module for magento thats going to list employees.
I have figured out almost everything. The only thing I got left is how the selected values is going to be highlighted.
The problem I´m having is for the backend.
I got 2 tabs per employee, one for employee data and one tab for magento categories.
1 employee can have 1 or more categories.
The database table that the categories are stored in are a non-eav table.
So my question is
What in a multiselect determines which values are selected? As it is now, only one value is selected.
I think you can do this by simply passing in an array of the id's to be selected into the 'value' attribute of the field being added for the multiselect in the _prepareForm() method. Something like the following.
$fieldset->addField('category_id', 'multiselect', array(
'name' => 'categories[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('mymodule/mymodel')->getMymodelValuesForForm(),
'value' => array(1,7,10),
));
The id of the form element (e.g. category_id) must not be an attribute in your model, otherwise when the form values get set with $form->setValues() later on, the attribute value will be overwritten.
I normally store multiple selections as a text column separated by commas much like most magento modules handles stores which requires a slightly different approach as shown below.
In the form block for the tab with the multiselect, you firstly define the element to be displayed like so in the _prepareForm() method. You then get the values from the model and set put them into the form data.
protected function _prepareForm()
{
...
$fieldset->addField('store_id', 'multiselect', array(
'name' => 'stores[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
));
...
if ( Mage::getSingleton('adminhtml/session')->getMymodelData() )
{
$data = Mage::getSingleton('adminhtml/session')->getMymodelData();
} elseif ( Mage::registry('mymodel_data') ) {
$data = Mage::registry('mymodel_data')->getData();
}
$data['store_id'] = isset($data['stores']) ? explode(',', $data['stores']) : array();
$form->setValues($data);
}
I normally store the selected stores (categories as in your case) in the main model as a text column and comma separated values of ids, hence the explode.
In the controller for for the edit action, I put the model being edited into the mage registry so we can load it and it's values in the step above.
Mage::register('mymodel_data', $model);
Thanks for answering.
This is how my field looks like:
$fieldset->addField('npn_CatID', 'multiselect', array(
'label' => Mage::helper('employeelist')->__('Kategori'),
'class' => 'required-entry',
'required' => true,
'name' => 'npn_CatID',
'values' => $data,
'value' => array(3,5)
));
npn_CatID is the value in my db where the category id is saved.
I have tried to change the name and field ID but cant get it working.
When its the field id is like above ONE value is selected and its the last one inserted for the chosen employee
My data array looks likes
array(array('value' => '1', 'label' => 'USB'), array('value' => '2', 'label' => 'Memories'))
I am semi-frustrated with this Yii CGridView problem and any help or guidance would be highly appreciated.
I have two related tables shops (shop_id primary) and contacts (shop_id foreign) such that a single shop may have multiple contacts. I'm using CGridview for pulling records and sorting and my relation function in shops model is something like:
'shopscontact' => array(self::HAS_MANY, 'Shopsmodel', 'shop_id');
On the shop grid, I need to display the shop row with any one of the available contacts. My attempt to filter, search the Grid has worked pretty fine, but I'm stuck in one very strange problem. The respective grid column does not display the value that is intended.
On CGridview file, I'm doing something like
array(
'name' => 'shopscontact.contact_firstname',
'header' => 'First Name',
'value' => '$data->shopscontact->contact_firstname'
),
to display the contact's first name. However, even under circumstances that searching/sorting are both working (I found out by checking the db associations), the grid column comes out empty! :( And when I do a var_dump
array(
'name' => 'shopscontact.contact_firstname',
'header' => 'First Name',
'value' => 'var_dump($data->shopscontact)'
),
The dump shows record values in _private attributes as follows:
private '_attributes' (CActiveRecord) =>
array
'contact_firstname' => string 'rec1' (length=4)
'contact_lastname' => string 'rec1 lsname' (length=11)
'contact_id' => string '1' (length=1)
< Edit: >
My criteria code in the model is as follows:
$criteria->with = array(
'owner',
'states',
'shopscontacts' => array(
'alias' => 'shopscontacts',
'select' => 'shopscontacts.contact_firstname,shopscontacts.contact_lastname',
'together' => true
)
);
< / Edit >
How do I access the values in their respective columns? Please help! :(
Hmm, I have not used the with() and together() methods much. What's interesting is how in the 'value' part of the column, $data->shopscontacts loads up the relation fresh, based on the relations() definition (and is not based on the criteria you declared).
A cleaner way to handle the array output might be like this:
'value' => 'array_shift($data->shopscontacts)->contact_lastname'
Perhaps a better way to do this, though, would be to set up a new (additional) relation, like this in your shops model:
public function relations()
{
return array(
'shopscontacts' => array(self::HAS_MANY, 'Shopsmodel', 'shop_id'), // original
'firstShopscontact' => array(self::HAS_ONE, 'Shopsmodel', 'shop_id'), // the new relation
);
}
Then, in your CGridView you can just set up a column like so:
'columns'=>array(
'firstShopscontact.contact_lastname',
),
Cheers
Since 'shopscontact' is the name of the has-many relation, $data->shopscontact should be returning an array with all the shops related... did you modify the relation in order to return only one record (if I didn't get you wrong, you only need to display one, right?)? If you did it, may I see your filtering code?
P.S. A hunch to get a fast but temporal solution: have you tried 'value' => '$data->shopscontact['contact_firstname']'?