I have been trying to find a solution to something that I believe is rather simple? What I would like to do is create a tabular form to collect some records for a survey.
Table: survey_record
id
meter_id
status_id
create_time
create_user
Table: survey_inspection
id
survey_record_id (FK)
bay_id
bay_usage_id
So table survey_inspection HAS_MANY inspections from survey_record.
Assuming an inspector is doing a survey for meter_id = 1001, the user identifies the status_id of the meter then, they have to fill in 4 inspection entries, as 1001 has 4 bays.
To generate the 4 bays I simply created a for loop. Which works fine.
View: _form.php
...
$meter=Meter::model()->findByPk($model->meter_id);
$bays = count($meter->bays); //retrieves the number of inspections required
<?php echo $form->dropDownListRow($model,'status_id',$model->getStatusId(),array('prompt'=>'Select Status ...')); ?>
...
<?php for ($i = 1; $i <= $bays; $i++): ?>
<?php echo $form->textFieldRow($inspection, "[$i]bay_id", array('readonly'=>true, 'value'=>"$i", 'class'=>'span1')); ?>
<?php echo $form->dropDownListRow($inspection, "[$i]bay_usage_id", $inspection->getUsageId(), array('prompt'=>'Bay Status ...') ); ?>
<?php endfor; ?>
...
However when I submit the form I am only receiving two (not four) results and I can't seem to display the validated fields correctly. So here's the famous controller file:SurveyRecordController.php
public function actionCreate($survey_id, $meter_id)
{
$model=new SurveyRecord;
$inspection = new SurveyInspection;
$model->survey_id = (int)$survey_id;
$model->meter_id = (int)$meter_id;
if(isset($_POST['SurveyRecord'], $_POST['SurveyInspection']))
{
$model->attributes=$_POST['SurveyRecord'];
$valid= $model->validate();
$i=1;
foreach($_POST['SurveyInspection'][$i] as $inspection)
{
$inspection = new SurveyInspection;
$inspection->bay_id =$_POST['SurveyInspection'][$i]['bay_id'];
$inspection->bay_usage_id =$_POST['SurveyInspection'][$i]['bay_usage_id'];
$valid= $inspection->validate() && $valid;
echo '<br/><br/><br/><pre>';
print_r($_POST['SurveyInspection'][$i]);
echo '</pre>';
if($valid)
{
if($model->save(false))
{
$inspection->survey_record_id = $model->id;
$inspection->save(false);
$this->redirect(array('/meter'));
}
}
$i++;
//$inspection->attributes=$_POST['SurveyInspection'][$i];
}
}
$this->render('create',array(
'model'=>$model,
'inspection'=>$inspection,
));
}
I have a funny feeling that I may not be doing the foreach loop correctly as when I view the array $_POST['SurveyInspection'][$i] I am only returned with two entries when there should be four.
Some information that may be helpful:
PHP version: 5.4.14
Yii version: 1.1.13
PostgreSQL version: 9.1.9
Thank you kindly :)
To my knowledge i think for the validation u have bypassed the default validation by passing
false to save method (ex : $model->save(false)) and u are also using yii's validate function . I think u try removing the false parameter and just use save() for the validation issue
The foreach loop is wrong. You can make it proper and a bit cleaner:
foreach($_POST['SurveyInspection'] as $i => $value)
{
$inspection = new SurveyInspection;
$inspection->bay_id = $value['bay_id'];
$inspection->bay_usage_id = $value['bay_usage_id'];
...
$i++ is not needed, as foreach will loop every element.
I've taken a completely different approach, valuable suggestions are always welcome :)
Hope this will be helpful for some of you.
Controller:
public function actionCreate($survey_id, $meter_id)
{
$bays = $this->getBayCount($meter_id);
for ($i=1;$i<=$bays;$i++)
{
$model=new SurveyRecord;
$model->survey_id = (int)$survey_id;
$model->meter_id = (int)$meter_id;
${'inspection_'.$i} = new SurveyInspection($i);
if(isset($_POST['SurveyRecord'], $_POST["SurveyInspection"][$i]))
{
$model->attributes = $_POST['SurveyRecord'];
${'inspection_'.$i}->attributes = $_POST["SurveyInspection"][$i];
echo '<br/><br/><br/><pre>';
print_r(${'inspection_'.$i}->attributes);
echo '</pre>';
}
}
for ($i=1;$i<=$bays;$i++)
{
${'inspection_'.$i} = new SurveyInspection($i);
$inspection['inspection_'.$i] = ${'inspection_'.$i};
}
$this->render('create',array(
'inspection'=>$inspection,
'model'=>$model
));
}
View:
...
<div class="control">
<?php echo $form->dropDownListRow($model,'status_id',$model->getStatusId(),array('prompt'=>'Select Status ...')); ?>
<?php
$meter=Meter::model()->findByPk($model->meter_id);
$bays = count($meter->bays);
?>
<?php for ($i=1; $i<=$bays; $i++): ?>
<table>
<tr>
<td><?php echo $form->textFieldRow($inspection["inspection_$i"], "[$i]bay_id",
array('readonly'=>true, 'value'=>"$i", 'class'=>'span1')); ?></td>
<td><?php echo $form->dropDownListRow($inspection["inspection_$i"], "[$i]bay_usage_id", $inspection["inspection_$i"]->getUsageId(),
array('prompt'=>'Bay Status ...') ); ?></td>
</tr>
</table>
<?php endfor; ?>
</div>
...
Credit: http://yiiblog.info/blog/index.php/post/108/Rename+ACtiveRecord+$_POST+array's+Name+to+update+multimodels
Note: There's still some work to be done on the view/controller (doesn't seem to be able to select on $_POST for my dropdowns on second model), will post once I have fixed it.
Thanks for your help #PeterM and #Ninad for your input.
Related
i tried to use print_r($list) but the result array().There is no element in the array.I want to show data form my table.there is user table, job table and industry table.Can anybody suggest me where is mistake.
This is my model function get_data_by_query used in controller
public function get_data_by_query($qry)
{
$query = $this->db->query($qry);
return $query->result();
}
This is my controller where i am verifying email, phone number.
public function Dashboard()
{
if ($this->Common_model->Is_User_Logged())
{
$condition='';
$data['email_verified']=self::IsEmailVerified();
$data['phone_verified']=self::IsPhoneVerified();
$userdata=$this->session->userdata('user_logged_in');
$data['user_email']=$userdata['email'];
//print_r($data);
$res=$this->Common_model->get_data_by_query("SELECT * FROM user WHERE user_id={$userdata['id']} limit 1");
//print_r($res);
$data['user_skills'] = $res[0]->user_skills;
//print_r($data);
$arr = array($res[0]->user_skills);
//print_r($arr[0]);
//exit;
$condition.=" and FIND_IN_SET(job_title,'$arr[0]')";
print_r($condition);
$sql_get="SELECT j.*,j.job_industry,i.industry_title
FROM job j
LEFT JOIN industry i on i.industry_id=j.job_industry
WHERE job_status=1 ".$condition." ";
//print_r($sql_get);
$data['list']=$this->Common_model->get_data_by_query($sql_get);
//print_r($data['list']);
$data['user_phone']=$res[0]->user_mobile;
$this->load->view('user/header');
$this->load->view('user/home', $data);
$this->load->view('user/footer');
}
else
{
redirect('user');
}
}
This is my view
<?php
if(!empty($list)>0)
{
foreach ($list as $row)
{
?>
<tr>
<td><?php echo $row->job_role;?></td>
<td><?php echo $row->industry_title;?></td>
<td><?php echo $row->job_vacancy;?></td>
<td><?php echo $row->job_keyword;?></td>
<!--<td><?php echo $row->job_type;?></td>-->
</tr>
<?php
} }
?>
what is the reason that $list is empty array although i have data in my table. I will be thankful for you.
After a lot of effort, i found that there is no problem in above code. The problem is in tje SQL query. I am trying to resolve that query.
i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)
I'm trying to figure out how to get the right response from Multidimensional array in a SOAP request.
In fact, I would like to be able to Submit a "VAT" number and get the MULTISCORE value
functions.php
<?php
function score ($name)
{
$details=array(
array(
VAT=>"BE0422370068",
COMPANY=>"DEXIA",
MULTISCORE=>25,
CITY=>"HASSELT"
)
/*
array(
VAT=>"BE0402607507",
COMPANY=>"SCANIA",
MULTISCORE=>50,
CITY=>"BRUSSEL"
),
array(
VAT=>"BE0446140711",
COMPANY=>"DELHAIZE",
MULTISCORE=>50,
CITY=>"GENT"
)
*/
);
foreach($details as $va=>$var) //BTW
{
foreach($va as $co=>$cor) //COMPANY
{
foreach($co as $mu=$mur) //MULTISCORE
{
foreach($mu as $ci=<$cir) //CITY
{
if($name==$va) //If VAT exist
$score=$mur; //Show MULTISCORE value
}
}
}
}
return $score;
}
?>
These functions are called from following PHP request
Client.php
<?php
require 'lib/nusoap.php';
$client = new nusoap_client("http://localhost:8080/service.php?wsdl");
if (isset($_POST["cia"]))
{
$cia_name = $_POST["cia"];
}
if (!isset($_POST['submit'])) {
?>
<html>
<head>
<title>Scania Finance GRAYDON</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Company: <input type="text" size="12" maxlength="12" name="cia"><br /><br />
<input type="submit" value="submit" name="submit">
</form>
<?php
} else {
$response = $client->call('score',array("name"=>"$cia_name"));
if (empty($response))
echo "Please go <b>'Back'</b> and enter Company name";
else
echo "GRAYDON - MultiScore of Company $cia_name is equal to <b>".$response."</b></br></br>";
if ($response < '30'){
echo "SORRY, Graydon MultiScore is less than 30!";
} elseif ($response < '60'){
echo "CAN BE DISCUSSED, Graydon MultiScore is between 30 and 60, the visit of a Financial Salesman is needed!";
} else {
echo "GREAT, Graydon MultiScore is greater than 60, we can do Business together!";
}
}
?>
</body>
I can't find the way to call the right Array values.
You need to do two things.
1) in your function.php file write this line:-
$score = $details[$key];
return $score;
2) In your client.php file
$response is now Array so you need to print it via
print_r($response);
Now you can get MULTISCORE by $response['MULTISCORE'] and COMPANY NAME by $response['COMPANY'];
Note:- You wrote echo $response so you got only "Array" print.
Suggestion:- You should ON Error Reporting in developement mode otherwise you cannot debug code properly.
Write this line as:-
echo "GRAYDON - MultiScore of VAT ".$vat_num." is equal to <b>".$response['MULTISCORE']."</b></br></br>";
check new condion like this:-
if($response['MULTISCORE'] < '30'){
// your code
}
if you want company name then,
print company name:-
echo $response['COMPANY'];
You don't need to run foreach loop in this case. If you simply want MULTISCORE by submitting VAT value then it is very easy by below way:
refer array_search and array_column
function score ($name)
{
$details=array(
array(
'VAT'=>"BE0422370068",
'COMPANY'=>"DEXIA",
'MULTISCORE'=>25,
'CITY'=>"HASSELT"
)
/*
array(
'VAT'=>"BE0402607507",
COMPANY=>"SCANIA",
MULTISCORE=>50,
CITY=>"BRUSSEL"
),
array(
VAT=>"BE0446140711",
COMPANY=>"DELHAIZE",
MULTISCORE=>50,
CITY=>"GENT"
)
*/
);
$key = array_search($name, array_column($details, 'VAT'));
// $key = array_search('BE0402607507', array_column($details, 'VAT'));
$score = $details[$key]['MULTISCORE'];
return $score;
}
if you want all array values by submitting VAT then you need to write following line:-
$score = $details[$key];
return $score;
Now you will get company name by echo $score['COMPANY']; and multiscore by echo $score['MULTISCORE'];
Hope this will help you :)
Ok, anyway, I can't get it. As already said, tried several options as you asked but can't get the value only returns "Array".
For people are looking for how to retrieve one value of a multidimensional array using a SOAP request, to test it use XAMPP, here my work files on a PHPSOAP.zip
workfiles:
https://drive.google.com/file/d/0B-pCOHYZNf6COFNLdFV5RkpITGM/view?usp=sharing
Ravi Hirani thank you for your help!
I'm trying to implement SlickGrid on the edit page of a CakePHP project, and when the page loads I get this error in the javascript console:
slick.grid.js:2173TypeError:'Slick.Editors.Text is not a constructor' (evaluating 'new (editor || getEditor(activeRow, activeCell))')
The data renders correctly in the grid on my page, but when I click on a cell to edit it, it just turns white and I can't type anything. If I click on another cell, that cell will turn white and the first one will stay white.
Here is my php/jQuery code:
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-1.7.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery.event.drag-2.0.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.core.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.grid.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.editors.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.formatters.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.dataview.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellselectionmodel.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangedecorator.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangeselector.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.rowselectionmodel.js"); ?>
<?php // Setup rows and cols array for grid
$columns = array();
foreach($route['Stop'] as $stop) {
$columns[] = array( "name" => $stop['name'],
"field" => $stop['id'],
"id" => $stop['id'],
"editor" => "Slick.Editors.Text");
}
$tripId = 1;
$thisTrip['id'] = $tripId;
foreach($route['RouteTrip'] as $routeTrip) {
if($routeTrip['trip_id'] != $tripId) {
$rows[] = $thisTrip;
$tripId = $routeTrip['trip_id'];
$thisTrip['id'] = $tripId;
}
else {
$thisTrip[$routeTrip['stop_id']] = $routeTrip['time'];
}
}
?>
<?php
echo $this->Html->scriptBlock('
var rows = '.json_encode($rows).';
var columns = '.json_encode($columns).';
var options = { rowHeight:21,
defaultColumnWidth:100,
editable:true,
enableAddRow:true,
enableCellNavigation:true,
asyncEditorLoading:false,
autoHeight:true,
autoEdit:true
};
slickgrid = new Slick.Grid($("#scheduleTable"), rows, columns, options);
slickgrid.setSelectionModel(new Slick.CellSelectionModel());
slickgrid.updateRowCount();
slickgrid.render();
');
?>
The $rows and $columns are correctly formatted, and each column has an "editor" attribute with "Slick.Editors.Text" as its value.
Help?
I have also got this error initially when i started working with slickgrid.
The error is because you have specified the editor as string and not as a class.
So, remove the double quotes in "editor" => "Slick.Editors.Text" and give as "editor" => Slick.Editors.Text
This solved the error for me. Hope this solution will solve yours too.
Include the slick.editors.js file.
Also, make sure that the editor is being specified as a class, not as a string (I'm not familiar with PHP, so it's not obvious to me from the source code, but I suspect that's the case).
I am relatively new to The Zend framework having only been working with it probably two months at the most. I am now trying to get a list of results from a query I run, send it through the zend paginator class and display 4 results per page, however it does not seem to be recognising when it has got 4 results, I believe there is an error in my code but I can not for the life of me see it, I was hoping someone here will be able to pick up on it and help me and out and probably tell me it is something stupid that I have missed. Thanks here is the code I have written.
This the query in my model
public function getAllNews()
{
$db = Zend_Registry::get('db');
$sql = "SELECT * FROM $this->_name WHERE flag = 1 ORDER BY created_at";
$query = $db->query($sql);
while ($row = $query->fetchAll()) {
$result[] = $row;
}
return $result;
}
This is code in my controller
function preDispatch()
{
$this->_helper->layout->setLayout('latestnews');
Zend_Loader::loadClass('newsArticles');
$allNews = new newsArticles();
$this->view->allNews = $allNews->getAllnews();
//die (var_dump($this->view->allNews));
$data = $this->view->allNews;
// Instantiate the Zend Paginator and give it the Zend_Db_Select instance Argument ($selection)
$paginator = Zend_Paginator::factory($data);
// Set parameters for paginator
$paginator->setCurrentPageNumber($this->_getParam("page")); // Note: For this to work of course, your URL must be something like this: http://localhost:8888/index/index/page/1 <- meaning we are currently on page one, and pass that value into the "setCurrentPageNumber"
$paginator->setItemCountPerPage(1);
$paginator->setPageRange(4);
// Make paginator available in your views
$this->view->paginator = $paginator;
//die(var_dump($data));
}
Below is the view that builds the paginator,
<?php if ($this->pageCount): ?>
<div class="paginationControl">
<!-- Previous page link -->
<?php if (isset($this->previous)): ?>
< Previous |
<?php else: ?>
<span class="disabled">< Previous</span> |
<?php endif; ?>
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<?= $page; ?> |
<?php else: ?>
<?= $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
<!-- Next page link -->
<?php if (isset($this->next)): ?>
Next >
<?php else: ?>
<span class="disabled">Next ></span>
<?php endif; ?>
</div>
<?php endif; ?>
And finally the code the makes up my view
<div id="rightColumn">
<h3>Latest News</h3>
<?php if (count($this->paginator)): ?>
<ul>
<?php foreach ($this->paginator as $item): ?>
<?php
foreach ($item as $k => $v)
{
echo "<li>" . $v['title'] . "</li>";
}
?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?= $this->paginationControl($this->paginator, 'Sliding', '/latestnews/partial_pagination_control.phtml'); ?>
</div>
I will be greatful for any help you can give me.
Thanks
Sico
$paginator should be set to 4 as you want to show only 4 records at a time :
$paginator->setItemCountPerPage(4);
So I think the root of your problem is in your model class with the getAllNews function. The Zend_Db fetchAll function retrieves an associative array of all the records matching your query. You are returning an array of one element that is an array of all the rows retrieved by your select statement.
Try this:
public function getAllNews()
{
$db = Zend_Registry::get('db');
$sql = "SELECT * FROM $this->_name WHERE flag = 1 ORDER BY created_at";
return $db->fetchAll($sql);
}
You sould not pass values to paginator if you want it to limit your query.
There is a code will work for you
$usersTable = $this->getTable();
$registerSelect = $usersTable->select()->where('status = ?', 'OK')->order('lastLogin DESC');
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($registerSelect));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage($limit);