PHP Concrete 5 Pass Variables to Add.php - php

I'm creating a new block and I want to pass a defined variable to the block instance on add.
In my controller, I have the following:
// declare the var
public $hasMap = 0;
public function add() {
$this->set('hasMap', $this->generateMapNumber());
}
The generateMapNumber() function looks like this:
public function generateMapNumber() {
return intval(mt_rand(1,time()));
}
In my add.php form I have a hidden field:
<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->hasMap?>" />
When I create a new block, hasMap is always 0 and the hidden input value is always 0 too. Any suggestions? Thank you!
--- EDIT ---
From the concrete5 documentation:
// This...
$controller->set($key, $value)
// ... takes a string $key and a mixed $value, and makes a variable of that name
// available from within a block's view, add or edit template. This is
// typically used within the add(), edit() or view() function

Calling $this->set('name', $value) in a block controller sets a variable of that name with the given value in the appropriate add/edit/view file -- you don't need to get it from within the controller object. So just call <?php echo $hasMap; ?> in your add.php file, instead of $myObj->hasMap.

It will not be the same value, because the function will give diferrent values every timy it is called.

So here's the solution. In the controller...
public $hasMap = 0;
// no need for this:
// public function add() { }
public function generateMapNumber() {
if (intval($this->hasMap)>0) {
return $this->hasMap;
} else {
return intval(mt_rand(1,time()));
}
}
And then in the add.php file...
<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->generateMapNumber()?>" />
It works perfectly. On add, a new number is generated and on edit, the existing number is drawn from the hasMap field in the db.
Thanks for all the input. Hope that helps someone else!

Related

Converting array key and values into single variables

