I have a dropdownlist in my _form model and I want to add a empty value (which I want as default). I have the following:
In _form:
<?php echo $form->labelEx($model,'country_id'); ?>
<?php echo $form->dropDownList($model,'country_id',Country::items(),array('empty' => '--Select a country--')); ?>
<?php echo $form->error($model,'country_id'); ?>
In Model Country:
public static function items()
{
return CHtml::listData(Country::model()->findAllBySql(
'SELECT * from country'),
'id', 'name');
}
Even my empty option is in the first row in dropdownlist, the 1st country in list shows as default.
I tried:
<?php echo $form->dropDownList($model,'country_id',
Country::items(),array('empty'=>'--Select a country--',
'options'=>
array(
'3'=>array('selected'=>'selected')
)
));
?>
In this way I can choose the default option, but cant set it to empty value, just countries that came from model:items.
Any idea?
Are you sure that country_id property of your model is not set to anything when you print the dropdown list? The following works for me if $model instance is created using new Country() operator but not by populating properties from database:
<?php echo $form->dropDownList(
$model,
'country_id',
Country::items(),
array(
'empty'=>'--Select a country--')
);
?>
Read documentation. There is 'prompt' parameter.
Try this:
<?php
echo $form->dropDownList($model,'country_id',Country::items(), array(
'prompt' => '--Select a country--'
));
?>
See more details here http://www.yiiframework.com/forum/index.php/topic/11195-how-to-edit-the-default-option-in-dropdownlist/
You always can do something like array_merge in your items method
public static function items()
{
return array_merge(array(''=>'--Select a country--'), CHtml::listData(Country::model()->findAllBySql(
'SELECT * from country'),
'id', 'name'));
}
I believe youre looking for:
echo $form->dropDownList($model,'country_id',Country::items(),array('prompt'=>''));
if you use yiibooster maybe this will help
<?php echo $form->dropDownListGroup(
$model,
'kode_cuti_sub2',
array(
'empty'=>'--Select a country--',
'widgetOptions' => array(
'data' => array('Something ...', 'Pilih Jenis Cuti'=>Chtml::listData(Cuti::model()->cuti_sub2(),'kode','jenis_cuti')),
'options' => array(
'placeholder' => 'Pilih NIP Pegawai',
'width' => '100%',
),
),
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
)
); ?>
in my case it's worked
Related
I have translates table with example data:
So, this table holds records, which will represent custom translation texts.
Now i want to build a form to edit all of those rows in one page / form.
This is controlle code:
public function translate() {
$this->loadModel('Translate');
$data = $this->Translate->find('all');
$this->set('data', $data);
pr ($this->request->data);
if ($this->request->is('post','put')) {
if ($this->Translate->save($this->request->data)) {
$this->Session->setFlash('Recipe Saved!');
return $this->redirect($this->referer());
}
}
}
And view - please note, that i have used loop for creating inputs, not sure if cakephp has better way to do this.
<?php echo $this->Form->create('Translate'); ?>
<?php
foreach ($data as $d) {
echo $this->Form->input('text', array('label' => 'Link strony', 'type' => 'text','value'=>$d['Translate']['text']));
echo $this->Form->input('id', array('type' => 'hidden', 'value' => $d['Translate']['id']));
}
?>
<?php echo $this->Form->end(array('class' => 'btn btn-success floatRight', 'label' => 'Zapisz')); ?>
For now, this code works, but not as i expect. $this->request->data shows only last input, ignoring other ones. Attached, you see debug of $this->request->data. Only last item is edited. All i want is to have ability to edit selected input and save. Thanks for help.
Looks like you're saving multiple rows in a single form. In that case,
you need to change your approach a bit.
Use proper indices in the Form helper.
Use saveAll() instead of save() to save multiple data.
Changes to the View file:
<?php
foreach ($data as $k => $d) {
echo $this->Form->input('Translate.'.$k.'.text', array(
'label' => 'Link strony',
'type' => 'text',
'value' =>$d['Translate']['text']
));
echo $this->Form->input('Translate.'.$k.'.id', array(
'type' => 'hidden',
'value' => $d['Translate']['id']
));
}
?>
And then, in your controller:
if ($this->request->is('post','put')) {
$this->Translate->saveAll($this->request->data['Translate']);
/* Other code */
}
Try to specify the name as array (translate[]) :
echo $this->Form->input('text', array('label' => 'Link strony', 'type' => 'text','value'=>$d['Translate']['text'],'name'=>'translate[]'));
I have 3 dependent dropdowns, and a textfield being dependent to the last dropdown. If one of the value in the last dropdown, I want the textfield value dynamically changes based on the selected value (it's from the same Database table).
This is the view of the third dropdown:
<div class="row" id="id_subkeg">
<?php echo $form->labelEx($model, 'id_subkeg'); ?>
<?php
echo $form->dropDownList($model, 'id_subkeg', array(), array(
'style' => 'width: 100%',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('dynamicSatuan'),
'update' => '#' . CHtml::activeId($model, 'satuan'),
//'update'=>'#seksi',
'data' => array('id_subkeg' => 'js:this.value'),
)
)
);
?>
<?php echo $form->error($model, 'id_subkeg'); ?>
</div>
This is the textfield view:
<div class="row" id="satuan">
<?php echo $form->labelEx($model, 'satuan'); ?>
<p class="hint" style="font-size: 80%">Contoh: Dokumen.</p>
<?php echo $form->textField($model, 'satuan', array('style' => 'width: 98%;', 'readonly' => FALSE)); ?>
<?php echo $form->error($model, 'satuan'); ?>
</div>
And this is the action in the controller:
public function actionDynamicSatuan() {
//$data = Subkegiatan::model()->findByPk($_POST['id_subkeg']);
$data = Subkegiatan::model()->findByPk('id_subkeg=:id_subkeg', array(':id_subkeg' => (int) $_POST['id_subkeg']));
echo $data->satuan;
}
But it's not been working for days. I don't know which part I've missed. My guess is that the dropdown is a dependent dropdown to the one above it. So I must have missed at some part.
Any help is highly appreciated.
UPDATE:
After days of searching, finally got it:
public function actionDynamicSatuan() {
$param_country = (int) $_POST['id_subkeg'];
$maxOrderNumber = Yii::app()->db->createCommand()
->select('satuan')
->from('subkegiatan')
->where('id_subkeg = ' . $param_country)
->queryScalar();
echo '<b>SATUAN: '. $maxOrderNumber.'</b>';
//echo CHtml::tag('input', array('type' => 'text', 'value' => $maxOrderNumber));
}
Instead of update, use success callback:
echo $form->dropDownList($model, 'id_subkeg', array(), array(
'style' => 'width: 100%',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('dynamicSatuan'),
'data' => array('id_subkeg' => 'js:this.value'),
'success'=> 'function(data) {
$("#your_id_here").empty();
$("#your_id_here").append(data);
}'
)
)
);
I'm kinda noob yet using cakephp, but I would love to know how to use it, for that, I'm trying to develop something pretty simple.
I have a form, that has an input type = 'text' and I wanna search in my database what I just type in this input.
How can I do that ?
I know that I have to get what is inside of my input text and execute a function in my controller that will receive a parameter and execute the query and return the same query to my view.
Other thing that I couldn't do it yet is this:
<button type="submit" class="btn"><i class="icon-search"></i></button>
I wanna change this to cake format, like:
echo $this->Form->input('button', array('class' => 'btn', type = 'submit'));
but no idea how to add the icon.
Thanks.
You can specify the button text like.
<?php
echo $this->Form->button(
"<i class='icon-search'></i>",
array(
'class' => 'btn',
'type' => 'submit',
'escape' => false
)); // make sure you've use escap = false with html input.
?>
and for the search you can define the action like this.
<?php
public function search() {
$conditions = array();
$params = $this->passedArgs;
if(isset($params['text_field_name']) && !empty($params['text_field_name'])){
$conditions['ModelName.text_field_name like'] = $params['text_field_name'].'%';
}
$this->Paginate->settings = array(
'conditions' => $conditions
);
$this->set('variable_name', $this->Paginator->paginate());
}
?>
you can also use this for searching
---- in your .ctp file
<?php echo $this->Form->create('ModelName'); ?>
<?php echo $this->Form->input('ModelName.search_word'); ?>
<?php echo $this->Form->submit(" <i class='icon-search'></i> " , array('escape' => false , 'class' => 'btn' ) ); ?>
<?php echo $this->Form->end(); ?> // note that no params for end() method
---- in your controller file
$searchWord = $this->request->data['ModelName']['search_word'] ;
$this->paginate = array('limit' => 30 ,
'conditions' => array('OR' => array('ModelName.field1' => "%".$searchWord."%" ,
'ModelName.field2 LIKE' => "%".$searchWord."%" )));
$this->set('searchResults', $this->paginate());
I am a new cake php developer.I am trying to insert multiple record but i cant.My table Structure is given below:
Table Name :
agents
==============================================
id | Contact | Name | email_add | Address
==============================================
Controller Code :
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if(empty($this->data) == false)
{
if($this->Agent->save($this->data))
{
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
}
else
{
$this->set('errors', $this->Agent->invalidFields());
}
}
Model Code Is :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Agent extends AppModel
{
public $name='Agent';
public $usetables='agents';
public $validate = array(
'contact' => array(
'contact_not_empty' => array(
'rule' => 'notEmpty',
'message' => 'Please Give Contact No',
'last' => true
),
),
'name' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
Its not possible to insert records with this code.What should I do?
Let me explain everything.
First of all your html form must be looks like following.
<?php echo $this->Form->create('User'); ?>
<tr>
<td>
<?php
echo $this->Form->input('User.0.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.1.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.2.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
</td>
<td>
<input type="submit" value="Add" >
</td>
</tr>
<?php echo $this->Form->end(); ?>
As you can see to save many record at same time using cakephp you must define it as above it will parse input fields as array this is cakephp convention.
I mean User.0.address for first array element
User.1.address for second array element
User.2.address for third array element and so on.
Now.
In Controller file.
<?php
function add()
{
$this->User->saveAll($this->data['User']);
}
And yes here you are done saving multiple record at same time.
I just gave you how cakephp works all you need to do is set above hint as per your need.
Best of luck...
Cheers...
Feel Free to ask... :)
Try this saveall() in your query except save, hope this helps
if($this->Agent->saveall($this->data))
Let me know if it work.
I think this
php echo $this->Form->create('Agents', array('action' => 'send_money'));?>
should be replaced with
php echo $this->Form->create('Agent', array('action' => 'send_money'));?>
and use saveall() in place of save.
I´m developing an application using Zend Framework 2 and I use FormRow helper to render a label, the input and errors (if present) in a Form.
//within the view
echo $this->formRow($form->get('Name'));
When a user submits the form without filling the required input text field FormRow render´s it with the following error message:
<label>
<span>Name: </span>
<input class="input-error" type="text" value="" placeholder="Insert Name Here" name="Name">
</label>
<ul>
<li>Value is required and can't be empty</li>
</ul>
How can I set a class for the li tag to style it afterwards?
I know that I can echo the formElementErrors with the desired class attribute via..
<?php echo $this->formElementErrors($form->get("Name"), array('class' => "valuerequired", 'message' => "errortestmessage")); ?>
..but FormRow will still render the error message without the class.
Just for reference I´m setting the entity this way:
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'Name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
See the code of formElementErrors
Basically you could do something like:
$this->formElementErrors($elem)
->setMessageOpenFormat('<ul%s><li class="some-class">')
->setMessageSeparatorString('</li><li class="some-class">');
But that is quite unhandy...
The better solution would be to extend the Zend\Form\View\Helper\FormElementErrors by your own class and then register the view-helper formElementErrors to your class. So basically you'd have something like this:
namespace Mymodule\Form\View\Helper;
use Zend\Form\View\Helper\FormElementErrors as OriginalFormElementErrors;
class FormElementErrors extends OriginalFormElementErrors
{
protected $messageCloseString = '</li></ul>';
protected $messageOpenFormat = '<ul%s><li class="some-class">';
protected $messageSeparatorString = '</li><li class="some-class">';
}
Last thing then would be to register the view helper with this new Class. For this you provide the following code inside your Modules Module.php
public function getViewHelperConfig()
{
return array(
'invokables' => array(
'formelementerrors' => 'Mymodule\Form\View\Helper\FormElementErrors'
),
);
}
displaimer: This code isn't tested, let me know if there are some errors, but i think this should work out quite well.
Ok, the solution to my own problem was right in front of me, instead of using:
//within the view
echo $this->formRow($form->get('Name'));
I called each element of the form individually:
//within the view
echo $this->formLabel($form->get('Name'));
echo $this->formInput($form->get('Name'));
echo $this->formElementErrors($form->get("Name"), array('class' => "some_class", 'message' => "errormessage"));
Don´t know if it´s the most efficient way of doing it, plz drop a line if you think otherwise.
FormRow check if "form_element_errors" plugin registered. And if so use it as default to display error messages.
So Sam's example work. You should redefine standard plugin and inform mvc about it.
I'v done it in module.config.php
'view_helpers' => array(
'invokables' => array(
'formElementErrors'=> 'MyModule\View\Helper\FormElementErrors',
and FormRow start display errors as I wish :)
As your problem, please try
Change
//within the view
echo $this->formRow($form->get('Name'));
to
//within the view
echo $this->formRow($form->get('Name'),null,false);
// Note: add more 2 last parameters, false- for $renderErrors => will NOT render Errors Message.
//Look original function in helper/formrow.php: function __invoke(ElementInterface $element = null, $labelPosition = null, $renderErrors = null, $partial = null)
Render Errors Message as your funciton
echo $this->formElementErrors($form->get('name'), array('class' => 'your-class-here'));
From the documentation of ZF2. Here's the link: http://framework.zend.com/manual/2.0/en/modules/zend.form.view.helpers.html#formelementerrors
echo $this->formElementErrors($element, array('class' => 'help-inline'));
// <ul class="help-inline"><li>Value is required and can't be empty</li></ul>
I use echo $this->formElementErrors($form, array('class' => "error-messages")); to show all error messages in one place:
echo $this->formElementErrors($form, array('class' => "error-messages"));// Print all error messagess
echo $this->formLabel($form->get('Name'));
echo $this->formInput($form->get('Name'));
echo $this->formLabel($form->get('Name2'));
echo $this->formInput($form->get('Name2'));