Drop down menu for CakePHP 3.x of URLs to views - php

I have a table called a_forms, and I'm trying to create a drop down menu on a page of AForms that has a list of all the rows of a_forms. I want each choice in the drop down to link directly to the view of that form. Here is my forms table:
fid int(3) unsigned auto_increment (primary key)
title varchar(100)
created timestamp CURRENT_TIMESTAMP on update
modified timestamp
I was able to get as far populating the drop down menu, however I'm having trouble with the second part - linking each choice with the view selected. I'm a beginner to CakePHP so I am probably missing something. Here is the function in AFormsController:
public function forms($id = null)
{
$query = $this->AssessmentForms->find('all');
$result = $query->toArray();
$assessmentForm = $this->AssessmentForms->get($id, [ 'contain' => [] ]);
$this->set('assessmentForm', $assessmentForm);
$this->set('_serialize', ['assessmentForm']);
$data = $this->AssessmentForms->find('list', array('fields' => array('fid', 'title')));
$this->set('forms', $data);
}
forms.ctp:
<?php $this->Form->input('aform.select one', ['type' => 'select', 'options' => $forms, 'empty' => 'Choose One', 'onchange' => 'this.form.submit();']);?>
That gives me "Record not found in table "a_forms" with primary key [NULL]"
I also tried:
<?php $this->Form->create('Forms', array( 'url' => ['controller'=>'a_forms', 'action'=>'view', $aForm->fid])); ?>
And added this to the controller:
$aForms = $this->AForms->find('list');
It doesn't throw an error but I get a "Undefined variable: aForms [APP/Template/AForms/forms.ctp, line 10" in the view
I saw other people struggling with the 'onchange' method so I'm not sure if that's the right approach. I'm using version 3.1.0. Let me know if you need any more information!

Still don't quite know how to appropriately create queries with find(), but I found a way around with:
<ul class="dropdown-menu">
<?php foreach ($aForms as $aForm): ?>
<li> <?= $this->Html->link($aForm->title, ['action' => 'fill', $aForm->fid]) ?></li>
<?php endforeach; ?>
</ul>
And this in the controller:
$this->set('assessmentForms', $this->paginate($this->AssessmentForms));
$this->set('_serialize', ['assessmentForms']);
I pulled that directly from the bake-generated index() function. If anyone has a more syntactically non-hackish way of solving this, please let me know!

Related

Going from, SELECT * FROM users WHERE url = "pretty url", to displaying 1 row from database with Lithium Framework

Hi I am new to php and mysql and jumped right into using the Lithium framework.....I know, bad idea.
BUT basically my question is, how do I go from;
$users = \app\models\Users::findByUrl($this->request->query['url']);
return array(
'users' => $users,
);
in my UsersController to actually echo'ing 1 specific row of data in my users/index.php.html page, according to the query string in my url?
My desired structure is localhost/users/"url", and "url" is a value in my mysql db labeled "url" in my Users table. e.g. localhost/users/Bob. "Bob" is "url" value.
My users/index.php.html page is using foreach ($users as $user) to echo the information like this;
<?=$user->firstname ?>
Snag and Confusion:
When I was using;
$users = \app\models\Users::find('all');
return array(
'users' => $users,
);
in my UsersController, the users/index.php.html page retrieved all the users in my database.
The content displays correctly, BUT I need the data from just the clicked-on user, so this is when I started using; $users = \app\models\Users::findByUrl($this->request->query['url']);
When linking to the users page this is how I do it;
<?php if( $user->avatar ):?>
<a href="/users/<?=$user->url?>">
<img class="img-responsive" src="/img/users/<?=$user->avatar?>" />
</a>
<?php else: ?>
Not sure if I need to add conditions to my controller, add something to my router, change my htaccess, or do something with params.... Pleease help, any direction would be greatly appreciated.
Finders return everything by default. If you want a single object, do:
Users::findFirstByUrl($this->request->query['url'])
...which is short-hand for:
Users::first(['conditions' => ['url' => $this->request->query['url']]]) or
Users::find('first', ['conditions' => ['url' => $this->request->query['url']]]).

YiiBooster Select2Row Data/Tag Issues

