I Want to Select a value in drop-down automatically based on controller in
codeigniter,when a view is loaded then select field value is auto select by the
controller as per requirment. basically i want to manage the drop down from
controller.
What should i need to do?
For Example:-
My View File Code is
<select id="category">
<option value="first">first</option>
<option value="second">second</option>
<option value="Third">Third</option>
<option value="fourth">fourth</option>
</select>
Here is my controllers
firstcontroller,secondcontroller,thirdcontroller,fourthcontroller
Required Code:- firstcontroller load select field value is first.
same as secondcontroller - second then third, fourth are in same way.Is there a way to manage the slect field from controller.
Could you not just pass an argument to your view telling it which controller is being handled?
Alternatively if you got an instance of the CI object you could parse the URL to see which controller was requested.
$CI =& get_instance();
$controller = $CI->uri->segment(1);
$controller_pretty = str_replace('controller', '', $controller);
Best way to make it, is to deal with URI Class by using $this->uri->segment(n).
In your controller, lets say in controllers/firstcontroller.php write the next code:
class Firstcontroller extends CI_Controller{
public function index()
{
// Load form helper
$this->load->helper('form');
// First we need to catch first segment of the URL as it's name of the controller
// so $this->uri->segment(1) will be the first part/segment after your base url (www.website.com/segment1)
$current_controller = $this->uri->segment(1);
// Array of available options for dropdown element
$dropdownOptions = array(
'firstcontroller' => '1st Controller',
'secondcontroller' => '2nd Controller',
'thirdcontroller' => '3rd Controller',
'fourthcontroller' => '4th Controller',
);
// Assign a form_dropdown function to variable for later use in our view file
// form_dropdown will generate a <select /> html element for you
$data['dropdown'] = form_dropdown('dropdown_name', $dropdownOptions, $current_controller);
// Load a view with datas
$this->load->view('samplepage', $data);
}
}
And in your views/dropdownpage.php file put this:
Dropdown:
<?php echo $dropdown;?>
Related
I have to do one of these pages with a form that will search for a meal and its recipe according to a dishtype or cuisine type etc...
Here is my function to return the view but there is an error in the line that i show in bold below :
public static function SearchPage()
{
$DishType = DishType::getAllDishType();
$CuisineType = CuisineType::getAllCuisineType()
return view("vueRecipeSearch", [
'DishType' => DishType::getAllDishType(),
CuisineType::getAllCuisineType()
]);
}
And Here is a part of a view where i would like to use a variable:
<label for="DishType">Dish type :</label>
<select id="DishType" name ="DishType">
#foreach($DishType as $Dish)
<option value="Dessert">{{$Dish->dish}}</option>
#endforeach
</select>
and i'd like to do the same with the cuisine type but can't because I don't know how to return multiple variables..
return view("vueRecipeSearch", [
'DishType' => DishType::getAllDishType(),
'CuisineType' => CuisineType::getAllCuisineType()
]);
Then you have access in your blade file with the array keys: DishType and CuisineType.
Obviously possible to send two variables from controller to blade.
$dishType' = DishType::getAllDishType();
$cuisineType = CuisineType::getAllCuisineType();
return \view("vueRecipeSearch", compact('dishType', 'cuisineType'));
And on the blade file, you have to access these two variables like by $dishType and $cuisineType.
return view ('vueRecipeSearch',compact('dishType', 'cuisineType'));
No Need Add Forward Slash or Backward Slash. Simple
I am currently working on a front-end form using ajax data request. In my code i have this in the php block that gets displayed in a partial when a category in select-box is selected to show subcategories.
function onChangeCat()
{
$this['subs'] = Cat::whereHas('parent', function ($query) use($cats){
$query->where('cats','=', $cats );
})->pluck('cat_title', 'id');
I am trying to connect it to a route so that when a user clicks on a category, related subcategories get displayed in the second select-box.
This is my route file with #id of category select-box as parameter
Route::get('ajax/{cats}' , function () {
//
return json_encode();
});
How do i connect the codes in php block and routes to work so that only related subcategories of category is displayed?
To pass current element value to Ajax Handler you need to give it name - attribute and add data-request="onChange" handler. all other stuff will be handled by October CMS Ajax Api
<select name="country" data-request="onChange">
<option id="1">A</option>
<option id="2">B</option>
<option id="3">C</option>
<option id="4">D</option>
</select>
In your Ajax handler
function onChange() {
$id = post('country'); // as we name it `country` for select
// ^ - this will be your selected value [id]
return ['data' => 'some data'];
}
Further process data [ IF its needed ] Other wise you can just use data-request-update="calcresult: '#result'" with returning Html Markup
<script>
function myFunction(data) {
console.log(data)
}
</script>
<select
name="first"
data-request="onChange"
data-request-success="myFunction(data)">
...
</select>
Up on success-full request this will call myFunction with return data in our case it will be {'data':'some data'} JSON Object, whatever you return from the Ajax-Handler.
if any doubt please comment.
October CMS has a $this->params() method which can be called to get url parameters from the current request (see here). Your code should look like the following (untested):
Route::get('ajax/{cats}' , function () {
$results = Cat::whereHas('parent', function ($query) {
$query->where('cats', $this->param('cats'));
})->pluck('cat_title', 'id')->all();
return $results;
}
I want to get a list of productTypes from the database and output them to a dropdownlist which will then be used to ajax populate a second dropdown list.
Step 1: Controller gets productTypes from database
Step 2: Controller converts the productTypes object to a list
Step 3a: Output list to test in view
Step 3b: Populate a dropdown with the list view
Snippet of controller
public function init()
{
$this->dynamicTypes();
$this->render('calculator', array('types' => $this->_types));
}
public function dynamicTypes()
{
$this->_types = CHtml::listData(ProductType::model()->findAll(), 'id', 'type');
}
View File Snippet
<?php
// Step 3a (this works fine)
echo '<pre>';
print_r($types);
echo '</pre>';
// Step 3b - Returns an error
echo $form->dropDownList('productTypes',1, array($types));
?>
<?php $this->endWidget(); ?>
</div>
With step 3b, I have tried the following:
echo $form->dropDownList('productTypes',1, array($types));
Error Msg: get_class() expects parameter 1 to be object, string given
According to http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail, the dropDownList method takes the following arguments:
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))
where the first argument is a string indicating the name of the input field.
What have I done wrong and how can I fix this?
UPDATE
echo CHtml::dropDownList('productTypes',1, array($types));
seems to work, but when I look at the dropdown in the view, for some reason, there is a 0 in the dropdownlist. For some reason, it is putting the options into an optiongroup
<select name="productTypes" id="productTypes">
<optgroup label="0">
<option value="1">Scrap</option>
<option value="2">Coin</option>
<option value="3">Bar</option>
</optgroup>
</select>
SOLVED:
Removed array($types), replaced with just $types
echo CHtml::dropDownList('productTypes',1, $types);
Seems like the $form is an object of the CActiveForm class. This version of the dropDownList method takes an instance of CModel class.
See the method signature here CActiveForm::dropDownList
Use
echo CHtml::dropDownList('productTypes',1, array($types));
instead of
echo $form->dropDownList('productTypes',1, array($types));
Q1 : How to call a function of component from view?
one of my function is using most of the controllers.
public function actionDynamicdepartment()
{
//Department
$data = Department::model()->findAll('p_id=0 AND company_id=:company_id', array(':company_id'=>(int) $_POST['company_id']));
$data = CHtml::listData($data,'id','name');
$dddepatment = "<option value=''>Please select a department</option>";
foreach($data as $value=>$name)
$dddepatment .= CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
//Section and Team
$ddsection = "<option value=''>Please select a section</option>";
$ddteam = "<option value=''>Please select a team</option>";
// return data (JSON formatted)
echo CJSON::encode(array(
'dddepartment'=>$dddepatment,
'ddsection'=>$ddsection,
'ddteam'=>$ddteam
));
}
I want to put it into component or some place.
And I want to call those function from my views. e.g
<div class="row">
<?php echo $form->labelEx($model,'company_id'); ?>
<?php
$records = Company::model()->findAll();
$company = CHtml::listData($records, 'id', 'name');
echo $form->dropDownList($model,'company_id', $company, array('prompt'=>'Please select a company',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('department/dynamicdepartment'), //url to call.
'dataType'=>'json',
'data'=>array('company_id'=>'js:this.value'),
'success'=>'function(data) {
$("#FaMovehistory_department_id").html(data.dddepartment);
$("#FaMovehistory_section_id").html(data.ddsection);
$("#FaMovehistory_team_id").html(data.ddteam);
}',
)
)
);
?>
</div>
Or
Q2 : put those function at one of the controller (department.php). And can I call those function from different view?
Q3 : if do as Q2, is there any traffic?
What I use to do is to define a CWidget (like Dmitry said) and then I create some functions (I tend to make them static, as if it was a library), so if, for instance, your Widget is called "Departments", you could do something like this:
Yii::import("application.components.Departments");
Departments::actionDynamicdepartment();
Pretty straightforward. You could, for this situation, return that CJson instead of echoing. However, you may not be interested in having a static response from this method.
For your last questions, I tend to approach the population of dropdowns in a more classic manner, having an ajax call (I use jquery) requesting a central controller and passing some variables to it. That, of course, generates traffic.
So, to sum up, if you want to recieve a list of departments and avoid changing it during the current page, you could go for a widget/component. If, on the other side, your dropdown needs to be responsive along with the rest of the items in a form, a controller's action is your best (and probably unique) option.
You need to create a widget instead of component.
Each widget has its own view, and you will be able to describe in its class logic of his behaviour (move the code from the controller) Then call it in the main view:
<?php $this->widget('path.to.your.widget') ?>
Read more: http://www.yiiframework.com/doc/api/1.1/CWidget and http://www.yiiframework.com/doc/guide/1.1/en/basics.view#widget
I'm trying to merge 3 models to create a fourth one. I have model1, model2 and model3 and I want to merge them into modelMaster. I've also created controllers for all of them. When I call modelMaster/create action, I render the modelMaster/create view which renders the modelMaster/_form view. Inside this _form view, I also want to render model1/_form, model2/_form and a CHtml::dropDownList(), wich takes datas from model3. However, this doesn't work. How can I combine these three different views into one another?
If you try to skip the form generate from the _form views and use unique model names, I think you can use this manual: single form with more models
So the generate of the form definition handles always the parent view and the _form's only the inputs
The other way to use single model in views, create a form model by extend CFormModel, and handle the data binding between this model and the wrapped submodels
If you want to nest several forms into one master form you have to adjust the form templates accordingly. All of your modelMaster/create, model1/_form, model2/_form-views create and render a new CActiveForm (and thus several <form> tags).
Since you cannot nest form-elements in html (how should html know which action to pass the data to) you have to avoid this by doing the following:
Extract the inputs of the form you want to nest into a new view, e.g. model1/_formInputs would look like
...
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name');
<?php echo $form->error($model,'name');
...
alter the model1/create and the other views and get a reference to the form created there, by assigning the return of $this->beginWidget to the variable $form (if not already done):
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'foo',
)); ?>
replace the former input fields with
<?php $this->renderPartial('model1/_formInputs', array('form' => $form); ?>
Now, for example the old model1/create-view should work as expected
To get your multi-model-form working you just have to get the reference to the form created in modelMaster/create and use it to renderPartial all */_formInputs you require. Please also remember to include the models for the inputs into the renderPartial-call. So modelMaster/create would look something like:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'foo',
)); ?>
/* Master Inputs here */
// Rendering other models' inputs
<?php $this->renderPartial('model1/_formInputs', array('form' => $form, 'model' => $model1); ?>
<?php $this->renderPartial('model2/_formInputs', array('form' => $form, 'model' => $model2); ?>
/* Render Form Buttons here */
<?php $this->endWidget(); ?>
Submit with Ajax, in Yii it is easy to do and it will keep things easy to understand in the controllers, each controller will have a save and respond with json to confirm the save. There is already ajax validation.
/**
* Performs the AJAX validation.
* #param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='employee-form')
{
$valid = CActiveForm::validate($model);
if(strlen($valid) > 2) {
echo $valid;
Yii::app()->end();
}
}
}
As you can see I have modified it to return the error if there is one (validate returns [] if it is valid, I should probably check for that instead of strlen >2 ), otherwise let the script continue, in this case it will go to the save function.