Get array from model, then pass to view - arrays

Simple, but for me as a beginner, a problem. I need to pass an array from my model (array is filled with info while reading a text file) to a controller and then finally to a view.
My model:
function show_notes(){
$file = "notes.txt";
foreach(file($file) as $entry)
{
list($user, $content) = array_map('trim', explode(':', $entry));
$notes = array (
'user'=> '$user',
'content'=> '$content'
);
}
return $notes;
}
Controller:
function members_area()
{
$this->load->model('Note_model');
$notes[] = $this->Note_model->show_notes();
$this->load->view('includes/header');
$this->load->view('members_area', $notes);
$this->load->view('includes/footer');
}
And in view I use this:
foreach ($notes as $item)
{
echo "<h1>$user</h>";
echo "<p>$content</p>";
}
And I am getting error that notes variable is undefined in my view.
I think I just don't understand how arrays work. I have tried to read about that, I have tried some examples similar to this, but still can't get it.

In your controller:
$data['notes'] = $this->Note_model->show_notes();
...
$this->load->view('members_area', $data);
EDIT:
In your view:
<?php foreach ($notes as $item):?>
<h1><?php echo $item['user']; ?></h1>
<p><?php echo $item['content'] ?></p>
<?php endforeach; ?>
In your model:
$notes = array();
foreach(file($file) as $entry)
{
list($user, $content) = array_map('trim', explode(':', $entry));
array_push($notes, array('user' => $user, 'content' => $content));
}
return $notes;

Replace this
$notes[] = $this->Note_model->show_notes();
with this
$notes['notes'] = $this->Note_model->show_notes();

Related

Categories tags in module (mod_articles_categories)

I need to display tags of every sub category in categories list module (mod_articles_categories).
For articles in similar module (mod_articles_news) I always do something like this:
<?php $itemtags = (new JHelperTags)->getItemTags('com_content.article', $item->id);
$taglayout = new JLayoutFile('joomla.content.tags');
foreach ($itemtags as $tag) { echo $tag->title; } ?>
But code like this doesn't work fork categories even I change 'com_content.article' to 'com_content.category'
Maybe someone knows what I doin' wrong?
Thanks in advance
Ok, finally I got the solution:
<?php foreach ($list as $item) :
$itemtags = (new JHelperTags)->getItemTags('com_content.category', $item->id);
$taglayout = new JLayoutFile('joomla.content.tags');?>
<?php if (!empty($itemtags)) { foreach ($itemtags as $tag) { echo $tag->title.' '; }; } ?>
<div><?php echo $item->title; ?></div>
<?php endforeach; ?>

Yii2 using array to build activeform - cannot get & echo second array element

I have created and registered a Yii2 component function 'formSchema' which
contains the array as such:
class FormSchema extends Component{
public function formSchema()
{
$fields = array(
['field' => 'username', 'controltype' => 'textinput'],
['field' => 'email', 'controltype' => 'textArea'],
);
return $fields;
}
}
?>
I call the array in the active form, however I cannot get the
['controltype'] using the same successful method as I do to retrieve ['field'] as
below. I would like to get that array element however seem unable to get any but the first level element:
<div class="usermanager-form">
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
$fields = $items = Yii::$app->formschema->formSchema();
foreach($fields as $field)
{
$field = $field['field'];
echo $form->field($model, $field);
}
?>
You may use array values in this way:
$fields = Yii::$app->formschema->formSchema();
foreach ($fields as $field) {
echo $form->field($model, $field['field'])->{$field['controltype']}();
}

ZF2 nested views as array

is it possible to add multiple views in a array to a parent view in Zend Framework 2?
For example:
childView.php
echo $this->data;
parentView.php:
foreach($this->views as $view)
echo '<div>'.$view.'</div>';
controller.php:
public function actionIndex(){
$children = array(1,2,3);
foreach($children as $child){
$childView = new ViewModel(array('data' => $child));
$childView->setTemplate('childView');
$childrenViews[] = $childView;
}
$view = new ViewModel();
$view->setTemplate('parentView');
// some function that adds the childrenViews to the parentView;
return $view;
}
Expected output: <div>1</div><div>2</div><div>3</div>
ps: It's dummy code so please ignore possible syntax errors.
You could do the following:
public function actionIndex(){
$children = array(1,2,3);
foreach($children as $child){
$childView = new ViewModel(array('data' => $child));
$childView->setTemplate('childView');
$view->addChild($childView, 'the-child-views', true);
}
$view = new ViewModel();
$view->setTemplate('parentView');
return $view;
}
This line:
$view->addChild($childView, 'the-child-views', true);
Will append the child views to this one var. So you can echo your views using:
<?php echo $this->the-child-views ?>
Hope it's what you are looking for.
You can just assign the array of ViewModels to your parent View Model.
<?php
public function actionIndex()
{
$children = array(1,2,3);
foreach($children as $child){
$childView = new ViewModel(array('data' => $child));
$childView->setTemplate('childView');
$childrenViews[] = $childView;
}
$view = new ViewModel();
$view->setVariable('children', $children); // assign to $children
/**
* Or set in constructor
*/
//$view = new ViewModel(array(
// 'children' => $children
//));
$view->setTemplate('parentView');
return $view;
}
Now you can just iterate over them in your parent template:
parentView.phtml
<?php // $children or $this->children to access your array of ViewModels ?>
<?php foreach($children as $child): ?>
<?php echo $child // automatically rendered for you ?>
<?php endforeach ?>
I think it should work with the partial helper:
http://framework.zend.com/manual/2.1/en/modules/zend.view.helpers.html#partial-helper

