Create custom field inside OptionsetField in Silverstripe CMS 3.1 - php

I want to choose the type of my calendar events from some predefined values but also, create a new (custom) type if it's not listed.
So i have created the field in $db like so:
'Type' => 'Varchar',
'EventCustomType' => 'Varchar'
Then, in the getCMSFields() i have:
$f->addFieldsToTab("Root.Main", $eventType = new OptionsetField(
'Type',
_t('CalendarEvent.EVENTTYPE','Type'),
array (
'music' => _t('CalendarEvent.MUSIC','Music'),
'sport' => _t('CalendarEvent.SPORT','Sport'),
'drama' => _t('CalendarEvent.DRAMA','Drama'),
'custom' => TextField::create('EventCustomType','Event type')
)
)
);
The problem is that i don't know how to insert the label "Custom" before the Textareafield and style them in the same line.
Also, i'm not sure if i need a second field for the custom one. Can i insert the custom value inside "Type" field or validate it ?
Thanks for any suggestions

This could be achieved by having a separate field for "EventCustomType" and then using Display Logic to show it with something like...
$eventType = OptionsetField::create(
'Type',
_t('CalendarEvent.EVENTTYPE','Type'),
array (
'music' => _t('CalendarEvent.MUSIC','Music'),
'sport' => _t('CalendarEvent.SPORT','Sport'),
'drama' => _t('CalendarEvent.DRAMA','Drama'),
'custom' => _t('CalendarEvent.CUSTOM','Custom'),
)
);
$fEventCustomType = TextField::create('EventCustomType','Event type')
->displayIf('Type')->isEqualTo('custom');
$f->addFieldsToTab("Root.Main", array($eventType,$fEventCustomType));
As an alternative if you wanted to rescue This module then you could create this to save into one field as it is designed to do as you are asking... but it is with an error (last time I tried) so it is refernce only for now.

Finally, i have figured it out with separate fields:
$eventType = OptionsetField::create(
'Type',
_t('CalendarEvent.EVENTTYPE','Type'),
array (
'music' => _t('CalendarEvent.MUSIC','Music'),
'sport' => _t('CalendarEvent.SPORT','Sport'),
'drama' => _t('CalendarEvent.DRAMA','Drama'),
'custom' => _t('CalendarEvent.CUSTOM','Custom'),
)
);
$customEventType = TextField::create('EventCustomType','Custom type');
$f->addFieldsToTab("Root.Main", array($eventType,$customEventType));
and jQuery:
$('#Root_Main').entwine({
onmatch: function(){
var $tab = this.closest('.tab');
var $eventType = $tab.find('ul.eventType');
var $customType = $tab.find('.customEventType').hide();
if($eventType.find('input:checked').val() == 'custom'){
$customType.show();
}
$eventType.find('input').change(function(){
if($(this).val() == 'custom'){
$customType.show();
}else{
$customType.hide();
}
});
}
});

Related

Make a php array load faster

I successfully edited the checkout page of the WooCommerce city field in order to be a dropdown field with a lot of cities in it around 13k values the problem is that on mobile and some low-end devices this field isn't performing well how I can make this array load faster is a DB call worth it in this situation, is there any way stop the dropdown and make the field only searchable is it worth splitting the array or loading from a text file?
The code I made
<?php
// Add custom checkout select fields
add_filter('woocommerce_checkout_fields', 'add_custom_checkout_select_fields');
function add_custom_checkout_select_fields($fields)
{
$arr = array(); // very big array arround 13k values
// Define HERE in the array, your desired cities
$cities = $arr;
// Format in the right way the options array of cities
$options = array(
'' => __('Choose City', 'woocommerce') . '…'
);
foreach ($cities as $city)
{
$options[$city] = $city;
}
// Adding 2 custom select fields
$fields['billing']['billing_city2'] = $fields['shipping']['shipping_city2'] = array(
'type' => 'select',
'required' => true,
'options' => $options,
'autocomplete' => 'address-level2',
'input_class' => array(
'wc-enhanced-select',
)
);
// Copying data from WooCommerce city fields
$fields['billing']['billing_city2']['class'] = array_merge($fields['billing']['billing_city']['class'], array(
'hidden'
));
$fields['shipping']['shipping_city2']['class'] = array_merge($fields['shipping']['shipping_city']['class'], array(
'hidden'
));
$fields['billing']['billing_city2']['label'] = $fields['billing']['billing_city']['label'];
$fields['shipping']['shipping_city2']['label'] = $fields['shipping']['shipping_city']['label'];
$fields['billing']['billing_city2']['priority'] = $fields['billing']['billing_city']['priority'] + 5;
$fields['shipping']['shipping_city2']['priority'] = $fields['shipping']['shipping_city']['priority'] + 5;
wc_enqueue_js("
jQuery( ':input.wc-enhanced-select' ).filter( ':not(.enhanced)' ).each( function() {
var select2_args = { minimumResultsForSearch: 1 };
jQuery( this ).select2( select2_args ).addClass( 'enhanced' );
});");
return $fields;
}

Cannot autocomplete other textfields using CJuiAutoComplete

I have a model that has fields id_peg, nama_peg, and jabatan_peg. So here's what I wanna do:
Autosuggestion that shows the list ofid_peg as I type in the text field id_peg
When I select the suggested id_peg, the fields nama_peg and jabatan_peg are autocompleted based on that corresponding selected value (retrieved from database)
I've been trying to do the first one and I did it. But I'm stuck at the second one.
This is what I did:
view/melaporkan.php:
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'test1',
'source' => $this->createUrl('search'),
// additional javascript options for the autocomplete plugin
'options' => array(
'showAnim' => 'fold',
'select' => 'js:function(event, ui) {
$('#nama_peg').val(ui.item.nama_peg);
$('#jabatan_peg').val(ui.item.jabatan_peg);
}',
),
));
controllers/sitecontroller.php
public function actionSearch() {
$res = array(0 => array('id' => 1, 'value' => "id_peg"), 1 => array('id' => 2, 'value' => "jabatan_peg"), 2 => array('id' => 2, 'value' => "nama_peg"));
if (isset($_GET['term'])) {
$qtxt = "SELECT id_peg FROM pegawai WHERE id_peg LIKE :id_peg";
$command = Yii::app()->db->createCommand($qtxt);
$command->bindValue(":id_peg", '%' . $_GET['term'] . '%', PDO::PARAM_STR);
$res = $command->queryColumn();
}
echo CJSON::encode($res);
Yii::app()->end();
}
All it did was autosuggest for id_peg. When clicked some random id_peg, nama_peg and jabatan_peg were still empty.
What did I do wrong?
Actually the problem is controllers/sitecontroller.php page.
You are sending only id_peg as JSON format but trying to get as ui.item.jabatan_peg.
It is always better to send your value as
[{"id":"Caprimulgus europaeus","value":"European Nightjar"}] pattern
and get the value ui.item.value at your select function.

