Dynamic checkbox and get the values from the checkbox checked - php

I am having difficulty creating dynamic checkboxes from db, and getting the values from the checkboxes when checked.
I have this Controller:
public function proporEvento(){
$natureza = $this->evento_model->naturezaEvento();
$apoio = $this->evento_model->apoioPertendido();
$espaco = $this->evento_model->espaco();
$material = $this->evento_model->material();
$suportgraf = $this->evento_model->suporteGrafico();
$audiovisual = $this->evento_model->audioVisual();
$data['title'] = 'Propor Evento';
$data['naturezaEvento'] = $natureza;
$data['apoioPertendido'] = $apoio;
$data['espaco'] = $espaco;
$data['material'] = $material;
$data['suporteGraf'] = $suportgraf;
$data['audioVisual'] = $audiovisual;
$this->load->view('cliente/clienteheaderdash_view', $data);
$this->load->view('cliente/clientemenu_view', $data);
$this->load->view('cliente/clienteproporevento_view', $data);
$this->load->view('cliente/clientefooterdash_view', $data);
}
Have this model:
public function naturezaEvento(){
$query = $this->db->get('tblnaturezaevento');
return $query->result();
}
public function apoioPertendido(){
$query = $this->db->get('tblapoio');
return $query->result();
}
public function espaco(){
$query = $this->db->get('tblespaco');
return $query->result();
}
public function material(){
$query = $this->db->get('tblmaterial');
return $query->result();
}
public function suporteGrafico(){
$query = $this->db->get('tblsuportegraf');
return $query->result();
}
public function audioVisual(){
$query = $this->db->get('tblaudiovisual');
return $query->result();
}
...and I have this view (one part for example):
<label>Apoio Pertendido</label>
<div class="form-group">
<?php foreach ($apoioPertendido as $row) { ?>
<label>
<input type="checkbox" class="flat-red" name="apoiopretendido[]" value="<?php echo $row->idApoio ?>" /> <?php echo $row->descricao; ?>
</label>
</br>
<?php } ?>
</div>
this code create the <input type="checkbox"...> correctly but how can I get the values from checked checkbox?
My form to go with this controller function:
public function etapa2(){
//$this->load->library('form_validation');
// $this->form_validation->set_rules('naturezaEvento', 'naturezaEvento', '|required|');
//$this->form_validation->set_rules('denominacao', 'denominacao', '|required|');
// $this->form_validation->set_rules('datainicio', 'datainicio', '|required|');
// $this->form_validation->set_rules('horainicio', 'horainicio', '|required|');
// $this->form_validation->set_rules('datafim', 'datafim', '|required|');
// $this->form_validation->set_rules('datainicio', 'datainicio', '|required|');
//if($this->form_validation->run() == FALSE){
//$this->index();
//}else{
$datageral['idcliente'] = $this->session->userdata('idcliente');
$datageral['idnatureza']=$this->input->post('naturezaEvento'); //insere o id do campo natureza da tabela tblnaturezaevento
$datageral['denominacaotitulo'] = $this->input->post('denominacao');
$datageral['datainicio']=$this->input->post('datainicio');
$datageral['horainicio']=$this->input->post('horainicio');
$datageral['datafim']=$this->input->post('datafim');
$datageral['horafim']=$this->input->post('horafim');
$datageral['planotrabalho']=$this->input->post('planotrabalho');
$datageral['raidertecnico']=$this->input->post('raidertecnico');
$datageral['programa']=$this->input->post('programa');
$datageral['mesa']=$this->input->post('mesa');
$datageral['notas']=$this->input->post('notas');
//'valorprovisorio' => $this->input->post('notas'), TODO fazer o valor provisório
//checkbox apoio
$apoiopertendido = $this->evento_model->apoioPertendido();
foreach ($apoiopertendido as $row) {
if ($this->input->post($row->checked, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
//checkbox espaços
$espacopertendido = $this->evento_model->espaco();
//$esp = array();
foreach ($espacopertendido as $row) {
if ($this->input->post($row->tag, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
//Material Necessário
$material = $this->evento_model->material();
//$materialnecessario = array();
foreach ($material as $row) {
$datageral[$row->tag] = $this->input->post($row->tag);
}
//checkbox suportes graficos
$suporteGrafico = $this->evento_model->suporteGrafico();
//$suporte = array();
foreach ($suporteGrafico as $row) {
if ($this->input->post($row->tag, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
//Registo Audio Visual
$audioVisual = $this->evento_model->audioVisual();
//$audiov = array();
foreach ($audioVisual as $row) {
if ($this->input->post($row->tag, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
$this->load->view('cliente/clienteheaderdash_view');
$this->load->view('cliente/clientemenu_view');
$this->load->view('cliente/clienteetapa2_view', $datageral);
$this->load->view('cliente/clientefooterdash_view');
// }
}

Related

Unable to Update and delete in CodeIgniter?

I'm new in CodeIgniter, just watched the tutorial on youtube and followed the steps.
I can't edit or delete records of my database. I can insert or fetch records, but update and delete functions always return error. Here is my code
Controller:
function __construct()
{
parent::__construct();
$this->load->model('Danhmuc_model');
}
function xoadm()
{
$id = $this->uri->segment(5);
$this->Danhmuc_model->delete($id);
$this->session->set_flashdata('mess',' Đã xóa thành công');
redirect(admin_url('danhmuc/xemdm'));
}
function suadm()
{
$data = array();
$id = $this->uri->segment(5);
$row = $this->Danhmuc_model->get_info($id);
if($this->input->post())
{
$this->form_validation->set_rules('ten_dm',"Tên danh mục",'required');
if($this->form_validation->run())
{
$tendm = $this->input->post('ten_dm');
$input = array('ten_dm'=>$tendm);
$this->Danhmuc_model->update($id,$input);
$this->session->set_flashdata('mess',' Đã sửa thành công');
}
}
$data['row'] = $row;
$data['temp'] = 'admin/danhmuc/suadm';
$this->load->view('admin/index',$data);
}
Model:
function update($id, $data)
{
if (!$id)
{
return FALSE;
}
$where = array();
$where[$this->key] = $id;
$this->update_rule($where, $data);
return TRUE;
}
/**
* Xoa row tu id
* $id : gia tri cua khoa chinh
*/
function delete($id)
{
if (!$id)
{
return FALSE;
}
//neu la so
if(is_numeric($id))
{
$where = array($this->key => $id);
}else
{
//xoa nhieu row
//$id = 1,2,3...
$where = $this->key . " IN (".$id.") ";
}
$this->del_rule($where);
return TRUE;
}
View:
Edit view:
<td>
<input name="title" class="form-control" type="text" value="<?php echo $row['ten_dm'] ?>">
</td>
If I use this value="<?php echo $row['ten_dm'] ?>", the text box doesn't appear the category's title (I'm inserting and editing categories)
https://imgur.com/lW7FeDA
https://imgur.com/Z6TjnhL
But if I use this value="<?php echo $row->ten_dm ?>", error with this message
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: danhmuc/suadm.php
Line Number: 13
I can't understand where is the error, please help me. Thanks in advance.

Array to string conversion on CodeIgniter

my problem is a want to insert multiple check box on my web application.
error Message
Array to string conversion
please help....
Controller :
public function add_overview_product($type)
{
if ($this->input->post('submit')) {
$type = $type;
$id_overview = $this->input->post('id_overview');
$records = array();
for ($i=0; $i < count($id_overview) ; $i++) {
$records[] = array(
'type' => $type,
'id_overview' => $id_overview[$i]
);
}
$check_idoverview = $this->Biostar->check_idoverview($type,$id_overview);
if ($check_idoverview > 0) {
$message = 'Sorry, The Product can not input twice with the same "TYPE" ';
} else {
foreach ($records as $key => $value) {
$datafield = array(
'type' => $type,
'id_overview' => $id_overview
);
$this->Biostar->saveoverviewproduct($datafield);
}
$data['type'] = $type;
$data['content'] = 'biostar/add_specification';
$this->load->view('dashboard/index', $data);
}
}
$data['diy'] = $diy;
$data['content'] = 'biostar/add_overview_product';
$this->load->view('dashboard/index', $data);
}
My : Model
public function saveoverviewproduct($datafield){
$sql = $this->db->insert('overview_biostar',$datafield);
return $sql;
}
public function check_idoverview($type,$id_overview){
$this->db->select('type');
$this->db->where('type',$type);
$this->db->where('id_overview',$id_overview);
$query = $this->db->get('overview_biostar')->rows();
return $query;
}
View:
<form method="post"action="<?php echo base_url(); ?>biostar/add_overview_product/<?php echo $type; ?>" >
<div class="box-body">
<?php foreach ($audio as $row){ ?>
<div class="checkbox">
<label>
<input type="checkbox" name="id_overview[]" value="<?php echo $row['title']; ?>"><?php echo $row['title']; ?>
</label>
</div>
<?php } ?>
</div>
$check_idoverview = $this->Biostar->check_idoverview($type,$id_overview);
$id_overview is an array. It should be a string.

How to update the existing values

I am creating an API where I'm inserting product_id, Product_Size, quantity, product_name in an array called product-info.
Now I want to update the other values when product id is already existing.
my code for insertion in controller:
if(!empty($product_info1)){
foreach ($product_info1 as $value) {
$product_id = isset($value->product_id) ? $value->product_id : 0;
$Product_Size = isset($value->Product_Size) ? $value->Product_Size : 0;
$quantity = isset($value->quantity) ? $value->quantity : 0;
$product_name = isset($value->product_name) ? $value->product_name : 0;
if( $ok = 1)
$this->api_details_model->productinventory_track($product_id,$Product_Size,$quantity,$product_name);
{
$api_status="true";
$api_message="Done";
}
// $this->api_details_model->checkProductid($product_id);
}
}
model:
function productinventory_track($product_id,$Product_Size='',$quantity='',$product_name='')
{
if($product_id>=0)
{
$data = array('product_name'=>$product_name,'size_id'=>$Product_Size,'stock_count'=>$quantity,'product_id'=>$product_id);
if($this->db->insert('product_inventory', $data)){ return true; }else{ return false; }
}
please tell me the code for update
Controller:
$productInfo = $this->db->api_details_model->get($product_id);
$productArray['product_name'] = 'yourValue';
$productArray['size_id'] = 'yourValue';
$productArray['stock_count'] = 'yourValue';
// Means that there is no product with that ID in the database
if($productInfo == null)
$this->db->api_details_model->add($productArray);
// It was found an ID in the database
else
$this->db->api_details_model->edit($product_id, $productArray);
Functions in model:
public function add($data)
{
$this->db->insert('product_inventory', $data);
}
public function edit($id, $data)
{
$this->db->where('id', $id)
->update('product_inventory', $data);
}
public function get($id)
{
$this->db->where('id', $id);
return $this->db->get('product_inventory')->row();
}

Getting file_put_content into a folder

I am trying to put my files in a folder from the file_put_contents can someone help me with that.
$invoegen_titel=$_POST['titel_form'];
$invoegen_datum=$_POST['datum'];
$invoegen_tekst=$_POST['tekst'];
$html_tekst= $invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>";
$previous = $_SERVER['HTTP_REFERER'];
$folder='blog';
var_dump(file_put_contents($folder."/".time().".html","<h1>".$invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>"));
make sure that the directory is present. file_put_contents doesn't create the directory if it is not present.
Please specify what problems you are encountering on your code.
change these parts
$folder = time(); //make sure that time() returns string
$folder = "blog/".$folder.'.html';
file_put_contents($folder, $html_tekst);
var_dump(file_get_contents($folder));
Use this:
$lifeTime = 5; // life time, seconds
$cached = TRUE;
$config = array(
'group'=>'default', // dir
'id' => '1', // id cache
'echo' => TRUE, // echo or return
'log'=>false, // echo log, or not
'ext' => 'js' // extention cache file, default .html
);
$CacheFile = new CacheFile('/usr/cache/', $cached);
$CacheFile->config($config, $lifeTime);
if (!$CacheFile->start()){
echo $invoegen_titel."</h1>"."<br>"."<p>".$invoegen_datum."</p>"."<br>"."<p>".$invoegen_tekst."</p>";
$CacheFile->end();
}
PHP class:
class CacheFile{
private $cacheDir = '';
private $cacheSubDir = '';
private $fileName = '';
private $cache = false;
private $lifeTime = 0;
private $echo = true;
private $group = true;
private $log = true;
private $fileExt = 'html';
public function __construct($cacheDir, $cache){
$this->cacheDir = $cacheDir;
$this->cache = $cache;
}
private function createdPatch(){
if ($this->cache){
if (!is_dir($this->cacheSubDir)){
mkdir($this->cacheSubDir, 0777, true);
}
chmod($this->cacheSubDir, 0755);
}
}
private function getSubDir($keyType, $keyValue){
return (($keyType != '')?($keyType.'/'):'').mb_substr($keyValue, 0, 1)."/".mb_substr($keyValue, 1, 1)."/".mb_substr($keyValue, 2, 1)."/";
}
private function getCacheName($key){
return md5($key).".".$this->fileExt;
}
public function config($conf = array('group'=>'post', 'id' => '0', 'echo' => TRUE), $time = 31536000){
$this->group = $conf['group'];
$this->cacheSubDir = $this->cacheDir.$this->getSubDir($conf['group'], md5($conf['id']));
$this->fileName = $this->getCacheName($conf['group'].$conf['id']);
$this->lifeTime = $time;
if (isset($conf['echo']))
$this->echo = $conf['echo'];
if (isset($conf['log']))
$this->log = $conf['log'];
if (isset($conf['ext']))
$this->fileExt = $conf['ext'];
}
public function start(){
if ($data = $this->get()) {
if ($this->echo){
echo $data;
return true;
}else{
return $data;
}
}
ob_start();
ob_implicit_flush(false);
return false;
}
function end(){
$data = ob_get_contents();
ob_end_clean();
if ($this->cache){
$this->save($data.(($this->log)?'<!-- c:'.$this->group.':('.date("Y-m-d H:i:s", (time()+$this->lifeTime)).'/'.date("Y-m-d H:i:s").') -->':""));
}
$return = $data.(($this->log)?'<!-- g:'.$this->group.':('.date("Y-m-d H:i:s", (time()+$this->lifeTime)).'/'.date("Y-m-d H:i:s").') -->':"");
if ($this->echo){
echo $return;
return true;
}
return $return;
}
public function get(){
if (!file_exists($this->cacheSubDir.$this->fileName))
return false;
if (time() >= filemtime($this->cacheSubDir.$this->fileName) + $this->lifeTime){
unlink($this->cacheSubDir.$this->fileName);
return false;
}
if ($this->cache && file_exists($this->cacheSubDir.$this->fileName))
if ($data = file_get_contents($this->cacheSubDir.$this->fileName, false))
return $data;
return false;
}
public function remove(){
if (file_exists($this->cacheSubDir.$this->fileName)){
echo unlink($this->cacheSubDir.$this->fileName);
return true;
}
return false;
}
public function save($data){
$this->createdPatch();
if (file_put_contents($this->cacheSubDir.$this->fileName, $data, LOCK_EX))
return true;
return false;
}
}
I fixed it
<?php $list = file_get_contents('list.json'); $list = json_decode($list, true); $selector = $_POST['selector']; $d_or_t = $_POST['d_or_t']; if (isset($selector) && isset($d_or_t)) { // overwrite the selected domain of the list with the new value if they are not empty if ($d_or_t == "domain") { $list[$selector]['domain'] = $_POST['new']; } if ($d_or_t == "template") { $list[$selector]['template'] = $_POST['new']; } /*else { echo '<script type="text/javascript">alert("U bent vergeten een veld in te voelen!");</script>'; }*/ // store the new json } ?>
<!DOCTYPE html>
<html>
<head>
<title>Json values veranderen</title>
</head>
<body>
<h2>Domain of Template veranderen met PHP script</h2>
<form action="test.php" id="form" method="post">
<select name="selector">
<?php foreach ($list AS $key => $value) : ?>
<option value="<?php echo $key; ?>">
<?php echo $key; ?>
</option>
<?php endforeach; ?>
</select>
<select name="d_or_t">
<option>domain</option>
<option>template</option>
</select>
<input type="text" name="new" placeholder="Nieuw">
<input type="submit" value="Veranderen">
</form>
</body>
</html>
<?php
echo "<ul>";
foreach ($list as $key => $value)
{
echo "<li>".$key."<ul>";
foreach ($value as $key1 => $value1)
{
echo "<li>".$key1.": ".$value1."</li>"; }
echo "</ul>"."</li>";
}
echo "</ul>";
file_put_contents('list.json', json_encode($list));
?>

PHP Todo CheckList Checked Feature

I need help with a PHP ToDo List. I have most of it working except for the check box to move it from a completed list to a still need to do list. here is the code I have so far:
For the edit screen:
%% views/header.html %%
<h1>{{$title}}</h1>
<div class='inputs'>
<form action="##todo/update##" method="post">
<input type="hidden" id="id" name="id" value="{{$todo['id']}}" />
<label for="description">Description:</label>
<input type="text" id="description" name="description" value="{{$todo ['description']}}" />
<label for="done">Done?:</label>
<input type="checkbox" id="done" name="done" value="1" />
<input type="submit" value="Update" />
<form>
</div>
<p><< Back</p>
%% views/footer.html %%
For the todo.inc file:
<?php
include_once "include/util.inc";
include_once "models/todo.inc";
function safeParam($arr, $index, $default) {
if ($arr && isset($arr[$index])) {
return $arr[$index];
}
return $default;
}
function get_view($params) {
$id = safeParam($params, 0, false);
if ($id === false) {
die("No todo id specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo with id $id found.");
}
// #formatter:off
renderTemplate(
"views/todo_view.inc",
array(
'title' => 'Viewing To Do',
'todo' => $todo
)
);
// #formatter:on
}
function get_list($params) {
$todos = findAllCurrentToDos();
$dones = findAllDoneToDos();
// #formatter:off
renderTemplate(
"views/index.inc",
array(
'title' => 'To Do List',
'todos' => $todos,
'dones' => $dones
)
);
// #formatter:on
}
function get_edit($params) {
$id = safeParam($params, 0, false);
if (!$id) {
die("No todo specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo found.");
}
// #formatter:off
renderTemplate(
"views/todo_edit.inc",
array(
'title' => 'Editing To Do',
'todo' => $todo
)
);
// #formatter:on
}
function post_add($params) {
if (!isset($_POST['description'])) {
die("no description given");
}
$description = htmlentities($_POST['description']);
addToDo($description);
redirectRelative("index");
}
function validate_present($elements) {
$errors = '';
foreach ($elements as $element) {
if (!isset($_POST[$element])) {
$errors .= "Missing $element\n";
}
}
return $errors;
}
function post_update($params) {
$errors = validate_present(array('id', 'description', 'done'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = $_POST['done'];
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
function get_delete($params) {
$id = safeParam($params, 0, false);
if (!$id) {
die("No todo specified");
}
$todo = findToDoById($id);
if (!$todo) {
die("No todo found.");
}
deleteToDo($id);
redirectRelative("index");
}
?>
Your error is in these two functions.
function validate_present($elements) {
$errors = '';
foreach ($elements as $element) {
if (!isset($_POST[$element])) {
$errors .= "Missing $element\n";
}
}
return $errors;
}
function post_update($params) {
$errors = validate_present(array('id', 'description', 'done'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = $_POST['done'];
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}
You are attempting to validate that done exists in validate_present when called by post_update. done obviously cannot exists since it is not sent to the server when the checkbox is not checked. The $_POST does not even contain that variable, so it returns that element is missing (since it technically is). I would leave validate_present alone and change post_update as follows:
function post_update($params) {
$errors = validate_present(array('id', 'description'));
if ($errors) {
die($errors);
}
$id = $_POST['id'];
$description = $_POST['description'];
$done = (isset($_POST['done'])? 1 : 0);
updateToDo($id, $description, $done);
redirectRelative("todo/view/$id");
}

Categories