Cakephp generated form not submitting all data - php

I have a view called Prices.ctp with the following code. It creates a form which echo's all the data from a variable called $products which contains all the data from a table called Products.
<?php echo $this->Form->create('Product', array('action' => 'changePrice')); ?>
<fieldset>
<h3>Products</h3>
<?php
foreach($products as $k=>$v){
echo $this->Form->hidden('id', array('value'=> $v["Product"]['id']));
echo $this->Form->input('name', array('value' => $v["Product"]["name"] ));
echo $this->Form->hidden('slug', array('value'=>$v["Product"]['slug']));
echo $this->Form->hidden('description', array('value'=>$v["Product"]['description']));
echo $this->Form->hidden('cateID', array('value'=>$v["Product"]['cateID']));
echo $this->Form->input('price', array('value' => $v["Product"]['price']));
echo $this->Form->hidden('photo', array('value'=>$v["Product"]['photo']));
echo $this->Form->hidden('photo_dir', array('value'=>$v["Product"]['photo_dir']));
echo $this->Form->hidden('active', array('value'=>$v["Product"]['active']));
echo $this->Form->hidden('views', array('value'=>$v["Product"]['views']));
echo $this->Form->hidden('created', array('value'=>$v["Product"]['created']));
echo $this->Form->hidden('modified', array('value'=>$v["Product"]['modified']));
}?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
It shoots to this controller method, called changePrice
public function changePrice(){
$this->Product->saveMany($this->request->data['Product']);
$this->Session->setFlash( "Prices Saved.");
$this->redirect ( "/admin/products/" );
return;
}
However when I used debug() to check the contents of of $this->request->data it shows that only the final iteration of the foreach loop in the view is being sent.
To re-word, if the original $products variable (passed into the view prices.ctp) has 4 products: product1, product2, product3, and product4, all with their own data from the Product table (id, name, etc), when the submit button is pressed on the page, only product4's variables will be passed into $this->request->data.
Why is this happening?
Cheers

you can do like this to get the data of all products
<?php
foreach($products as $k=>$v){
echo $this->Form->hidden("Product.{$k}.id", array('value'=> $v["Product"]['id']));
echo $this->Form->input("Product.{$k}.name", array('value' => $v["Product"]["name"] ));
echo $this->Form->hidden("Product.{$k}.slug", array('value'=>$v["Product"]['slug']));
echo $this->Form->hidden("Product.{$k}.description", array('value'=>$v["Product"]['description']));
echo $this->Form->hidden("Product.{$k}.cateID", array('value'=>$v["Product"]['cateID']));
echo $this->Form->input("Product.{$k}.price", array('value' => $v["Product"]['price']));
echo $this->Form->hidden("Product.{$k}.photo", array('value'=>$v["Product"]['photo']));
echo $this->Form->hidden("Product.{$k}.photo_dir", array('value'=>$v["Product"]['photo_dir']));
echo $this->Form->hidden("Product.{$k}.active", array('value'=>$v["Product"]['active']));
echo $this->Form->hidden("Product.{$k}.views", array('value'=>$v["Product"]['views']));
echo $this->Form->hidden("Product.{$k}.created", array('value'=>$v["Product"]['created']));
echo $this->Form->hidden("Product.{$k}.modified", array('value'=>$v["Product"]['modified']));
}
?>

Related

Isssue with display data from database

I use framework:
CodeIgniter
I try display values from enrol table. Connetcion with DB working correct etc. Because standard app function in this way working correct. I try add my custom own code but something went wrong and result is empty.
I try combinate in this way:
<?php
$enrol_history = $this->db->get_where('enrol', array('active_shop' => $active_shop, 'monthly_subscription_fee' => $monthly_subscription_fee))->row_array();
?>
<?php echo $active_shop['active_shop']; ?>
<?php echo $enrol_history['monthly_subscription_fee']; ?>
<?php echo $active_shop ?>
<?php echo $monthly_subscription_fee ?>
Everytime empty result.
update:
I also try:
Crud_model.php
public function get_installation_details($monthly_subscription_fee = "")
{
return $this->db->get_where('enrol', array('monthly_subscription_fee' => $monthly_subscription_fee));
}
code:
<?php $installation_details = $this->crud_model->get_installation_details($monthly_subscription_fee)->row_array(); ?>
<?php echo $installation_details['monthly_subscription_fee']; ?>
update:
<?php
$enrol_history = $this->db->get_where('enrol', array('active_shop' => $enrol['active_shop'], 'monthly_subscription_fee' => $enrol['monthly_subscription_fee'],))->row_array();
?>
<?php echo $enrol['monthly_subscription_fee']; ?>
<?php echo $enrol['active_shop']; ?>
This is correct. Because in admin panel I can get in this way this values from DB. But in frontend I cannot do it...

