How to load data to an already loaded view? - php

I have a little project, where i use codeigniter, jquery and bootstrap.
I have "Startsite" where the user have to say:
Option 1: Edit project
Option 2: Create project
I think it is useful to show my Controller as first:
In the construct method i load all models, in the index i load data to all dropdowns in my "startsite", in saveProject i save my created project and the method i have a issue is editProject. Look here:
class projekt extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('html');
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('projektklassen_model');
$this->load->model('kundengruppen_model');
$this->load->model('produktgruppen_model');
$this->load->model('ablehnungsgrund_model');
$this->load->model('absatzregion_model');
$this->load->model('anfragetyp_model');
$this->load->model('businessunit_model');
$this->load->model('endkundeOEM_model');
$this->load->model('lieferanten_model');
$this->load->model('prozentverteilungEOP_model');
$this->load->model('prozentverteilungSOP_model');
$this->load->model('realisierungsstatus_model');
$this->load->model('gsmbereich_model');
$this->load->model('firma_model');
$this->load->model('projekt_model');
}
public function index()
{
$data['projektklassen'] = $this->projektklassen_model->getProjektklassen();
$data['kundengruppen'] = $this->kundengruppen_model->getKundengruppen();
$data['produktgruppen'] = $this->produktgruppen_model->getProduktgruppen();
$data['ablehnungsgruende'] = $this->ablehnungsgrund_model->getAblehnungsgruende();
$data['absatzregionen'] = $this->absatzregion_model->getAbsatzregionen();
$data['anfragetypen'] = $this->anfragetyp_model->getAnfragetypen();
$data['businessunits'] = $this->businessunit_model->getBusinessunits();
$data['endkundenOEM'] = $this->endkundeOEM_model->getEndkundenOEM();
$data['lieferanten'] = $this->lieferanten_model->getLieferanten();
$data['prozentverteilungenEOP'] = $this->prozentverteilungEOP_model->getProzentverteilungenEOP();
$data['prozentverteilungenSOP'] = $this->prozentverteilungSOP_model->getProzentverteilungenSOP();
$data['realisierungsstati'] = $this->realisierungsstatus_model->getRealisierungsstatus();
$data['gsmbereiche'] = $this->gsmbereich_model->getGSMBereiche();
$data['firmen'] = $this->firma_model->getFirmen();
$data['projekte'] = $this->projekt_model->getProjekte();
$data['preFormVisible'] = true;
$this->load->view('project2', $data);
}
function saveProjekt(){
if($this->input->post('btGenerate')){
$pdm = $this->projekt_model->getPDM();
$this->projekt_model->addprojekt($pdm);
}
redirect('projekt');
}
function editProjekt(){
if($this->input->post('btladeProjekt')){
$data['proDetails'] = $this->projekt_model->editprojekt();
$data['preFormVisible'] = false;
$this->load->view('project2', $data);
}
redirect('projekt');
} }
What should happend?
The user choose on the "startsite" to edit an project. He select a project in a dropdown and click an button.
Here the form from the startsite:
<?php echo form_open('projekt/editProjekt', array('name' => 'preform')); ?>
<div class="col-sm-6 col-md-6 col-lg-6">
<label for='projekt'>Projekt</label>
<?php echo form_dropdown('projekt', $projekte, '', 'class="form-control" id="projekt"'); ?>
</div>
<div class="col-sm-6 col-md-4 col-lg-3">
<button type="submit" id="btladeProjekt" name="btladeProjekt" value="btladeProjekt" class="btn btn-primary headbutton"><i class="glyphicon glyphicon-pencil"></i> Projekt bearbeiten </button>
</div>
<?php echo form_close(); ?>
Now the controller method editProject calls a method in the model. I show you:
function editprojekt() {
$serverName = "de-sal-v-sql011";
$connectionInfo = array( "Database"=>"NB_Roll_Plan", "UID"=>"s-global_it-bit002", "PWD"=>"\$Ev1danzA\$");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$projektID = $this->input->post('projekt');
$data = array();
$tsql = "SELECT ProjektID, Projektname, KDGR, Kundenname, ProduktgruppeID, Projektklasse, MABVertrieb, GSMBereich, Ansprechpartner_kunde,ProjektanfrageNR_kunde,
Anfragedatum, Abgabedatum_angebot, PDM, übergeordnetePDM, Kommentar, Projektrisiken from Projekt WHERE ProjektID = ? ORDER BY Projektname ASC";
$var = array($projektID);
$query = sqlsrv_query($conn, $tsql, $var);
if($query != false){
while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
$data['ProjektID'] = $row['ProjektID'];
$data['Projektname'] = $row['Projektname'];
$data['KDGR'] = $row['KDGR'];
$data['Kundenname'] = $row['Kundenname'];
$data['ProduktgruppeID'] = $row['ProduktgruppeID'];
$data['Projektklasse'] = $row['Projektklasse'];
$data['MABVertrieb'] = $row['MABVertrieb'];
$data['GSMBereich'] = $row['GSMBereich'];
$data['Ansprechpartner_kunde'] = $row['Ansprechpartner_kunde'];
$data['ProjektanfrageNR_kunde'] = $row['ProjektanfrageNR_kunde'];
$data['Anfragedatum'] = $row['Anfragedatum'];
$data['Abgabedatum_angebot'] = $row['Abgabedatum_angebot'];
$data['PDM'] = $row['PDM'];
$data['übergeordnetePDM'] = $row['übergeordnetePDM'];
$data['Kommentar'] = $row['Kommentar'];
$data['Projektrisiken'] = $row['Projektrisiken'];
}
sqlsrv_free_stmt($query);
}else{
die( print_r( sqlsrv_errors(), true));
}
return $data;
}
Now i want to display the returned data in the view, but when i try this nothing happens.
<?php
if(isset($proDetails)){
echo "test";
echo "<input type='text' class='form-control' id='proname' name='proname' value='".$proDetails->ProjektID."'/>";
}else{
echo "<input type='text' class='form-control' id='proname' name='proname'>";
}
?>
What did i miss? Thx in advance

