I want to make two drop down
Select Group
Select Members (multi Drop Down)
When user select the first drop down (Group), i want to populate the Members Multidropdowen with the members of selected Group dynamically.
Select Members is a multidropdown and User can select more then One members.
I am able to accomplish dependent drop-down, or an independent Multidropdown, but i am not able to integrate these two.
I have tried the extensions http://www.yiiframework[dot]com/extension/emultiselect and http://www.yiiframework[dot]com/extension/echmultiselect.
You to implement an ajax update for the first dropdown to update the 2nd one:
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
and in your controller you can have :
public function actionDynamiccities()
{
$data=Location::model()->findAll('parent_id=:parent_id',
array(':parent_id'=>(int) $_POST['country_id']));
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
Source:
http://www.yiiframework.com/wiki/24/
Related
I want to set the default value of a resource field to the authenticated user's id. I have a model called Note which has a one to many relationship with Game and User.
User hasMany Note
Game hasMany Note
Note belongsTo User
Note belongsTo Game
In Laravel Nova my fields looks like this for the note
ID::make()->sortable(),
Text::make('Note', 'note')->onlyOnIndex(),
Textarea::make('Note', 'note')->alwaysShow(),
BelongsTo::make('Game', 'game')->hideWhenCreating()->hideWhenUpdating(),
BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating(),
DateTime::make('Created At', 'created_at')->hideWhenCreating(),
DateTime::make('Updated At', 'updated_at')->hideWhenCreating(),
Because I am referencing the Note on the Game Nova resource, when I create a Note, the game_id column is populated correctly. But, I want the user_id column to be the value of the authenticated user. It does not seem to work like this, how would I accomplish it?
If I understand correctly from the line BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating() you're trying to set a default value for the column without showing the field on the form?
I don't think this is possible in this way. As soon as you use the hide functions the fields aren't rendered and will never be passed along with the request. I tried this, and the user_id field was never sent with the request.
I think there are two ways to do this:
Show the field in the form and set the default value using the metadata (and perhaps making the field read-only for good measure).
BelongsTo::make('Created By', 'user', 'App\Nova\User')->withMeta([
"belongsToId" => auth()->user()->id,
])
See this part of the Nova docs
Or use the Eloquent creating event. The following will go in your Note model.
public static function boot()
{
parent::boot();
static::creating(function($note)
{
$note->user_id = auth()->user()->id;
});
}
Granted, the above method is a bit simple. You'd be better off using proper event listeners.
Sidenote: from an architectural point of view, I'd go with option 2. Setting a default value without getting the end-user involved sounds like a job for the Eloquent model, not for a Nova form.
You can use a method resolveUsing(). An example
<?php
//...
Select::make('My Select', 'my_custom_name')
->options(['a' => 'a', 'b' => 'b', 'c' => 'c'])
->resolveUsing(function ($value, $resource, $attribute) {
// $value = model attribute value
// $attribute = 'my_custom_name'
return 'b';
});
I have a team-based app where one database services multiple teams. We have a custom fields table which allows for each team to create their own custom fields they want to create in addition to the global fields universally available to every team. Each custom field record has a name, type, and church_id field in the create.blade input form. Now with the nature of having separate teams, we need a system where they could create their own custom field that might share the same name of a custom field created and connected to another church team. This has been done and works just fine.
The problem is that we need to also make it so that only one custom field by a specific name can be created within the same church team. We do not want duplicate fields within the same church team. And herein lies my question, what is the best way in the store function to keep duplicates from occurring within the same team-based records. I have looked at firstOrNew, firstOrCreate, and updateOrCreate but which one is best suited to my need.
As I said, the fields we have in the form are 'name', 'type', and 'church_id' and these correspond to the custom field DB fields as 'name', 'type', and 'created_by_team_id'. What I need to have happen is for the system to check to see if there is a record matching the input 'name' that shares the same 'created_by_team_id' as the input 'church_id. If there is a record by that 'name' which also shares a marching 'id' then the system recognizes that as a duplicate and does NOT create a new record in the DB. But, if there is a record that shares the same 'name' but does not share the same 'created_by_team_id/church_id' then the system goes ahead and creates that new record because it is not a duplicate.
This is my create function:
{
if (! Gate::allows('custom_field_create')) {
return abort(401);
}
if (auth()->user()->role->contains(1)) {
$churches = Team::all();
$churchArr = array('empty' => 'Please select a church...');
foreach ($churches as $church) {
$churchArr[$church->id] = $church->name;
}
$churches->created_by_id = auth()->user()->id;
$church_id = null;
} else {
$churches = false;
$church_id = auth()->user()->team_id;
$churchArr = [];
}
return view('admin.custom_fields.create', compact('churches', 'churchArr', 'church_id'));
And this is my store function:
{
if (! Gate::allows('custom_field_create')) {
return abort(401);
}
$custom_field = CustomField::create($request->all());
$custom_field->created_by_team_id = $request->input('church_id');
$custom_field->save();
return redirect()->route('admin.custom_fields.index');
As I stated, I have been looking at and trying the firstOrNew, firstOrCreate, and updateOrCreate methods but all my attempts have been a failure. What would be the proper way to implement one of these methods to achieve my goals using my fields and DB criteria to avoid creating duplicate fields by the same name within the same team-based id?
I found the workable solution to be updateOrCreate. This allows the use of both 'name' and 'type' to be needing to be found to match. If either one is found but not the other it will create a new record. If both are found it just updates the record, which by nature avoids the duplicate creation. This allows the 'church_id' field to just added on as a filler rather than using it as one of the fields keyed on to.
$custom_field = CustomField::updateOrCreate(['name' => $request->input('name'), 'type' => $request->input('type')]);
$custom_field->created_by_team_id = $request->input('church_id');
$custom_field->save();
I have a view about holidays where a user uses a form to choose a place to travel and a hotel. It has two models: HolidaysPlaces and HolidaysHotels.
The user have to fill the form in this order using the view:
The user completes the fields called Place and City (related with the HolidaysPlaces model).
The user checked a checkbox if he/she wants to choose a hotel. It able a field called Hotel (related with HolidaysHotels model).
The user completes that field.
The user press a Create button.
The controller receives and saves both models.
But the problem is when the user doesn't select the checkbox (number 2 of the list): The Hotel fieldis still required (with the red asterisk as defined in its model file). So the Create button doesn't work in this case.
How can I disabled the required feature?
Add a scenario for this case in your HolidaysHotels model, and include only the fields that you want checked.
Example: If you have 3 fields name, date and age that are required, create a scenario for two only, and set the scenario in the controller. Only those two fields will be checked.
In model:
public function scenarios(){
$scenarios = parent::scenarios();
$scenarios['create'] = ['name', 'date'];
return $scenarios;
}
In controller:
$holiday = new HolidayHotels();
$holiday->scenario = 'create';
To know more about scenarios: http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios
You can add some condition based validation in your model rules. Here is the snippet for both client and server validation. You can many conditions inside the function block.
['field-1', 'required', 'when' => function ($model) {
return $model->check_box == '1';
}, 'whenClient' => "function (attribute, value) {
return $('#checkbox-id').is(':checked') ';
}"],
The easiest way to solve it is to send the model with empty strings. Then the controller checks if the strings are empty. If so, the model is not saved. Else, it is saved.
It was the only way that works for me.
I have the following database structure:
Enquiries
id
total_widgets
total_amount
customer_id
Customers
id,
first_name,
last_name
Using the form when you are creating an Enquiry you can enter the Customers details into the section and this will store using firstOrCreate and then get the id in order to link to Enquiry to the Customer
Now, the issue is that this is all done inside the store method within the Customers controller, like the following:
public function store(Request $request)
{
$rules = array(
"first_name" => "required",
"last_name" => "required",
"total_widgets" => "required"
);
// Handle validation
// Create customer
$customer = \App\Customers::firstOrCreate(['first_name' => $request-
>get('first_name')]);
$enquiry = new \App\Enquiries();
$enquiry->customer_id = $customer->id;
$enquiry->save();
}
The issue with doing it like this is that it's not separated out and that if the process of creating a customer changes, then I would need to change this a lot of times. (Everytime I have a section which requires a customer)..
Is there a better way to do this? For example, should the customer be created separately and then the id is passed into the $request?
Another way of doing this is :
1) In Enquiries form add button called "add new customer".
2) When you click on this button a modal will appear and then fill details click submit.
3) On clicking submit make an ajax call to Customercontroller and insert the data then return the last inserted id.
4) Now you can see the new user in drop down box(There will be some drop down for selecting the user) of enquirey form just select it and then press submit.
5) It will passed to the enquirey controller and and store it.
Hope this will help you.
I've created a button within the Admin theme, which is named 'Create order for Johnsons'
Basically on this button I want to point it to the new create order screen for customerid 3 and store 2. Something like this:
$key=Mage::getSingleton('adminhtml/url')->getSecretKey("sales_order_create","index");
echo $COUrl=Mage::helper("adminhtml")->getUrl("adminhtml/sales_order/new/",array("customer_id"=>"3","key"=>$key));
Please can anybody help me?
You don't need to specify the key, getUrl does that for you when in an admin context.
echo $this->getUrl('*/sales_order_create/start', array('customer_id' => 3));
When using start like this it wipes all parameters except customer_id so a store cannot be specified. It will respect a store_id parameter if you change the URL to */sales_order_create/index but that does not start a new order so it would be problematic. To get that to work you will have to create a new controller and action for your own use and make it almost exactly like Mage_Adminhtml_Sales_Order_CreateController::startAction():
/**
* Start order create action
*/
public function startAction()
{
Mage::getSingleton('adminhtml/session_quote')->clear();
$this->_redirect('*/sales_order_create', array(
'customer_id' => $this->getRequest()->getParam('customer_id'),
'store_id' => $this->getRequest()->getParam('store_id')
));
}
If you want to create a new customer instead of choosing one upon creating a new order you have to set customer_id as false this way:
Mage::getModel('adminhtml/session_quote')->setData('customer_id',false);
Why? Because using
$this->getUrl('*/sales_order_create/any_action_controller', array(
'customer_id' => false
));
won't help for the reason of implementation in Sales/Order/CreateController
if ($customerId = $this->getRequest()->getParam('customer_id')) {
$this->_getSession()->setCustomerId((int) $customerId);
}
As you can see there's "int" there that will convert anything you send through and we need false to be set as customer_id since otherwise Magento will create grids first.