I need to get the real value, instead of the number position of a Select form field
I explain it with one example:
first in the form
$procesa=new Querys();
$datosAsignaturas=$procesa->getDatosAsignaturas();
$groups = array();
foreach ($datosAsignaturas as $id => $list) {
$groups[$id] =$list["nombreA"];
}
$selection= $factory-> createElement(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'subjects',
'attributes' => array(
'id' => 'subjects',
'options' => $groups
),
));
$this->add($selection);
Second, the view
<div class="form_element">
<?php $element = $form->get('subjects');
?>
<label>
<?php echo $element->getOption('value'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
third
["subjects"]=> string(1) "1"
i need something like this
["subjects"]=> string(1) "Maths"
Proper assignement of values to a Zend\Form\Element\Select is through the means of value_options inside options or using the element function setValueOptions(). Here a simple example:
$form->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'language',
'options' => array(
'label' => 'Which is your mother tongue?',
'empty_option' => 'Please choose your language',
'value_options' => array(
'0' => 'French',
'1' => 'English',
'2' => 'Japanese',
'3' => 'Chinese',
),
)
));
Now if you need to access the value options like this, you simply call getValueOptions() on the element and you'll receive exactly the same array as above. Then you could do something like this (which I'm assuming is what you're trying to do):
$elemLanguage = $form->get('language');
echo "<select name='{$elemLanguage->getName()}'>\n";
foreach($elemLanguage->getValueOptions() as $id => $language) {
echo "<option value='{$id}'>{$id} - {$language}</option>\n";
}
echo '</select>';
Maybe you mean :
<div class="form_element">
<?php $element = $form->get('subjects');
?>
<label>
<?php echo $element->getOption('label'); //-------- label instead value?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
And about the form
$procesa=new Querys();
$datosAsignaturas=$procesa->getDatosAsignaturas();
$groups = array();
foreach ($datosAsignaturas as $id => $list) {
$groups[$id] =$list["nombreA"];
}
$selection= $factory-> createElement(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'subjects',
'attributes' => array(
'id' => 'subjects',
'options' => $groups
),
'options'=>array(
'label'=>"Your label",
'description' => 'your description',
'value_options' => array(
'0' => 'French',
'1' => 'English',
'2' => 'Japanese',
'3' => 'Chinese',
),
)
));
$this->add($selection);
Related
I am having trouble submitting/saving data to the CakePHP Model. I constructed the form as usual as I always do, but this time I am getting notices and warning an also data is not getting saved. Here is the form I have constructed and method in Controller:
educationaldetails.ctp
<?php
if (empty($Education)):
echo $this->Form->create('Candidate', array('class' => 'dynamic_field_form'));
echo $this->Form->input('CandidatesEducation.0.candidate_id', array(
'type' => 'hidden',
'value' => $userId
));
echo $this->Form->input('CandidatesEducation.0.grade_level', array(
'options' => array(
'Basic' => 'Basic',
'Masters' => 'Masters',
'Doctorate' => 'Doctorate',
'Certificate' => 'Certificate'
)
));
echo $this->Form->input('CandidatesEducation.0.course');
echo $this->Form->input('CandidatesEducation.0.specialization');
echo $this->Form->input('CandidatesEducation.0.university');
echo $this->Form->input('CandidatesEducation.0.year_started', array(
'type' => 'year'
));
echo $this->Form->input('CandidatesEducation.0.year_completed', array(
'type' => 'year'
));
echo $this->Form->input('CandidatesEducation.0.type', array(
'options' => array(
'Full' => 'Full',
'Part-Time' => 'Part-Time',
'Correspondence' => 'Correspondence'
)));
echo $this->Form->input('CandidatesEducation.0.created_on', array(
'type' => 'hidden',
'value' => date('Y-m-d H:i:s')
));
echo $this->Form->input('CandidatesEducation.0.created_ip', array(
'type' => 'hidden',
'value' => $clientIp
));
echo $this->Form->button('Submit', array('type' => 'submit', 'class' => 'submit_button'));
echo $this->Form->end();
endif;
CandidatesController.php
public function educationaldetails() {
$this->layout = 'front_common';
$this->loadModel('CandidatesEducation');
$Education = $this->CandidatesEducation->find('first', array(
'conditions' => array(
'candidate_id = ' => $this->Auth->user('id')
)
));
$this->set('Education', $Education);
// Checking if in case the Candidates Education is available then polpulate the form
if (!empty($Education)):
// If Form is empty then populating the form with respective data.
if (empty($this->request->data)):
$this->request->data = $Education;
endif;
endif;
if ($this->request->is(array('post', 'put')) && !empty($this->request->data)):
$this->Candidate->id = $this->Auth->user('id');
if ($this->Candidate->saveAssociated($this->request->data)):
$this->Session->setFlash('You educational details has been successfully updated', array(
'class' => 'success'
));
return $this->redirect(array(
'controller' => 'candidates',
'action' => 'jbseeker_myprofile',
$this->Auth->user('id')
));
else:
$this->Session->setFlash('You personal details has not been '
. 'updated successfully, please try again later!!', array(
'class' => 'failure'
));
endif;
endif;
}
Here is the screenshot of errors I am getting, Not able to figure out what is happening while other forms are working correctly. looks like something something wrong with view?
This error is coming out because you are not passing the proper arguments to the session->setFlash() method, you are doing like this:
$this->Session->setFlash('You personal details has not been updated successfully, please try again later!!', array(
'class' => 'failure'
));
In docs it is mentioned like:
$this->Session->setFlash('You personal details has not been updated successfully, please try again later!!',
'default', array(
'class' => 'failure'
));
Hi so if i understand :
array(
'CandidatesEducation' => array(
(int) 0 => array(
'candidate_id' => '5',
'grade_level' => 'Basic',
'course' => 'Masters of Computer Application',
'specialization' => '',
'university' => 'Mumbai University',
'year_started' => array(
'year' => '2011'
),
'year_completed' => array(
'year' => '2014'
),
'type' => 'Full',
'created_on' => '2014-11-27 15:44:36',
'created_ip' => '127.0.0.1'
)
)
),
Is your data , and you just need to save this in your candidates_educations table , so in this case i would do :
$this->Candidate->CandidatesEducation->save($this->request->data);
and your $data had to look :
array(
'CandidatesEducation' => array(
'candidate_id' => '5',
'grade_level' => 'Basic',
'course' => 'Masters of Computer Application',
'specialization' => '',
'university' => 'Mumbai University',
'year_started' => array(
'year' => '2011'
),
'year_completed' => array(
'year' => '2014'
),
'type' => 'Full',
'created_on' => '2014-11-27 15:44:36',
'created_ip' => '127.0.0.1'
)
);
the saveAssociated is used when you create your Model AND Model associated , not only your Associated model.
And : i m not sure for year_started and year completed rm of data, it depends of your table schema ; what's the type of year_completed and year_started ?
I'm new to cakePHP, so I may be missing something obvious.
I have an add form that was working and saving to the database, and suddenly stopped. I didn't think I added anything significant, mostly just styling stuff...unfortunately my last backup was before I had finished the add function, so I don't have a way to go back to when it worked. If anyone can take a look and see where I'm going wrong, I would appreciate it!
My Task model:
App::uses('AuthComponent', 'Controller/Component');
class Task extends AppModel {
public $belongsTo = 'User';
public $validate = array(
'task_name' => array(
'custom' => array(
'rule' => array('custom', '/^[a-z0-9 ]*$/i'),
'required' => true,
'message' => 'This field accepts letters and numbers only.'
),
'maxLength' => array(
'rule' => array('maxLength', 50),
'message' => 'Task name cannot exceed 50 characters'
)
),
'frequency' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => true
)
),
'day' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => true
)
),
'user_id' => array(
'numeric' => array(
'rule' => 'numeric'
)
),
'month_type' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false
)
),
'month_number' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false
)
),
'month_day' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'allowEmpty' => true
)
),
'day_number' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false
)
)
);
}
The add function from my TasksController file:
public function add() {
if ($this->request->is('post')) {
$this->Task->create();
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash(__('Task saved!'));
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('The task could not be saved'));
}
}
}
And the form from my tasks/add.ctp file:
<?php
echo $this->Form->create('Task',array('class' => 'taskForm'));
$userId = $this->Session->read('Auth.User.id');?>
<fieldset>
<legend class="welcomeText"><?php echo __('Add a Task'); ?></legend>
<?php
echo $this->Form->hidden('user_id', array('value' => $userId));
echo $this->Form->input('task_name', array('label' => 'Task Name', 'maxLength' => 50));
//set frequency
echo "<p>How often should this task be done?</p>";
$options = array('unset' => 'Decide Later','daily' => 'Daily','weekly' => 'Weekly','monthly' => 'Monthly');
$attributes = array('value' => 'unset','separator' => '<br/>','class' => 'frequencyRadio','legend' => false);
echo $this->Form->radio('frequency', $options, $attributes);
//optional answers
//if "weekly" is selected
echo "<div id=\"weeklyRadio\" >";
echo "<p>Set a day of the week for this task?</p>";
$options = array('unset' => 'Decide later','monday' => 'Monday','tuesday' => 'Tuesday','wednesday' => 'Wednesday',
'thursday' => 'Thursday','friday' => 'Friday','saturday' => 'Saturday','sunday' => 'Sunday');
$attributes = array('value' => 'unset','separator' => '<br/>','class' => 'weeklyRadio','legend' => false);
echo $this->Form->radio('day',$options,$attributes);
echo "</div>";
//if "monthly" is selected
?>
<div id="monthlyRadio">
<p>Schedule this task?</p>
<input type="radio" name="data[Task][month_type]" id="TaskMonthTypeUnset"
value="unset" class="monthlyRadio" required="required" checked="checked" />
<label for="TaskMonthTypeUnset">Decide later</label><br/>
<input type="radio" name="data[Task][month_type]" id="TaskMonthTypeNumber"
value="number" class="monthlyRadio" required="required" />
<label for="TaskMonthTypeNumber">
<?php
echo "On the ";
$options = array(1 => '1st',2 => '2nd',3 => '3rd',4 => '4th',5 => '5th',6 => '6th',7 => '7th',8 => '8th',9 => '9th',
10 => '10th',11 => '11th',12 => '12th',13 => '13th',14 => '14th',15 => '15th', 16 => '16th',
17 => '17th',18 => '18th',19 => '19th',20 => '20th',21 => '21st',22 => '22nd',23 => '23rd',
24 => '24th',25 => '25th',26 => '26th',27 => '27th',28 => '28th',29 => '29th',30 => '30th',31 => '31st');
echo $this->Form->select('month_number',$options,array('value' => null));
echo " of the month";
?>
</label><br/>
<input type="radio" name="data[Task][month_type]" id="TaskMonthTypeDay" value="day" class="monthlyRadio" required="required" />
<label for="TaskMonthTypeDay">
<?php
echo "On the ";
$options = array(1 => '1st',2 => '2nd',3 => '3rd',4 => '4th',5 => '5th',6 => 'last');
echo $this->Form->select('day_number',$options,array('value' => null));
echo " ";
$options = array('monday' => 'Monday','tuesday' => 'Tuesday','wednesday' => 'Wednesday',
'thursday' => 'Thursday','friday' => 'Friday','saturday' => 'Saturday','sunday' => 'Sunday');
echo $this->Form->select('month_day',$options,array('value' => null));
echo " of the month";
?>
</label>
</div>
<?php
echo $this->Form->submit('Add Task', array('class' => 'formSubmit', 'title' => 'Create Task') );
?>
</fieldset>
<?php echo $this->Form->end(); ?>
There is also a javascript file that shows and hides the optional radio buttons, but I assume that wouldn't have anything to do with why it stopped saving to the database.
When I click the "Add Task" button on the form, it doesn't do anything at all (doesn't save to the database, and doesn't redirect to the index.ctp view like it used to). No idea what I'm missing here!
UPDATE
Fixed the problem! The places in my form where I specified a default value of null, it was passing an empty string. The data model was expecting numeric values for 'month_number' and 'day_number,' so it wasn't processing.
I fixed it by adding 0 => '' to the selection list, and specifying 0 as the default value, and now it works fine.
Thanks for the help!
I don't see errors in your code.
Add this in the controller add and make a debug for more information about what happens.
public function add() {
$this->loadModel('Task');
debug($this->request->is('post')); //try this first
//debug($this->request); //after try this
if ($this->request->is('post')) {
$this->Task->create();
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash(__('Task saved!'));
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('The task could not be saved'));
}
}
}
loadModel adds this. update your question with that display the debug, and I update mi answer.
It looks like you have the submit form button assigned to a different class, which is why its not firing the form.
echo $this->Form->submit('Add Task', array('class' => 'formSubmit', 'title' => 'Create Task') );
Try changing it to either of the following
echo $this->Form->submit('Add Task', array(
'class' => 'taskForm',
'title' => 'Create Task'));
echo $this->Form->button('Add Task', array(
'class' => 'taskForm',
'title' => 'Create Task',
'action' => 'submit;));
or amend the form ending tag to see if it fires properly.
Change this
echo $this->Form->end();
to
echo $this-Form->end('Submit');
there are 2 columns check box in cgridViewtable and two bootstrap widgets TbButton in view page.
I can not get value of my checkbox very good. My value in checkboxs transfer into controller but changed id of checkboxs After a period of timeand , and controller don't knew checkbox,
View:
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'profile-information-form',
'enableAjaxValidation' => false,
));
$this->widget('bootstrap.widgets.TbButton', array('buttonType' => 'submit', 'type' => 'primary', 'label' => Yii::t('fa_ir', 'First validation'),));
$this->widget('bootstrap.widgets.TbButton', array('buttonType' => 'submit', 'type' => 'primary', 'label' => Yii::t('fa_ir', 'End validation'),));
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'profile-information-grid',
'dataProvider' => $model->children(),
'filter' => $model,
'columns' => array(
array(
'header' => '',
'value' => '$this->grid->dataProvider->pagination->offset + $row+1', // row is zero based
),
array(
'name' => 'ProfileInformation.user.scope',
'value' => 'CHtml::encode($data->user->scope->name)',
'filter' => Scope::model()->options,
),
array(
'name' => 'id',
'value' => 'CHtml::encode($data->id)',
),
array(
'name' => 'center',
'value' => 'CHtml::encode($data->center)',
),
array(
'name' => 'sendCount',
'value' => 'CHtml::encode($data->sendCount)',
'filter' => '',
),
// Use CCheckbox column with selectableRows = 2 for Select All
array('class' => 'CCheckBoxColumn', 'selectableRows' => 2, 'visible' => (Lookup::isUser2(Yii::app()->user->id) or Lookup::isAdmin(Yii::app()->user->id))),
array('class' => 'CCheckBoxColumn', 'selectableRows' => 2, 'visible' => (Lookup::isUser1(Yii::app()->user->id) or Lookup::isAdmin(Yii::app()->user->id))),
),
));
// action button
$this->endWidget();
Controller:
if (isset($_POST['profile-information-grid_c10']) & isset($_POST['yt0'])) {
////Do action1
}
if (isset($_POST['profile-information-grid_c12']) & isset($_POST['yt1'])) {
////Do action2
}
}
my problem is in $_POST['profile-information-grid_c10'] and _POST['profile-information-grid_c12'] , before id were $_POST['profile-information-grid_c8'] and $_POST['profile-information-grid_c10'] , and now is $_POST['profile-information-grid_c12'] and $_POST['profile-information-grid_c14'].
my problem is very involved. I cannot explain very good.
I want to have a fix id.
I donto why change id of check box?
Can I assign ids for checkboxs?
Can I assign ids for checkboxs? Sure, you better explicitly set checkbox column id:
'class' => 'CCheckBoxColumn', 'id'=>'column1', ... see these docs.
This way you firmly set it and you'll have no things like these yt0, yt2...
The same you can do for the buttons. See TButton docs.
Also you need to use double && in logical condition:
isset($_POST['profile-information-grid_c12']) & isset($_POST['yt1'])
I am trying to do foreach inside array.
I am trying to generate the select box using array value everything seems ok when i give a value manually.
array(
'name' => __('Testing Selection', 'test'),
'id' => 'testing',
'css' => 'min-width:150px;',
'std' => '2',
'default' => '2',
'type' => 'select',
'options' => array(
'1' => __('Test1', 'test'),
'2' => __('Test2', 'test'),
'3' => __('Test3', 'test'),
),
),
In the above code options key contains three values like 1, 2, 3 and the above code is working. But i want to loop all product id here using foreach but it seems not working for me may be i am trying a wrong way. I know foreach inside array is invalid that's why i am trying this way.
$foos = array(
'name' => __('Testing Selection', 'test'),
'id' => 'testing',
'css' => 'min-width:150px;',
'std' => '2',
'default' => '2',
'type' => 'select',
'options' => array(),
),
After array i did foreach
$args = array('post_type' => 'product', 'posts_per_page' => '-1');
$getproducts = get_posts($args);
foreach ($getproducts as $product) {
$foos['options'][] = array(
$product->ID => $product->get_title,
);
}
I want to list 20 more products in the select box everything manually is hard to me can anyone suggest me to use the foreach inside array?
With PHP functions like array_map() or array_reduce() you can create the new array inside an array. array_map () is useful for creating the values for an array, but you can not manipulate the keys with it. Because of that we can use array_reduce() to simulate the behavior of array_map() and to create the associative array needed for options.
$foos = array(
'name' => 'Testing Selection',
'id' => 'testing',
'css' => 'min-width:150px;',
'std' => '2',
'default' => '2',
'type' => 'select',
'options' => array_reduce( get_posts( 'post_type=product&posts_per_page=-1' ), function( $result, $item ) {
$result[$item->ID] = $item->post_title;
return $result;
})
);
If you don't like the approach, you can create new function that will return the required array for options, and thus improve the readability of code.
I'm not sure exactly what you have in mind, but try this template:
<select>
<?php
$items = array(
'one' => 'Item one',
'two' => 'Item two',
'three' => 'Item three'
);
foreach(array_keys($items) as $item_id) {
echo "<option name=\"$item_id\">$items[$item_id]</option>\n";
}
?>
</select>
If you want to insert data to database , then you should go with foreach key value combination.
Here given the example
<?php
if(isset($_POST['submit'])){
$myArray = array();
$myArray = array(
'name' => $_POST['name'],
'contact' => $_POST['contact'],
'address' => $_POST['address']
);
foreach($myArray as $key=>$value){
echo $value;
}
}
?>
<html>
<head>
</head>
<body>
<form action="#" method="post">
name<input type="text" name="name"/>
contact<input type="text" name="contact"/>
address<input type="text" name="address"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
I added in my project sorting data by select->order by $GET-variables. But when I navigate through the pages by paginator, of course this variables are not passing on the next page. What is the best way to pass this variables and use it with paginator?
Controller:
public function indexAction()
{
$sortForm = new \Records\Form\SortingForm();
$field = 'date';
$order = 'desc';
$request = $this->getRequest();
if ($request->isGet()){
$sortForm->setValidationGroup(array('field', 'order'));
$sortData = $request->getQuery()->toArray();
$sortForm->setData($sortData);
if($sortForm->isValid()) {
$sortForm->getData($sortData);
$field = (string) $this->params()->fromQuery('field', 'date');
$order = (string) $this->params()->fromQuery('order', 'desc');
}
}
$query = $this->getRecordsTable()->fetchAll($field, $order);
$paginator = new Paginator\Paginator(new Paginator\Adapter\Iterator($query));
$paginator->setCurrentPageNumber($this->params()->fromRoute('page', 1));
$paginator->setItemCountPerPage(25);
$vm = new ViewModel(array('records' => $paginator));
Model:
public function fetchAll($field, $order)
{
$this->field = $field;
$this->order = $order;
$resultSet = $this->tableGateway->select(function (Select $select) {
$select->columns(array('date', 'name', 'email', 'homepage', 'text', 'image', 'file'));
$select->order($this->field.' '.$this->order);
});
$resultSet->buffer();
$resultSet->next();
return $resultSet;
}
Form:
public function __construct($name = null)
{
parent::__construct('records');
$this->setAttribute('method', 'get');
$this->add(array(
'name' => 'field',
'required' => false,
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Sort by: ',
'value_options' => array(
'date' => 'Date',
'email' => 'E-mail',
'name' => 'Username',
),
)));
$this->add(array(
'name' => 'order',
'required' => false,
'type' => 'Zend\Form\Element\Select',
'options' => array(
'value_options' => array(
'asc' => 'ascending',
'desc' => 'descending',
),
)));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
Paginator view:
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?php echo $this->url($this->route, array('page' => $page)); ?>">
<?php echo $page; ?>
</a> |
<?php else: ?>
<?php echo $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
And another one: when I passing get-variables, the query string looks like http://guest-book.me/page/7?field=date&order=asc&submit=Go How I can do not send pair submit=>value?
Thank you for help! :)
Firstly, you need to make sure the route you're using for the Paginator has a Query String child route, I would recommend having a route specifically for use with listings with pagination, an example:
'router' => array(
'routes' => array(
'paginator_route' => array(
'type' => 'segment',
'options' => array(
'route' => '/list/:controller/:action[/page/:page][/]',
'constraints' => array(
//'__NAMESPACE__' => 'Application\Controller',
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'page' => '[0-9]+',
),
'defaults' => array(
'controller' => 'index',
'action' => 'list',
'page' => 1,
),
),
'may_terminate' => true, // with or without Query string
'child_routes' => array(
'query' => array( // allows us to match query string
'type' => 'Query',
'options' => array(
'defaults' => array(
// Query string defaults here..
)
)
),
),
),
You now need to modify your pagination view to allow us to use current parameters as a base when generating the new links:
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<?php // the last param allows us to reuse the matched params ?>
<a href="<?php echo $this->url($this->route, array('page' => $page), TRUE); ?>">
<?php echo $page; ?>
</a> |
<?php else: ?>
<?php echo $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
Your pagination links should now retain the Query string values :-)
you can create a helper that pass a GET parameter to url too. i've created a sample module for this : https://github.com/samsonasik/SanSamplePagination