How to generate input select in laravel blade form and customize its options value? - forms

I'm trying to create a laravel form that have an input select generating from array of strings coming from controller.
How can I set values of options manually?
In controller :
public function create()
{
$eventTypes = EventType::all()->lists('title');
return View::make('events.create')->with(compact('eventTypes'));
}
In view (blade) :
{{ Form::label('eventType', 'Type') }}
{{ Form::select('eventType', $eventTypes, null, array('class'=> 'form-control')) }}
And select created as :
<select class="form-control" id="eventType" name="eventType">
<option value="0">Sport Competition</option>
<option value="1">Movie</option>
<option value="2">Concert</option>
</select>
I just want to set values manually.

The value in the options is just the key of the array. The second parameter to the lists() method will let you choose a field to use as the key:
// use the 'id' field values for the array keys
$eventTypes = EventType::lists('title', 'id');
If you want to do something more custom than that, you'll need to manually build your array with the key/value pairs you want.
Edit
As mentioned by #lukasgeiter in the comments, there is no need to call all() first.
EventType::all()->lists() will first generate a Collection of all the EventType objects. It will then call lists() on the Collection object, meaning it will loop through that Collection to build an array with your requested fields.
EventType::lists() will call lists() on the query builder object, which will just select the two requested fields and return those as the array. It will not build any EventType objects (unless you select a field built by a Model accessor).

Related

Get an array with DomainObjects in a single Extbase ControllerAction argument

I'm creating an extbase extension to handle very simple product orders.
The model is:
Order --1:n--> OrderItem --1:1--> Product
To order a selection of products, the customer goes to checkout page and uses a Fluid based Order form. All selected products are available in the fluid template as {products}.
The OrderController->createAction processes new Orders by creating OrderItems from the given Products.
Writing the code I'd like to have would look like this:
class OrderController
{
public function create(Order $order, array $products)
{
foreach ($products as $product) {
$orderItem = new OrderItem()
->setProduct($product)
->setPrice($product->getPrice());
$order->addOrderItem($orderItem);
}
$this->orderRepository->add($order);
}
}
How to assign products to a Fluid form fields, in order to receive them as ControllerAction array argument?
How to trigger extbase to automagically provide an array of product objects to the ControllerAction?
I wonder if it is even possible to simplify the Controller createAction like shown below and assemble objects elsewhere:
public function create(Order $order) {
$this->orderRepository->add($order);
}
My suggestion for the fluid template would be:
// basic form with the order as main object
<f:form action="create" object="{order}">
// each order item with a product, using index to have no array with an empty index (Extbase does not like that)
<f:for each="{products}" key="index" as="product">
// Here you can set the product
<f:form.hidden prpoerty="orderItems.{index}.product" value="{product} />
</f:for>
</f:form>
This should be enough to use your single-line create action.
You can change the field type from select to whatever you want, but the __identity is mandatory to say Extbase which record it has to link.
When you want the orderItems to be new created, you need to remove the __identity field.

How to retrieve only part of a document back in a call

