How do I join fields of a form with codeigniter? - php

I have this snippet of code
<input type="text" id="name1" name="name1">
<input type="text" id="name2" name="name2">
<input type="text" id="name3" name="name3">
And I want to concat them inside a variable (something like $variable = name1.name2.name3), so I could set that value inside an array (in the controller) like this:
$form_data = array(
'Name' => set_value($variable),
'Sexo' => $this->input->post('optionsRadios')
);
I don't know if the above code is possible, but that's the idea for this thing that I want to do.

Why not something like this?
$variable = $this->input->post('name1')
. $this->input->post('name2')
. $this->input->post('name3');

Related

Looping an array from form element

hope you can help me on this..
i have this simple code :
foreach ($by_sellers as $seller_id => $info) {
print_r($info);
echo 'AMOUNT : ' . $info['total'] .'; STORE : '. $info['name'];
}
and the output is this :
Array(
['total'] => 100
['name'] => 'Store Name'
)
AMOUNT : ; STORE :
its really weird coz i cant read the values of the variable if done individually but it display on var_dump & print_r.. those data comes from input forms..
<input name="by_sellers[1]['total']" value="100">
<input name="by_sellers[1]['name']" value="Store Name">
hope someone find the light on this problem.. thanx..
found the solution and its a simple one..
i just edit the html code from this
<input name="by_sellers[1]['total']" value="100">
<input name="by_sellers[1]['name']" value="Store Name">
to this (removing the quotes of the string name)
<input name="by_sellers[1][total]" value="100">
<input name="by_sellers[1][name]" value="Store Name">

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

Loop through 3 arrays at once and save values in the database

I have three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.
I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}

set two values for an input name attribute

i have a check box list that some limited check boxes can be selected. for this i set the name attr of all them "answer" to work with the js function properly(i got the function from some where).
<?php
else if($result['type'] == "multipleChoice"){
echo'
<div><input type="checkbox" name="answer ans1" value="'.$res['probAns1'].'"/><input type="text" class="prob-ans" name="prob-ans1" value="'.$res['probAns1'].'"/><lable>:گزینه 1</lable></div>
<div><input type="checkbox" name="answer ans2" value="'.$res['probAns2'].'"/><input type="text" class="prob-ans" name="prob-ans2" value="'.$res['probAns2'].'"/><lable>:گزینه 2</lable></div>
<div><input type="checkbox" name="answer ans3" value="'.$res['probAns3'].'"/><input type="text" class="prob-ans" name="prob-ans3" value="'.$res['probAns3'].'"/><lable>:گزینه 3</lable></div>
<div><input type="checkbox" name="answer ans4" value="'.$res['probAns4'].'"/><input type="text" class="prob-ans" name="prob-ans4" value="'.$res['probAns4'].'"/><lable>:گزینه 4</lable></div>
';
?>
first is it correct to set two value for name attr. i did it but didnt work. like it isnt acceptable the second value.
if not how can i specify them if i have just name="answer"? i want to set some values in php if one of these check boxes is set.
<?php
if($result['type'] == "multipleChoice"){
$question->probAns1 = mysql_real_escape_string($_POST['prob-ans1']);
$question->probAns2 = mysql_real_escape_string($_POST['prob-ans2']);
$question->probAns3 = mysql_real_escape_string($_POST['prob-ans3']);
$question->probAns4 = mysql_real_escape_string($_POST['prob-ans4']);
if(isset($_POST['ans1'])){
$question->answer1 = $_POST['prob-ans1'];
}
}
?>
No, you can't have two names like you did. Following however is possible:
<input type="checkbox" name="answer[]" value="abc" />
<input type="checkbox" name="answer[]" value="def" />
Your $_POST will look like following (if both are checked):
array(
'answer' => array(
0 => 'abc',
1 => 'def'
)
)
You can also specify the array-keys, thus name="answer[answ1]" value="abc" will give you $_POST['answer']['answ1'] == 'abc'
Here is link of what you need to do.
In one sentence, you need to use arrays of html elements.

Codeigniter: One view for adding and editing a post

I'm working on a CMS in Codeigniter and one main part is a form for creating and editing posts.
I've been planning on using the same view file for both since all of the elements are shared. The only difference would be the form is blank when creating and it's populated when being edited. Is this the right way to go?
I was thinking about having a method for each, so post/create and post/edit($id).
In the create method in the post controller I have all the form data like this (for errors):
$this->data['item_title'] = array(
'name' => 'item_title',
'id' => 'item_title',
'type' => 'text',
'value' => $this->form_validation->set_value('item_title'),
);
I'm thinking about just altering the value to hold the database value instead of set_value(), so something like:
public function edit($id) {
$post_data = $this->post_model->get_post_data($id)
$this->data['item_title'] = array(
'name' => 'item_title',
'id' => 'item_title',
'type' => 'text',
'value' => $post_data['post_title'],
);
}
Am I on the right track or is there a better way to approach this? Should I just use 2 views?
i use a partial _form.php that is shared by a new and edit controller action. on both actions i have the same validations so i moved those to the controller constructor, then for each input i just use a ternary operator that says if the existing value $title is provided then populate the <input> value using it, otherwise use the codeigniter set_value() helper to populate with the validation value.
<input type="text" name="title" value="<?php echo isset($title) ? set_value("title", $title) : set_value("title"); ?>" />
I usually use one view with a few variables in it. The values of the fields can either be set from the data from the server or they can be left blank. Depending on whether data is being provided or not I change which action the form will use because it may be adding or editing.
This should be the most efficient method since it uses the idea of reusability :)
A quick example
<form action="<?php echo !$data ? "admin/add" : "admin/edit" ?> method="post">
<input type="text name="test" value="<?php echo $data['test'] ? $data['test'] : "" ?>" />
</form>
I'm not pro at CodeIgniter (much better at CakePHP) but in the heart of MVC is that one action has one view.
You have no reason to put it in one view. :)
It's certainly possible, as I do it all of the time.
Normally, I would have:
Action
function edit($PageID = -1)
{
$Page = new stdClass();
if($PageID === -1)
{
$Page->Title = $Page->Description = $Page->Keywords = '';
$Page->PageID = -1;
}
else
{
$this->load->model('page_model');
$Page = $this->page_model->GetByPageID($PageID);
if(empty($Page))
{
show_404();
return;
}
}
if($this->input->post('Save', true) !== false)
{
// perform validation
if($PageID === -1)
{
// insert
}
else
{
// update
}
}
$data = array
(
'Page' => $Page
);
$this->load->view('edit_page', $data);
}
View
<?= form_open(); ?>
<fieldset>
<label for="title">Title: </label>
<input type="text" name="title" id="title" value="<?= Form::Get('title', $Page->Title); ?>" />
<br />
<label for="description">Description: </label>
<input type="text" name="description" id="description" value="<?= Form::Get('description', $Page->Description); ?>" />
<br />
<label for="keywords">Keywords: </label>
<input type="text" name="keywords" id="keywords" value="<?= Form::Get('keywords', $Page->Keywords); ?>" />
<br />
<input type="submit" name="Save" value="Save" />
</fieldset>
</form>
Edit
Sorry, I should have mentioned, Form::Get is not a CodeIgniter function, but one I have created. Simply, it takes the path to the Post value you need to read. If it doesn't exist, i.e. you haven't posted, then it will simply display the value from the second parameter.
If I can dig the code out for you, I will post it.

Categories