cakephp post data field missing from SQL update statement

Having trouble geting cakephp to update a record.
Controller Code:
public function viewBenefit($id) {
if ($this->request->is('post')) {
$this->set('post', $this->request->data);
$this->Benefit->id = $id;
if ($this->Benefit->save($this->Benefit->data)) {
$myVars['Sucsess'] = TRUE;
$this->Session->setFlash('Updates Saved');
} else {
$myVars['NewID'] = 0;
$myVars['Sucsess'] = False;
$this->Session->setFlash('There was an error.');
}
}
$this->Benefit->recursive = 2;
$this->Benefit->id = $id;
$this->set('benefit', $this->Benefit->read());
}
Relevant View Code:
<?php echo $this->Form->create('Benefit',array('action'=>'edit','url' => '#')); ?>
<?php echo $this->Form->input('id',array('type'=>'hidden')) . "\n"; ?>
<?php echo $this->Form->input('short_description',array('type'=>'textarea')) . "\n"; ?>
<?php echo $this->Form->end(); ?>
NOTE: The Form is sumbitted via JS
POST Data (via debug($post); )
array(
'Benefit' => array(
'id' => '1952e98e-f589-47d4-b458-11a1bd58ba3b',
'short_description' => '<p>This is great sample insurance 321321</p>'
)
)
SQL UPDATE statment:
UPDATE `c16memberdev`.`benefits` SET `modified` = '2012-12-04 10:45:16' WHERE `c16memberdev`.`benefits`.`id` = '1952e98e-f589-47d4-b458-11a1bd58ba3b'
As you can see the field "short_description" does not get added to the SQL statement, and therefore the data not added to the database. Thanks for your help.
Try changing
$this->Benefit->save($this->Benefit->data)
to
$this->Benefit->save($this->request->data)

Updating specified rows in CakePHP using array of ID's?

This code is only updating one row (the one that matches the first in the array):
Edit: showing more code!
Here's my view. It's grabbing db entries based on an association (there's one model "clients" that has a one-to-many relationship with two other models, Programs and Users).
<div class="view">
<h2><?php echo h($program['Program']['title'])?></h1>
<?php echo $this->Form->create('User', array('action' => 'pushing')); ?>
<table id="pushTable">
<tr><th colspan="5">Select the athletes you would like to push this program to:</th></tr>
<tr>
<?php $i=0; ?>
<?php foreach ($clients['Players'] as $player) {?>
<?php if ($i == 0) {?><tr><?php } ?>
<td><?php echo $this->Form->checkbox($player['id']) . ' ' . $player['username'];?></td>
<?php if ($i == 4) {?></tr><?php $i = 0; } else { $i++; } ?>
<?php } ?>
</tr>
</table>
<?php echo $this->Form->end(__('Push')); ?>
</div>
In my Users controller:
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
$athletes = $this->request->data['User'];
foreach ( $athletes as $player => $flag){
if ($flag == 0){
unset($athletes[$player]);
}
}
$this->User->updateAll(
array('User.data' => "'foo'"),
array('User.id' => $athletes)
);
$this->Session->setFlash(__('Programs were pushed!'));
}
}
}
$athletes is the array is collected from checked boxes, and there seem to me no problems with that... so I'm not sure why the updateAll isn't iterating over each ID in the array...
Maybe it's not working for a db related reason? I'm developing on MAMP... maybe the db isn't set up for "atomic" stuff (only heard about that here today!).
I had previously tried using a foreach to loop over the id's, then in the foreach just did this (edit: more code!)
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
foreach ($this->request->data['User'] as $player => $flag) {
if ($flag) {
$this->User->id = $player; // set ID to player we want to save ($player is id that was suplpied in view to checkbox
$this->User->saveField('data', 'foo'); // then, push the data!
}
}
$this->Session->setFlash(__('Programs were pushed!'));
}
$this->autoRender = false;
$this->redirect(array('action' => 'index'));
}
But that caused weird results with redirection. No matter where I put redirection in that action, the save just wanted to do its own thing. That $this->autoRender did nothing. The controller still tried to resolve to the /pushing/ route
Give this a shot :)
In your view:
<div class="view">
<h2><?php echo h($program['Program']['title'])?></h1>
<?php echo $this->Form->create('User', array('action' => 'pushing')); ?>
<table id="pushTable">
<tr><th colspan="5">Select the athletes you would like to push this program to:</th></tr>
<tr>
<?php $i=0; ?>
<?php foreach ($clients['Players'] as $player) {?>
<?php if ($i == 0) {?><tr><?php } ?>
<td><?php echo $this->Form->input('Player.' . $player['id']. '.id', array('type' => 'checkbox', 'value' => $player['id'])) . ' ' . $player['username'];?></td>
<?php if ($i == 4) {?></tr><?php $i = 0; } else { $i++; } ?>
<?php } ?>
</tr>
</table>
<?php echo $this->Form->end(__('Push')); ?>
</div>
In your controller:
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
$athletes = $this->request->data['Player'];
$athlete_ids = array();
foreach($athletes as $a){
$athlete_ids[$a['id']] = $a['id'];
}
$this->User->updateAll(
array('User.data' => "'foo'"),
array('User.id' => $athlete_ids)
);
$this->Session->setFlash(__('Programs were pushed!'));
}
}
}
Hi had to change the code a bit to make it for work me..
$contactsids = array();
foreach($selected as $key => $val){
if(($val <> '') && ($val <> 0) ) {
$contactsids[$val] = $val;
}
}
$this->Contact->updateAll(
array('Contact.contact_category_id' => $category_id),
array('Contact.id' => $contactsids)
);

Resources