I know that you can use extract() to achieve this however my circumstances are as followed:
I am building a very small basic MVC framework for personal projects and I have this in my controller:
public function index(){
$data = [
'title' => 'Welcome'
];
$this->view('pages/index', $data);
}
As you can see this passes the data array into the view and you can echo it like:
echo $data['title'];
But I want to echo it like echo $title; I know that extract() can do this but that means I have to manually put extract($data); at the top of every page which isnt the end of the world but I was just curious if there was a way it could be done automatically? I have tried to use extract by putting it inside the view function but that did not work. I have also tried to use extract by putting it in the header file that is required_once in index.php (thus making the header file a static header thats always required) but neither has worked so any advice would be great.
Here is the code for the view function as requested:
public function view($view, $data = []){
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
Simple that is it ,use compact and extract function
index method
public function index(){
$title='Welcome';
$this->view('pages/index', compact('title'));
}
Wiew method
public function view($view, $data = []){
extract($data);
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
In html
<h1> hello <?php echo $title; ?></h1>
Here is where I went wrong, I put extract in the view method before and it didn't work.
However the advice here was to put it in the view function and I now understand that I put the extract function after require_once '../../views/'.$view.'.php'; I just put extract before that line of code and it is now working!

Why does CI create a new row instead of updating?

I'm creating a UI in my application which will allow the user to decide the state of received content, this includes updating it. How does CI handle this?
I've tried the different update methods provided in the query builder part of the documentation, including replace and update, I pass on the data from the view to the controller, to the model in the form of an array. Yet still, when I try it, it creates a new row with that single value and with all other columns empty.
view.php
<form action="Application/Update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<?php echo anchor('http://localhost/dir/dir/dir/index.php/Application/Update', 'update'); ?>
</form>
controller.php
public function Update() {
$this->load->helper('url');
$this->load->model('Main');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
$mar = $this->Main->Update($id, $value);
if ($mar == TRUE) {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage', 'refresh');
}
else {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage');
}
}
model.php
public function Update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update = $this->db->update('table', $data);
}
As I said, I expect the row to be updated based on the row-id provided. Instead it creates a completely new row with that single value. It doesn't return any error messages though.
There are a number of mistakes here.
SO to date we have established that performing var_dumps in the controller results in NULL for all your "POST" values.
I've assumed the following for simplicity.
Controller Name is: Program.php (Application is NOT an Allowed controller name as it's a foldername)
Model Name is: Mdl_update.php
View is: update_view.php
Issue #1:
Your Form has an issue where you are using an anchor tag which is just a link. It does nothing in submitting any data from the form.
So we have to remove the Anchor Tag and replace it with a Form Submit. You have to Submit the form to get any chance of sending the form data.
For testing your GET and POST I've added in Two different Forms.
In update_view.php
<!-- Set the Method to GET -->
<form action="program/update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with GET">
</form>
<!-- Set the Method to POST as this is what the Controller is Expecting -->
<form action="program/update" method="post">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with POST">
</form>
What I used to display the Form in the controller by simply calling the program/index in the Program controller.
public function index() {
$this->load->helper('url');
$data['row'] = array('id' => 2);
$data = $this->load->view('update_view', $data, TRUE);
echo $data;
}
So your Controller is looking for POST and not GET. This can be proven by changing the controller up a bit for debugging.
public function update() {
$this->load->helper('url');
$this->load->model('mdl_update');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
echo '<h2>POST Values</h2>';
var_dump($id);
var_dump($value);
// ****************************
// These are added in for debugging/Demonstration to show values for the form using the GET method.
$id_get = $this->input->get('mar-id');
$value_get = $this->input->get('mar-read');
echo '<h2>GET Values</h2>';
var_dump($id_get);
var_dump($value_get);
// ****************************
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__); // Added for Debug
$mar = $this->mdl_update->Update($id, $value);
if ($mar == TRUE) {
redirect(base_url('program/otherpage'), 'refresh');
} else {
redirect(base_url('program/otherpage'));
}
}
So you are looking for POST Data when your form method is set to GET. Please be aware of what you are setting. They must match.
If you want to use GET, you need to use $this->input->get()
The code above will let you test both.
So you now have a POST and GET Form and the controller is setup to demonstrate the two different types. Choose Either GET or POST!. That is up to you on which one you choose.
Issue #2: Expecting a return value from your Model when you are not returning anything.
In your Controller you have the line...
$mar = $this->mdl_update->Update($id, $value);
And in your Model you have...
public function update ($id,$value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$this->db->update('db_table', $data);
}
Your Model Method is not returning anything.
You should always look up what your return values are. I am expecting that your intention was to return the value of the update. Looking through the CI Code itself it appears that if things go wrong it will return FALSE (if the database debug is disabled - learnt something new)
I've added in some debug to assist in viewing what is going on here.
public function update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update_result = $this->db->update('db_table', $data);
echo $this->db->last_query(); // Added for DEBUG
return $update_result;
}
Now I cannot get your code to create new rows as you claim. It's impossible, with this code, to add new rows. So thats happening from something you haven't shown us but that is an aside and not important here.
If we alter the controller to view the model etc (I am only showing the changes ) we would change
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
$mar = $this->mdl_update->Update($id, $value);
To this
$mar = $this->mdl_update->Update($id, $value);
var_dump($mar);
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
If you run this and submit either the GET ( Results are NULL ) or POST, the update will always return TRUE. So your redirect etc needs to be looked at on how you decide on one or the other.
I think you should set your table columns to not allow them to be NULL AND add in some "Validation" in your controller.
ISSUE 3: No Form Validation
CodeIgniter has a Form Validation Class that I suggest you read. This is getting way too long to go into that here...
So as you go through this, you can add/remove debugging to test what is going on and progress it along the way as I have hopefully shown.
if anything is unclear, just ask. I'm sure I may have left something out.

cant get passed parameter by url in php

