The problem is very simple but why it is complicating for me.I have written data validation also.But for empty fields also it is accepting the input.please check whether any error in my action.php.
Model/action.php
<?php
App::uses('AppModel', 'Model');
class Actions extends AppModel {
public $validate = array(
'value_to_plot' => array(
'required'=>true,
'message' => 'atleast select one measure'
),
'column_name' => array(
'required'=>true,
'rule'=>array('notBlank'),
'message' => 'atleast select one table'
)
);
}
?>
View/Actions/index.ctp
<div align="center">
<fieldset>
<?php echo $this->Form->create('valueToSend',array('type' => 'get'));?>
<?php if(isset($_GET['table_name'])){ ?>
<table class="table table-bordered table-hover table-striped">
<?php echo $this->Form->hidden('table_name', array('hiddenField' => true, 'value'=> $_GET['table_name'],'id'=>'table_name'));
echo $this->Form->hidden('chart', array('hiddenField' => true, 'value'=> "column3d",'id'=>"chart"));
?>
<tr>
<th>MEASURES</th>
<td>
<?php echo $this->Form->select('value_to_plot',$measures1,array('class'=>'form-control','id'=>'measures','required'=>true),['empty' => 'choose one']);?>
</td>
</tr>
<tr>
<th>DIMENSIONS</th>
<td>
<?php echo $this->Form->select('column_name[]',$measures2,array('multiple'=>'true','class'=>'form-control','id'=>'dimensions','required'=>true),['empty' =>'choose one']);?>
</td>
</tr>
</table>
<div style="text-align:center">
<?php echo $this->Form->end('submit'); ?>
</div>
<?php } ?>
</fieldset>
</div>
Controller/ActionsController.php
<?php
App::uses('AppController', 'Controller');
class ActionsController extends AppController {
public function beforeFilter() {
if(!isset($_SESSION['Auth']) && empty($_SESSION['Auth'])) {
$userId = $_SESSION['Auth[User[id]]'];
return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
}
}
public Function index(){
App::import('Model', 'ConnectionManager');
$con = new ConnectionManager;
$cn = $con->getDataSource('default');
$tablequery="SELECT TABLE_NAME as table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='phygital_visualize' AND TABLE_NAME != 'report'";
$rows = $cn->query($tablequery);
//$rows = $result->fetchAll('assoc');
$dataToTable = [];
foreach ($rows as $row) {
$dataToTable[$row['TABLES']['table_name']] = $row['TABLES']['table_name'];
}
$this->set('table',$dataToTable);
if(isset($_GET['table_name'])){
$table_name = $_GET['table_name'];
$column = "select column_name as name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='$table_name' ";
$result = $cn->query($column) ;
foreach ($result as $key => $value) {
foreach($value as $key => $value) {
foreach($value as $key =>$value){
$column_counts[$value] = $value;
}
}
}
$column_counts = array_unique($column_counts);
//print_r($column_counts);
$measures1=array();
$measures2=array();
$diff=array();
foreach($column_counts as $key => $value){
$sql="select * from $table_name where concat('',$value * 1 ) = $value limit 1";
$resultset = $cn->query($sql) ;
if(!empty($resultset)){
if(!in_array($value, $measures1)){
$measures1[$value]= $value;
}
}
}
$measures2 = array_diff($column_counts,$measures1);
$this->set('measures1',$measures1);
$this->set('measures2',$measures2);
}
}
}
?>
This will validate and save your data
if ($this->request->is('post')) {
$this->Actions->set($this->request->data);
if ($this->Actions->save($this->request->data)) {
// Set a session flash message and redirect.
}
}
I think you're confusing "'required'=>true" with "'allowEmpty' => true". The former means that you cannot save the record without that field being included in the list of fields updated, no matter whether it holds actual data or not. The latter, which I think is what you really mean, allows a field to be empty although it doesn't force a declaration.
Related
I have input data that I will fill with different values, I do multiple updates
but I have an error which is:
Unknown column 'Array' in 'field list' UPDATE service SET
charges_order = WHERE array id_service = '1'
how to overcome this?
example img
View
<?php $no = 1; foreach ($invoice as $m) { ?>
<tbody id="tbody">
<form class="form-signin" method="post" action="<?php echo base_url();?>backend/report/update/<?php echo $m->id_service; ?>">
<tr class="deleted">
<td><input type="text" class="form-control" name="charges_order[]" value="<?php echo $m->charges_order;?>"></td>
</tr>
</form>
</tbody>
<div class="box-footer">
<button type="submit" class="btn bg-blue btns-flat margin">Simpan</button>
</div>
<?php } ?>
Controller
public function update($id_service)
{
foreach ($this->input->post('charges_order') as $data) {
$data = array(
'charges_order' => $this->input->post('charges_order')
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
}
Model
public function update($id_service, $data)
{
$this->db->where('id_service', $id_service);
$this->db->update('service', $data);
}
Change your controller to this-
public function update($id_service){
$charges_order = json_encode($this->input->post('charges_order'));
$data = array(
'charges_order' => $charges_order
);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
This should work for you.
You are in a loop. You must use the variable.
$data = array(
'charges_order' => $data
);
You can convert array into a string and then update the table.
//example
[1,2,3,4] -> "1,2,3,4"
Here is the code
public function update($id_service)
{
$data = array(
'charges_order' => implode(",", $_POST['charges_order'])
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
When you are retrieving, you can reverse the process
public function get_orders($id_service)
{
$this->db->select('charges_order');
$this->db->where('id_service', $id_service);
$result = $this->db->get('service')->result_array();
return explode(",", $result["charges_order"]); //returns an array
}
Here is my codes,
//FROM MY CONTROLLER
$companies = $this->Uploads_model->getallcompanies();
$general = $this->Uploads_model->getallcontract();
$this->data['companieslist'] = $companies;
$this->data['uploads'] = $general;
$this->render('contracts/index_view');
// MY VIEW
foreach($companieslist as $company){
$general_c[] = $company->company_id;
$general_c[] = $company->company_name;
}
foreach ( $uploads as $key => $con ) {
?>
<tr>
<td class="center">
<label class="pos-rel">
<input type="checkbox" class="ace"/>
<span class="lbl"></span>
</label>
</td>
<td>
<a href="#">
<?php
if($con->Company_id == $general_c[$company_id]){ // MY QUESTION IS HERE
echo $con->Company_name;
}
?>
</a>
</td>
So, am working on this web app where am supposed to display in table all contract files followed with company owned this contract.
I have two tables in my Database as follow Companies_tbl and contract_tbl.
I have Company_id as a foreign key in contract_tbl.
Create a custom function to filter your contracts based on Company_id
function getContractsForId($contracts,$Company_id) {
return array_filter($contracts,function(){
return $contracts->Company_id === $Company_id;
});
}
template loop:
foreach( getContractsForId($uploads,$Company_id) as $key => $con) {
//...html...
//remove the if
}
You are not building the array of companies the right way.
foreach($companieslist as $company){
$general_c[] = $company->company_id;
$general_c[] = $company->company_name;
}
After you looped once, the $general_c array will look like this:
$general_c = [
0 => 1, //company id
1 => 'Company name'
]
After the second time:
$general_c = [
0 => 1, //company id
1 => 'Company name',
2 => 2, //company id
3 => 'Company name 2'
]
What you want is the following:
foreach($companieslist as $company){
$general_c[$company->company_id] = $company->company_name;
}
And below:
<?php
if($general_c[$con->Company_id]) {
echo $general_c[$con->Company_id];
} ?>
This will let you output the company name based on ID.
But i suggest you do a MySQL join in your model. Add something like this to your Uploads_model:
function getContractsWithCompany() {
$query = $this->db->select('*')
->from('contract_tbl')
->join('Companies_tbl', 'Companies_tbl.id = contract_tbl.Company_id')
->get();
return $query->result();
}
You need first to group files by Company_id then list the specific company files
$companies = $this->Uploads_model->getallcompanies();
$general = $this->Uploads_model->getallcontract();
$this->data['companieslist'] = $companies;
$this->data['uploads'] = array();
//group file list by Company_id
foreach ($general as $key => $file) {
if(!isset($this->data['uploads'][$file->Company_id ]))
$this->data['uploads'][$file->Company_id] = array();
$this->data['uploads'][$file->Company_id][] = $file;
}
// in your view
foreach($companieslist as $company){
$general_c[] = $company->company_id;
$general_c[] = $company->company_name;
if(isset($uploads[$company->company_id])) {
foreach ( $uploads[$company->company_id] as $key => $con ) {
?>
<tr>
<td class="center">
<label class="pos-rel">
<input type="checkbox" class="ace"/>
<span class="lbl"></span>
</label>
</td>
<td>
<?=$company->company_name?>
</td>
</tr>
<!-- and the rest of logic -->
<?php
}
}
}
Currently I'm trying to display all the payments I have received that were inserted into my database (payment_history) I want to show them in a html table, but every time I try it, It only shows me 1 user on the html table, but I have more than one user in the SQL table on phpmyadmin.
Php sided code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class payment_history_model extends MY_Model {
public function __construct(){
parent::__construct();
}
public function getPaymentHistory(){
$accounts = $this->model->fetch("*", PAYMENT_HISTORY, getDatabyUser(0), "id", "asc");
if(!empty($accounts)){
foreach ($accounts as $key => $row) {
$user = $this->model->get("*", USER_MANAGEMENT, "id = '".$row->uid."'");
if(!empty($user)){
$accounts[$key]->user = $user->fullname;
}else{
$accounts[$key]->user = "";
}
}
}
return $accounts;
}
}
My html table code.
<thead>
<tr>
<th><?=l('User')?></th>
<th><?=l('Invoice')?></th>
<th><?=l('First name')?></th>
<th><?=l('Last name')?></th>
<th><?=l('Receiver email')?></th>
<th><?=l('Payer email')?></th>
<th><?=l('Package')?></th>
<th><?=l('Price')?></th>
<th><?=l('Currency')?></th>
<th><?=l('Street')?></th>
<th><?=l('City')?></th>
<th><?=l('Country')?></th>
<th><?=l('Payment date')?></th>
<th><?=l('Payment status')?></th>
<th><?=l('Option')?></th>
</tr>
</thead>
<tbody>
<?php
if(!empty($result)){
foreach ($result as $key => $row) {
?>
<tr class="pending" data-action="<?=cn('ajax_action_item')?>" data-id="<?=$row->id?>">
<td>
<input type="checkbox" name="id[]" id="md_checkbox_<?=$key?>" class="filled-in chk-col-red checkItem" value="<?=$row->id?>">
<label class="p0 m0" for="md_checkbox_<?=$key?>"> </label>
</td>
<td><?=$row->user?></td>
<td><?=$row->invoice?></td>
<td><?=$row->first_name?></td>
<td><?=$row->last_name?></td>
<td><?=$row->receiver_email?></td>
<td><?=$row->payer_email?></td>
<td><?=$row->item_name?></td>
<td><?=$row->mc_gross?></td>
<td><?=$row->mc_currency?></td>
<td><?=$row->address_street?></td>
<td><?=$row->address_city?></td>
<td><?=$row->address_country?></td>
<td><?=$row->payment_date?></td>
<td><?=$row->payment_status?></td>
<td><?=$row->Option?></td>
</tr>
</tbody>
Ok, your class MyModel from http://pastebin.com/Vc8tUvpH contains fetch method:
function fetch($select = "*", $table = "", $where = "", $order = "", $by = "DESC", $start = -1, $limit = 0, $return_array = false)
{
...
}
Now, we can say that the problem can be in $where = getDatabyUser(0).
Most likely getDatabyUser(0) adds where clause which limits your result to one row.
You should try:
output getDatabyUser(0) like var_dump(getDatabyUser(0))
open phpmyadmin and add the same where clause and check result
Now it looks like you're trying to get payment history for user with ID = 0.
You can check it also, by replacing getDatabyUser(0) with ""(empty string).
public function getPaymentHistory(){
$accounts = $this->model->fetch("*", PAYMENT_HISTORY, "", "id", "asc");
if(!empty($accounts)){
foreach ($accounts as $key => $row) {
$user = $this->model->get("*", USER_MANAGEMENT, "id = '".$row->uid."'");
if(!empty($user)){
$accounts[$key]->user = $user->fullname;
}else{
$accounts[$key]->user = "";
}
}
}
return $accounts;
}
We have two models which are related by a has and belongs to many (HABTM) relationship: Jobs, Tests. We are able to add/edit the relationships successfully (we know because they show up in the join table), but we can't get the existing values to appear in the view. The select/checkboxes (we've tried both) are always empty.
Here are the model relationships:
//Job.php
public $hasAndBelongsToMany = array (
'Test' => array (
'classname' => 'Test',
'foreignKey'=>'job_id',
'joinTable' => 'jobs_tests',
'associatedForeignKey' => 'test_id'
)
);
//Test.php
public $hasAndBelongsToMany = array(
'Job' => array(
'className'=> 'Job',
'joinTable'=>'jobs_tests',
'foreignKey' => 'test_id',
'associatedForeignKey'=> 'job_id'
)
);
Here is the /view/Jobs/edit.ctp
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
//This is always empty (nothing selected/checked).
What are we doing wrong?
Update:
Here is the JobsController action:
public function admin_edit( $id=NULL ) {
$this->layout = 'admin';
if (!$id)
$this->redirect( array('controller'=>'jobs', 'action'=>'index'));
$this->loadModel('Company');
$companies = $this->Company->find('all');
$company_options = array();
foreach ($companies as $company) {
$company_options[ $company['Company']['id'] ] = $company['Company']['name'];
}
$this->set('company_options', $company_options);
$this->loadModel('Test');
$tests = $this->Test->find('all');
$tests_options = array();
foreach ($tests as $test) {
$test_options[ $test['Test']['id'] ] = $test['Test']['name'];
}
$this->set('test_options', $test_options);
$category_options = $this->Job->validCategories;
$this->set('category_options', $category_options);
if ($this->request->isPut() ) {
$data = $this->request->data;
//debug($data);exit;
$save = $this->Job->save( $data );
if ($save) {
$this->Session->setFlash('Job edited');
//$job = $this->Job->findById( $id );
} else {
$this->Session->setFlash('Error editting job');
}
}
$job = $this->Job->findById($id);
$this->request->data = $job;
$this->set('job', $job);
}
Here is the form in the admin_edit.ctp view:
<?php echo $this->Form->create('Job'); ?>
<fieldset>
<?php
echo $this->Form->input('id', array('type'=>'hidden'));
echo $this->Form->input('name', array('class'=>'form-control'));
echo $this->Form->input('email', array('class'=>'form-control'));
echo $this->Form->input('location', array('class'=>'form-control'));
echo '<label>Type</label>';
echo $this->Form->select('type', array('FT'=>'Full Time', 'PT'=>'Part Time', 'IN'=>'Internship'), array('empty'=>false, 'class'=>'form-control'));
echo '<label>Company</label>';
echo $this->Form->select('company_id', $company_options, array('class'=>'form-control'));
echo $this->Form->input('short_description', array('label' => 'Short Description', 'class'=>'form-control'));
echo $this->Form->input('full_description', array('type'=>'textarea', 'label' => 'Full Description', 'class'=>'form-control'));
echo $this->Form->input('is_private', array('label'=>'Is Private?', 'class'=>'form-control') );
echo '<label>Category</label>';
echo $this->Form->select('category', $category_options, array('class'=>'form-control'));
echo '<label>Tests</label>';
//echo $this->Form->select('Test.id', $test_options, array('class'=>'form-control', 'multiple'=>true));
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]=$test['id'];
//$selected[ $test['id'] ] = $test['name'];
}
debug($selected);
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
PHEW! This was a stumper but the solution turned out to be simple... The values in $options['selected'] were strings (of numbers), which was confusing CakePHP. We converted them to ints using intval() and it works perfectly now, using all the original settings...
Here's the revised version of what is in the view (notice the intval()):
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]= intval($test['id']);
}
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
Also, as a sidenote, this is evidence that pretty much everything that was challenged in the comments above works completely fine:
$options['selected'] does not need to be key=>value pairs.
The pattern we're using does not overwrite the request->data and passes the data to the form helper just fine.
non-camelCased variable names passed to the view ($some_variable_name) are still picked up correctly by the form helper.
Hopefully this comes in handy to someone else.
What if you pass set the default values using Model::find('list').
//controller
$this->set('test_options', $this->YourModel->find('list'));
//view
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
Model
$id = $this->session->userdata('id');
$q = $this->db->get_where('shipping_address', array('customer_id' => $id));
if ($q->num_rows == 0)
{
$data['id'] = 'You dont have a shipping address saved.';
} else {
foreach ($q->result() as $row)
{
$data['first'] = $row->firstname;
$data['last'] = $row->lastname;
}
}
return $data;
Controller
$this->load->model('Customer_accounts');
$customer = $this->Customer_accounts->get_customer_info();
$ship = $this->Customer_accounts->shipping_address();
$data = $ship + $customer;
$this->load->view('account_dashboard/personal_information', $data);
View
<?php foreach ($ship as $row) : ?>
<table class="fixCap" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php echo $row['firstname'] . $row['lastname']; ?></td>
</tr>
. . .
</tr>
</table>
<?php endforeach; ?>
Var_dump
Is only showing an array with 1 of the the table rows but it should be showing 2 rows which contain the defined customer_id
Problem
Unable to pass the all the db data to the foreach what am I doing wrong?
use:
$data = array_merge($ship, $customer); // they will merged as one array
or you can do it this way if u want them separated
$data = array();
$data['ship'] = $ship;
$data['customer'] = $customer;
//In the view
//ship
foreach($data['ship'] as $ship)
{
//Ship values
}
//customer
foreach($data['customer'] as $customer)
{
//Customer value
}
thx
You are not actually puling the result from database with your code.
try something like this
$ret = $q->get()->result();
foreach($ret as $row)
{
}
The problem was in my Model I replaced the above code with
Model
return $this->db->get_where('shipping_address', array('customer_id' => $id))->result();
And in my
View
#I echoed the vars as objects
$row->firstname