Alright I think I have understand what is you required #JamesnxD. You can load the all the drop down in a view and the edit form in another view do like this
$this->load->view('front/dropdown');
$this->load->view('front/editform',$data);
$this->load->view('front/front_footer');

some change your model function and add a param.
function editprojekt($proID) {
$projektID = $proID
}
and change your index method
public function index($proID = '') {
if($proID) {
$data['proDetails'] = $this->projekt_model->editprojekt($proID);
} else {
$data['proDetails'] = false;
}
}
Finally when you edit content you call projekt/index/12 (12 = projektID) in browser url

you know that you can use array to load helper, model and library
$this->load->helper(array('html', 'url', 'form'));
$this->load->model(array('projektklassen_model', 'kundengruppen_model', 'produktgruppen_model', 'ablehnungsgrund_model','absatzregion_model','anfragetyp_model','businessunit_model','endkundeOEM_model','lieferanten_model','prozentverteilungEOP_model','prozentverteilungSOP_model','realisierungsstatus_model','gsmbereich_model','firma_model','projekt_model'));

Related

Update function code igniter does not save changes

hi am making this edit function in my code igniter hmvc project. i am getting the value of the things i want to edit, and it is posted to the textbox i want to. but, i cannot save the changes. my model is this,
public function update(){
$sql = "UPDATE $this->table SET PROVINCE = ? WHERE PROV_ID = ?";
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
// print_r($input);
// exit;
$query = $this->db->query($sql, $input);
return $query;
}
when i print_r the input, it says
Array ( [PROVINCE] => Province [PROV_ID] => )
i think dont get the uri value. how can i fix this?
here is my controller
/// EDIT
public function update(){
$data['content'] = $this->Provinces_Model->getrow();
$data['content_view'] = 'Provinces/edit_view';
$this->templates->admin_template($data);
}
public function update_row(){
if($this->Provinces_Model->update()){
redirect('Provinces/index');
}else{
$this->update();
}
}
}
here is my full model
//// EDIT
public function getrow(){
$this->db->where('PROV_ID', $this->uri->segment(3));
$query = $this->db->get($this->table);
return $query->row();
}
public function update(){
$sql = "UPDATE $this->table SET PROVINCE = ? WHERE PROV_ID = ?";
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
// print_r($input);
// exit;
$query = $this->db->query($sql, $input);
return $query;
}
here is my edit view
<?php
echo form_open('Provinces/update_row');
?>
<p>
<label class="field" for="PROVINCE"><span>*</span>Province Name:</label>
<input type = "text" name="PROVINCE" class ="textbox-300" value= "<?php echo $content->PROVINCE; ?>">
<label class = "error"><?php echo form_error("PROVINCE"); ?></label>
</p>
<?php
echo form_submit('submit','Update');
echo form_close();
?>
here is the part of my table where i click to edit
<td><?php echo anchor("Provinces/update/$i->PROV_ID","<i class='fa fa-edit'>" ); ?></td>
Try this
public function update() {
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
$this->db->where('prov_id',$input['PROV_ID']);
$this->db->update('province',$input);
}
get the all segments of URI in an array
For that use this line...
$segs = $this->uri->segment_array();
foreach ($segs as $segment)
{
echo $segment;
echo '<br />';
}
and use that specific key to get the ID or something else!!