so I've been trying to get select2Row to work for me forever and I just can't seem to get a hang of it. What I'm trying to do is provide the user with Tags that list a school/university name, while at the same time storing the value of said tag when I save the form. I've noticed that I cannot use both data and tags, else my drop down wont populate so that's not an option. Tags only seem to want text, rather than text and matching values. Any ideas?
<div class="row">
<?php
echo $form->select2Row($model, 'school_id', array(
'asDropDownList'=>false,
'options'=>array(
'tags'=>School::model()->schoolNames,
//'maximumSelectionSize'=>1,
'width'=>'297px',
'tokenSeparators'=>array(','),
),
));
?>
<?php echo $form->error($model,'school_id'); ?>
</div>
And here is the function for schoolNames
public function getSchoolNames()
{
$schools = array();
$result = $this->findAllBySQL("SELECT DISTINCT name FROM School");
foreach($result as $school){
$schools[] = $school->name;
}
return $schools;
}
I've tried using this instead, but the tags won't populate
public function getSchools()
{
$query = "SELECT id,name FROM School";
$results = $this->findAllBySQL($query);
return CHtml::listData($results, 'id', 'name');
}
So at the moment, select2Row is generating a list of tags using getSchoolNames() and that all works fine, except once you submit the form using those tags you'll get this
Please fix the following input errors:
School must be an integer.
Sorry for all the trouble, I'm still a little new to this. I'm sure the answer is probably right in front of me. Thanks either way =)
try this:
echo $form1->select2Row($model, 'school_id', array(
'data' => School::model()->schoolNames,
'multiple' => 'multiple',
'options' => array(
"width" => '70%',
),
));

How to filter the rows of a gridview in yii using radio buttons

I used the below code to create two radio buttons(approved messages and rejected messages) in Yii framework
<?php echo CHtml::activeRadioButtonList($model, 'Approved', array('Approved Messages', 'Rejected Messages'), array('labelOptions'=>array('style'=>'display:inline'),'separator'=>'')) ?>
Now I have to filter and display all the rows in CGridView of the table where column 'approved' has value=1 when I click on "approved messages" radio button and all the rows in CGridView of the table where column 'Approved' has value=0 when I click on "rejected messages" radio button. How can I do this
I used a drop down for this, the values are Yes and No. Just translate the approved column into text using the following code:
array(
'name' => 'approved',
'value' => '($data->approved ? "Yes" : "No")',
'filter' = >CHtml::dropDownList('Approved', '',
array(
' '=>'All',
'1'=>'On',
'0'=>'Off',
)
),
)
This link is where I got this info: http://www.yiiframework.com/forum/index.php/topic/30694-cgridview-filter-dropdown-from-array/
I googled using cgridview filter example
Alright, lets put in the radio buttons instead of all the dropdowns haha.
I assume you have your view set up something like this:
// view/index.php (or similar)
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'filter'=>Message::model(),
'columns'=>
[
'id',
'username',
'email:email',
'approved'=>[
'name'=>'approved',
'filter'=>$this->approvedFilter(),
// I like moving stuff like this out of the way.
// But maybe it's smarter to put it in your model instead?
]
]
));
Next for the controller.
// MessageController.php (or similar)
public function actionIndex()
{
$model = Message::model();
// All we need to do is to assign the incoming value to the model we are using...
if ( isset( $_GET['Message']['Approved'] )){
$model->approved = $_GET['Message']['Approved'];
}
$this->render('index', ['model'=>$model]);
}
// Oh yeah the filter. I just copied your code.
public function approvedFilter(){
return CHtml::activeRadioButtonList(
Message::model(), 'approved', array(0,1),
array(
'labelOptions'=>array('style'=>'display:inline'),
'separator'=>''
)
);
}
This code has been tested, but I made some last minute changes, so sorry if it blows up!
And I still think a simple 'approved:boolean' is much cleaner. ;)

Need help to create CRUD screen with dropdown (relation) using yii-framework

