Add multi attribute in scenarios. Yii user - yii2

I want to add multi attribute in scenarios. It is user_lastname, user_status.
It override user model
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['create'][] = 'user_name';
$scenarios['update'][] = 'user_name';
$scenarios['register'][] = 'user_name'; ;
return $scenarios;
}
I sample but I found a problem about array to string conversion
public function scenarios()
{
$scenarios = parent::scenarios();
// add field to scenarios
$scenarios['create'][] = ['user_name','user_lastname','user_status'];
$scenarios['update'][] = ['user_name','user_lastname','user_status'];
$scenarios['register'][] = ['user_name','user_lastname','user_status'];
return $scenarios;
}

Remove array [] from scenario list.
public function scenarios()
{
$scenarios = parent::scenarios();
// add field to scenarios
$scenarios['create'] = ['user_name','user_lastname','user_status'];
$scenarios['update'] = ['user_name','user_lastname','user_status'];
$scenarios['register'] = ['user_name','user_lastname','user_status'];
return $scenarios;
}
Use const to declare scenario names. For Example, const SCENARIO_CREATE = 'create';

If you want to append elements to existing array you need to add every item separately:
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['create'][] = 'user_name';
$scenarios['update'][] = 'user_name';
$scenarios['register'][] = 'user_name';
$scenarios['create'][] = 'user_lastname';
$scenarios['update'][] = 'user_lastname';
$scenarios['register'][] = 'user_lastname';
$scenarios['create'][] = 'user_status';
$scenarios['update'][] = 'user_status';
$scenarios['register'][] = 'user_status';
return $scenarios;
}
$scenarios['create'][] = ['user_name','user_lastname','user_status']; will just add one item as array.

Related

User registration in yii2?

I am getting the following exception
PHP Fatal Error – yii\base\ErrorException
Maximum execution time of 60 seconds exceeded !!!!!!!
public $password;
public function generateAuthKey()
{
return $this->auth_key = Yii::$app->security->generateRandomString();
}
public function setPassword($password)
{
return $this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
public function save($runValidation = true, $attributeNames = null)
{
$user = new Users();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
$this->id = $user->id;
return true;
}
}
in your User model you should canghe the function name save() with another name eg saveUser so this is not recalled by the inner $user->save() that is a normal ActiveRecord function for save.
Calling User->save() as you are doing you produce an infinite nested loop ..
.....
public function saveUser($runValidation = true, $attributeNames = null)
{
$user = new Users();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
$this->id = $user->id;
return true;
}
}
...
In your controller Action eg:action Create you should call your $user->saveUser(...)
*/
public function actionCreateForCatone2()
{
....
$user->saveUser(...);
...
}

laravel 4 output json order desc

I use laravel 4.2
How can I output json in desc order? Thanks.
Below is my code :
public function show($id) {
$member = $this->getMember ();
$transition = $member->getTransition ( $id )->first ();
$transition_info = $transition-> transitionInfo;
return ResponseWrapper::toJson ( $transition_info );
}
...
public function index() {
$member = $this->getMember ();
$transitions = $member->getTransitions ();
return ResponseWrapper::toJson ( $transitions );
}
/* 12/28 update */
Maybe I should change in below model?
(project/app/models/Member.php)
public function getTransitions()
{
$array = $this->hasMany('Transition', 'payeer_id', 'id')->select($this->transition_index_payeer_column)->get()->all();
$arrayb = $this->hasMany('Transition', 'remitter_id', 'id')->select($this->transition_index_remitter_column)->whereRaw('NOT (card_type_remitter = "focas" and focas_status = "")')->get()->all();
$reuslt = array_merge ( $array, $arrayb );
return $reuslt;
}
You should try this:
public function index() {
$member = $this->getMember ();
$transitions = $member->orderBy('id','desc')->getTransitions ();
return ResponseWrapper::toJson ( $transitions );
}
Try this one,
public function index() {
$member = $this->getMember ();
$transitions = $member->getTransitions()->orderBy('id','desc')->get();
return ResponseWrapper::toJson ( $transitions );
}
For Laravel V4 :
$transitions = $member::orderBy('id', 'DESC')->getTransitions();

How to add a fuction in a model yii2

