In my _form.php I want to create a dropdown that contains names of relevant users (relevant = users with the role "releaseManager".
This is the code:
echo $form->field($model, 'Assignee')->dropDownList([$assignees = Yii::$app->db->createCommand('SELECT username FROM user, auth_assignment WHERE id=user_id AND item_name="releaseManager"')
->queryAll()]);
The problem is that along with the correct names I also get numbers.
For example: I have 2 relevant names, so I get 2 rows of 0 before the first name and a row with "1" before the second. As if it states the place in the array or I don't know what..
I tried using queryScalar() but then I get only one name instead of 2.
I will really appreciate your help.
Could be you need ArrayHelper::map()
use yii\helpers\ArrayHelper;
<?php
echo $form->field($model, 'Assignee')->
dropDownList(ArrayHelper::map(Yii::$app->db->
createCommand('SELECT username FROM user, auth_assignment WHERE id=user_id AND item_name="releaseManager"')
->queryAll(), 'username', 'username'));
?>
For re-usability we can also create separate method in model:
public function getUserNames()
{
$usernames = Yii::$app->db->createCommand('SELECT username FROM user, auth_assignment WHERE id=user_id AND item_name="releaseManager"')
->queryAll();
$result = yii\helpers\ArrayHelper::map($usernames, 'user_id', 'username');
return $result;
}
Form
echo $form->field($model, 'Assignee')->dropDownList(PathTOModel/ModelName::getUserNames())
Related
I want to have the same name of image in database and in the image folder one I move. In folder is work but in database don't have ideas, can someone help me! Thanks
public function postRegister(Request $request) {
request()->validate([
'email' => 'required',
'password' => 'required|min:8',
'fullname'=>'required',
'birthday'=>'required',
'country'=>'required',
'address'=>'required|min:10',
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$data = $request->all();
// dd($image);
$check = $this->create($data);
return Redirect::to("login")->withSuccess('Great! You have Successfully loggedin');
}
If you want to set your image name to your db record.
Pass it to your $data before calling create method.
public function postRegister(Request $request) {
....
$data = $request->all();
$data['imageName'] = $file_name.".".$image->getClientOriginalExtension();
$check = $this->create($data);
return Redirect::to("login")->withSuccess('Great! You have Successfully loggedin');
}
If you want use mass assignment for save data you can use YourModelName::create(data).but you should pay attention to 2 thing .
first one define all fillable fields that you want allow to assign mass in your model class.so you should add your imageName field in fillable array .
second you should append yourImageName to your data that assign mass.like :data['yourImageField']=setvalue.
But if you want to assign row by row(its more safe and better i think) you should do like this: modelObject->Imagefield="imageName" and at end modelObject->save().
I have 3 models Employees Customers and Partners
I want to display the count of all the tables employees customers and partners in dashboard view of Employees model.
EmployeesController.php
<?php
namespace App\Controller;
class EmployeesController extends AppController
{
public function dashboard()
{
}
}
?>
I'm new to cakephp and I have no idea how to query other model tables at all.
Please point me to good tutorial or documentation for this. It will be helpful
I fixed it using the following codes.
// Controller
$this->loadModel("Customer");
$query = $this->Customers->find('all', [
'conditions' => ['Customers.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[0] = $query->count();
$this->loadModel("Employee");
$query = $this->Employees->find('all', [
'conditions' => ['Employees.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[1] = $query->count();
$this->loadModel("Partner");
$query = $this->Partners->find('all', [
'conditions' => ['Partners.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[2] = $query->count();
$this->set(compact('entity_count'));
// View
<?= $entity_count[0] ?>
The query to use would be a nested query, assigned to an array. Then you can access the values from there.
In particular, you would want to write something like:
$result = List();
$result->query('SELECT COUNT(SELECT * FROM usertable), COUNT(SELECT * FROM partnertable), COUNT(SELECT * FROM customertable)');
To then access the values, you would refere to $result based on the position in the array, ie. $result[0] would be the first value, $result[1] the second and so on.
If you need to specify the items for the counts (such as active users, active customers etc) add where clauses into the select statements within the count expression
Eg. SELECT * FROM usertable WHERE active="yes"
Once you have the data you need, you can then edit the source file where you require them to be displayed and decide where to place them using a php echo to the html stream
I am looking for a way to retrieve all models in a database. Then loop through all of the models and read out the values for name, firstname and phonenumber.
So far I've gotten this and failed to go past it:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
I am then looking to implement those three values in a simple HTML table:
<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>
The table should be part of a PDF output, so ideally I would save it to a variable:
$html_table = '<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>';
I would need to get this for every model that fulfills the criteria of status = 'active' in the database.
So far I've only been able to get tables via gridView and not in a HTML template either.
You don't really need a data provider to achieve this, you could simply try :
$models = Employee::find()->where(['status'=>'active'])->orderBy('name ASC')->all();
foreach ($models as $model) {
echo "<tr><td>{$model->firstname}</td><td>{$model->name}</td><td>{$model->phone}</td></tr>";
}
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data
You can get all models like this:
$employees = Employee::find()
->select('firstname, name, phone')
->asArray()
->where(['status'=>'active'])
->all();
This way you will get an array of arrays containing the 3 selected fields, so now you only need to use a foreach to loop through them and create the table:
$html = '<table>';
foreach($employees as $employee) {
$html .= '<tr><td>'.$employee['firstname'].'</td><td>'.$employee['name'].'</td><td>'.$employee['phone'].'</td></tr>';
}
$html .= '</table>'
In Yii2 I'm trying to construct hidden input
echo $form->field($model, 'hidden1')->hiddenInput()->label(false);
But I also need it to have some value option, how can I do that ?
Use the following:
echo $form->field($model, 'hidden1')->hiddenInput(['value'=> $value])->label(false);
Changing the value here doesn't make sense, because it's active field. It means value will be synchronized with the model value.
Just change the value of $model->hidden1 to change it. Or it will be changed after receiving data from user after submitting form.
With using non-active hidden input it will be like that:
use yii\helpers\Html;
...
echo Html::hiddenInput('name', $value);
But the latter is more suitable for using outside of model.
simple you can write:
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'abc value'])->label(false); ?>
You can do it with the options
echo $form->field($model, 'hidden1',
['options' => ['value'=> 'your value'] ])->hiddenInput()->label(false);
you can also do this
$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);
this is a better option if you set value on controller
$model = new SomeModelName();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->group_id]);
} else {
$model->hidden1 = 'your value';
return $this->render('create', [
'model' => $model,
]);
}
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input :
Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') ,
just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>
or
<input type="hidden" name="test" value="1" />
Use This.
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
And you can simply do this magic.
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
In your case it will be something semilar to this, every time you create an object just pass the user ID to the user_id property, and save yourself a lot of coding.
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
I know it is old post but sometimes HTML is ok :
<input id="model-field" name="Model[field]" type="hidden" value="<?= $model->field ?>">
Please take care
id : lower caps with a - and not a _
name : 1st letter in caps
With links to each user.
For example. "SELECT * FROM users WHERE rating > 50" this query yields 120 results... how to print those results on a page in order of rating with links to each profile..
a leaderboard if you will
A good place to start would be to review the docs at http://book.cakephp.org/ but in short it will follow Cake's MVC principles. You'll need a model to interact with the database and pass this data back to a controller. The controller will then pass that information to the relevant view script and which point you can layout the recordset as you wish.
First, you should read up on CakePHP like #simnom has suggested. Once you do, your query and view code should look something like this:
Users Controller:
$users = $this->User->find('all', array('order'=> array('User.rating' => 'desc'), 'conditions'=>array('User.rating >' => '50')));
$this->set('users', $users);
View Code:
<?php
foreach ($users as $user):
echo $this->Html->link("View User", array('controller' => 'users', 'action' => 'view', $user['id']));
endforeach;
?>