updating and/or creating objects with dynamic forms - php

Hi I have a relatioship between client and phones.
Using an array name in the form I managed to save all numbers to a client:
form:
<input type="text" class="form-control phone-number" name="phoneNumbers[work][]" value="">
controller:
$numbers = [];
foreach(Input::get('phoneNumbers') as $phone_type => $array){
foreach($array as $index => $phone_number ){
$phone = new Phone(array(
'name' => $phone_type,
'number' => $phone_number
));
array_push($numbers, $phone);
}
}
$client->phones()->saveMany($numbers);
But now on to updating... Wouldn't it be better to just remove all phones and recreate them with the new ones? As I'm not sure how to write the script to update the phones.

Delete and re-create, easiest way to achieve this (works pretty well, I did it a couple of times for an admin panel).

When the phones/numbers are saved to the model, each would receive an id. When you output this to your update form, tag each one with the appropriate id. The input can then update the correct phones. Loop through them same way, finding and updating each.

Related

Codeigniter large form insertion

I've a form with 120 fields to insert into the DB. The form is inserting fine and the approach I used is below:
I'm fetching all the fields from the view as below in the controller and passing the array($postdata) to the model file to insert.
**View**
$postdata = array(
'firstname' => $this->input->post('firstname'), //1st field
'lastname' => $this->input->post('lastname'), // 2nd field
'age' => $this->input->post('age'),
....
....
'test' => $this->input->post('test') // 120th field.
);
$this->Form_Model->insertdata($postdata);
**Model:**
function insertdata($data = array()) {
$sql_query = $this->db->insert('form_insert', $data);
redirect('Form');
}
My question is Is there any better way to insert. This approach feels bit repetitive.
If you simply want to get an array of all the data submitted, you can do it like this:
$postdata = $this->input->post();
This means, all the data submitted from the form will be there in this array.
And if you want to remove any particular element from this array, you can use unset().
Say for example, you may have named your submit button as "submit_btn" like this:
<input type="submit" name="submit_btn" />
then this value would be there in the above returned array. You can remove it like this:
$postdata = $this->input->post();
unset( $postdata['submit_btn']);
Btw, I have a couple of suggestions. The logic part is done in a Controller(you referred it by mistake as View). A View is simply for the displaying. And the Model is for the database communication.
Also, it would always be better to do some validations on the input that you received from the User through form submissions. We may don't even know what data they are sending!
And move that redirect() you used in the Model to the Controller from where you were trying to call that insertdata() method. In that Model, you just return a value (true or false or maybe something else) and do the business logic inside the Controller
You were kind of mixing up everything. That's why I thought to give you some pointers to help you.
Hope it helps :)

PHP - Array of termins as form option (LIMIT array element usage)

