Yii, changing original posted attributes - php

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)
}
}

Related

Yii2: How to send new variable from view to controller?

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

model->attributes in Yii2 always has NULL value

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()?>

How to insert fields from two models onto one form

I have done everything like in this example.
But I don't understand how to save the id fields to the related tables. I have two tables, company and entity, with one to one relations. It saves all the fields that I inserted, but not company_id and entity_id. Do I need to use aftersave?
In the Company controller:
public function actionCreate()
{
$model1=new Company;
$model2=new Entity;
if(isset($_POST['Company'], $_POST['Entity']))
{
// populate input data to $a and $b
$model1->attributes=$_POST['Company'];
$model2->attributes=$_POST['Entity'];
// validate BOTH $a and $b
$valid=$model1->validate();
//$valid=$model2->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$model1->save(false);
$model2->save(false);
// ...redirect to another page
}
}
$this->render('create', array(
'model1'=>$model1,
'model2'=>$model2,
));
}
In the Company model:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'entity'=>array(self::HAS_ONE, 'Entity', 'entity_id')
);
}
Ok, those are normal doubts when we begin playing with Yii. Let's see:
The "rules" method (in the models) should be only used to columns that are filled by the user. In your case, I guess "entity_id" is handled by the server, so remove it from "rules". With that new configuration, you can validate both objects before saving.
If validation succeeds, first save one model and use its "id" to save the other one that makes the reference. Something like that:
public function actionCreate()
{
$model1=new Company;
$model2=new Entity;
if(isset($_POST['Company'], $_POST['Entity']))
{
// populate input data to $a and $b
$model1->attributes=$_POST['Company'];
$model2->attributes=$_POST['Entity'];
// validate BOTH $a and $b
$valid=$model1->validate();
$valid=$model2->validate() && $valid;
if($valid)
{
$model2->save( );
$model1->entity_id = $model2->id;
$model1->save( );
}
}
$this->render('create', array(
'model1'=>$model1,
'model2'=>$model2,
));
}

kohana form validation

There is a 'main.php' view that contains a form with email and name fields and a submit button. Eveyrthing works fine with action_index (the code is below), but I'm curious how to modify the code below so it validates if the email was entered correctly. It should not put values in the database if the email field is not valid. I hope it is possible to made using ->rule. Is it? If yes, then how where to add the validation? (I had no luck trying it in different ways).
public function action_index()
{
if ( !empty($_POST) ) {
$model = ORM::factory('tbl1'); // create
$model->values($_POST); // load values to model
if ($model->check()) {
$model->save(); // save the model
} else {
//show errors
}
}
$this->response->body(View::factory('main'));
}
Thank you.
Use rules function in your ORM model:
public function rules()
{
return array(
'email' => array(
array('email', array(':value')),
),
);
}

Problem with `id` field in URL when Editing in CakePHP

I am facing issue about id field in the regular http://localhost/bekzcart/admin/users/edit/6 structure.
I have 6 fields for user, all are validated as 'non empty' through model. While editing one user I put one hidden field.
On submitting the form, naturally it gives me error (coming from model) saying 'non empty'. Without entering anything in that field, I hit submit again, now I face the issue.
What happens this time is that 'id' field from the url is now gone, http://localhost/bekzcart/admin/users/edit) and there is a new entry in database (ideally it should update though).
What might be the error?
My Users Controller:
class UsersController extends AppController {
var $name = 'Users';
function admin_edit($id) {
$this->User->id = $id;
$userLevels = $this->User->Level->find('list', array('fields' => array('LEVEL_ID', 'lEVEL_NAME')));
$this->set('levels', $userLevels);
if (empty($this->data)) {
$this->data = $this->User->read();
} else {
$this->User->set($this->data);
if ($this->User->validates(array('fieldList' => array('USER_LOGIN', 'USER_NAME', 'USER_EMAIL', 'USER_ADDRESS', 'USER_PHONE')))) {
$this->data['User']['USER_MODIFIED'] = DboSource::expression('NOW()');
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('Edit User Success.', true));
} else {
$this->Session->setFlash(__('Something wrong with the query', true));
}
}
}
}
}
User Model:
class User extends AppModel {
var $name = 'User';
var $primaryKey = 'USER_ID';
// Validation in here
// Association in here
}
My related view: admin_edit.ctp
$this->Form->input('id', array('type' => 'hidden')) // The Hidden Id Not Work
Many-many thanks for advance,
regrad
Brian ...
what version of cake are you using? update to the latest one, echo $this->Form->input('id'); will automatically be hidden.
And post the full code that generates the form, the output form should be something like this:
<form id="AdminUserEditForm" accept-charset="utf-8" action="/admin/users/edit/1" method="post">
One more suggestion: add 'created' and 'modified' fields to your users table (type datetime). Cake will keep track of these fields for you.
The field id must be replaced by the primary key used by the related table, in this case is USER_ID
$this->Form->input('USER_ID', array('type' => 'hidden'))

Categories