Magento form - how to display input fields on the same row? - magento

I have this form:
$form = new Varien_Data_Form();
$costsForm = $form->addFieldset('costs', array(
'legend' => Mage::helper('starmall_config')->__('Shipping costs')
));
$data = array();
$costsArr = Mage::helper("starmall_config")->getShippingWeightRateList();
for ($i=0; $i < count($costsArr); $i++) {
$data["ship_cost_" . $i . "_from"] = $costsArr[$i]["from"];
$data["ship_cost_" . $i . "_to"] = $costsArr[$i]["to"];
// 1st column
$costsForm->addField("ship_cost_" . $i . "_from", 'text', array(
'name' => "ship_cost_" . $i . "_from",
'label' => $costsArr[$i]["label"],
'class' => 'required-entry',
'style' => 'width:50px',
'required' => true,
));
// 2nd column
// how to add a new field on the same row in another column
// 3rd column
// how to add a new field on the same row in another column
// 4th column
// how to add a new field on the same row in another column
}
It looks like this:
I want to add multiple input fields on the same row. Can this be done in Magento 1.7 ?

1) If you add fields directly to the form ( e.g. $form->addField(....) )
\app\design\adminhtml\default\default\template\widget\form\renderer\element.phtml
around line 29:
change:
<span class="field-row">
into:
<span class="field-row <?= $_element->getId();?>">
Now you have access to the form row with a class, and you can play with CSS to achieve what you need.
2) If you add fields to a form fieldset ( e.g. $fieldset->addField(....) )
provide parameter "container_id", for example:
$fieldset->addField('test_field', 'text', array(
'name' => 'test_field',
'label' => $this->__('Test field'),
'required' => false,
'disabled' => false,
'style' => 'width:50px;',
'container_id' => 'some-row-id'
));
After rendering you will see:
<tr id="some-row-id">
And now you can play easily with CSS to get what you need.
Kind Regards,
Janusz

Hello as Magento actually stores one value per path (see core_config_data table) the only way I can think of to achieve this would be to save your data in json or serialized format, then overwrite the renderer to split the information into separate input fields. even easyer would be to just add some javascript that automatically splits the json to separate inputs and then combines it back toghether on submit so you do not have to edit the models and renderers.

Try to use setNoSpan() method.
For example:
$checkbox = $this->addField('is_enabled', 'checkbox', array(
'onclick' => 'this.value = this.checked ? 1 : 0;',
'name' => 'is_enabled',
))->setNoSpan(true);
or
$checkbox = $this->addField('is_enabled', 'checkbox', array(
'onclick' => 'this.value = this.checked ? 1 : 0;',
'name' => 'is_enabled',
'no_span' => true
));
You can see usage of this element in follow file:
app/design/adminhtml/default/default/template/widget/form/renderer/element.phtml
<?php $_element = $this->getElement() ?>
<?php if($_element->getNoSpan() !== true): ?>
<span class="field-row">
<?php endif; ?>
<?php echo $_element->getLabelHtml() ?>
<?php echo $_element->getElementHtml() ?>
<?php if($_element->getNoSpan() !== true): ?>
</span>
<?php endif; ?>

Related

Ajax is not working in yii

