Getting a value from select - Drupal - drupal

I have a question. How to get a value from a $form['item'] so that i can use the value to filter data in form['item_2'].
Example:
For option where table looks like :
item_id item_name
1 pencile
2 book
So when i chose 2 book it will filter out data in the other form where i have table looking like :
newitem_id item_id newitem_name
1 1 hard
2 1 soft
3 2 novel
The example code :
function my_module_form($form,&$form_submit){
$form=array();
$select=db_query("SELECT * FROM {table_1}");
$options_one=array();
foreach($select as $data){
$options_one[$data ->item_id] = $data -> item_name;
}
$form['item'] = array(
'#title'=>t('Items'),
'#type' => 'select',
'#options' => $options_one,
'#required' => TRUE,
);
$temp=1;
$select = db_query("SELECT * FROM {table_2} WHERE newitem_id=:item_id",array(':item_id'=>$temp));
$options_two=array();
foreach($select as $data){
$options_two[$data ->newitem_id] = $data -> newitem_name;
}
$form['item_2'] = array(
'#title'=>t('Items'),
'#type' => 'select',
'#options' => $options_two,
'#required' => TRUE,
);
Now in the code for $temp i use number one and it gives me hard and soft values in dropdown. But how can i add the selected value from the $form['item'] to the $temp.

You could either use simple jQuery in your case or you could use drupal FORM API #ajax property.An array of elements whose values can control the behavior of the element with respect to the Drupal AJAX framework.AJAX (Asynchronous Javascript and XML) is a term used for dynamic communication between the browser and the server, without page reloads.You could find more details on this property here.If you find it difficult you could try the examples for developers which drupal provides shows exactly how the values in a dropdown is dependent on another drop down.
Drupal Developer examples
Using Simple Jquery(if your values just static values.If you need to take values from db,should be using jQuery+ajax)
Jsfiddle

Related

Sort and paginate by custom date field with Wordpress / ACF / Timber

I'll try to describe what it is I want to achieve, please let me know if too much/not enough detail!
I'm making a site that needs to have documents uploaded to it. These documents will belong to one only of four categories and there will be one page per category. On this page, by default all documents will display. Users will also be able to view only the documents from each year by clicking a link.
It also needs to have pagination so a max of 10 documents are displayed per page.
So how I would ideally like to do this is to make a custom post type (documents) which would then display an ACF custom field set. The field set would have three fields (doc_type, doc_file and release_date). doc_type would be a select field of the four categories, doc_file a file upload and release_date a datepicker field.
When you click on a page, the controller would select by doc_type to only show the documents that belong to that category.
I want to order by release_date and use the year from this field as the display text of my links. For the actual href, I'm imagining something like /path/to/page.php?year=2017.
So there's a few problems here: first is that I am not sure if what I want to do is even possible - let alone a good way of doing things - with WordPress. I'm more used to pure PHP and mySQL, and so I might be trying to shoehorn more general solutions into WP. Can anyone confirm if it's possible to achieve what I want?
Second, I'm specifically running into some issues when I try to execute this plan.
I can successfully get each page to only display the documents that belong to it, like so (although I'm generating $last by grabbing info from the URI, which seems dodgy).
$docArgs = array(
'post_type' => 'documents',
'meta_key' => 'doc_type',
'meta_value' => $last,
);
$context['documents'] = Timber::get_posts($docArgs);
When I try to get my sorting on though, de nada:
$docArgs = array(
'post_type' => 'documents',
'meta_key' => 'doc_type',
'meta_value' => $last,
'meta_query' => array(
array(
'key' => 'release_date',
'orderby' => 'meta_value_num',
'order' => DESC,
),
),
);
I assume I've got the syntax wrong, but I'm basically really confused about the whole thing. Any suggestions?

How to convert an integer based entity field into a human readable name in Twig

In a Symfony 2.4+ project, what is the best way to register an array of values for a field that saves as an integer but needs to display human readable values in a template?
I have an entity with a property that is populated with integer values that represent different constant values:
/**
* The repetition frequency for billing cycle:
* #ORM\Column(type="smallint")
*/
protected $repetition = 0;
I would like to store the names of these values somewhere, so initially I put them in my entity with a getter:
protected $repetitionName = array(
0 => 'Setup',
1 => 'Second',
2 => 'Minute',
3 => 'Hour',
4 => 'Day',
5 => 'Week',
6 => 'Month',
7 => 'Year'
);
public function getRepetitionName() {
return $this->repetitionName;
}
This seems like a great central repository for the values.
Then in my twig template I don't want to display the integer, I want the corresponding name value. So I translate them like this:
<div class="billingCycle">{{ entity.repetitionName[entity.repetition] }}</div>
And in my form builder I make a field that references that array like this:
$builder->add('repetition', 'choice', array(
'label' => 'Billing Cycle',
'help' => 'The repetition frequency when this service is billed.',
'choices' => $builder->getData()->getRepetitionNamePer(),
// default to monthly (the most common)
'empty_data' => 6,
'required' => TRUE
));
The Problems With This Approach
1. Translation: If I want to translate this at any point, it's hard coded in one place.
2. Reusability: If I have other entities that have repetition (e.g. event calendar) it would be nice to reuse this.
3. Configurability: Ideally these would be editable in a config file instead of the entity code.
Alternative Solution: Custom Form Type as Global Service with Config Parameters
The better option seems to set some default parameters in the config file:
parameters:
gutensite_component.options.status:
0: Inactive
1: Active
gutensite_component.options.repetition:
0: Setup
1: Second
2: Minute
3: Hour
4: Day
5: Week
6: Month
7: Year
Then create a custom form type Gutensite\ComponentBundle\FormType\RepetitionType that loads the options from the config parameters. See the Documentation for a great example of this. Then just refer to that field type like this:
$builder->add('repetition', 'repetition', array(
'label' => 'Billing Cycle',
'help' => 'The repetition frequency when this service is billed.',
// default to monthly (the most common)
'empty_data' => 6,
'required' => TRUE
));
The inconvenient part of this solution, is that you have to either parameter to twig in your config (which is bloat for every template even if you don't need it), or always remember to manually pass the parameters to twig from your controller.
// I add to the standard object `$controller->view` which gets passed to Twig
$controller->view->options['repetition'] = $this->container->getParameter('gutensite_component.options.repetition');
To be accessed like:
<div class="priceValue label label-primary">${{ entity.price }}/<span class="billingCycle">{{ view.options.repetition[entity.repetition] }}</span></div>
This is more clunky than I would like but it is reusable. Maybe others have better solutions to pass the configuration to twig than what is represented here.
Other Suggestions?
Do you have any other suggestions, best practices or lessons learned? Please share.
What I would do is to save those values as objects of a new entity and set a manyToOne relation from your main entity (or any other entity as your calendar event entity) to the repetition entity
If so, you can easily add new repetitions every time you want or get all objects of the main entity using any specific repetition.
Also you can build a nice form for a new object of the main entity with an input (human readable) of repetition values:
$builder->add('repetition', 'entity', array(
'class' => 'AcmeDefaultBundle:Repetition', // This is your new 'repetition entity'
'property' => 'repetitionName', // The field of your 'repetition entity' that stores the name (the one that will show a human readable value instead of the id)
'expanded' => true, // True if you prefer checkbox instead of a dropdown list
'label' => 'Billing Cycle',
'help' => 'The repetition frequency when this service is billed.',
'required' => true,
));
Now when you want to show the name of the repetition in twig you will use:
<div class="billingCycle">{{ entity.Repetition.repetitionName }}</div> (you can also translate that value later)
A cleaner way (if you use it only for this entity) is to define a public method in your entity that returns you that array:
public function getRepetitionNames() {
return array(
0 => 'Setup',
1 => 'Second',
2 => 'Minute',
3 => 'Hour',
4 => 'Day',
5 => 'Week',
6 => 'Month',
7 => 'Year'
);
}
Another method to retrieve the label based by your "repetition" field value:
/**
* #param $key
* #return null
*/
function getRepetitionLabel(){
$repetitions = $this->getRepetitionNames();
return isset($repetitions[$this->repetition]) ? $repetitions[$this->repetition] : 0;
}
Will be much easier to access it in twig now:
<div class="billingCycle">{{ entity.repetitionLabel }}</div>
Last, in your form use your entity to retrieve the values:
$object = $builder->getData();
$repetitionChoices = $object->getRepetitionNames();
$builder->add('repetition', 'choice', array(
'label' => 'Billing Cycle',
'help' => 'The repetition frequency when this service is billed.',
'choices' => $repetitionChoices
'empty_data' => 6,
'required' => TRUE
));
If you plan to use it in more entities, you could use a interface.

Symfony2 Form entity

I have a problem, I want to create a simple search form with a filter assembly. These filters are attributes that belong to attribute groups.
group 1
[] Attribute 1
[] Attribute 2
[] Attribute 3
group 2
[] Attribute 1
[] Attribute 2
[] Attribute 3
But the problem is that I can not do (graphic aspect)
$builder->add('attribut', 'entity', array(
'class' => 'RestoFrontBundle:Attribut',
'group_by' => 'groupeAttribut.id',
'expanded' => true,
'multiple' => true,
'query_builder' => function(AttributRepository $er) {
return $er->createQueryBuilder('a')
->join("a.groupeAttribut", 'g')
->where("a.statut = 1");
}
))
->getForm();
Also I can not manage the game if the checkbox has been checked.
You note that the graphic aspect is the hard part. That is due to the way checkboxes are used in HTML. Unlike select inputs there is no notion of an optgroup. The closest analog for checkboxes would be a fieldset with a legend.
You may want explore using a Choice Field type rather than an entity type. Provide your choices via some provider function within which you format the options array(s) whether or not you retrieved them from a database. ( For the record, that's exactly how I populate the select at http://stayattache.com which has multiple places to retrieve options from. ) You may even want to explore creating your own form field type and template to format the output. Checkout the documentation on creating your own field type.
I hope that helps a bit. There are probably plenty of other ways to approach this as well.

Drupal 7 db_insert on WYSIWYG textarea field

this is my first post here at stackoverflow and i'll try make sharp and short ;-)
I am running into problems when inserting a textarea form field using CKeditor into the database.
Here is my form element:
$form['add']['description'] = array(
'#wysiwyg' => true,
'#name' => 'description',
'#title' => t('description'),
'#type' => 'text_format',
'#base_type' => 'textarea',
);
When submitting the form i do get a SQL error like this because Drupal appends the placeholder elements 'value' and 'format'
db_insert failed. Message = SQLSTATE[21S01]:
Insert value list does not match column list:
1136 Column count doesn't match value count at row 1,
query= INSERT INTO {tablename} (description)
VALUES (:db_insert_placeholder_13_value, :db_insert_placeholder_13_format)
Unfortunately i exactly have to set up the textarea this way to make the CKeditor work. Can you advice me how to get rid of the
:db_insert_placeholder_13_value,
:db_insert_placeholder_13_format
to a single variable again?
I really appriciate your help
PROBLEM SOLVED --- silly me, should have used my glasses more :-D
Just use the correct array index inside the submit hook for saving the data to the database and it will work:
function MYMODULE_form_add_submit($form, &$form_state) {
...
'description' => $form_state['values']['description']['value'],
...
}
If you're just interested in the text itself (not the format), add a validation handler for the form and use something like this
function MYMODULE_form_name_validate($form, &$form_state) {
$form_state['values']['description'] = $form_state['values']['description']['value'];
}

Wordpress Loops: Excluding by Tag String, Register by Function?

I have 3 loops running on the front page.
One for the slider, and it wants posts that have the tag "slider".
One for featured articles, and it wants posts that have the tag "featured".
And a third I am calling in loop_latest.php, it wants the 6 latest posts; the trick here is those need to be the 6 latests that do NOT have the tags "slider" or "featured".
So I have this query.
$query = new WP_Query(
array(
'showposts' => '6',
'tag_not_in' => array('featured, slider'),
) );
I'm pretty sure the problem here is that "tag_not_in" doesn't like strings, it wants IDs.
SO! Is there a way to pass it the strings?
If not, how do I divine what the IDs of tags are?
Can I run some code in "functions.php" to set and reserve the ids? featured == 777, slider == 888
Something like that?
I'd like to be able to SET them so that gets packaged with this theme. Rather than have to hope that when the client registers the tags "slider" and "featured" they match up with what I have chosen in the loops/query.
the correct parameter is tag__not_in (with 2 underscores).
additionally - to get your tag ID put this code in your functions.php
function get_tag_id_by_name($tag_name) {
global $wpdb;
$tag_ID = $wpdb->get_var("SELECT * FROM ".$wpdb->terms." WHERE `name` = '".$tag_name."'");
return $tag_ID;
}
and your new code should be:
$featuredtag = get_tag_id_by_name('featured');
$slidertag = get_tag_id_by_name('slider');
$query = new WP_Query(
array(
'showposts' => '6',
'tag__not_in' => array($featuredtag, $slidertag),
) );

Resources