Pass post variable to url

How can i pass the post variable to segment url? i can read it from url but i can't set it...
What i have so far : $route['shop/find/(:any)']= "shop/find/$1"; on routes,my find.php on views, and my function `
function find()
{
$this->load->model('shopFront/find');
$this->load->model('currency');
$this->load->model('shopFront/calculate');
$this->load->model('shop/proccess');
$data = $this->commondatashop->general();
$inputSlug = $this->input->post('findSlug');
$data['tofind'] = $inputSlug;
$data['cartInfo'] = $this->shopcart;
$data['Currency'] = $this->currency;
$data['Calculate'] = $this->calculate;
$data['Proccess'] = $this->proccess;
$data['title'] = "1.4.U Shop | Find";
$finder = $this->find;
$data['finderservice'] = $finder;
$data['user_id'] = $this->session->userdata('user_id');
$data['user_name'] = $this->session->userdata('user_name');
$this->load->view('shop/top/topNew',$data);
$this->load->view('shop/content/find',$data);
//footer
$curravailable = $this->calculate->getCurrencies();
if ( $curravailable !== false )
{
$data['currencies'] = $curravailable;
}
else
{
$data['currencies'] = 'none';
}
$this->load->view('shop/footer',$data);
}`
How can i post the variable to the find()function with url segment?
you need to have find accept an argument with a default
function find($i=0) {
//$i is whatever is in the URL or defaults to 0
In your view:
echo form_open('/shop/find');
echo form_input('findSlug','');
echo form_submit('submit', 'Submit');
echo form_close();
Controller:
$data[slug] = $this->input->post('findSlug');
You need to load form helper too

Twitter Typeahead in CodeIgniter. Not passing array datum to hidden form field

I'm trying to use the typeahead.js Twitter Typeahead (not Bootstrap typeahead) to display names pulled from a mysql table using the CodeIgniter framework. The model also collects id values along with the name.
The controller and model seem to be presenting the correct array format.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$mode = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($mode == 'signin')
$this->db->where("status !=", "enter");
else
$this->db->where("status", "enter");
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['value']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
}
Controller (relevant functions)
function get_person() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->get_post();
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
Sample JSON data returned
[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]
View
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="hidden" name="person_id" id="person_id" value="" />
<input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>
<script>
$(function($) {
$('input.people-typeahead').typeahead({
name: 'people',
remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
dataType: 'json'
});
$("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(person_id).val() = datum.id
});
});
</script>
In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. I'm almost certain that this is an issue with the javascript code in the view not being correct, but quite frankly, I have no js skills to sort it out!
I see an issue here :
$(person_id).val() = datum.id
You are using jQuery's .val() incorrectly and the use of the selector is wrong too. It should look like :
$("#person_id").val(datum.id);
jQuery .val() documentation
I finally figured out how to get this working. Part of the problem was that I could find no examples of using typeahead.js in CodeIgniter that showed how the various script, view, controller and model components interact. I tried switching to Twitter bootstrap typeahead. However, despite finding references to using it with an arrays rather than a string, I still could not get a working solution.
In the end I went back to Twitter typeahead and started from scratch. I found this tutorial helped enormously:
Twitter Bootstrap typeahead.js with underscore.js Templating – A Tutorial - Alan Greenblatt
I'm posting what worked for me in case it can help anyone else with similar issues. This version also includes setting the remote source as a variable which allowed me to define it through PHP so that I could select data in the model based on the URL.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$modeinout = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($modeinout == 'signin'){
$this->db->where('status !=', 'enter');
}
else {
$this->db->where('status', 'enter');
}
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['name']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
Controller (relevant functions)
function signin() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['title'] = "Sign Someone In";
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['mode'] = 'signin';
$this->load->view("home/attendance/signinout", $data);
}
function signout() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['id'] = '';
$data['title'] = "Sign Someone Out";
$data['mode'] = 'signout';
$this->load->view("home/attendance/signinout", $data);
}
function get_people() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->post('query');
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
View
<?php
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script>
var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
$(function($) {
_.compile = function(templ) {
var compiled = this.template(templ);
compiled.render = function(ctx) {
return this(ctx);
}
return compiled;
}
$('.person-typeahead').typeahead({
template: '<p><strong><%= name %></strong>: <%= id %></p>',
name: 'people',
valueKey: 'name',
engine: _,
remote: (person_url),
dataType: 'json'
}).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
$('#person_id').val(datum.id);
$('#person_name').val(datum.name);
});
});
</script>
<?=jquery_validate('attendance/signout');?>

