Yii - Populating a dropdown list - php

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));

Related

CRUD for global constants array codeigniter

I have an array defined in the constants.php file:
define('cancel_reasons', json_encode(array(
'Service(s) are no longer needed',
'Choosing another company to work with',
'Disatisfied with service(s) provided',
'Service(s) are too expensive', )));
I want to know how I can perform crud operations on this array. In my dashboard view, I have a button called "cancel reasons" which I send to a controller, and loads a page which reads the current items in the array. Here is my code for reading the array in the controller page which displays as a dropdown select option:
public function crudCancelConstants() {
//View array of cancel_reasons in constants.php
$reasons = json_decode(cancel_reasons);
echo '<h5> View all cancellation reasons below: </h5>';
echo '<select>';
echo '<option value="Select" selected>View Reasons</option>';
foreach ($reasons as $key => $value) {
echo ('<option value="'.$reasons.'">'.$value.'</option>');
}
echo '<select>';
}
So how do I go about adding "add, delete, and edit" functionality to this array? Also, would passing this array into a view instead of a controller make it easier to implement? Thanks in advance.

How to use route for dependent relationship in octobercms?

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;
}

Select a value in drop-down automatically based on controller in codeigniter?

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;?>

Populate form fields from database using Codeigniter

i am trying to populate two form fields from data that is retrieved from a database, in order for the user to update them. The table is called records and it is quite simple:
Record_ID
title
content
My model:
function get_data()
{
$r = $this->uri->segment(3);
$query = $this->db->get_where('records', array('Record_ID' => $r));
return $query->result();
}
My controller:
function set_values()
{
$data = $this->entries_model->get_data();
$this->load->view('update_view', $data);
}
and my update record view:
<?php
echo form_open('site/update',$data);?>
Title:
<?php echo form_input('title',set_value('title'));?>
Content:
<?php echo form_input('content',set_value('content'));
echo form_submit('submit', 'Submit');?>
<?php echo form_close();?>
The problem is that i get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/update_view.php
Line Number: 10
My question is twofold:
How do i access this data in my view form and
how do i populate the respective fields with it.
I am new to Codeigniter, my questions may look simplistic but any help would be appreciated. Thanks in advance.
There are a few things going on here:
$data is an array or object that is passed to a view. It's ELEMENTS are then available as variables in the view. So, $data['myelement'] = 'somevalue' in the controller would be accessed as $somevalue in the view.
If you pass a 2nd parameter to the form_open() method, it is expected to be a key/value pair of attributes for the tag that will be generated. like, array('class' => 'form_class', 'id' => 'form_id')
If you want to set the values of your form inputs, use the view helper function set_value(). In your case, use the controller to set elements in the $data array you'll pass to the view. $data['form_values'] = array('title' => $title, 'content' => $content);
Then, in the view:
You should pass a array to your view file. So replace:
$data = $this->entries_model->get_data();
with:
$data['entries_data'] = $this->entries_model->get_data();
and on your view file replace:
echo form_open('site/update',$data);?>
with:
echo form_open('site/update',$entries_data);?>
first you need to pass data in proper way
replace
$data = $this->entries_model->get_data();
with:
$data['data'] = $this->entries_model->get_data();
for setting value in set_value you need to do the in-line condition check to check either data is an object or not if object then put value other wise just empty
<?php echo form_input('title',set_value((is_object($data)?$data->title:'')));?>
you have to do the same thing for your all form fields
Jcory has answered your question but let me add a little to it.
In you model instead of return $query->result(); do this return $query->row(); this is because using returning a return object requires that you should loop through the resultset in your view
Instead of $data = $this->entries_model->get_data(); do this $data['entry'] = $this->entries_model->get_data();
In your view do this <?php echo form_input('title',set_value('title',$entry->title));?>
I hope these changes may solve the problem

ZEND: Cannot Access Post Data

Greets.
{{Solved}}
In order to get POST data you MUST use $this->formHidden in order to hold all the data. Even though variables are inside the they don't get passed if they aren't in some sort of form item.
I am unable to access post data in ZEND.
Path of User -
START
INDEX PAGE
->Submit Page
->Pay Page
I created a controller, extended the Zend Controller, and added an action called payAction. The user can go from the Index Page to the Submit Page. After I have all their data inside variables, I used a form and a submit button to go to the "pay page". However, I cannot get any of the POST data.
public function payAction()
{
$data = $this->getRequest();
}
I have tried putting getRequest, getParam, getRawBody inside that controller function.
In the page itself I have tried.
echo 'Hello';
echo $request;
echo $data;
echo $_POST['payZip'];
echo $_POST['data'];
echo $_POST[$data];
echo $request;
echo $this->values['payZip'];
echo $payZip;
echo $this->values['shippingDone'];
echo $stuff;
Is there ANYTHING I can place in my controller or in my view in order to get my post data? I used a form method="post" and a button and it DOES allow me to get to the page. I can see Hello. But NONE of the post data is available.
Any assistance would be appreciated.
Thank you.
-- Update
$data = $this->getRequest();
$param = $this->_request->getParam('payZip');
if($this->getRequest()->isPost())
{
print_r($this->_getAllParams());
echo $param;
}
Doing that gives me -
HelloArray ( [controller] => wheel [action] => pay [module] => default [shipping] => UPS Ground [payPal] => Secure Payment System )
But I still can't print payZip... I did echo and nothing comes out.
To get parameters from Zend Framework you need to do this in the Action Controller:
$data = $this->_request->getParams();
You can also get individual params like this
$param = $this->_request->getParam('payZip');
What it appears your doing wrong is you're only getting the "request object". You need to then call that objects method to get the request data.
Here's some simple code I often use when testing parameters:
public function indexAction()
{
#::DEBUG::
echo '<pre>'; print_r($this->_request->getParams()); echo '</pre>';
#::DEBUG::
}
This will show all your parameters. What you will notice is that you will also get the names of the Module, Controller and Action with your params.
EDIT
Ps. If you're trying to use the parameter in the view script you need to do this:
echo $this->data['payZip'];
echo $this->param;
In your Action Controller, you save your data to the "view" object by doing this:
$this->view->myVariable = 'Hello';
But when you're in a view script, you are IN the view script, so $this represents $this->view from the action controller.
So, you access the variable like this:
echo $this->myVariable;
Wrapping everything into a bigger code chunk for understanding:
Your Controller
public function indexAction()
{
// get all parameters and pass them to the view
$this->view->params = $this->_request->getParams();
// get an individual parameter and pass it to the view
$this->view->payZip = $this->_request->getParam('payZip');
}
Your View Script
<!-- Dump all parameters -->
<pre><?php print_r($this->params); ?></pre>
<!-- Print payZip -->
<p>My PayZip is: <?php echo $this->payZip; ?></p>
<!-- Print payZip from full parameter array -->
<p>My PayZip (array) is: <?php echo $this->data['payZip']; ?></p>
I hope that helps!

Categories