I use an ActiveForm in Yii2 for my SearchModel. After click on search button the form fields remember previous values but SorterDropdown is refreshed.
<?php echo SorterDropdown::widget(['sort' => $dataProvider->sort,
'label' => $model->sortedBy($dataProvider->sort->attributes),])
?>
SorterDropdown is just a wrapper of ButtonDropdown.
How can I forse the SorterDropdown to remember sort order (and show it) after the form submition?
class SorterDropdown extends LinkSorter
{
public $label;
protected function renderSortLinks()
{
$attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
$links = [];
foreach ($attributes as $name) {
$links[] = Html::tag('li', $this->sort->link($name, ['tabindex' => '-1']));
}
if (empty($this->label))
$this->label = 'Sort';
return \yii\bootstrap\ButtonDropdown::widget([
'encodeLabel' => false,
'label' => $this->label,
'dropdown' => [
'items' => $links,
],
]);
}
You should add some class to li element, which indicate active state of it and special style in CSS file.
Related
I have a form where images can be submitted, this isn't originally my code, I'm inheriting it and I'm trying to figure it out and fix the problem.
When editing the datas from this form, the input file is empty as opposed to the other inputs. So saving actually replaces the current file to "array" in database.
I would like to be able to keep the current one if it is unchanged ?
Form edit :
<h1>Edit</h1>
<?php
echo $this->Form->create($template,['enctype' => 'multipart/form-data']);
echo $this->Form->input('title');
echo $this->Form->input('works_id');
echo $this->Form->input('photo',['type' => 'file']);
echo $this->Form->input('text', ['rows' => '4']);
echo $this->Form->input('url');
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
edit function from controller :
public function edit($id = null){
$template = $this->Templates->get($id);
if ($this->request->is(['post', 'put'])) {
$template = $this->Templates->patchEntity($template, $this->request->data,['associated' => ['Works']]);
if ($this->Templates->save($template)) {
$this->Flash->success(__('Your template has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your template.'));
}
$this->set('template', $template);
$works = $this->Templates->Works->find('list');
$this->set(compact('works'));
}
In my database it saves on two colomns :
file_dir and filename, so it confuses me even more on how to get the file in the edit form.
edit : adding TemplatesTable :
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class TemplatesTable extends Table
{
protected function _initializeSchema(\Cake\Database\Schema\Table $table){
$table->columnType('photo', 'proffer.file');
return $table;
}
public function initialize(array $config){
$this->addBehavior('Timestamp');
$this->addBehavior('Proffer.Proffer', [
'photo' => [
'root' => WWW_ROOT.'files',
'dir' => 'photo_dir',
'thumbnailSizes' => [
'square' => ['w' => 200, 'h' => 200],
'portrait' => ['w' => 100, 'h' => 300, 'crop' => true],
],
'thumbnailMethod' => 'gd' // Options are Imagick, Gd or Gmagick
]
]);
$this->belongsTo(
'Works',
[
'foreignKey' => 'work_id',
]
);
}
public function validationDefault(Validator $validator){
$validator
->notEmpty('work_id')
->notEmpty('title');
return $validator;
}
}
According to the docs, the Proffer behavior can handle empty uploads out of the box, and you just have to configure the validation rules for the field accordingly to allow it to be empty on update:
If you want your users to submit a file when creating a record, but
not when updating it, you can configure this using the basic Cake
rules.
$validator
->requirePresence('image', 'create')
->allowEmpty('image', 'update');
So now your users do not need to upload a file every time they update
a record.
https://github.com/davidyell/CakePHP3-Proffer/blob/0.8.2/docs/validation.md
https://github.com/davidyell/CakePHP3-Proffer/blob/0.8.2/src/Model/Behavior/ProfferBehavior.php#L56
So in your case that would be:
->requirePresence('photo', 'create')
->allowEmpty('photo', 'update')
I do my project in yii2.
I have form which get data from db to dropdown list(using kartik depdtop widget).
First field is "type_of_goods", depending on "type_of_goods" customer receive "goods".
After they are two text input field with "goods_amount" and "total_cost" of goods depends on "goods_amount" (goods_amount * price).
Customer inputs goods amount he wants to buy, or money amount to which he wants to buy and js script shows him value in another field in both cases.
Price value is in goods table in DB.
Can I get goods_id or some information about goods from "goods"-field(to perform db query and get price and put it into js function), or maybe even price to put it into js script which do things that I wrote above.
How can I realize it? Is it right way to do it?
Code:
View
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'form-horizontal col-lg-11',
'enctype' => 'multipart/form-data'
],
]); ?>
<?= $form->field($type_of_goods, 'id')
->dropDownList(
ArrayHelper::map(Type_of_goods::find()->all(), 'id', 'name'),
['id'=>'type_of_goods_id']
);
?>
<?= $form->field($goods, 'id')->widget(DepDrop::classname(), [
'options' => ['id' => 'id'],
'pluginOptions' => [
'depends' => ['type_of_goods_id'],
'placeholder' => 'Choose your goods',
'url' => \yii\helpers\Url::to(['goods/goods-dep-type'])
]
]);
?>
<?= $form->field($goods, 'price')->textInput();
?>
<?= $form->field($order, 'amount')->textInput();
?>
<?php ActiveForm::end(); ?>
Controller:
public function actionGoodsDepType()
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$game_id = $parents[0];
$out = \app\models\Goods::gelGoodsList($goods_type_id);
echo Json::encode(['output' => $out, 'selected' => '']);
return;
}
}
echo Json::encode(['output' => '', 'selected' => '']);
}
Model:
public static function gelGoodsList($type_id)
{
$query = self::find()
->where(['type_id' => $type_id])
->select(['id', 'name'])->asArray()->all();
return $query;
}
public static function getPrice($id)
{
$query = self::find()
->where(['id' => $id])
->select(['price'])->asArray()->one();
return $query;
}
You would need to create an AJAX request each time user inputs new value. This might work well (place at the bottom of the view file):
$this->registerJs("
$('#Type_of_goods-price').on('change', function() { // Should be ID of a field where user writes something
$.post('index.php?r=controller/get-price', { // Controller name and action
input_price: $('#Type_of_goods-price').val() // We need to pass parameter 'input_price'
}, function(data) {
total_price = $.parseJSON(data)['result']; // Let's say, controller returns: json_encode(['result' => $totalPrice]);
$('#Type_of_goods-total').value = total_price; // Assign returned value to a different field that displays total amount of price
}
});
");
You only need to set correct elements' correct IDs and write a method in controller (using this example, it would be controller controller name and actionGetPrice method name).
I have successfully added my own form (from the same module) into my custom template, but now I wish to load the taxonomy add term form (used by ubercart I think for product categories in the catalog vocab) into my template.
I have gotten this far with my module - filename simpleadmin.module
/**
* #file
* A module to simplify the admin by replacing add/edit node pages
*/
function simpleadmin_menu() {
$items['admin/products/categories/add'] = array(
'title' => 'Add Category',
'page callback' => 'simpleadmin_category_add',
'access arguments' => array('access administration pages'),
'menu_name' => 'menu-store',
);
return $items;
}
function simpleadmin_category_add() {
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
$output = drupal_get_form('taxonomy_form_term');
return theme('simpleadmin_category_add', array('categoryform' => $output));
}
function simpleadmin_theme() {
return array(
'simpleadmin_category_add' => array(
'template' => 'simpleadmin-template',
'variables' => array('categoryform' => NULL),
'render element' => 'form',
),
);
}
?>
And as for the theme file itself - filename simpleadmin-template.tpl.php, only very simple at the moment until I get the form to load into it:
<div>
This is the form template ABOVE the form
</div>
<?php
dpm($categoryform);
print drupal_render($categoryform);
?>
<div>
This is the form template BELOW the form
</div>
Its telling me that it is
Trying to get property of non-object in taxonomy_form_term()
and throwing up an error. Should I be using node_add() and passing the nodetype?
To render a taxonomy term form, the function should be able to know the vocabulary to which it belongs to. Otherwise how would it know which form to show? I think this is the proper way to do it.
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
if ($vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_name')) {
$form = drupal_get_form('taxonomy_form_term', $vocabulary);
return theme('simpleadmin_category_add', array('categoryform' => $form));
}
To redirect your form use hook_form_alter
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
//get your vocabulary id or use print_r or dpm for proper validation
if($form_id == 'taxonomy_form_term' && $form['#vocabulary']['vid'] = '7' ){
$form['#submit'][] = 'onix_sections_form_submit';
}
}
function yourmodule_form_submit($form, &$form_state) {
$form_state['redirect'] = 'user';
}
I have a Zend_Form form, with some custom decorators, like this:
$decorators = array();
$decorators[] = new Zend_Form_Decorator_ViewHelper(array());
$decorators[] = new Zend_Form_Decorator_Errors;
$decorators[] = new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'class' => 'form-item'));
$decorators[] = new Zend_Form_Decorator_Label(array('class' => 'form-label'));
$decorators[] = new Zend_Form_Decorator_Callback(array(
'callback' => function($content, $element, $options) {
return sprintf('<div class="form-row">%s</div>', $content);
},
'placement' => false
));
$this->setElementDecorators($decorators);
The problem is, that all of the fields are rendered as text inputs. Why does it happen?
EDIT: I discovered, that it doesn't render all the inputs necessarily as text inputs, but renders them with type of the first input in form. Here is example of a form that i use(the decorators are set int parent's init):
<?php
class Form_Users_Add extends Form_Base {
protected $pbxs = array(1 => 'Element 1', 2 => 'Element 2');
public function init() {
$monitors = new Zend_Form_Element_Checkbox('prefered_screen_count');
$monitors->setCheckedValue(2);
$monitors->setUncheckedValue(1);
$monitors->setLabel('two_monitors');
$this->addElement($monitors);
$pbx = new Zend_Form_Element_Select('asterisk_id');
$pbx->setMultiOptions($this->pbxs);
$pbx->setLabel('users_asterisk_id');
$this->addElement($pbx);
parent::init();
}
}
Yay! I have solved the issue! The cause was that I used INSTANCES of classes, not the names. This way every element was using the same instance of the decorator.
I've a fully working backend page with a grid and a corresponding form to edit the changes on the corresponding model. I added a new field on the table, bit type, as it will answer to a yes/no configuration option from the user. I added the checkbox on both grid and form.
My problem is that after a couple of hours of searching and trying different approaches I can not set the checkbox checked value both on the grid and the form reading the corresponding field from the database. Also when I click on save on the form the value corresponding to the checkbox is always saved with 1. Everything else on the grid and the form works as it should. I have read here, here, here, here and some more sites and SO questions/answers but still no clue on what I'm doing wrong. Some solutions recommend using a combo box with YES/NO options, but I want a checkbox, can't be so difficult.
Grid code inside the function _prepareColumns():
protected function _prepareColumns() {
...
$this->addColumn('banner_gral', array(
'header' => Mage::helper('banners')->__('General'),
'align' => 'center',
'index' => 'banner_gral',
'type' => 'checkbox',
'values' => $this->getBannerGral()==1 ? 'true' : 'false',
));
...
}
public function __construct()
{
parent::__construct();
$this->setId('bannersgrid');
$this->setDefaultSort('bannerid');
$this->setDefaultDir('asc');
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
public function getGridUrl()
{
return $this->getUrl('*/*/grid', array('_current'=>true));
}
protected function _prepareCollection()
{
$collection = Mage::getModel('banners/bannersadmin')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
Form code to add the checkbox inside the function _prepareForm():
protected function _prepareForm()
{
$id = $this->getRequest()->getParam('id');
$params = array('id' => $this->getRequest()->getParam('id'));
if (Mage::registry('banners_data')->getdata()) {
$data = Mage::registry('banners_data')->getdata();
}
elseif (Mage::getSingleton('adminhtml/session')) {
$data = Mage::getSingleton('adminhtml/session')->getdata();
Mage::getSingleton('adminhtml/session')->getdata(null);
}
else {
$data = array();
}
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', $params),
'method' => 'post',
'enctype' => 'multipart/form-data',
));
...
$fieldset->addField('banner_gral', 'checkbox', array(
'label' => Mage::helper('banners')->__('Is general'),
'name' => 'banner_gral',
'class' => 'banner_gral',
'checked' => $this->getBannerGral()==1 ? 'true' : 'false',
'onclick' => 'this.value == this.checked ? 1 : 0',
'note' => Mage::helper('banners')->__('blablablabla'),
'tabindex' => 2
));
...
}
On the saveAction() of my form I have:
$campaign->setbanner_gral(!empty($data['banner_gral']));
In your controller saveAction() when saving the checkbox data do
$banner_gral = isset($your_form_Data['banner_gral']) ? 1 : 0;
For Grid and Form Page
In your controller you should have Mage::register(...)->getData() or Mage::register(...)
public function editAction()
....
Mage::register('example_data', $model);
On your form _prepareForm()
$model = Mage::registry('example_data'); // NOTE registry('example_data'); NOT registry('example_data')->getData();
$fieldset->addField('entire_range', 'checkbox', array(
....
'checked' => $model->getBannerGral()==1 ? 'true' : 'false',
......
))
see http://www.magentocommerce.com/boards/viewthread/20536/
On your grid _prepareColumns()
$this->addColumn('banner_gral', array(
....
'type' => 'checkbox',
'index' => 'banner_gral',
'values' => array(1,2),
'field_name' => 'checkbox_name',
....
));
#R.S answered one issue, how to save the checkbox value on the corresponding model/database field. But the issue on how to correctly display the checkbox on both the grid and the form was not solved. After doing some more searches I finally got to these two links that helped me solve my problem.
To correct the grid issue: Understanding the Grid Serializer Block
Now the part of code where the checkbox column is added, see that I added array(1,2) on the values element.
$this->addColumn('banner_gral', array(
'header' => Mage::helper('banners')->__('General'),
'width' => '20px',
'type' => 'checkbox',
'align' => 'center',
'index' => 'banner_gral',
'values' => array(1,2),
'editable' => 'false',
));
Also if you take a look into the core code of Magento, the class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Checkbox returns an array of values. Taking a look here finally got me into the right path.
/**
* Returns values of the column
*
* #return array
*/
public function getValues()
{
if (is_null($this->_values)) {
$this->_values = $this->getColumn()->getData('values') ? $this->getColumn()->getData('values') : array();
}
return $this->_values;
}
To correct the form issue: Mage_Adminhtml_Block_System_Store_Edit_Form Class Reference
The issue on this case was that I was trying to use the $this but what I needed to use was the $data that is loaded at the beginning of the _prepareForm function. #R.S pointed the right direction, but it is not possible to use $model->getBannerGral() as the $data on the registry is an array, not a model. So, using $data["banner_gral"] I could get the needed value for the checkbox. Tested and it is working.
$fieldset->addField('banner_gral', 'checkbox', array(
'label' => Mage::helper('banners')->__('Is general'),
'name' => 'banner_gral',
'checked' => $data["banner_gral"],
'onclick' => 'this.value = this.checked ? 1 : 0;',
'note' => Mage::helper('banners')->__('blablablabla'),
'tabindex' => 2
));