Let me just explain you my problem. I am working on a php form template which could be useful for more events in our company. In this form I collect few things about our employees but that is out of question.
My problem is that in form I have HTML SELECT element, where are some OPTIONs inside. I have this option in PHP array, for better imagination for example termins for Blood donation. I need to handle that only one employee can sign in for specific termin.
Can I somehow limit "the usage of array element"? I mean, when someone has already signed in for termin X, just don't allow another employee to pick this termin.
Thanks.
<-- EDIT -->
here is the code:
This is my config.php (the file, where all variables are configured
$termins = array(
'8:00' => '',
'8:30' => '',
'9:00' => '',
'9:30' => '',
'10:00' => '',
'10:30' => '',
'11:00' => ''
);
and here is index.php where I fill the options into select element
<?php
foreach($termins as $key => $value) {
echo '<option value="myvalue">' . $key . ' </option>';
}
?>
I think that "Disable" is the way how to solve this. When the option is already picked, i just have to change the OPTION to "Disabled". But this comes to my second question: How to change the property of html OPTION element to Disabled and keep this change? Should I use php sessions?
First of all, that HTML SELECT elements are in database? If yes, doing a LEFT JOIN between form's registered users table and HTML SELECT options table you will have elements that do not match between those two tables.

how to replace text with another similar to mail merge?

I am working in Magento, and i have developed a module to send text messages to customers. In the settings of the module, the admin can set the message that will be sent to the customer. I'm trying to add a features that will allow the replacement of texts with data from my database.
for example, i currently have the following code that fetches the saved settings for the body of the text message:
$body = $settings['sms_notification_message'];
The message that is fetched looks like this:
Dear {{firstname}},
your order ({{ordernumber}}) has been shipped.
tracking#: {(trackingnumber}}
Thanks for your business!
{{storename}}
The goal is to have the module replace the variables in "{{ }}" with the customer and store information.
Unfortunately, i'm unable to figure out how to make it replace the information before sending the message. It is currently being send as is.
The easiest way to do it would be to use str_replace, like so:
// Set up the message
$message = <<< MESSAGE
Dear {{firstname}},
your order ({{ordernumber}}) has been shipped.
tracking#: {{trackingnumber}}
Thanks for your business!
{{storename}}
MESSAGE;
// Assign the values in an associative array
$values = [
'firstname' => 'firstnamevalue',
'ordernumber' => 'ordernumbervalue',
'trackingnumber' => 'trackingnumbervalue',
'storename' => 'storenamevalue'
];
// Create arrays $target indicating the value to change
$targets = [];
foreach ($values as $k => $v) {
$targets[] = '{{'.$k.'}}';
}
// Use str_replace to perform the substitution
echo str_replace($targets,$values,$message);

How to send Jqxgrid in a form without using hidden textbox?

My CI view consists of a grid and data is added dynamically to this grid.This is saved to a database when a save button is clicked..
Here is the screenshot of the view.
[IMG]http://i40.tinypic.com/16a7dhl.png[/IMG]
When I submit the form,Grid data is first stored in an array and then array elements are joined together with a seperator in between them into a string.This string is stored in a hidden textbox and is submitted along with the form.After submission,in the controller they are seperated again & stored in the database.I have read that this method is prone to error.
Is there a better way to send array of data in a table to the controller than the above method? I have used Jqxgrid.
Use the jqxGrid's "getrows" to get all records as an Array.
You can use an array for the names of the fields.
<input type="hidden" name="field_name[]" value="foo">
<input type="hidden" name="field_name[]" value="bar">
$post = $this->input->post();
extract($post);
foreach($field_name as $k => $v){
$this->db->insert('tablename', array('fieldname' => $v));
}

cakePHP pagination and passedArgs

I am trying to build in a "search" box on a results page in my cakephp app. The page uses the cakePHP pagination component to show and "page" results. This is perfect, but I am having difficulties to get the next part to work.
The desired outcome:
A cakephp form (post) with an input box and a couple of select boxes, including a date selector so that I can select between dates. The user should be able to populate these fields and submit
On submit, the user selection should change the cakePHP pagination conditions in the controller
In the view I want the pagination bar to keep record of the user selection, so that when I filter through different pages, it keeps the users search. I understand this can be achieved using $this->passedArgs, hence why I am using post and not get.
The code:
// Form:
<?php
echo $this->Form->create('search', array('class' => false));
echo $this->Form->input('searchFor');
echo $this->Form->input('dateFrom');
echo $this->Form->input('dateTo');
echo $this->Form->end();
?>
// Controller:
if($this->request->is("post")) {
$filters = $this->request->data["search"];
$this->passedArgs["searchFor"] = $filters["searchFor"];
$this->passedArgs["dateFrom"] = $filters["dateFrom"]." 00:00:00";
$this->passedArgs["dateTo"] = $filters["dateTo"]." 00:00:00";
// Assign search parameters:
if($this->passedArgs["searchFor"] != "") {
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
$conditions["Model.created >="] = $this->passedArgs["dateFrom"];
$conditions["Model.created <="] = $this->passedArgs["dateTo"];
} else {
$conditions = array("Result.status_id >=" => 12);
}
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
$this->set("results",$this->paginate("Model");
// The view file:
<?php
$this->Paginator->options(array('url' => $this->passedArgs));
?>
Where I am now:
The initial page loads with all of the results
When I populate the search boxes it does return my results
The problem:
I am convinced the way I am doing it is incorrect as I now need to do 2 checks, a) being if results has been posted and b) check if there is passedArgs available. I am 100% convinced this is not the right way of doing it.
Let's say I have 2 free form fields for search, say name and surname, if I leave surname blank my url would be written as below, and this does not look or appear to be correct. That means I have to assign default values to ensure the items below does not happen, which does not appear to be very dynamic.
http://localhost/site/controller/action/surname:0/name:John/date:0/
On refresh it says the page does not exist because the posted values is not available anylonger.
usually I proceed like this in the controller:
//transform POST into GET
if($this->request->is("post")) {
$url = array('action'=>'index');
$filters = array();
if(isset($this->data['searchFor']) && $this->data['searchFor']){
//maybe clean up user input here??? or urlencode??
$filters['searchFor'] = $this->data['searchFor'];
}
//redirect user to the index page including the selected filters
$this->redirect(array_merge($url,$filters));
}
$conditions = array();
//check filters on passedArgs
if(isset($this->passedArgs["searchFor"])){
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
//paginate as normal
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
The idea is to transform the POST sent by your form into GET. so you wont have problems with the paginator nor the refresh
Hope this helps
What you want can be done a lot more simple and DRY by using this search plugin.
It automates what you want more or less plus it already can do more than your code.
So I suggest you to use the plugin directly or take a look at it how it does the trick. :)

Categories