In my Yii web application, any type of Ajax call like Ajax validation, Ajax for dependent dropdown etc.... Is not working.
My codes are,
In my form page:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'workdetails-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
in controller:
public function actionCreate() {
$model = new Workdetails;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Workdetails'])) {
$model->attributes = $_POST['Workdetails'];
if ($model->validate()) {
if ($model->save()) {
$this->redirect(array('create'));
}
}
}
$this->render('create', array(
'model' => $model,
));
}
For dependant dropdown:
<div class="form-group col-sm-6">
<?php echo $form->label($model, 'designationid', array('class' => 'req')); ?>
<?php
$designation = CHtml::listData(Designation::model()->findAll(), 'designationid', 'designation_name');
echo $form->dropDownList($model, 'designationid', $designation, array(
'class' => 'form-control',
'prompt' => 'Please Select',
'ajax' => array(
'type' => 'POST',
'url' => $this->createUrl('workdetails/Fetchemployee'), // here for a specific item, there should be different URL
'update' => '#' . CHtml::activeId($model, 'employeeid'), // here for a specific item, there should be different update
'data'=>array('designationid'=>'js:this.value'),
)));
?>
<?php echo $form->error($model, 'designationid', array('class' => 'school_val_error')); ?>
</div>
How to solve this...
Please help me..
Arya I had the same problem with Yii1 and i gave up using yii-ajax validation cause i could not find a way to fix it. First make sure you have initialize/ register Yii-js file these are
yiiactiveform and yii.js
If you don't have these files on your project, it means you have not registered them. To register the core JS file proceed with this config in your main.
'clientScript' => array(
'scriptMap' => array(
'jquery.js' => true,
'jquery.min.js' => true,
),
),
or if that doesn't work use this on your main view in the header section.
Yii::app()->clientScript->registerCoreScript('jquery');
You can also add it to your base controller which is at components/Controller.php
public function init() {
parent::init();
Yii::app()->clientScript->registerCoreScript('jquery');
}
On your view have this when creating your forms. It will help in placing the error messages. to your elements
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'patient-registration-form',
'enableClientValidation' => True,
'enableAjaxValidation' => FALSE,
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
for(var i in data) $("#"+i).parent().addClass("has-error");
return false;
}
else {
form.children().removeClass("has-error");
return true;
}
}',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError) {
if(hasError) $("#"+attribute.id).parent().addClass("has-error");
else $("#"+attribute.id).parent().removeClass("has-error");
$("#"+attribute.id).parent().addClass("has-success");
}'
),
'htmlOptions' => array(
'class' => 'form-horizontal form-bordered form-row-stripped',
),
));
?>
alternatively use Yii2 it has fixed alot of stufff and if you are loading the current page with ajax you need to render the the whole page including the js file again. since when you use renderPartial it doesn't initalize the js files hence no js scripts will work, including validation.

How to make the Yii-CActiveForm not set a list item to selected?

In a Yii application I have models User and Expert ('expert'=>array(self::BELONGS_TO, 'Expert', 'expert_id'),).
There is a form for creating/editing user data. Now I want to extend it with a drop-down list:
<?php
/**
* #var $experts Expert[]
*/
$expertsDropDownListData = array();
foreach ($experts as $expert) {
$expertsDropDownListData[$expert->id] = $expert->name;
}
?>
<div class="row">
<?php
echo $form->labelEx($user, '', array('label' => Yii::t('app', 'Some text...')));
?>
<?php
echo $form->dropDownList(
$user, 'expert[id]', $expertsDropDownListData,
array(
'empty' => Yii::t('app', 'Please select an expert.'),
// 'options' => array('' => array('selected' => 'selected')),
// 'prompt'=>'Choose One',
)
);
?>
<?php echo $form->error($user, 'expert[id]'); ?>
</div>
I want the drop-down list never to have an expert entry as ould default entry. On page load alwys the empty value should be "selected". It works on pages of users, that don't have a related expert (in the users table the columnt expert_id is NULL). But on the pages of the user, that have an expert, the expert entry of the user gets selected.
How to permit the CActiveForm object selecting an antry and display a form without preselected value irrespective of the tables/objects relationships?
You can fill the attribute $model->expert with null after load.
// Controller
$user = User::model()->findByPk(1);
...your awesome code here...
// never show a default value
$user->expert=null;
if(isset($_POST)) {
// $user->expert will be set here with data from view
$user->attributes = $_POST;
}
...
// View
<div class="row">
<?php
echo $form->labelEx($user, '', array('label' => Yii::t('app', 'Some text...')));
?>
<?php
echo $form->dropDownList(
$user, 'expert', CHtml::listData($experts,'id', 'name'),
array('empty' => Yii::t('app', 'Please select an expert.'),)
);
?>
<?php echo $form->error($user, 'expert'); ?>
</div>

update 2 elements by ajax in yii

