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.
Related
Im working on a piece of code to alter permissions for users of an app. Currently, each permission is added one at a time, Im revising it to be added in a faster way, being able to select multiple permissions to add at once.
The checkboxes aren't going to be the same number, since they are only the permissions the user doesn't yet have. It needs to pass an id with the permissions.
The problem is, my checkbox form doesn't appear to be sending any data to the controller. Upon submitting, it just loads a blank page with the url of the controller.
Heres the view code, that generates the checkbox form
<?php
if (!empty($lstAvailablePermissions)) {
$c=0;
echo $form->create('Administrator', array('action'=>'addPermission'));
echo $form->input('id');
foreach($lstAvailablePermissions as $key){
echo "<br>";
echo $form->input(
'permission',
array(
'id'=>$key,
'label'=>$key,
'type'=>'checkbox',
'multiple'=>'checkbox',
'value' => $key,
'name' =>'data[Administrator][permission]['.$c.']'
));
$c=$c+1;
}
echo $form->button(__('Add', true), array('type'=>'submit', 'class' => 'button', 'style'=>'padding: 2px; font-size: 12px;'));
echo $form->end();
}
?>
and the method in the controller
function AddPermission() {
if (empty($this->data)) { $this->RedirectWithFlash(__("Only POST Requests", true), "/administrators"); }
ErrorLogWarning("This is the form data sent to the controller", $this->data);
$length=count($this->data['Administrator']['permission']);
for ($i = 0; $i < $length; $i++){
$this->Acl->allow(
array('model' => 'Administrator', 'foreign_key' => $this->data['Administrator']['id']),
$this->data['Administrator']['permission'][$i]
);
}
$this->RedirectWithSuccessFlash(__("Permission added", true), array('action'=>'edit', $this->data['Administrator']['id']));
}
can anyone help me figure out whats going on? I assume ill need to loop through the data once its in the controller, but it doesn't even send the error message as of right now.
EDIT: problem appears to be fixed by adding the name property at the bottom of the form echo, which send it as an array which can be looped through in the controller.
I think the problem might be that you specify 'action'=>'addPermission' when you create the form, but your controller action is named AddPermission (capital A). Try changing to 'action'=>'AddPermission'.
Also, I think you might only get the last permission input because you're adding the permission inputs in a loop. Try indexing the inputs like this:
foreach($lstAvailablePermissions as $i => $key) {
echo "<br>";
echo $form->input(
"Administrator.{$i).permission",
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
Here is the code in my controller:
$this->view->myArray = array();
$this->view->test = "";
$out = $this->view->partialLoop('tab/partial.phtml', $data);
echo $this->view->test; // Output: This works
echo count($this->view->myArray); // Output: 0
And the partial partial.phtml:
$v->test = $this->partialLoop()->view;
$v = "This works";
echo $v->test; // Output: This works
$v->myArray[] = "hello";
echo count($v->myArray); // Output: 0
I don't think that accessing view variables from a partialLoop is a wonderful idea. That aside, why doesn't it work for my array variable?
it doesn't work because you don't have access to the view variables in the partial. You have access to the data you pass to the partial.
$out = $this->view->partialLoop('tab/partial.phtml', $data);
This line of code would have access to the information contained in $data.
So this code in your current partial is basically meaningless:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
I don't think I've ever seen partials used in quite this manner before. The point of the partial is to establish a different variable scope for a specific portion of the view.
The partial and partialLoop are view helpers so the only action you need to take in your controller (data may be or come from a model as well) is to make available any data you want to use in your partials as well as any data you want available in your normal view scope.
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
To use a partial or partialLoop you need to pass an array of some type or an object that implements toArray().
[EDIT]
Clean up your code your still in left field.
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
I don't seem to be able to pass the view any further then this, if I assign to an actual partial script and attempt to output the view object errors are thrown:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
it looks like an empty partial() (partialLoop()) call will give you access to the view object, when you already have access to the view object. If you leave the scope of the view object you will have only the access available to your current scope as provided by __get() and __call().
I hope I was able to explain this enough to help.
maybe you cant set the value of $v or the item because its private or static or discarded
also from the code you posted its using recursion which could make it a lot more breakable (ie the controller is referencing the views data, and the view is setting it or hasnt set it or has set it twice)
agreed i dont think accessing view var's from a partialLoop is a good idea.
edit:
$this->view->assign('variablename', $my_array);
I think the variable is otherwise "lost" on the Rerender, so work on your variables in your controller, and before you are done assign them to the view. I wouldn't really do array operations on $this->view->myArray
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!
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