Dependent dropdown for country and state in yii 1.13

I had created two database tables as,
Country
State
In Country table i had countryid & cname field. In State table i had state_id, state_name & country_cid.
Now i need to make a dependent dropdown i.e. when i select country dropdown box, then the particular state for that country should be displayed. I had done below coding. But it displays only country and not displays state.
This is in views/sample/register.php file.
<div class="row">
<?php echo $form->labelEx($model,'countryid');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('SampleController/dynamicSubcategory'),
array('coountry_id'=>'js:this.value'),
'dataType' => 'JSON',
'success'=>'js:function(data)'
. '{'
. 'var html="<option value=>-----Select city-----</option>";'
. '$.each(data,function(i,obj)'
. '{'
. 'html+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. '});'
. '$("#state_id").html(html);'
. '}'
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_id','', array());
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$countryId=$_POST['coountry_id'];
$criteria=new CDbCriteria();
$criteria->select=array('state_id,state_name');
$criteria->condition='country_cid='.$countryId;
$criteria->order='state_name';
$cityAry= State::model()->findAll($criteria);
$ary=array();
foreach($cityAry as $i=>$obj)
{
$ary[$i]['state_id']=$obj->id;
$ary[$i]['state_name']=$obj->name;
}
echo json_encode($ary);
}
I had created Country model & State model. I had analyzed many sites. But i can't get right. Please anybody help.
You can try below code which I have used in one of my projects -
**Code in the view file :**
<?php $arrOptionsCountry = array('prompt'=>'Select Country','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site','SearchValueStates'),'update'=>'#Airports_state','beforeSend'=>'stateLoading'));
echo $form->dropDownList($model,'country',$arrCountryList,$arrOptionsCountry,array('class'=>'span11 customDropdown1_select'));
$arrOptionsState = array('prompt'=>'Select State','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site', 'SearchValueCities'),'update'=>'#station_name','beforeSend'=>'cityLoading'));
echo $form->dropDownList($model,'state',$arrStatesList,$arrOptionsState);
echo $form->dropDownList($model,'city',$arrCityList);
?>
**Site Controller :**
public function actionSearchValueStates()
{
$arrParam =array();
if(isset($_POST['Airports']['country']))
{
$Term = $_POST['Airports']['country'] ;
$case = "STATE-LIST";
$prompt = "Select State";
$arrParam['id'] = isset($Term)?$Term:null ;
$data = States::getList($case,$arrParam);
$data = CHtml::listData($data,'id','name');
echo CHtml::tag('option',array('value'=>''),$prompt,true);
foreach($data as $value=>$name)
{
echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
}
}
Yii::app()->end();
}
I got the answer for my question.
This is in views/sample/register.php file
<div class="row">
<?php echo $form->labelEx($model,'country');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/dynamicSubcategory'),
'update'=>'#state_name',
'data'=>array('country_id'=>'js:this.value'),
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_name','', array(), array(
'prompt'=>'Select State'
));
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$data=State::model()->findAll('country_cid=:countryid',
array(':countryid'=>(int) $_POST['country_id']));
$data=CHtml::listData($data,'state_id','state_name');
echo "<option value=''>Select State</option>";
foreach($data as $value=>$state_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($state_name),true);
}
This code works fine for dependent dropdown in yii

Codeigniter - How to create a form with undefined number of input?