I have a ajax link in yii when user click it do something and update a element html (content of td) without refresh page how can change 2 element html?
I explain more:
in view i have a table by some td for show information a td for send information (there are a image ajaxlink) and a td by message of content (example: "not send")
When user click image link call a function and valid information (...) and change message of td ('validation is success').("not send" change to "validation is success")
I did what I was told but i want to remove ajaxlink and replace it by a simple image how
can I do it?
i add:
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'))
view.php:
<td id="send_<?php echo CHtml::encode($profileInformationServices->id); ?>"><?php echo "not send"; ?></td>
<td id="sended_<?php echo CHtml::encode($profileInformationServices->id); ?>">
<?php
echo $profileInformationServices->send ? CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array( 'title' => 'sended success')):
CHtml::ajaxLink(CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array(
'title' => 'Send for valid')), Yii::app()->createUrl('/profileInformationService/send'),
array( // ajaxOptions
'type' => 'POST',
'data' => array( 'id' => $profileInformationServices->id ),
'update' => '#send_'.$profileInformationServices->id,
)
);
?>
</td>
controller:
public function actionSend() {
if (Yii::app()->request->isPostRequest) {
$model = $this->loadModel($_POST["id"]);
$model->send = 1;
$model->save();
echo "sended success";
}
}
Use ajaxLink callback to change the text in td.
<?php
//I am keeping your ternary code in if-else condition for readability
if($profileInformationServices->send)
{
echo CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'));
}
else
{
echo CHtml::ajaxLink
(
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array('title' => 'Send for valid')),
Yii::app()->createUrl('/profileInformationService/send'),
array
(
'type' => 'POST',
'data' => array('id' => $profileInformationServices->id),
'success'=>'function(data)
{
if(data=="sended success")
{
$("#send_'.$profileInformationServices->id.'").html("validation is success");
}
}',
)
);
}
?>

how to give value of dropdown in controller in codeigniter

i have this code in codeigniter (section of form in codeigniter controller) :
$this->data['SalaryType'] = array(
'name' => 'SalaryType',
'id' => 'SalaryType',
'type' => 'text',
'value' => $this->form_validation->set_value('SalaryType'),
);
$this->data['DefaultSalary'] = array(
'name' => 'DefaultSalary',
'id' => 'DefaultSalary',
'type' => 'text',
'value' => $this->form_validation->set_value('DefaultSalary'),
);
$this->data['Salary_options'] = array(
'language' => 'monthly',
'world' => 'world'
);
(section of form in codeigniter view) :
<p>
Salary Type: <br />
<?php echo form_dropdown($SalaryType,$Salary_options,'monthly');?>
</p>
<p>
Default Salary: <br />
<?php echo form_input($DefaultSalary);?>
</p>
and i want use dropdown value but form send input value alone , and i can't access to dropdown value.
i check with print_r($_POST); but in post array observation 'DefaultSalary'.
You have initialized dropdown in wrong way
<?php echo form_dropdown($SalaryType,$Salary_options,'monthly');?>
use instead
<?php echo form_dropdown('DefaultSalary',$Salary_options,'language');?>
1st parameter is the name of the control
2nd parameter is the options array ->which is correct
3rd parameter is the selected index from the options array not value that can be in your case 'language' instead of 'monthly'
read form_helper
And you will be able to access it using $this->input->post('DefaultSalary'); and it will return the value of the option selected
May be your name attr of the drop down is not setting...
For adding id to form_drop down you can try this..
form_dropdown('country', $options_array, '1','id="select_id"')
Note : this is not tested.

CakePHP validation messages position

Normally, the CakePHP's validation messages from models like:
class User extends AppModel {
public $name = 'User';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
'regexp' => array(
'rule' => '/^[a-z0-9]{3,10}$/i',
'message' => 'Only letters and integers, min 3, max. 10 characters'
)
)
)
}
Are printed below the inputs, I mean that messages: 'message' => 'A username is required'
So it looks like:
|INPUT|
[Message]
How do I can change that so the messages gonna be added to the array:
$errors[] = 'Message';
And then, I would like to use foreach to print them in one place.
Is that possible?
CakePHP has all of the validation errors available to the view in $this->validationErrors. So I loop through them thusly:
<?php if ( !empty($this->validationErrors['Model']) ) { ?>
<div id="errorlist">
<h3>You have errors in your submission. <?php echo $warnimage; ?></h3>
<div>
<ul>
<?php foreach( $this->validationErrors['Model'] as $val ){ ?>
<li><?php echo $val; ?></li>
<?php } ?>
</ul>
</div>
</div>
<?php } ?>
EDIT
Where to place this code?
Place the code in the view where you would like it displayed.
How to disable displaying those errors below inputs?
I don't disable that display but suppose if you wished you could just unset $this->validationErrors['Model']. (untested)
Another solution is to use elements as shown in this article by Miles Johnson.

Resources