please help me, this is simple thing but I don't know why this still keep error for an hour,
on my view I've got :
<a href="admin/editProduct?idd=$id">
on my controller that directed from above :
public function editProduct(){
$data["id"] = $_GET['idd'];
$data["produk"] = $this->model_get->get_data_list(2);
//this below doesn't work either, i just want to past the parameter to my model
//$data["produk"] = $this->model_get->get_data_list($_GET['idd']);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}
I can not use the array id. It keeps telling me undefined variable idd.
I don't know what to do anymore, please anyone help!
I am using Codeigniter framework
Change your view as:
<a href="admin/editProduct/<?php echo $id;?>">
And in the controller, either get the id as parameter,
public function editProduct($id) {
}
or as uri segment
public function editProduct() {
$id = $this->uri->segment(3);
}
Change your link (in view) with this
<a href="admin/editProduct/$id">
And change your controller as
public function editProduct($id) {
}
Then user $id inside your controller
Make the href link as follows:
...
And edit the controller like this:
public function editProduct($id){
...
$this->model_get->get_data_list($id);
}
Where $id will be the passed $id.
make
try this this works fine
public function editProduct()
{
$id=$this->uri->segment(3);
$data["produk"] = $this->model_get->get_data_list($id);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}

last inserted id/latest inserted id function codeigniter

Codes:
View
<html>
<body>
<?php echo form_open('samplecontroller/sample'); ?>
<input type="text" name="samplename"/>
<input type="submit" value="go"/>
<?php echo form_close(); ?>
</body>
</html>
Controller
<?php
Class samplecontroller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Sample_insert');
}
function index()
{
$this->load->view('sample.php');
}
function show($data)
{
$this->load->view('sampleresult',$data);
}
function sample()
{
if($result = $this->Sample_insert->insert_into_sample())
{
$this->show($result);
}
}
}
?>
Model
<?php
Class Sample_insert extends CI_Model
{
function insert_into_sample()
{
$sample = array(
'samplename' => $this->input->post('samplename'),
);
$this->db->insert('sample', $sample);
$latest_id = $this->db->insert_id();
return $latest_id;
}
}
?>
The flow is that, i have 2 views. The other one contains only 1 text input, after which goes to controller then controller passes it on to model then model gets the value within the text input then inserts to my sample table.
The sample table has 2 columns, id(PK,AI) and name
after it inserts, on my model. i added a line, return $latest_id. Then passes goes back to my controller then passes it off to another view that only has
print_r($data);
After all that, it displays an error.
Message: Undefined variable: data
Im not sure where the flow went wrong or if i made a syntax mistake. If someone knows/expert on insert_id(), could you pin point where exactly i am wrong? anyways, ive made my research and been getting results on the web how buggy insert_id is. Im not sure if its true or not but ive been redirected mostly to forums wherein insert_id returns null and some say its a bug. Im hoping it isnt.
As per your comment, You have to do some changes in your controller.
function show($data)
{
$this->load->view('sampleresult',array("data"=>$data));
}
You can get inserted id in view in the name of $data.
For ex:
echo $data;
Edit: As per your comment in answer, For multiple row insert in model, add below code
$id_arr = array();
foreach($sample_data as $sample)
{
$this->db->insert('sample', $sample);
$id_arr[] = $this->db->insert_id();
}
return $id_arr;
Now in your view, you will get ids in $data
foreach($data as $id)
{
echo $id;
}

Refactoring: Getting rid of an optional variable for a function

Here's the situation; below is a piece of PHP code which is frequently reused.
if (! isset($_REQUEST['process_form'])
{
// render form
echo "<form>";
// snipped
// important bit! Remember which id we are processing
echo "<input hidden='id' value='$id'>";
// snipped
} else {
// process the form
}
I wish to encapsulate this into a function, akin to
class ProcessForm() {
function execute(array $request, $id) { };
}
The issue here is; the $id parameter is only needed when rendering the form. When processing the form after a user input or through an AJAX handler, I don't need the $id at all.
How could I refactor to get rid of the optional variable $id?
Optional parameters in PHP works like so
function example($id = NULL)
{
if(is_null($id))
echo '$id was omitted';
}

Categories