Cakephp adding option field with array values

I am trying to create a drop down menu (option) and to fill this drop down i have sent an array list to the view:
$country = $this->country_list;
$this->set(compact('country'));
Now my question is does cake have a buildin method for me to set an input field using ($this->Form->input()) with the data of the array list?
take this example
$sizes = array(
's' => 'Small',
'm' => 'Medium',
'l' => 'Large'
);
echo $this->Form->input('size', array('options' => $sizes, 'default' => 'm'));
In the controller, set the value
$this->set('countries', $this->Country->find('list', array('fields' => 'Country.name')));
To show the dropdown box in the view
$this->Form->input('country_id');

Get value from custom category attribute

I am trying to get the value from a custom category attribute in Magento. The attribute is a select field and is been made with the install script below:
$this->startSetup();
$this->addAttribute('catalog_category', 'category_categorycolor', array(
'group' => 'General Information',
'input' => 'select',
'type' => 'varchar',
'label' => 'Categorie kleur',
'backend' => '',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'option' => array (
'value' => array('yellow' => array('Geel'),
'purple' => array('Paars'),
'blue' => array('Blauw'),
'red' => array('Rood'),
'orange' => array('Oranje'),
'green' => array('Groen'),
'darkblue' => array('Donkerblauw'),
'lightgreen' => array('Lichtgroen'),
)
),
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
$this->endSetup();
Unfortunately only getting numbers and not text value. I use this line to retrieve the value:
<?php $_category_categorycolor = $_category->getData('category_categorycolor'); if($_category_categorycolor): ?> <?php echo $_category_categorycolor; ?> <?php endif; ?>
Can someone help me?
Something like this:
$category_id = '10';
$attribute_code = 'category_categorycolor';
$category = Mage::getModel('catalog/category')->load($category_id);
echo $category->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($category);
The sollution is pretty messy (the only one I know of).
$opt = array(); // will contain all options in a $key => $value manner
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_categorycolor');
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
foreach ($options as $o) {
$opt[$o['value']] = $o['label'];
}
}
$categoryColorId = $_category->getData('category_categorycolor');
$categoryColorLabel = $opt[$categoryColorId];
// if you have problems, do a Zend_Debug::dump($opt);
// - it should contain an array of all the options you added
Didn't test it out, let me know if it works or not.
PS: can't reply to your comment, not sure why. What does $opt contain ?
The numbers you are getting back are the id's of each value in the dropdown. You have to load the dropdown values too.
See the following page. It helped me understand this.
http://www.sharpdotinc.com/mdost/2009/04/06/magento-getting-product-attributes-values-and-labels/

How sort CgridView using a 'count' columne

Situation: CausalType 1 -> N Causal
Into admin view for causaltype, i'm using cgridview, and I must show the number of causala of each causalType.
I setup the relation into CausalType
return array(
"causals" => array (self::HAS_MANY, "Causal", "causalTypeId" ),
);
I added class variable
public $activeCausalCount;
and this is the column in admin view
array (
'name' => 'activeCausalCount',
'value' => 'count($data->causals)',
),
Actually this is my criteria in search()
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('isActive',$this->isActive);
The count of causal of each type is correct, but I've some problem
1) I need to count only ACTIVE causals (count causals where causals.isActive = 1)
2) I need to sort the column
3) I need to filter (by integer)
If you really need sorting and filtering on COUNT, then that can be little big process.
one way is...
Add a column to your CausalType table ( call it activeCausals )
define a relation in CausalType model
"totalActiveCasuals" => array(
self::STAT,
"Causal",
"causalTypeId",
'condition'=>'totalActiveCasuals.isActive=1'
),
and define afterSave method in Causal
protected function afterSave()
{
$this->causaltype->activeCausals = $this->causaltype->totalActiveCasuals;
$this->causaltype->save();
return parent::afterSave();
}
now you can filter, sort on new column activeCausals very very easily.
Add a new relation to your CasualType of type STAT like this:
return array(
"casuals" => array (self::HAS_MANY, "Causal", "causalTypeId" ),
"totalCasuals" => array (self::STAT, "Causal", "causalTypeId" ),
"totalActiveCasuals" => array (self::STAT, "Causal", "causalTypeId", 'condition' => 'active = true' ),
);
then in your view just use it as a normal attribute/relation

Categories