I need to retrieve only part of a document and call it via a helper so that I can render a subtemplate multiple times as the part I require to pull from the db is an array of object itself. I have the following as the fields. What I need to do with my helper is only retrieve the ordersDispatch array of one particular document which would be uniquely called by the tripNumber field.
I have tried several things but nothing has come close to only having an array of the objects in the orderDisptach field be returned in a fashion that it can be used by the helper to render my subtemplate for each object in the array.
{
tripNumber: companyRecord.lastTripNum + 1,
custID: $('input:hidden[name=orderCustomerId]').val(),
custContact: $('input:text[name=customerContact]').val(),
custEmail: $('input:text[name=customerEmail]').val(),
trailerSealNum: $('input:text[name=trailerSealNum]').val(),
orderBroker: $('input:text[name=orderBroker]').val(),
orderEquipment: $('input:text[name=orderEquipment]').val(),
orderLoadNum: $('input:text[name=orderLoadNum]').val(),
orderPlacedDate: $('input:text[name=orderPlacedDate]').val(),
orderPrivateNotes: $('textarea[name=orderPrivateNotes]').val(),
orderPublicNotes: $('textarea[name=orderPublicNotes]').val(),
orderCurrency: $("input[name=orderCurrency]:checked").val(),
orderCharges: $('input:text[name=orderCharges]').val(),
orderFUELCheck: $('input:checkbox[name=orderFUELCheck]').is(':checked'),
orderFUELPerc: $('input:text[name=orderFUELPerc]').val(),
orderFUELTotal: $('input:text[name=orderFUELTotal]').val(),
orderGSTCheck: $('input:checkbox[name=orderGSTCheck]').is(':checked'),
orderGSTPerc: $('input:text[name=orderGSTPerc]').val(),
orderGSTTotal: $('input:text[name=orderGSTTotal]').val(),
orderPSTCheck: $('input:checkbox[name=orderPSTCheck]').is(':checked'),
orderPSTPerc: $('input:text[name=orderPSTPerc]').val(),
orderPSTTotal: $('input:text[name=orderPSTTotal]').val(),
orderTAXCheck: $('input:checkbox[name=orderTAXCheck]').is(':checked'),
orderTAXPerc: $('input:text[name=orderTAXPerc]').val(),
orderTAXTotal: $('input:text[name=orderTAXTotal]').val(),
orderTotalCharges: $('input:text[name=orderTotalCharges]').val(),
ordeBlockInvoicing: $('input:checkbox[name=ordeBlockInvoicing]').is(':checked'),
orderExtraCharges: orderExtraCharges,
orderPickups: puLocations,
orderDeliveries: delLocations,
orderDispatch: dispatchLocations,
createdDate: new Date(),
createdUser: currentUser.username
Any help in building a helper that will accomplish this would be greatly appreciated as I am new to meteor and mongo.
The following helper should give you what you need:
Template.oneTrip.helpers({
orderDispatch: function(tn){
return Trips.findOne({ tripNumber: tn }).orderDispatch;
}
});
Trips.findOne({ tripNumber: tn }) gets you an individual document and .orderDispatch returns the value of the orderDispatch key which in your case will be an array.
html:
<template name="oneTrip">
{{#each orderDispatch this._id}} <!-- assuming you've already set the data context to an individual order -->
{{this}} <!-- now the data context is an element of the orderDispatch array -->
{{/each}}
</template>

Put the current value of combobox or the html select box from DB

I Have this code
{{Form::select('area_id', Area::lists('area_description','area_id') ,'',array('class' => 'form-control'))}
How do I get the current value of Select box from database. BTW I'm using Laravel with Blade Template.
You can use use something like this:
{{
Form::select(
'area_id',
Area::lists('area_description','area_id'),
old('area_id'), // or Input::old('area_id')
['class' => 'form-control']
)
}}
In this case, instead of using Area::lists('area_description','area_id') inyour template use pass it from your controller, for example (in your controller):
$area_ids = Area::lists('area_description','area_id');
return view('view_name')->with('area_ids', $area_ids);
Then use the following in your template:
{{ Form::select('area_id', $area_ids, old('area_id'), ['class' => 'form-control']) }}
For Laravel-5.1.x
The lists method now returns a Collection instance instead of a plain
array for Eloquent queries. If you would like to convert the
Collection into a plain array, use the all method:
$area_ids = Area::lists('area_description','area_id')->all();
Check the upgrade guide for details.
I Have already solved my own problem wew.
with this code:
{{Form::select('area_id', $area_ids , $person->area_id ,array('class' => 'form-control'))}}
I forgot that it should be the id or the option value not the option content. The option that I mean is the <option> tag.

How to generate form using Illuminate/HTML and database values in Laravel?

I saw this question: Generate drop-down list input with values from DB table, but the answer was not clear.
So, how can I generate form using Illuminate/HTML and database values in Laravel?
It's this simple.
First, you have to pass an array with the select values from the controller:
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$categories = Category::lists('name','id');
return view('myformview', compact('categories'));
}
Where "Category" is the model I want to retrieve data from. Note I am passing two values to the array. The first one is the text will be displayed in the select, and the second one is the value of the option.
Let's see now the form:
{!! Form::label('category_id', 'Category:') !!}<br>
{!! Form::select(
'category_id',
$categories
)
!!}
The first parameter of Form::select is the name of the select. The second one is the array with the options values.
In my particular case I get back this HTML code:
<select id="category_id" name="category_id">
<option value="5">First category</option>
<option value="6">Second category</option>
<option value="7">Third category</option>
</select>
I hope this will be helpful for you. I tested it in Laravel 5

Zend Framework : Setting up default values for part of the multicheckbox element options not possible

I'm writing this question cause I have difficulties setting up default values for a _MultiCheckbox element of a Zend Framework 1.9.3.
I create Zend_Form_Element_MultiCheckbox with multiple options like this:
$multiCheckbox = new Zend_Form_Element_MultiCheckbox( 'elId',
array ( 'disableLoadDefaultDecorators' =>true ) );
$multiCheckbox ->setName( 'elId' )
->setLabel('elId')
->setRequired( false )
->setAttrib('class', 'inputtext')
->setDecorators( array( 'ViewHelper' ) )
->setMultiOptions( $options );
where the $options array is an associative array 'key' => 'value'. The field is displayed just fine and I can get all the checked values for that element.
When returning to that page I need to restore from the DB the whole list of options again and mark the checked ones. I have tried to do it like that:
$multiCheckbox ->setValue( $defaults );
where $default is array, containing elements of type 'checked_option_field_id' => true(eg. array( '1222' => true, '1443' => true ) ). That action checks ALL the checkboxes and not only the once I need and I have passed to the setValue() method.
I have tried to pass just an array containing elements of type 'checked_option_field_id', (eg. array( '1222', '1443' ) )but that also doesn't work - NONE of the checkboxes is checked.
I have used the form setDefaults() method with those two kinds of arrays, but the results are same - as this method uses again setValue() for each element.
MultiCheckbox element is rendered like that ( result when try to set checked value for only one option ):
<label for="elId-1222"><input type="checkbox" name="elId[]" id="elId-1222" value="1222" checked="checked" class="inputtext">BoRoom </label><br />
<label for="elId-1443"><input type="checkbox" name="elId[]" id="elId-1443" value="1443" checked="checked" class="inputtext">BoRoom Eng2 </label><br/>
That element populates the checked option values in the elId[] array. That is the element name.
setDefaults() form method gets all form elements by name and commit their default values by calling setDefault() form method and after that setValue() element method. So my multicheckbox element has name elId ( it does not get all the element options one by one ) and set default values for all options instead of just the given in the array.
That is how I see it and I can't find solution how to set default values only for some of the options of a multicheckbox element.
Chris is correct that setValue() expects an array of values to be 'checked' (not an array of bool values keyed by your option IDs).
If you are looking for the logic behind the form generation, don't look at the Zend_Form_Element object (or the many extended elements from it), look at the Zend_View_Helper objects. Specifically the Zend_View_Helper_FormRadio object.
When generating the HTML the options array is looped, then the value is checked against the value array - the array passed to setValue(), using in_array().
From Zend_View_Helper_FormRadio line: 150
// is it checked?
$checked = '';
if (in_array($opt_value, $value)) {
$checked = ' checked="checked"';
}
Not sure what that's not working for you, but if you're passing:
$element->setMultiOptions(array('1111' => 'Some Label',
'2222' 'Some Other Label',
'3333', 'Not Selected Label'));
$element->setValue(array('1111','2222');
It should work. Maybe if you could include some code it would be easier to see what's going on?
The setValue() expects a array with those values that need to be checked, in this case for example you need to pass a array with values 1222, 1443 for them to be marked as checked.
You need to serialize the checkbox value before insert in database. To show the database value selected again you have to unserialize the data to show.
The details you can read from following link
http://abser-web-tips.blogspot.com/2010/09/zend-framework-multiple-check-box.html
Thanks