I need to create CRUD screen using yii-framework. Simple CRUD screen using one table is working perfectly fine. I'm facing problem/issue while using dropdown (linking table).
I have installed giix extension which is suppose to create CRUD with dropdown if FK is specified but I dnt have MySql Engine InnoDB on my hosting provider, so I'm not able to use that extension. I need to do it manually.
I have two tables
main:-
id
store_id
prefix
store:-
id
name
Now store_id of main is FK to id of store table. And I want to create CRUD for main table.
So that Add Screen should show:-
Store Name:- Dropdown
prefix:- Textbox
View screen should use name column of store table instead of showing store_id
Thanks in anticipation.
Generate CRUD using Gii, then read my blog. http://jmmurphy.blogspot.com/2013/05/using-yii-model-relations.html
Basically you will have something like this for your store_id field after Gii Generation
<?php echo $form->labelEx($model,'store_id'); ?>
<?php echo $form->textField($model, 'store_id', array('size'=>60,'maxlength'=>255));?>
<?php echo $form->error($model,'store_id'); ?>
The textField line is replaced by:
<?php $list = CHtml::listData(Store::model()->findAll(), 'id', 'name'); ?>
<?php echo $form->dropDownList($model, 'store_id', $list, array('empty'=>'(Select a Store)')); ?>
You also need to define relations in your Main model so that you can access related tables (even if your database does not support foreign keys) like this:
public function relations()
{
return array(
'store'=>array(self::BELONGS_TO, 'Store', 'store_id'),
);
}
And to complete this relation, you should also add the following relation to your Store model:
public function relations()
{
return array(
'main'=>array(self::HAS_MANY, 'Main', 'store_id'),
);
}
These relations define a One to Many relation between Store and Main where store is the parent, and Main is the Child. To make it a One to One relationship change HAS_MANY to HAS_ONE. The HAS_* goes in the parent model and points to the foreign key attribute in the child table. The BELONGS_TO goes in the child and tells the attribute in the child table that points to the primary key in the parent.
Now to see the store name in the view action, you need to change 'store_id' in your view.php to an array that looks like:
array(
'name' => 'store_id',
'value' => $model->store->name,
)
The admin view is slightly different. I am not sure exactly why, but to view the store name instead of the id in the admin view you will need to use an array that looks like:
array(
'name' => 'store_id',
'value' => '$data->store->name',
)
Note that Gii generates this so that $data is the model instead of $model, and also it does a funky double indirection thing so that you need to put the variable declaration in single quotes.
Thanks jmarkmurphy for your help. You helped me lot and I have marked your answer as correct only as you gave me guidance. Just posting exact code in detail.
I changed view.php with below code:-
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'store.name',
'prefix',
),
));
Also changed admin.php with below code:-
<?php echo CHtml::encode($data->store->name); ?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'main-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'store.name',
'prefix',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Thanks once again jmarkmurphy. Thanks a lot . My application is now working and exactly the way I wanted.

Select or Dropdown list from CActiveRecord in Yii

I have table types and i want to build selectbox with all values from this table
In my controller i wrote this code
$allRegistrationTypes = RegistrationType::model()->findAll();
$this->render('index', array('allRegistrationTypes' => $allRegistrationTypes))
How build selectbox in view file ?
Well then its pretty simple all you need to do is first create List Data like
CHtml::ListData(allRegistrationTypes,'value you want to pass when item is selected','value you have to display');
for ex
typeList = CHtml::ListData(allRegistrationTypes,'id','type');
now remember both id and type are fields in table
now all you have to do is if you are using form then
<?php echo $form->dropDownList($model, 'type_id', $typeList, array('empty'=>'Select a tyoe')); ?>
and if you need multiple you can pass multiple => multiple in the array as htmlOptions
You would use CHtml::dropDownList, or activeDropDownList if there is a "parent" model and you want to leverage its validation rules.
If you want to make the <select> element multiple-selection-capable, pass in 'multiple' => 'multiple' and 'size' => X as part of the $htmlOptions parameter.
Simplest Method to get "Select Box" in YII Framework:
<div class="row">
<?php
echo $form->labelEx($model,'county');
$data = CHtml::listData(County::model()->findAll(), 'id', 'county');
$htmlOptions = array('size' => '1', 'prompt'=>'-- select county --', );
echo $form->listBox($model,'county', $data, $htmlOptions);
echo $form->error($model,'county');
?>
</div>
Good Luck..

Categories