So I've been trying to create an 'add' function for a contest table that is also linked to a joining table as the contest has many sport events associated to it (and a sport events will also be included in many contests). I have managed to create it as below, however it is limited to only adding one row into the joining table based on the chosen game in a dropdown.
So now, how do I go about creating the form if I don't know how many sport events there might be? How will the website create another dropdown if one dropdown is used so that more sport events can be selected? Similarly, how does the controller know that there are x amount of dropdowns selected, and hence x amount of rows to be added to the joining table?
I'm sorry if I am using incorrect or ambiguous terms to describe my problem. I have only started learning and creating websites recently.
Thank you.
UPDATE: I may have a solution per the updated codes below. However I am now stuck on the inserting into the database page. For some reason when I click submit, the next page loads but with no error and no rows inserted. Please help :)
View
<h1>Add New Contest</h1>
<?php
echo form_open('contests/add/');
?>
<?php
echo "<br />" "<br />"
echo "Contest Name";
$data = array( 'name' => 'contest_name',
'value' => set_value('contest_name'),
);
echo form_input($data);
echo "<br />" "<br />"
echo "Game";
?>
<div class="field_wrapper">
<div>
<select name="field_name[]">
<option value="" disabled selected>Select Game</option>
<?php
foreach($events_lists->result() as $row) {
$sports_events_id = $row->sports_events_id;
$sports_events_start_date = $row->sports_events_start_date;
$sports_events_start_time = $row->sports_events_start_time;
$home_team_shorthand = $row->home_team_shorthand;
$away_team_shorthand = $row->away_team_shorthand;
?>
<option value="<?php echo $sports_events_id; ?>"><?php echo $home_team_shorthand; ?> v <?php echo $away_team_shorthand; ?> - <?php echo $sports_events_start_date; ?> <?php echo $sports_events_start_time; ?></option>
<?php } ?>
</select>
<img src="add-icon.png"/>
</div>
</div>
<?php
echo "<br />" "<br />"
$data = array( 'value' => 'Add Contest',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
Controller
function add()
{
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
foreach ($data['leagues_list']->result() as $row) {
$league_insert_id = $row->id;
$this->load->module('sports_events');
$data['events_lists'] = $this->sports_events->get_events_list($league_insert_id);
}
if ($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add_contest';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data1 = array(
'contest_name' => $this->input->post('contest_name')
);
if(isset($_REQUEST['submit'])) {
$data2 = $_REQUEST['field_name'];
}
if ($this->_transactions_new_contest($data1, $data2)) {
return $query;
$this->session->set_flashdata('team_phase_created', 'The team phase has been set');
redirect('/contests/');
}
}
}
Model
function _transactions_new_contest($data1, $data2){
$this->db->trans_start();
$this->db->insert('contests', $data1);
$contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
foreach ($contest_id->result() as $row) {
$contest_result_id = $row->id;
foreach($data2 as $value){
$this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $value . ')');
} }
$this->db->trans_complete();
}

CakePHP pagination not working beyond 1st page

