This is Controller.php
public function dropdown($id)
{
$stations = Station::lists('station_name','id');
return view('stations.show')->withStation($station);
return view('stations.dropdown',compact('stations', 'selectedStation','selectedStation'));
}
This is the view.php
{{ Form::select('station',$stations,null,['class' => 'form-control']) }}
<br>
<?php
if(isset($_GET['submit'])){
$selectedStation = $_GET['station'];
echo $selectedStation;echo "<br>";
}
else
{
echo "not working";
}
?>
corresponding Database table.
This gives me a drop-down like in the below image.
When a station is selected it displays only "id" of the selected station. How to retrieve other columns of the selected station ?.
Many ways that you can tackle this and I have also made some assumptions.
Your list (it would seem) only contains the name & the id.
I assume that you don't want to reload the page when you get the information for the specific item that you have chosen in the dropdown.
Here are the first 2 options that come to mind.
1.) AJAX - Use javascript framework like jQuery and monitor change() for the select, on change get the id and fire it to another route in Laravel which takes the ID and returns some more information in JSON. You can then use JS to display this to your users as you please.
2.) Preloaded JSON - Write new DB Query that gets all the information that you want and store it in JSON format inside some <script> tags. It wont be viewable to the user. Then you can use jQuery or other JS framework to grab that data again on change()
Part 2 will be faster, and if you have got 100,000s records i would advise that for perf.
Apologies if I totally misunderstood the question, it seems like you need a JS solution rather than Laravel/PHP solution. (Without a bad UX) if you did wan't more data you would need to post it and the fetch data from DB on new request.
To display all the columns of all stations you can do the following.
Please note, doing this you fetch all which may not be necessary and there may be better methods available on the eloquent model class depending on what you are trying to do.
Controller
public function showTable()
{
//Fetch all stations from the database
$stations = Station::all();
//Return fetched data to the view
return view('stations.show', ['stations' => $stations]);
}
View - stations/view.blade.php
<ul>
#foreach ($stations as $station)
<li>{{$station->station_name}} - {{$station->rainfall}}</li>
#endforeach
</ul>
For more information and examples about the eloquent model class you can check: https://laravel.com/docs/5.2/eloquent
Related
I'm sorry I haven't included "my attempt" as such with this one, I'm useless with jquery so need some advice!!
I would like to change the value of a second selctor based on the results of the first.
I have a database of builders and regions with the headers builder_name and builder_region. The list ends up looking like this ...
builder_1 region_1
builder_1 region_2
builder_2 region_1
builder_3 region_1
builder_3 region_2
builder_3 region_3
(You get the idea)
I'm using the following in the form I've built to get a list of the builders for the first select box ...
echo '<select class= "ml-select" name="gen_builder">';
echo '<option value=" ">Select Builder</option>';
while($row = mysql_fetch_array($rsBUILDER)) {
if($linebreak !== $row['builder_name']) {
echo '<option value="'.$row['builder_name'].'">'.$row['builder_name'].'</option>';
}
else {echo "";}
$linebreak = $row['builder_name'];
}
echo '</select>';
The $linebreak is to get rid of the duplicate builder names from the list, which works a treat.
What I would like to achieve is a second selector that selects the regions available, dependant upon the builder that has been selected in the first option. I hope this makes sense????
The second query needs to look at the builder selected in the first selector and filter out just the regions that are in rows with the builder name form selector one.
Please do say if you need further information, I'm not great at explaining myself.
As you said you don't have experience with jQuery or Ajax, I'll post my answer with as many comments as possible. I will assume that you have two select dropdowns in your page.
The first one contains the builders, so it will have id="builders".
The second one contains the regions, so it will have id="regions".
From what I understand, the first select will be exactly the one you posted in your question, generated server-side (by PHP). I only ask that you please make a slight change on it, making each option value be equal to the builder's database ID, and not its name (unless the builder's primary key is their name, and not an ID). This will make no difference for the final user but will be important for our jQuery solution. The second one will be empty, as the idea is to fill it dynamically with the regions related to the builder selected in the first dropdown.
Now let's get to the jQuery code:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
//The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
$('#builders').change(function() {
//$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
var currentValue = $(this).val();
//Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions);
$.get("get_regions.php", {'builder_id': currentValue}, function(data) {
//Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
var regions = $.parseJSON(data);
//Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
$('#regions').empty();
//Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
for (var i = 0; i < regions.length; i++) {
var regionOption = '<option value="'+regions[i]['region_name']+'">';
regionOption += regions[i]['region_name'];
regionOption += '</option>';
$('#regions').append(regionOption);
}
});
});
});
Despite any syntax errors (can't test the code from here) this should do the trick. Hope the comments were clear enough for you to understand how things work in jQuery.
I really need this as most of my products have options in Opencart. I need to show option quantities for each product in the admin list.
At the moment in the quantity column it just shows a number. It would be better if it said for example Strawberry: 12 Vanilla: 5.
Can someone please help me?
The first thing you should do is see if there is an extension for this on the OpenCart extension page. If there is no extension then this is what you will need to do. 1) Find which database table this information is in (I think its product). Then query it in your model , pass it to your controller, and then echo that variable/ array in your view. I will provide you roughly with the code you will need, however you need to tweak it to do what you want.
This should go in the appropriate Model file:
public function getProductName() {
$query = $this->database->query("SELECT * product_name FROM product"); /*this gets all the info you want, however I am not %100 on the names, so double check your database*/
if (isset($query){ /*says if array is not NULL and is set*/
return getProductName(); /* return the function */
}
else {$query = ""} /*else the array is NULL*/
{
This should go in your Controller:
$this->load->model('path/to/model/file') /*however you might not need this depending on which model file you place your query (model code)*/
$this->data['productName'] = $this->path_to_model->getProductName(); /*this passes it to your view file as the array productName*/
This should go in your View:
You will see certain HTML tags and foreach loops on your view page, you will want to basically copy the view code for displaying the array properly, however it should look something like this:
<tr>
<td>
<?php foreach ($productName->rows as $tempVariable) { /*this is roughly how you will get each product name from database table to print on a page, obviously if you want to display it next to its quantity you will need to change it around by using HTML and PHP code in conjugation, however I hope this has helped*/
echo $tempVariable; ?>
</td>
</tr>
I am working on a project which is designed in Codeigniter. I am new to the Codeigniter framework/php and trying to learn the same. Currently I have a page which displays the table of all the results. I want to have the option of being able to delete whichever row I want to. I've added the function in model and controller and a delete icon is present in the view but I am not sure how to co-ordinate the same.
Function in Model:
function delete_row($job){
$querystr = 'delete from jobs where job = \''.$job.'\'';
$query = $this->db->query($querystr);
$arr = $query->result_array();
$query->free_result();
return ;
}
Function in Controller:
public function delete(){
$this->load->model('Job');
$this->Job->delete_row($job);
$this->load->view('my_view');
return;
}
View:(my_view.php (snippet))
if($key==='job'){
echo "<input type = 'image' src = '/home/Downloads/DeleteButtonSmall.png' width='20' height ='15' name ='delete_box' >"; }
The view has lot of functions in it but this above line is the one which enable the delete image to all the rows visible on the display.
Please don't be harsh. Any suggestion on how to get this working. Also if the question isnt clear, feel free to post that in the comment. I will try to elaborate as much as I can.
Your question is not clear, but if you want to call a function in the controller (in this case delete) without refreshing you need to use ajax. and to give you more freedom use jQuery too.
here is a simple thing to give you an idea. http://jsfiddle.net/KV3WF/4/
in your controller you need to echo 1 if you deleted successfully and 0 if not.
i hope i helped in my answer if you found anything not clear please do ask.
if you want also you dont have to put onclick in html you can do it in javascript
$( document ).ready(function() {
$('#category').click(function(){ //you just give an id to whatever you want to select plus you can do it by selecting a class instead id..... so you can give multiple buttons the same class("category")
//DO the same ajax function in the jsfiddle.
});
//end of doc.ready
});
P.S. try to practice not to delete from the database, add a column named (hide) and update it to 1 (default is 0) when you want to delete.
Not sure if I understand your question, but from what I understand you are trying to delete a row based on what data you clicked
on your model you could try the Active Record Pattern for delete
Model
function delete_row($job){
$this->db->where('job', $job);
$this->db->delete('jobs');
// DELETE from jobs WHERE job = $job
}
On your controller, this is where you will pass the your identifier from the view so that it can interact with the model.
Controller
function delete($id = '')
{
$this->load->model->('Job');
$this->Job->delete_row($id);
redirect('to jobs view')
}
then on your view, you could define a link that calls your delete method in the controller and deletes a row based on the parameter you passed in the URI
say, if you pass something like this
www.example.com/controller/delete/worker
It would delete the row where job = worker
View
you could do it like this
<a href="controller/delete/worker">
<img src = '/home/Downloads/DeleteButtonSmall.png' width='20' height ='15' />
</a>
I am doing a small application. For that Ihave two table like sles and stores
The sales table looks like this
============
Sales
============
id
store_id
Stores
=============
id
store_name
store_location
store_code
description
I have done the model and CRUD for both tables. In stores table I have entered some vales as per the table.
Now in sales controller I have rendered both sales and stores. so here my action create looking like this
public function actionCreate()
{
$model=new Sales;
$stores = new Stores;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Sales'], $_POST['Stores']))
{
$model->attributes=$_POST['Sales'];
$stores->attributes=$_POST['Stores'];
$valid = $model->validate();
$valid = $stores->validate();
if($valid)
{
$stores->save(false);
$model->store_id = $stores->getPrimaryKey();
$model->save(false);
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
'stores'=>$stores,
));
}
and in sales(_form.php) is like this
<div class="row">
<?php echo $form->labelEx($stores,'store_name'); ?>
<?php echo $form->textField($stores,'store_name',array('size'=>60,'maxlength'=>80)); ?>
<?php echo $form->error($stores,'store_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($stores,'store_location'); ?>
<?php echo $form->textField($stores,'store_location',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($stores,'store_location'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($stores,'store_code'); ?>
<?php echo $form->textField($stores,'store_code',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($stores,'store_code'); ?>
</div>
Now here when I am doing a sales I want that when I will enter one store name by entering keys then it will start to show the related stores names and the store_location and store_code will be auto-fill. Now can someone kindly tell me how to do this? Any help and suggestions will be appreciable. Thanks a lot.
Edit
With this only one field can be autocomplete. But I want all the other related fields should be also autocomplete with this.
A few thoughts first, and then a general answer to your question.
First, a small niggle, you are really only validating the store model, because you reassign $valid right after checking the sale. Instead, the validation logic should be something more like this:
$valid = $model->validate() && $stores->validate();
If either is invalid, it will return false.
Second, I don't think this code is going to do what you want it to do. If you autocomplete the store information based on existing data and submit it back to the Create action, then your code will try to create a brand new store entry based on that information, introducing duplicate stores in your database. If you always created a brand new sale and a brand new store at the same time, this would work, but I'm pretty sure you don't want that.
Instead, to keep it simple this should be an action dedicated to creating only sales objects. Don't try to create a new store object, just start autofilling details into HTML span or div tags instead of into form fields. The only form field will be the field that is the store id, which will be added to your sales object to indicate the foreign key relationship.
Now, to get autofilling going on several fields, I am going to give you an outline and let you fill in the details. You are going to need a new action in your controller, and some Javascript on the page to handle the autofill.
public function actionGetStoreDetails($id) {
// Get the Store model associated with $id
// Create a JSON object based on this model. Hint, check out CJSON::encode()
// Return the result of the above function call.
}
Now you'll have a piece of Javascript on your view page that does something like the following, using jQuery as an example since it's already in Yii.
$(function () {
$('your-store-id-field-html-id-here').keyup(function () {
// Get the current value of the form field
// Make a $.get() request to the new action defined above, passing the ID
// In the callback function, you'll get a JSON object
// Take the elements of the JSON object, like store.store_name, and assign them to <span id="store_name"></span> type fields in your HTML.
});
});
I realize that this is not copy-and-paste code, but I hope it gives you a really good launching pad. You'll learn a ton if you take the time to fill in the blanks and figure out how to do it fully.
I have encountered something very, very weird. Working in VirtualBox, Ubuntu, Apache2, PHP, MySQL I got some very strange behaviour from one particular model.
I wanted to add ability to enter multiple language versions of the same string, say product name. I used jQuery to make nice tabs with languages and created temporary array to store all that information, used CActiveForm widget to collect and present data.
<?php foreach($languages as $language): ?>
<div id="tab_<?=$language->code?>">
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,"translations[$language->code][name]",array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,"translations[$language->code][name]"); ?>
</div>
</div>
[...]
So this is how I collect data into a $translations array. This is my $translations array:
$translations = array(
'name' => 'NewName',
'sub_name' => 'Subname'
);
Then I obviously assign it to a proper model in Controler action:
[...]
foreach ($translations as $key => $value){
$x = new Translations();
$x->language = $key;
$x->id = $product->id;
$x->name = $value['name'];
$x->sub_name = $value['sub_name']
$x->save();
}
[...]
Now there are also other fields that are only one per product:
[...]
<div class="row">
<?php echo $form->labelEx($model,'something'); ?>
<?php echo $form->textField($model,'something',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,"something"); ?>
</div>
</div>
And those are stored simply by
$product->save();
Everything is in a neat transaction.
HOWEVER....
What I get in result is like this (join on translations and product table):
id name subname something
1 NewN
2 NewName S
3 NewName Subname Som
4 NewName Subname Something
4 records when I only add ONE.... and more text I put in, more records are created. Split by random number of characters, sometimes as little as 4 sometimes as much as 12. This is repeatable but not always.... I am totaly dumbstruck by this behaviour.
Anyone ever saw anything like this and can shed ANY light on it?
Thanks in advance!
The problem could be coming in at many stages:
the form
the controller
binding the data from the form to the model
the model saving (ActiveRecord)
or even the database
So 'divide and conquer' your problem.
MySQL
Turn on your 'general mysql log' to see the queries that are being sent to MySQL. If they look like the weird forms you are seeing above, then it's not the database. It's unlikely you'll have any problems at this stage, but it's good to rule it out.
ActiveRecord
Then hardcode your values into the model. In your controller, just create an instance of the model and save it. Does that replicate the problem you're having? If so, it's a problem with your implementation of ActiveRecord. Try removing the relationships and work on that.
Controller
There could be something weird in your controller. Again, hardcode the data that you want to pass to the model when you create the instance.
Binding
It could be a problem with how you are binding data from the form to the model. Manually set the values of the form, then bind that data to the model as normal.
This is where back-end testing can really help you, as you can isolate what's working from what's not. Look into tools like Behat and PHPUnit.