I have the follow code
<?php
if (!empty($errors)) { ?>
<div class="errors">
<h5>Hay <?php echo count($errors); ?> Errores:</h5>
<ul>
<?php foreach ($errors as $field => $error) { ?>
<li style="color:red;"><?php echo $error[0]; ?></li>
<?php } ?>
</ul>
</div>
<?php }
echo $this->Form->create('Pagos');
$i = 0; ?>
<div class="data">
<!-- venc.ref, venc.proveedor, venc.moneda,
venc.vencimiento, venc.pago, venc.monto, venc.concepto, venc.id -->
<table class="table">
<thead>
<tr>
<th>Referencia</th>
<th>Proveedor</th>
<th>Moneda</th>
<th>vencimiento</th>
<th>Status</th>
<th>Monto</th>
<th>Concepto</th>
<th>Seleccione</th>
</tr>
</thead>
<tbody>
<?php foreach ($datos as $d) : ?>
<tr>
<td><?php echo $d['venc']['ref']; ?></td>
<td><?php echo $d['venc']['proveedor']; ?></td>
<td><?php echo $d['venc']['moneda']; ?></td>
<td><?php echo implode('/', array_reverse(explode('-', $d['venc']['vencimiento']))); ?></td>
<td><?php echo $d['venc']['pago']; ?></td>
<td><?php echo number_format($d['venc']['monto'],2,',','.'); ?></td>
<td><?php echo $d['venc']['concepto']; ?></td>
<td><?php
echo $this->Form->input('Pagos][.id',
array('label' => false, 'type' => 'hidden',
'value' => $d['venc']['id']));
echo $this->Form->input('Pagos][.monto',
array('label' => false, 'type' => 'hidden',
'value' => $d['venc']['monto']));
echo $this->Form->input('Pagos][.moneda_id',
array('label' => false, 'type' => 'hidden',
'value' => (strlen($d['venc']['moneda'])>1)?2:1 ));
echo $this->Form->input('Pagos][.selec', array('type' => 'checkbox',
'label' => false));
?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="row-form">
<div class="span2 offset3">
<?php echo $this->Js->submit('Pagar',
array('class' => 'btn btn-info',
'update' => '#contentWrap', 'id' => 'pagar')); ?>
</div>
</div>
<?php
if (false != $saved)
echo "<script> $('#dialogModal4').dialog('close'); </script>";
echo $this->Form->end();
echo $this->Js->writeBuffer();
//assuming this view is rendered without the default layout, make sure you write out the JS buffer at the bottom of the page
?>
and this is my controller function
function addpag() {
$consulta = 'SELECT venc.ref, venc.proveedor, venc.moneda,
venc.vencimiento, venc.pago, venc.monto, venc.concepto, venc.id
FROM v_vencimientos venc
Where (venc.vencimiento between "2015-12-12" and curdate()
and venc.pago <> "Vencida") or (venc.pago = "Vencida") ';
$datos = $this->ComprobantesCompra->query($consulta);
if (!isset($saved)) {
$this->set('saved', false);
} else {
$this->set('saved', $saved);
}
$this->set('datos', $datos);
$this->layout = 'ajax';
App::import('Model', 'Pago');
App::import('Model', 'PagosDetalle');
App::import('Model', 'FormasPago');
App::import('Model', 'ComprobantesComprasAsociado');
if (!empty($this->request->data)) {
$this->set('saved', true);
$Pagos['Pago'] = $this->request->data['Pagos'];
$i = 0;
$aux = array();
while ($i < sizeof($Pagos['Pago']) )
{
if (isset($Pagos['Pago'][$i+4]['selec'])) {
$valor = true;
} else {
$valor = false;
}
$aux[] =array( 'id' => $Pagos['Pago'][$i]['id'],
'monto' => $Pagos['Pago'][$i+1]['monto'],
'moneda_id' => $Pagos['Pago'][$i+2]['moneda_id']
'selec' => $valor,
'fecha' => date('Y-m-d'),
'pago_cuenta' => 0
);
if ($valor) {
$i += 5;
} else {
$i+=4;
}
}
$consecutivo = 0;
foreach ($aux as $detalle) {
//si se selecciono para ser pagado ingrese y realice el pago
if ($detalle['selec']) {
$consecutivo++;
$pag = new Pago();
$pag->create();
$pag->set('numero', date('Ymd') . $consecutivo);
$pag->set('proveedor_id', $this->ComprobantesCompra->getProveedorCompra($detalle['id']));
$pag->set('moneda_id', $detalle['moneda_id']);
$pag->set('pago_cuenta', $detalle['pago_cuenta']);
$pag->set('fecha', $detalle['fecha']);
$pag->set('monto', trim($detalle['monto']));
if (!$pag->save()) {
debug($pag->validationErrors);
} else {
$this->set('saved', true);
}
$id_pago = $pag->getInsertID();
$fpp = new FormasPago();
$fpp->create();
$fpp->set('tipo_pago', 'Efectivo');
$fpp->set('tipo_comprobante', 'P');
$fpp->set('moneda_id', $detalle['moneda_id']);
$fpp->set('cant_pagos', 1);
$fpp->set('importe', trim($detalle['monto']));
$fpp->set('comprobante_id', $id_pago);
if (!$fpp->save()) {
debug($fpp->validationErrors);
}
$pagdet = new PagosDetalle();
$pagdet->create();
$pagdet->set('pagos_id', $id_pago);
$pagdet->set('comprobantes_compra_id', $detalle['id']);
$pagdet->set('monto', trim($detalle['monto']));
if (!$pagdet->save()) {
debug($pagdet->validationErrors);
}
$cca = new ComprobantesComprasAsociado();
$pgd = new PagosDetalle();
//1ERO OBTENEMOS EL COMPROBANTE
$comprobante = $this->ComprobantesCompra->read(null, $detalle['id']);
$comprobante->id = $detalle['id'];
//2DO SUMAMOS RECIBOS
$sumarc = $pgd->find('all', array('conditions' =>
array('PagosDetalle.comprobantes_compra_id' => $detalle['id']),
'fields' => array('sum(PagosDetalle.monto) AS suma')));
$recibos = $sumarc[0][0]['suma'];
//3ERO SUMAMOS NOTAS DE CREDITO ASOCIADAS AL COMPROBANTE
$ncreditos = $cca->sumarNC($detalle['id']);
//4TO ACTUALIZAMOS
$saldo = $comprobante['ComprobantesCompra']['monto_total'] - $recibos - $ncreditos;
if ($saldo <= 0) {
$estado = 'Paga';
} else {
if ($comprobante['ComprobantesCompra']['monto_total'] == $saldo) {
$estado = 'Pendiente';
} else {
$estado = 'Parcialmente';
}
}
$comprobante->set('estado', $estado);
$comprobante->set('saldo', $saldo);
if (!$comprobante->save()) {
$this->set('errors', $comprobante->validationErrors);
}
}
}
$this->set('saved', true);
}
}
Here is the thing, i open with ajax a dialog and load that form inside, it saves all correct. But the fact is that doens't close the dialog
I really have no idea why this is happening, any idea/suggestion will be highly appreciated. I just need to close the dialog. The save part is done. Thanks in advance
I already fix this, the thing is that in the ctp the 'update' was bad selected, i choose the wrong id, my fault. This codes works of, hope this help somebody
Related
How to retrieve the array values from multiples checkbox? I have problem when I retrieve value array and echo the value. I get this error
Severity: Warning
Message: in_array() expects parameter 2 to be array, string given
Filename: page/update.php.
Please, could you help me again? Thank you.
You find three files: View, Model and Controller. Please check where I wrong...
UPDATE.PHP:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="row">
<div class="col-sm-12">
<?php echo form_open('page_controller/update_page_post'); ?>
<div class="form-group">
<div class="row">
<div class="col-sm-3 col-xs-12">
<label><?php echo trans('subcategory'); ?></label>
</div>
</div><div class="col-xm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped" role="grid">
<tbody>
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
//if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach ($array_of_values as $item) {
if(in_array($valuesub,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?></tr>
</tbody>
</table>
</div>
</div>
</div>
PAGE_CONTROLLER.PHP
public function update_page_post()
{
//validate inputs
$this->form_validation->set_rules('title', trans("title"), 'required|xss_clean|max_length[500]');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('form_data', $this->page_model->input_values());
redirect($this->agent->referrer());
} else {
//get id
$id = $this->input->post('id', true);
$redirect_url = $this->input->post('redirect_url', true);
if (!$this->page_model->check_page_name()) {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_page_slug_error"));
redirect($this->agent->referrer());
exit();
}
if ($this->page_model->update($id)) {
$this->session->set_flashdata('success', trans("msg_updated"));
if (!empty($redirect_url)) {
redirect($redirect_url);
} else {
redirect(admin_url() . 'pages');
}
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
PAGE_MODEL.PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Page_model extends CI_Model
{
//input values
public function input_values()
{
$checkbox = implode(',', $this->checkBox());
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'page_order' => $this->input->post('page_order', true),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'right_column_active' => $this->input->post('right_column_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $checkbox
);
return $data;
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
//update page
public function update($id)
{
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
in your you view,
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
foreach ($array_of_values as $item) {
if(in_array($subcat_recip_id,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?>
</tr>
change to :
<tr>
<?php $valuesub = ($page->subcat_recip_id);
$array_of_values = explode(",", $valuesub); ?>
<td>
<?php foreach ($array_of_values as $item) :?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($subcat_recip_id,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>'
<?php endforeach; ?>
</td>
<?=html_escape($valuesub)?>
</tr>
in model :
public function update($id){
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
change to :
public function update($id){
$data = $this->input_values();
if (empty($data["slug"])) {
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
please update if you getting error,
tq
Well, it remains a bug but with some changes yr last code works. The great problem is the loop, it re-load the $valuesub for how many times is the value. Ie. If the array is composed of three values, it reads three times the same value. Pls see the two screenshots: https://www.screencast.com/t/MfiEDhdFuX
I can't get this loop off !!
Code
<td>
<?php foreach ($menu_links as $item) :
$valuesub = ($page->subcat_recip_id);
$array_of_values = explode("," , $valuesub);
if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach($array_of_values as $dt): ?>
<?php //if(in_array($dt,$item)): ?>
<input type="checkbox" name="subcat_recip_id" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($dt,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>
<?php endforeach; endif;?>
<?php endforeach; ?>
</td><?php echo html_escape($valuesub); ?>
How to get value form multiples checkbox and post array in codeigniter? I have problem when I get value post array and echo the value. I see only the value of the last checked checkbox. How to show post value when submit?
You find three files: view, Controller and Model. Please check where I wrong...
UPDATE.PHP:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="row">
<div class="col-sm-12">
<?php echo form_open('page_controller/update_page_post'); ?>
<div class="form-group">
<div class="row">
<div class="col-sm-3 col-xs-12">
<label><?php echo trans('subcategory'); ?></label>
</div>
</div><div class="col-xm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped" role="grid">
<tbody>
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
//if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach ($array_of_values as $item) {
if(in_array($subcat_recip_id,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?></tr>
</tbody>
</table>
</div>
</div>
</div>
PAGE_MODEL.PHP:
<?php class Page_model extends CI_Model
{
public function input_values()
{
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $this->input->post('subcat_recip_id')
for ($i=0; $i<count($menu_links); $i++)
{
echo $subcat_recip_id[$i];
}
);
return $data;
}
//add page
public function add()
{
$data = $this->page_model->input_values();
if (empty($data["slug"]))
{
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"]))
{
$data["slug"] = "page-" . uniqid();
}
}
return $this->db->insert('pages', $data);
}
//update page
public function update($id)
{
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
PAGE_CONTROLLER.PHP
* Add Page Post*/
public function add_page_post()
{
//validate inputs
$this->form_validation->set_rules('title', trans("title"), 'required|xss_clean|max_length[500]');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('form_data', $this->page_model->input_values());
redirect($this->agent->referrer());
} else {
if (!$this->page_model->check_page_name()) {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_page_slug_error"));
redirect($this->agent->referrer());
exit();
}
if ($this->page_model->add()) {
$this->session->set_flashdata('success', trans("page") . " " . trans("msg_suc_added"));
redirect($this->agent->referrer());
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
I have tried this code
in your Page_model put this code.
public function input_values(){
$checkbox = implode(',', $this->checkBox());
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $checkbox
);
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
hopefully it helps
This is what $menu_links is:
public function get_menu_links_by_lang()
{
$lang_id = $this->input->post('lang_id', true);
if (!empty($lang_id)):
$menu_links = $this->navigation_model->get_menu_links_by_lang($lang_id);
foreach ($menu_links as $item):
if ($item["type"] != "category" && $item["location"] == "header" && $item['parent_id'] == "0"):
echo ' <option value="' . $item["id"] . '">' . $item["title"] . '</option>';
endif;
endforeach;
endif;
}
I edited a code to insert new form page and I need this page to enter some values into DB. All works Ok and they inserted to DB, only the checkbox doesn't work or better it take only the value of the last checked checkbox and not all the checkbox checked! I have tried it in many ways but I can't do it alone. Sorry.
I am designing an asset register, and I am trying to upload multiple images to an ID as away to identify the asset easier, but I am struggling to display one small image in my data table and multiple images in my view page.
I have tried with a foreach loop and tried to echo files from my database, but every time I am getting a small grayed out images in my views and tables
Controller
$data = array(
'formTitle' => 'Create Asset',
'title' => 'Create Asset',
);
$this->load->library('form_validation');
$this->form_validation->set_rules('asset_name', 'Asset Name', 'trim|required|callback_select_validate');
$this->form_validation->set_rules('asset_description', 'Asset Description', 'trim|required|callback_category_validate');
$postData = $this->input->post();
if($this->form_validation->run() === FALSE)
{
$data['supplier'] = $this->admin_model->get_supplier();
$data['asset_category'] = $this->admin_model->get_asset_category();
$data['location'] = $this->admin_model->get_location();
$data['room'] = $this->admin_model->get_room();
$data['status'] = $this->admin_model->get_status();
$this->load->view('frame/header_view');
$this->load->view('frame/sidebar_nav_view');
$this->load->view('asset/create_asset', $data);
}
else
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = './uploads/asset';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
$names= implode(',', $name_array);
//Prepare array of user data
$userData = array(
'name' => $this->input->post('asset_name'),
'item_description' => $this->input->post('asset_description'),
'brand' => $this->input->post('brand'),
'serial_number' => $this->input->post('asset_serial'),
'model' => $this->input->post('asset_model'),
'supplier' => $this->input->post('supplier'),
'category' => $this->input->post('asset_category'),
'location' => $this->input->post('location'),
'room' => $this->input->post('room'),
'date_pruchase' => $this->input->post('date_purchase'),
'purchase_price' => $this->input->post('purchase_price'),
'ip' => $this->input->post('ip'),
'mac' => $this->input->post('mac'),
'status' => $this->input->post('status'),
'files' => $names
);
//Pass user data to model
$insertUserData = $this->admin_model->inset_asset($userData);
//Storing insertion status message.
if($insertUserData){
$this->session->set_flashdata('success_msg', 'User data have been added successfully.');
print_r($userData);
}else{
$this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
}
redirect('admin/create_asset');
}
}
}
Model
function inset_asset($data = array())
{
if(!array_key_exists("created",$data)){
$data['created'] = date("Y-m-d H:i:s");
}
$insert = $this->db->insert('tbl_asset_register', $data);
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
My table/asset view view.
function asset_list(){
$data = array(
'formTitle' => 'Open Calls',
'title' => 'Open Calls',
'asset' => $this->admin_model->get_asset_list(),
);
$this->load->view('frame/header_view');
$this->load->view('frame/sidebar_nav_view');
$this->load->view('asset/view_asset', $data);
}
function show_asset($id)
{
$data = array(
'formTitle' => 'View Asset',
'title' => 'Asset Management'
);
$data["data"] = $this->admin_model->get_assets('', '', $id);
$this->load->view('frame/header_view');
$this->load->view('frame/sidebar_nav_view');
$this->load->view('asset/shows_asset', $data);
}
data table
<div class="row">
<div class="col-lg-12">
<table class="table table-striped table-bordered table-hover" id="dtBasicExample">
<thead>
<tr>
<th>Asset ID:</th>
<th>Name:</th>
<th>Location:</th>
<th>Room:</th>
<th>Serial No.:</th>
<th>View Images:</th>
<th><strong>Option</strong></th>
</tr>
</thead>
<tbody>
<?php foreach($asset as $row): ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->location; ?></td>
<td><?php echo $row->room; ?></td>
<td><?php echo $row->serial_number; ?></td>
<td><button type="button" class="btn btn-primary">view</button></td>
<td><button type="button" class="btn btn-primary">Edit</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
view Page
<div class="col-lg-12">
<ul class="gallery">
<?php if(!empty($files)){ foreach($files as $file){ ?>
<li class="item">
<img src="<?php echo base_url('uploads/asset/'.$file['files']); ?>" >
</li>
<?php } }else{ ?>
<p>Image(s) not found.....</p>
<?php } ?>
</ul>
</div>
I am looking at two ways to go for the table view. One a button to click to view all images or one small image in the table.
In my view I want to view all the images at the bottom of my pages.
I tried to implement standard PHP logic for add, edit articles to blog, so i have add method:
public function add()
{
$this->load->model('admin/Blog_Model');
if (!empty($this->input->post())) {
$user = $this->Blog_Model->addPost($this->input->post());
}
$this->getForm();
}
edit method:
public function edit($id = '')
{
$this->load->model('admin/Blog_Model');
if (!empty($this->input->post())) {
var_dump($id); exit;
$user = $this->Blog_Model->editPost($this->input->post(), $id);
}
$this->getForm($id);
}
and getForm method:
public function getForm($id = '')
{
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
$data['formTitle'] = array(
'name' => 'title',
'id' => 'content-title',
'value' => isset($post['title']) ? $post['title'] : '',
'placeholder' => 'Заглавие',
'class' => 'form-control'
);
$data['formContent'] = array(
'name' => 'content',
'id' => 'content-blog',
'value' => isset($post['content']) ? $post['content'] : '',
'placeholder' => 'Съдържание',
);
$data['formButton'] = array(
'type' => 'submit',
'content'=> 'Изпрати',
'class'=> 'btn btn-primary btn-block btn-flat'
);
$data['head'] = $this->load->view('admin/head', NULL, TRUE);
$data['left_column'] = $this->load->view('admin/left_column', NULL, TRUE);
$this->load->view('admin/header', $data);
$this->load->view('admin/blog_form', $data);
$this->load->view('admin/footer');
}
and blog_form view with form:
<div class="box-body pad">
<?php echo form_open($action); ?>
<div class="box-body">
<div class="form-group">
<label for="content-title">Заглавие:</label>
<?php echo form_input($formTitle); ?>
</div>
<div class="form-group">
<label for="content_blog">Съдържание:</label>
<?php echo form_textarea($formContent); ?>
</div>
<div class="col-xs-12 col-md-3 pull-right">
<?php echo form_button($formButton); ?>
</div>
</div>
<?php echo form_close(); ?>
</div>
So .. everything works perfect, but i have problem with this part:
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
if it's edit i want to send id like GET parameter. I think the problem is there than i does not use standard GET parameters instead of site_url function, when i show all articles here:
<?php foreach ($posts as $post) { ?>
<tr>
<td><?php echo $post['id']; ?></td>
<td><?php echo $post['title']; ?></td>
<td><?php echo $post['content']; ?></td>
<td><div class="btn-group">
Редактирай
Изтрий
</div></td>
</tr>
<?php } ?>
Try to change
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
to
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit/'.$id; // pass $id to edit controller
} else {
$data['action'] = 'admin/blog/add';
}
I have two tables in database profile_fields and profile_fields_values.
Table profile_fields has columns
id
fieldname
fieldtitle
fieldtype
orderby
required
published
Table profile_field_values has columns
id
field_id
user_id
field_value
Here I have to create a dynamic profile management.
How do I show dynamic forms in Yii?
You need to use Form Builder, it has plenty of example how to construct your form using an array. It also supports sub-forms. Just follow the examples from the linked tutorial, content it's to long to be referenced here.
Update:
class LoginForm extends CFormModel
{
public $username;
public $password;
}
$form = new LoginForm();
$form->validatorList->add(
CValidator::createValidator('required', $form, 'username, password')
);
or another example:
class SomeModel
{
public $orders;
public function rules()
{
return array(
array('orders', 'validateOrders'),
);
}
public function validateOrders($attribute, $params)
{
foreach($this->orders as $order)
if (empty($order)) {
$this->addError('orders', 'There is an empty order');
break;
}
}
}
A more broader example is on forum.
I am trying to build this dynamic profile management let me know my approach is my approach is right?
firstly i have created a input form(_form) where user can input fieldtype,fieldname,fieldtitle and field default value and etc which can be save in database table (profile_fields).In this fieldtype is bydefault set and user choose it from dropdownlist As like in the below form.
<?php
/* #var $this ProfileManagerController */
/* #var $model ProfileFields */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'profile-fields-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'location'); ?>
<?php echo $form->dropDownList($model,'location',CHtml::listData(Countries::model()->findAll('',array('orderby' => 'countryName ASC')),'countryCode','countryName'), array('empty' => array("*" => 'For All Countries'))); ?>
<?php echo $form->error($model,'location'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'profile_type'); ?>
<?php echo $form->dropDownList($model,'profile_type',Yii::app()->params['userRoles'], array('empty' => array("*" => 'For All users')), array($model->profile_type)); ?>
<?php //echo $form->dropDownList($model, 'profile_type', Yii::app()->params['userRoles'], array($model->profile_type)); ?>
<?php echo $form->error($model,'profile_type'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'section'); ?>
<?php echo $form->dropDownList($model,'section',array('profile'=>'profileSection','basicdetails'=>'BasicDetails','contactdetails'=>'ContactDetails','imagedetails'=>'ImageDetails','clientdetails'=>'ClientDetails','tagdetails'=>'TagDetails','otherdetails'=>'OtherDetails','alldetails'=>'AllDetails')); ?>
<?php echo $form->error($model,'section'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_name'); ?>
<?php echo $form->textField($model,'field_name',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'field_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_title'); ?>
<?php echo $form->textField($model,'field_title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'field_title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_type'); ?>
<?php echo $form->dropDownList($model,'field_type',array('text' => 'Text','date' => 'Date','email' => 'Email', 'radio' => 'Radio','multiselect' => 'Multi Select Dropdown List','file'=>'File','checkbox'=>'CheckBox','hidden'=>'Hidden','select'=>'Dropdownlist','password'=>'Password','checkboxlist'=>'Checkboxlist','radiolist'=>'Radiolist','textarea'=>'TextArea'),array('options' => array($model->field_type => array('selected' => true)))); ?>
<?php echo $form->error($model,'field_type'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'field_default_value'); ?>
<?php echo $form->textArea($model,'field_default_value',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'field_default_value'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'required'); ?>
<?php echo $form->dropDownList($model, 'required', array('1' => 'Yes', '0' => 'No')); ?>
<?php echo $form->error($model,'required'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'published'); ?>
<?php echo $form->dropDownList($model, 'published', array('1' => 'Yes', '0' => 'No')); ?>
<?php echo $form->error($model,'published'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'order_by'); ?>
<?php echo $form->textField($model,'order_by'); ?>
<?php echo $form->error($model,'order_by'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
secondly I have created a view index file which will show dynamically what type of fieldstypes and fieldsname and field title are set by the user in profile_field table and call the extension created by me and then another user can input accordingly .and these values are save in profile_field_values table .
----------index file---------------
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'completeProfile-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation' => false,
'clientOptions' => array('validataOnSubmit' => true),
'enableClientValidation' => true,
));
?>
<?php
if (!empty($field_data)) {
foreach ($field_data as $field) {
$selectedOptions = '';
$def_value='';
$field_name = $field->field_name; // required field
$field_type = $field->field_type; // required field
$field_id = $field->id; // required field
//for validation
$req = $field->required == 1 ? 'required' : ''; // required if using validation
$email = $field->field_type == 'email' ? 'email' : ''; // required if using validation
$password = $field->field_type == 'password' ? 'password' : ''; // required if using validation
$class = array($req, $email, $password); // class must be array type, if no class found, send empty array
//values present in ProfileFieldsValues to populate
$value = ProfileFieldsValues::model()->findByAttributes(array('user_id' => Yii::app()->user->id, 'field_id' => $field->id));
// set html options
$htmlOptions = array();
$htmlOptions['class'] = implode(" ", $class);
$htmlOptions['value'] = $value ? $value->field_value : '';
// field array - Must SET
$fieldArray = array();
$fieldArray['model'] = $field;
$fieldArray['form'] = $form;
$fieldArray['field_type'] = $field_type;
$fieldArray['field_name'] = $field_name;
$fieldArray['field_id'] = $field_id;
$fieldArray['default_value'] = $value ? $value->field_value : $field->field_default_value;
//If input type field is dropdowlist for selecttion
if($field_type == 'select' ){
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['select_box_array']=$def_value;
}else{
$fieldArray['select_box_array'] =$country;
}
$htmlOptions['prompt'] = 'SELECT ANY';
$value ? $htmlOptions['options']=array($value->field_value=>array('selected'=>'true')): $htmlOptions['prompt'] = 'SELECT ANY';
}
//if input type field is multiple select dropdownlist
if( $field_type == 'multiselect'){
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['select_box_array']=$def_value;
}else{
$fieldArray['select_box_array'] =$country;
}
$htmlOptions['prompt'] = 'SELECT Multiple';
if(!empty($value)){
$field_valu= explode(',',$value->field_value);
foreach($field_valu as $eachValue){
$selectedOptions[$eachValue] = array('selected'=>'selected');
}
$htmlOptions['options']= $selectedOptions;
}
}
// if input type field is radio button
if ($field_type == 'radiolist') {
$fl = ProfileFieldsValues::model()->findByAttributes(array('field_id' => $field->id, 'user_id' => Yii::app()->user->id));
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['radio_box_array']=$def_value;
}else{
$fieldArray['radio_box_array'] =array('hello','bye');
}
$value = $fl ? $fl->field_value : 0;
$htmlOptions = array('labelOptions' => array('style' => 'display:inline'), 'separator' => ' ','value' => $value);
}
//if input type field is checkbox list
if ($field_type == 'checkboxlist') {
$fl = ProfileFieldsValues::model()->findByAttributes(array('field_id' => $field->id, 'user_id' => Yii::app()->user->id));
if(!empty($field->field_default_value)){
$my_string = preg_replace(array('/\n/'), '#PH#', $field->field_default_value );
$my_array = explode('#PH#', $my_string);
foreach($my_array as $my_arr){
$def=explode('|',$my_arr);
$def_value[$def[0]]=$def[1];
}
$fieldArray['check_box_array']=$def_value;
}else{
$fieldArray['check_box_array'] =array('hello','bye');
}
$value = $fl ? (array)explode(",",$fl->field_value) : array(0);
$htmlOptions = array('labelOptions' => array('style' => 'display:inline'), 'separator' => ' ','value' => $value );
}
//if input type field is file
if ($field_type == 'file') {
$files = ProfileFieldsValues::model()->findByAttributes(array('field_id' => $field->id, 'user_id' => Yii::app()->user->id));
if(isset($files->field_value)){
echo CHtml::image(Yii::app()->request->baseUrl . '/images/user_images/' .$files->field_value, 'Image', array('class' => 'img-polaroid', 'width' => 200));
}
}
$fieldArray['htmlOptions'] = $htmlOptions;
if ($field->published == '1') {
if($field->field_type == 'checkbox' || $field->field_type == 'radio' ){ ?>
<div class="row">
<?php $this->widget('ext.dynamicFields.EDynamicFields', $fieldArray); ?>
<?php echo $field->field_title; ?>
<?php echo $form->error($field, $field->field_title); ?>
</div>
<?php }else{ ?>
<div class="row">
<?php echo $form->labelEx($field, $field->field_title); ?>
<?php $this->widget('ext.dynamicFields.EDynamicFields', $fieldArray); ?>
<?php echo $form->error($field, $field->field_title); ?>
</div>
<?php } ?>
<?php } ?>
<?php } ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php
}
$this->endWidget();
?>
</div><!-- form -->
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl(true) . '/js/jquery.validate.js'); ?>
<script type="text/javascript">
$("#completeProfile-form").validate({
});
</script>
I have created a extension for various input type fields like
1.text
2.email textbox
3.hidden input type field
4.textarea
5.dropdownlist
6. multiple select dropdownlist
7.password textfield
8.file
9.radiolist
10.radio button
11 checkbox
12checkboxlist
13 date field
<?php
/**
* Description of EDynamicFields
* It will show dynamic fields
*
* #author Gaurav Parashar
*/
class EDynamicFields extends CWidget {
public $field_type;
public $field_name;
public $field_id;
public $default_value;
public $select_box_array = array();
public $radio_box_array = array();
public $check_box_array = array();
public $htmlOptions = array();
public $model;
public $form;
public $select;
public function run() {
switch ($this->field_type) {
case 'text':
echo $this->form->textField($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'email':
echo $this->form->textField($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'hidden':
echo $this->form->hiddenField($this->model, "field_name[$this->field_type][$this->field_id]", $this->default_value);
break;
case 'textarea':
echo $this->form->textArea($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'select':
echo $this->form->dropDownList($this->model, "field_name[$this->field_type][$this->field_id]", $this->select_box_array, $this->htmlOptions);
break;
case 'password':
echo $form->passwordField($model,'password',$this->htmlOptions);
break;
case 'multiselect':
$newarr = array_merge($this->htmlOptions, array('multiple' => 'multiple'));
echo $this->form->dropDownList($this->model, "field_name[$this->field_type][$this->field_id]", $this->select_box_array, $newarr);
break;
case 'file':
echo $this->form->fileField($this->model, "field_name[$this->field_type][$this->field_id]" ,$this->htmlOptions);
break;
case 'radio':
echo $this->form->radioButton($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'radiolist':
echo CHtml::radioButtonList("ProfileFields[field_name][$this->field_type][$this->field_id]",$this->htmlOptions['value'],$this->radio_box_array,$this->htmlOptions);
break;
case 'checkbox':
echo $this->form->checkBox($this->model, "field_name[$this->field_type][$this->field_id]", $this->htmlOptions);
break;
case 'date':
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'attribute' => "field_name[$this->field_type][$this->field_id]",
'model' => $this->model,
'htmlOptions'=>array(
'class'=>'required',
),
'options' => array(
'dateFormat' => 'yy-mm-dd',
'maxDate' => 'new Date()', // One month ahead
//'minDate' => '-50y', // Today
'changeMonth' => true,
'changeYear' => true,
'yearRange'=>'2000:2099',
'minDate' => '2000-01-01', // minimum date
'maxDate' => '2099-12-31',
)
));
break;
case 'checkboxlist':
echo CHtml::checkBoxList("ProfileFields[field_name][$this->field_type][$this->field_id]",$this->htmlOptions['value'],$this->check_box_array,$this->htmlOptions);
break;
}
}
}