Can not save view as a variable to be used in template

I am trying to call a model from my controller, which in turn generates data from a view, saves it as content and returns it to the controller, which then adds it to a template I have.
Whats happening is that $content = $this->load->view('left/profile', $c_data); is printing the data instead of saving it in variable $content
Here is my code:
Controller:
function index($page = '1-Welcome to')
{
if (!$this->tank_auth->is_logged_in()) {
//display non-login page
redirect('/auth/login/');
} else {
//user information
$user['user_id'] = $this->tank_auth->get_user_id();
$user['username'] = $this->tank_auth->get_username();
//general page data
$main['title'] = $this->page_model->make_title(ucfirst($page));
//template data
$template['head'] = $this->load->view('templates/head', $main, TRUE);
//get left content
$c_data['make_profile'] = $this->left_model->make_profile($user);
//combine into one variable
$data['template'] = $template;
$data['page'] = $page;
$data['user'] = $user;
$data['left'] = $c_data;
print_r($data);
$this->load->view('main_template', $data);
}
}
Focus on $c_data['make_profile'] = $this->left_model->make_profile($user);
Here is make_profile
public function make_profile($user)
{
$user_id = $user['user_id'];
$query = $this->db->query(" SELECT location FROM user_profiles AS up
INNER JOIN avatars AS a
ON up.avatar_id = a.id
WHERE user_id='$user_id'");
$c_data['avatar_loc'] = $query->row_array();
$content = $this->load->view('left/profile', $c_data);
$content .= "hello";
return $content;
}
And here is my profile view:
<div id="profile">
<div id='avatar'><img src="<?php echo $avatar_loc['location'] ?>" alt="avatar_user"/></div>
<div id="profile_pop"></div>
</div>
Any idea why it isn't working? Thanks
Return the data from the view as a string:
$this->load->view('left/profile', $c_data, TRUE);
Read here (bottom of the page).

Helper Code Igniter inside smarty template

Is this possible if I put my form_helper with array parameter in my smarty template.
this is my method of my controller:
function input($pIntBookId = 0) {
$this->load->model('m_books');
if($this->input->post('mysubmit')){
if($this->input->post('id')){
$this->m_books->entryUpdate();
}else{
$this->m_books->entryInsert();
}
}
$arrData = $this->m_books->general();
if((int)$pIntBookId>0){
$strQuery = $this->m_books->getId($pIntBookId);
$arrData['idxFid']['value'] = $strQuery['book_id'];
$arrData['idxFtitle']['value'] = $strQuery['book_nm'];
$arrData['idxFauthor']['value'] = $strQuery['book_aut'];
$arrData['idxFpublisher']['value'] = $strQuery['book_pub'];
$arrData['idxFyear']['value'] = $strQuery['book_year'];
if($strQuery['book_st']=='yes'){
$arrData['idxFavailable']['checked'] = true;
}else{
$arrData['idxFavailable']['checked'] = false;
}
$arrData['idxFsummary']['value'] = $strQuery['book_ds'];
}
$this->mysmarty->assign('arrData',$arrData);
$this->mysmarty->view('v_booksinput.php');
}
Is this possible..? :
<td>{php} echo form_input($idxFtitle);{/php}</td>
You can write own smarty-function which does what you want.
{function name="my_input" data}
<input name="{data['value']}"></input>
{/function}

Categories