I have modified my signup form, I add a field that called billCode, so I want add a function to my signForm model to random integer number, I have a function to random integr and I put that into signup form model like this
class SignupForm extends Model {
// ...
// ...
public static function randomNumber()
{
$randBill = '';
for ($i=0; $i < 8; $i++){
$randBill .= mt_rand(0, 9);
}
return $randBill;
}
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->billCode = randomNumber();
return $user->save() ? $user : null;
}
}
when I press the submit button in signUp Form, yii2 keep give me this error
Call to undefined function frontend\models\randomNumber()
Any help?
Copy from comment
randomNumber is a static function, you can't call it just by randomNumber(). Using self::randomNumber() could be work.
You can call it by self keyword
class SignupForm extends Model {
// ...
// ...
public static function randomNumber()
{
$randBill = '';
for ($i=0; $i < 8; $i++){
$randBill .= mt_rand(0, 9);
}
return $randBill;
}
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
//$user->billCode = $this->randomNumber();
$user->billCode = self::randomNumber();
return $user->save() ? $user : null;
}
}

How to return a value through a call back function inside a function?

The way I get data is through a callback function [processclinicResults],
and it gives the array Collection to the value object _ClinicVO.
I have a problem that I can not directly get the return arrayCollection through getTableContent function, I tried to return value after
but it returns null.
Does anyone know how to make it easy to get the array?
I just don't want to declare the variables every time when I use the similar funciotn. Or I have to overwrite [clinicData]?
public function getTableContent( resultHandler:Function, faultHandler:Function = null ):void
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = 'SELECT * FROM Clinic;';
stmt.itemClass = ClinicVO;
stmt.addEventListener( SQLEvent.RESULT,
function ( event:SQLEvent ):void {
resultHandler.call( this, new ArrayCollection( stmt.getResult().data ) );
});
stmt.addEventListener( SQLErrorEvent.ERROR, faultHandler == null ? sqlErrorHandler : faultHandler );
stmt.execute();
}
public function errorConnectingToTable(evt:SQLErrorEvent):void {
trace("Error getting information from DB");
}
protected function processClinicResults(resultsArray:ArrayCollection=null):void {
if (resultsArray == null) {
trace("DB has NO data");
//there is no data
} else {
clinicData = resultsArray;
}
}
I could suggest you to use Flex ORM and responders to get access to your local DB as I do:
private var entityManager:EntityManager = EntityManager.instance;
public var LocalDBSqlConnection:SQLConnection;
LocalDBSqlConnection = new SQLConnection();
LocalDBSqlConnection.open(LocalDBFile);
public function loadClinic(responder:IResponder):void
{
var clinics:Array = entityManager.query("SELECT * FROM Clinic") as Array;
responder.result(new ArrayCollection(clinics));
}
Somewhere call this:
loadClinic( new mx.rpc.Responder(onResult, onError));
Handelers:
private function onResult(data:Object):void
{
YourData = data as ArrayCollection;
}
private function onError(info:Object):void
{
}
I'm sorry if it's not the way you are serching for=)

How to map poco to JSON using Automapper

In my MVC 2 application I have a typical method that calls a web service, builds a JSON data object and returns it to the view.
Everything works fine, but I was wondering if there is a way to do the mapping with Automapper so I can remove the ugly code from my controller. Thanks in advance
Here is my Action method
public virtual ActionResult AllErrors(string sidx, string sord,
int page=1, int rows=10)
{
var pageSize = rows;
var pageNumber = page;
var orderBy = string.Format("{0} {1}", sidx, sord);
var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);
int index = 0;
var list = new List<object>();
errors.ForEach(e => list.Add(
new {
i = index++,
cell = new[]
{
e.IngestionErrorId.ToString(),
e.RunId.ToString(),
e.ProcessDate.ToShortDateString(),
e.Status,
e.ErrorDetails
}
}));
var jsonData = new
{
total = totalPages,
page = pageNumber,
records = result.TotalRows,
rows = list.ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I solved it using the ConstructUsing method of AutoMapper.
Here is my map
public void CreateMap()
{
Mapper.CreateMap<List<IngestionErrorDataContract>, object[]>()
.ConvertUsing(
errors =>
{
int index = 0;
var list = new List<object>();
errors.ForEach(e => list.Add(
new
{
i = index++,
cell = new[]
{
e.IngestionErrorId.ToString(),
e.RunId.ToString(),
e.ProcessDate.ToShortDateString(),
e.Status,
e.ErrorDetails
}
}));
return list.ToArray();
});
}
and here is my action method now
public virtual ActionResult AllErrors(string sidx, string sord, int page=1, int rows=10)
{
var pageSize = rows;
var pageNumber = page;
var orderBy = string.Format("{0} {1}", sidx, sord);
var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);
var jsonData = new
{
total = totalPages,
page = pageNumber,
records = result.TotalRows,
rows = mapper.Map<List<IngestionErrorDataContract>,object[]>(errors)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Much better I think