I have a view in my site that has two divs. one houses a search box and the other is where the result of the search is shown. by default, nothing is loaded on the result div. only when there is a search via post request, the result div is populated. However, this is causing problem with the pagination functionality as the second time the page loads, it doesnt have the data to go around with listing the rest of the results. How can i modify my controller/view to meet this need?
My action in the controller:
public function search(){
if($this->request->is('post')){
if($this->request->data['User']['search']!=null){
$search_name=$this->request->data['User']['search'];
$this->Paginator->settings = array(
'conditions'=>array('User.name LIKE'=>'%'.$search_name.'%'),
'order' => array('User.datetime' => 'desc'),
'limit' => 10
);
$feed = $this->Paginator->paginate('User');
$this->set('search_result',$feed);
}
else{
$this->Session->setFlash(__("Cant make an empty search"));
return $this->redirect(array('action'=>'search'));
}
}
}
My View:
<?php
include 'header.ctp';
echo '<div id="feed">';
echo $this->Form->create(null, array('url' => array('controller' => 'users', 'action' => 'search')));
echo $this->Form->input('search');
echo $this->Form->end('Search');
echo 'search by name';
echo '</div>';
if(isset($search_result)){
echo '<div id="tweet_records">';
if(!empty($search_result)){
foreach ($search_result as $user) :
$formatted_text;
$latest_tweet_time;
$formatted_time;
if(!empty($user['Tweet'])){
$formatted_text=$this->Text->autoLinkUrls($user['Tweet']['0']['tweet']);
$latest_tweet_time=$user['Tweet']['0']['datetime'];
$formatted_time;
if(strlen($latest_tweet_time)!=0){
$formatted_time='Tweeted at '.$latest_tweet_time;
}
else{
$formatted_time='No tweets yet';
}
}
else if(empty($user['Tweet'])){
$formatted_text='No tweets yet';
$formatted_time='';
}
echo '<table id="t01">';
echo'<tr>';
echo '<td>'.
$user['User']['name'].'#'.$this->HTML->link($user['User']['username'], array('controller'=>'tweets','action'=>'profile',$user['User']['id'])).'<br>'.$formatted_text.' '.'<br>'.'<font color="blue">'.$formatted_time.'</font>';
echo '<div id="delete">';
$selector='true';
foreach ($user['Follower'] as $follower) :
if($follower['follower_user_id']==AuthComponent::user('id')){
$selector='false';
echo $this->Form->postlink('Unfollow',array('controller'=>'followers','action'=>'unfollow',$user['User']['id']),array('confirm'=>'Do you really want to unfollow this person?'));
}
endforeach;
if($selector=='true' & $user['User']['id']!=AuthComponent::user('id')){
echo $this->Form->postlink('Follow',array('controller'=>'followers','action'=>'follow',$user['User']['id']));
}
echo '</div>';
echo '</td>';
echo '</tr>';
endforeach;
echo'</table>';
echo 'Pages: ';
echo $this->Paginator->prev(
' < ',
array(),
null,
array('class' => 'prev disabled')
);
echo $this->Paginator->numbers();
echo $this->Paginator->next(
' > ' ,
array(),
null,
array('class' => 'next disabled')
);
}
else{
echo '<font color="red"> No results found </font>';
}
echo '</div>';
}
You are searching for results only on post request. But when you press the next button you are making a get request. So the first if statement doen't return true so you are not passing any data to your view.
Even if you remove the first if statement for post you'll still won't see any data because the next button doesn't post any data to make true the second statement.
PS:
On CakePHP include is not a preferable thing to do. Also you haven't mentioned the version you are using.

How to send the values of a php array of classes from a php file to another php file

i have an array of classes in a php file, this class has 3 fields, and i am using these fields to save the values of SELECTS and INPUT CHECKBOXs inside a FORM using POST, then i need to send this array of classes to another php file for proccessing data.
<?php
class info_subject{
public $code_as;
public $time_as;
public $selectionn_as;
}
$subjects[0] = new info_subject();//The only way I have seen for creating an array of classes
//is with a for loop, but if you have a better way for doing this, please let me know
$subjects[1] = new info_subject();
//here i am using the fields to save info in a form
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"".$subjects[$i]->time_as ."\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"".$asignaturas[$i]->selection_as."\">";
//and so on with every position of the array using $i
?>
//then there is a button to send the the dato to file2.php
//file2.php
<?php
$subjects=$_POST["$subjects"];//I am using this but i cant retrieve the fields of $subjects
?>
What can i do buddies?
instead of:
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"".$subjects[$i]->time_as ."\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"".$asignaturas[$i]->selection_as."\">";
you can try something like:
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"subjects[$i][".$subjects[$i]->time_as ."]\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"subjects[$i][".$asignaturas[$i]->selection_as."]\">";
and then in file2
$subjects=$_POST["subjects"];
and pick off what you need.
To be honest, I find your question hard to understand. Maybe try streamlining your problem and clean up some code/formatting and it will be easier for us to give you advice.
You can't submit a class or array via $_POST because the post array is an array which can only contain simple values.
Hi~ Jose Ricardo Citerio. I hope you can read Chinese
我不知道你是不是需要这样,在file1里面存储着select的option选项。然后file2接收去后处理
<?php
class info_subject{
public $code_as = ['name' => 'select_name', 'option' => ["k" => "v"]];
public $time_as;
public $selectionn_as;
}
$subjects = new info_subject();
echo "";
echo 'code_as["name"] . '">"';
//loop options for $subjects["option"] and print k and v; like => foreach($subjects->code_as["name"] as $k => $v){echo '' . $v . '';}
echo "";
echo 'xxx['name'] . '">please check';
?>
//then there is a button to send the the dato to file2.php
//file2.php
<?php
$subjects = $_POST["select_name"];
$subjects1 = $_POST["checkbox_name"];
?>

Categories