I have a table called persons with id and name fields.
I have a create.php view that loads the model called Persons and now I want to add a checkbox called hasCar to show if a person has a car (so it is a boolean condition).
Then I have the send button that send the $model array of the form to the controller so I need to add the hasCar variable to $model array.
But the checkbox is not a column of the persons table so I got some errors because it is not part of the model.
I added the checkbox in this way but it is not working, of course.
<?= $form->field($model, 'hasCar')->checkbox(); ?>
Is it possible to send the hasCar variable inside the $model array? I mean, how can I send the hasCar variable to the controller when the send button is pressed?
Create a new model extending Person that contains hasCar member, and load the model from PersonForm class, such as:
class PersonForm extends Person
{
public $hasCar;
public function rules()
{
return array_merge(parent::rules(), [
[['hasCar'], 'safe'],
]);
}
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'hasCar' => 'Has car',
]);
}
}
You can't pass the variable to the $model object orbit is affiliated with a db table, you are right about this. You need to pass the variable to the controller via a request method (GET, POST).
Try :
Yii::$app->request->post()
for POST, and :
Yii::$app->request->get()
for GET.
Also on the form add the checkbox as an HTML class component.
EXAMPLE:
CONTROLLER:
...
$hasCar = Yii::$app->request->post('hasCar');
....
VIEW:
...
// We use ActiveFormJS here
$this->registerJs(
$('#my-form').on('beforeSubmit', function (e) {
if (typeof $('#hasCar-checkbox').prop('value') !== 'undefined') {
return false; // false to cancel submit
}
return true; // true to continue submit
});
$this::POS_READY,
'form-before-submit-handler'
);
...
<?= HTML::checkbox('hasCar', false, ['id' => 'hasCar-checkbox', 'class' => 'form-control']) ?>
...
More on ActiveFormJS:
enter link description here
I hope this answer covered you.
Damian
Related
Hi everyone i have a many-to-many relationship between the turnos table and the dias table like this:
Currently, I'm doing the CRUD of the turnos table and for each turnos I have to assign many dias, I did it with the attach method.
Now the issue is in the edit method... how am I gonna get the assigned dias that is related to that turno so I can pass it to the view and the user can edit it?
If someone knows it please help me, I would appreciate it very much
//Dias Model
public function turnos()
{
return $this->belongsToMany(Turno::class);
}
//Turnos Model
public function dias()
{
return $this->belongsToMany(Dia::class);
}
// Controller
public function edit(Turno $turno)
{
// $dias = ??
return Inertia::render('Turnos/Editar', [
'turno' => $turno,
'dias' => ??
]);
}
The edit view Should looks like this:
You can load the relation with the load() method and just return the $turno variable that will contain the "turno" and the "dias".
public function edit(Turno $turno) {
$turno->load('dias');
return Inertia::render('Turnos/Editar', [
'turno' => $turno
]);
}
On the client side you can use v-model to fill your inputs.
I have a Document and Post (for that document) Backpack CRUD resources. I want to create a button inside the post datatable so that when I click that button, it will link to the documents of that post.
this is my model post
class Post extends Model{
...
function allDocuments(){
return '<i class="fa fa-list"></i> Documents';
}
}
this is my PostCrudController
class PostCrudController extends CrudController{
...
$this->crud->addButtonFromModelFunction('line', 'all_documents', 'allDocuments', 'beginning');
}
and that's my DocumentCrudController
class DocumentCrudController extends CrudController{
...
$this->crud->addFilter([
'name' => 'post_id',
'type' => 'select2',
'label'=> 'Post To Filter',
'value' => $_GET['post_id'] // <------- Hoped this works, but doesn't
], function() {
$condos = [];
foreach(Post::get() as $c){
$condos[$c->id] = $c->title." >> ".$c->category->name." >> ".$c->category->condomimium->name;
}
return $condos;
}, function($value) { // if the filter is active
$this->crud->addClause('where', 'post_id', $value);
});
}
I've seen that backpack datatables uses a POST request with the parameters (in my case post_id) to filter the datatable, but I need to call a GET request to preselect my filter with the datatable result accordingly.
thanks in advance
Why not using Request in laravel ? something like this $request->input(post_id); and instantiate the request in the method like this
use Illuminate\Http\Request;
public function store(Request $request) { // logic here }
Actually it works even without 'value' => $_GET['post_id']. Backpack recognizes automatically filter. The name of the filter must match to the name of the GET param
I've Yii2 form containing form fields depending on action of page. Ex. Few fields appears when then action is create and few appears when action is update. I want to add required validation based on this scenario.
Ex.
<?= $form->field($model, 'unique_identifier')->textInput(['maxlength' => 45]) ?>
I am showing this field only when action => 'update'.
Now I want to add required validation for this and I tried this:
[['unique_identifier'], 'required', 'on' => 'update'],
But above validation not working. If I remove on=>update then its validating on both create and update scenario.
Any help would be appreciated.
ActiveRecord does not set scenario automaticaly when you update or create items. You must override update() method in your model and set scenario that you need. E.g. in your case
public function update($runValidation = true, $attributeNames = null)
{
$this->scenario = 'update';
return parent::update($runValidation, $attributeNames);
}
Also you can set scenario in your actionUpdate
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
//load data from request, save model etc.
}
I'd like to ask, is it possible to change the original posted attributes in actionCreate()?
For example I have 3 attributes: name, phNumber, address
In the _form.php, it automatically posts these 3 attributes. BUT what if I want to change the posted name attribute to all Uppercases? Do I need to create my own method of creating a record just to change how the name will be recorded OR is there something that I can do in actionCreate() so that it only changes the name attribute?
For example, user types in
adam michael
for the name textbox, and I want to change only this attribute to
ADAM MICHAEL
to be recorded in the database instead of having to create another method.
Code below:
public function actionCreate() {
$model = new Masseuse;
if (isset($_POST['Masseuse'])) {
$model->setAttributes($_POST['Masseuse']);
if ($model->save()) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('servicemasseuse/create', 'mid' => $model->id));
}
}
$this->render('create', array( 'model' => $model));
}
Just simply do a $model->name=strtoupper($model->name);
Refer here
You must alter the user input prior to saving the data. You do this by creating an overwritten function in your model.
class Masseuse extends CActiveRecord {
// ...
public function beforeSave()
{
$this->name = strtoupper($this->name)
}
}
I have one temporary model as viewModel. In my CRUD actions (for example actionCreate) I want to get this viewModel data and assign that to a ActiveRecord model. I used below code but my model object atrribute always show NULL value for attributes:
$model = new _Users();
if ($model->load(Yii::$app->request->post())) {
Yii::info($model->attributes,'test'); // NULL
$attributesValue =[
'title' => $_POST['_Users']['title'],
'type' => $_POST['_Users']['type'],
];
$model->attributes = $attributesValue;
Yii::info($model->attributes,'test'); // NULL
$dbModel = new Users();
$dbModel->title = $model->title;
$dbModel->type = $model->type . ' CYC'; // CYC is static type code
Yii::info($dbModel->attributes,'test'); // NULL
if ($dbModel->save()) {
return $this->redirect(['view', 'id' => $dbModel->id]); // Page redirect to blank page
}
}
else {
return $this->render('create', [
'model' => $model,
]);
}
I think $model->load(Yii::$app->request->post()) not working and object attribute being NULL. Is it Yii2 bug or my code is incorrect??
If there is no rule for your attribute the $model->load() will ignore those not in the rules of the model.
Add your attributes to the rules function
public function rules()
{
return [
...
[['attribute_name'], 'type'],
...
];
}
To fetch data for an individually attributes(db-fields) in yii2.0 then you should just do as:
echo $yourModel->getAttribute('email');
ActiveRecord $attributes is a private property
Use $model->getAttribute(string)
You can use following codes:
$model = new _Users();
$model->attributes=Yii::$app->request->post('_Users');
$model->title= $model->title
$model->type = $model->type . ' CYC'; // CYC is static type code
#$model->sampleAttribute='Hello World';
Declare attribute as private then
echo $yourModel->attribute
work as expected
You must remove all public properties (title, type, etc.) in your _User model and $model->attributes = $post will work correctly.
I have also encountered the same problem, i Add my attributes to the rules function,but also error. And i found the reason for this problem. It is beause that the submit form's name in corresponding view file is not the same as the model's name which you use in controller
[controller file]:
$model=new SearchForm();
[view file]:
<input name="SearchForm[attribus]" ...
or
[view file]:
<?= $form->field($model,'atrribus')->textInput()?>