Yii2-How to access a variable from model to a controller? - variables

I am working on yii2. I have came across a point in which I have to send an email to a person when a meter is installed and it's images are uploaded to the server. Fro this I have already configured the swift mailer.
There is a model named Installations which have a function which saves all the installation data.
public static function saveAll($inputs){
$coutner = 0;
$arr_status = [];
foreach ($inputs as $input) {
$s = new Installations;
foreach ((array)$input as $key => $value) {
if($key != 'image_names') {
if ($s->hasAttribute($key)) {
$s->$key = $value;
}
}
}
$user = Yii::$app->user;
if (isset($input->auth_key) && Users::find()->where(['auth_key' => $input->auth_key])->exists()) {
$user = Users::find()->where(['auth_key' => $input->auth_key])->one();
}
$s->created_by = $user->id;
if (Installations::find()->where(['ref_no' => $input->ref_no])->exists()) {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 2, 'messages' => "Ref # Already exists"];
continue;
}
$s->sync_date = date('Y-m-d H:i:sā€Šā€Š');
if($s->save()){
if ($s->istallation_status == 'Installed') {
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[4]);
}
else if ($s->istallation_status != 'Installed' && $s->comm_status =='Failed')
{
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[5]);
}
$arr_status[] = ['install_id' => $input->install_id, 'status' => 1];
$coutner++;
if (isset($input->doc_images_name)) {
foreach ($input->doc_images_name as $img) {
$image = new InstallationImages;
$image->image_name = $img->image_name;
$image->installation_id = $s->id;
$image->save();
}
}
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img2) {
$image2 = new InstallationImagesSite;
$image2->image_name = $img2->image_name;
$image2->installation_id = $s->id;
$image2->save();
}
}
}else{
$arr_status[] = ['install_id' => $input->install_id, 'status' => 0, 'messages' => $s->errors];
}
$status = $s->istallation_status;
$msn = $s->meter_msn;
$com = $s->comm_status;
// want to pass these variables to the controller function
}
return ['status' => 'OK', 'details' => $arr_status, 'records_saved' => $coutner];
}
Now There Is a Controller name InstallationController. This controller contains all the APIs for my mobile application. Below are two main functions in it
public function actionAddnew()
{
$fp = fopen('debugeeeeeee.txt', 'w+');
fwrite($fp, file_get_contents('php://input'));
fclose($fp);
$inputs = json_decode(file_get_contents('php://input'));
return Installations::saveAll($inputs);
}
public function actionSavephoto()
{
try {
$count = 0;
foreach ($_FILES as $f) {
$dd = pathinfo($f['name']);
if (!isset($dd['extension']) || !in_array($dd['extension'], array('jpg', 'png', 'gif'))) {
return ['status' => 'ERROR', 'uploaded_files' => $count, 'message' => 'Invalid File'];
break;
}
if (move_uploaded_file($f['tmp_name'], Installations::UPLOAD_FOLDER . $f['name'])) {
$count++;
return ['status' => 'OK', 'uploaded_files' => $count];
break;
} else {
return ['status' => 'ERROR', 'uploaded_files' => $count];
break;
}
}
} catch (Exception $x) {
return ['status' => 'ERROR', 'message' => $x->getMessage()];
}
}
The mobile application will call the Addnew() api and after that it will call the savephoto. Now I want to pass $msn,$status and $com values from the Model to the controller function Savephoto.
For this I have tried to use session variables but still I am unable to get by desired result(s).
I have also checked the question Yii, how to pass variables to model from controller?
but it didn't worked for me.
How can I achieve it?
Any help would be highly appreciated.

The only way to get those values out of saveAll() is to return them. Presently, they are defined on an object in $s that is overwritten each loop. The best way to do that seems to be creating an array outside of your foreach ($inputs... loop and appending each created Installations object.
Return that at the end, and pass it (or just the relevant element from it) into actionSavephoto() as a parameter. Then, those values will be accessible of properties of that passed object. This handling will occur in the code that is not pictured which calls actionAddNew() and then actionSavephoto()

Related

Kendo UI Scheduler incorrectly calling WebAPI

I have been looking around the Telerik forums & Stackoverflow for an answer for this and I am completely stuck and unable to figure out the issue.
I am using the Kendo UI for Asp.Net Core Scheduler Control. I have it reading the data from my controller fine. However, I cannot get it call the HttpPut handler correctly.
When checking the traffic I get the following response, and therefor my breakpoint inside my HttpPut handler will never be hit.
400 - Bad Request
{"":["The input was not valid."]}
My code in my view is:
#(Html.Kendo().Scheduler<MeetingViewModel>()
.Name("SchedulerView")
.Height(500)
.Date(DateTime.Now.ToUniversalTime())
.StartTime(new DateTime(2018, 11, 28, 0, 00, 00).ToUniversalTime())
.MajorTick(30)
.ShowWorkHours(false)
.Footer(false)
.Editable(edit =>
{
//edit.Resize(false);
edit.Create(false);
})
.Views(views =>
{
views.TimelineView(timeline => timeline.EventHeight(50));
//views.TimelineWeekView(timeline => timeline.EventHeight(50));
//views.TimelineWorkWeekView(timeline => timeline.EventHeight(50));
//views.TimelineMonthView(timeline =>
//{
// timeline.StartTime(DateTime.Now);
// timeline.EndTime(DateTime.Now.AddMonths(1));
// timeline.MajorTick(1440);
// timeline.EventHeight(50);
//});
})
.Timezone("Etc/UTC")
.Group(group => group.Resources("WorkCenters" /*,"Attendees"*/).Orientation(SchedulerGroupOrientation.Vertical))
.Resources(resource =>
{
resource.Add(m => m.ScheduleRowID)
.Title("Work Center")
.Name("WorkCenters")
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(#Model.AvailableWorkCenters);
})
.DataSource(d => d
.ServerOperation(true)
.WebApi()
.Model(m =>
{
m.Id(f => f.ActivityID);
m.Field(f => f.Title).DefaultValue("No title");
//m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Description).DefaultValue("No Description");
})
.Events(events => events.Error("error_handler"))
.Read(read => read.Action("GetActivities", "Scheduler").Data("setRequestDateTimes"))
//.Create(create => create.Action("Post", "Scheduler"))
.Update(update => update.Action("PutActivity", "Scheduler", new { id = "{0}" }).Type(HttpVerbs.Put))
//.Destroy(destroy => destroy.Action("Delete", "Scheduler", new { id = "{0}" }))
)))
And my API Controller is as follows:
[Route("Api/[controller]")]
[ApiController]
public class SchedulerController : DawnController
{
public SchedulerController(DatabaseContext context) : base(context)
{
}
[HttpGet]
public DataSourceResult GetActivities([DataSourceRequest] DataSourceRequest request, DateTime requestStartDateTime, DateTime requestEndDateTime)
{
//Kendo doesnt seem to send the full date range. so + 1 day to end
requestEndDateTime = requestEndDateTime.AddDays(1);
List<MeetingViewModel> test = new List<MeetingViewModel>();
foreach (JobTask jobTask in Context.JobTask)
{
if (JobTask.HasActivityInDateRange(jobTask, requestStartDateTime, requestEndDateTime))
{
foreach (Activites jobTaskAct in jobTask.Activites)
{
test.Add(new MeetingViewModel()
{
JobTaskID = jobTask.JobTaskId,
ActivityID = jobTaskAct.ActivityId,
Title = jobTaskAct.Name,
Description = jobTaskAct.Description,
Start = jobTaskAct.StartTime.ToUniversalTime(),
End = jobTaskAct.EndTime.ToUniversalTime(),
IsAllDay = false,
ScheduleRowID = jobTaskAct.Workcenter.WorkCenterId,
});
}
}
}
return test.ToDataSourceResult(request);
}
[HttpPut("{id}")]
public IActionResult PutActivity(int id, MeetingViewModel task)
{
if (ModelState.IsValid && id == task.ActivityID)
{
try
{
//breakpoint here
bool a = true;
//update the db here
}
catch (DbUpdateConcurrencyException)
{
return new NotFoundResult();
}
return new StatusCodeResult(200);
}
else
{
return BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
}
}
}
Thanks
The URL exposing your controller method PutActivity in your controller example is PUT api/scheduler/{id}
To access that URL use this Update method.
.Update(update => update.Action("Put", "Scheduler", new { id = "{0}" }))
See this demo as example
Alternatively
If you want to implment the URL api/Scheduler/PutActivity/{id} (similar pattern to your GET) then you will need to modify the attribute over the put method as follows.
[HttpPut("PutActivity/{id}")]
public IActionResult PutActivity(int id, MeetingViewModel task)
Then you can call api/Scheduler/PutActivity/{id} with this asp.net action call.
.Update(update => update.Action("PutActivity", "Scheduler", new { id = "{0}" }).Type(HttpVerbs.Put))

Yii2 signup without saving session data

I have registration form in my Yii2 advanced application. In my application only admin can register users. But when I register new user, admin session data are destroyed and new user's session data are set. What I am trying is not to change session data when I register new user. Admin user is still should be set to session data. How to solve this problem. This is my action in controller:
public function actionSignup()
{
$model = new SignupForm();
if(Yii::$app->user->can('admin'))
{
if (($response = self::ajaxValidate($model)) !== false)
return $response;
if (self::postValidate($model))
{
try
{
$trans = Yii::$app->db->beginTransaction();
if ($user = $model->signup()) {
Yii::$app->getUser()->login($user);
}
//tagidan tushgan odamining child_left, child_right tini o'zgartirish
$under = UserModel::findOne($user->id_parent_under);
if ($under->id_child_left == 0)
$under->id_child_left = $user->id;
else
$under->id_child_right = $user->id;
$under->update(false);
ChildrenBinaryModel::insertNewUser($user);
ChildrenClassicModel::insertNewUser($user);
$parents = ChildrenBinaryModel::find()->with('user')->where(["id_child" => $user->id])->orderBy(['depth' => SORT_ASC])->all();
$c_user = $user;
foreach($parents as $p)
{
$p_user = $p->user;
if ($p_user->id_child_left == $c_user->id)
$p_user->ball_left += 100;
else
$p_user->ball_right += 100;
$p_user->update(false);
$c_user = $p_user;
}
$trans->commit();
}
catch(\Exception $e)
{
$trans->rollBack();
return $this->renderContent($e->getMessage());
}
return $this->render('index');
}
return $this->render('signup', [
'model' => $model,
]);
}else{
throw new ForbiddenHttpException;
}
}
Checkout the documentation for \yii\web\User::login(). When this is run in your code by calling Yii::$app->getUser()->login($user), the session data is set to match your $user.
If it's always the admin user that's signing up new users, I'm not sure you even need to run the login method.
I have solved this problem. In order to make answer clearly and simple I will show you default signup action in site controller (Yii2 advanced template):
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->user->enableSession = false &&
Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
Only I have done was adding this
Yii::$app->user->enableSession = false
inside the if statement

Magento product.create websites argument

I have a question about the websites argument in the magento api.
Nowhere can I find an explanation of what this variable is.
Does this variable represent a storeview? a store? a website?
Where in the api can I retrieve a list of available options?
If I cannot retrieve a list from the API, where in the backend menu can I find the static variable that I can use?
Do I need the website ID or storeID?
I use soap v1
function call($which,$vars=null)
{
// retourneer de output soap client api call
if($vars !== null)
{
return $this->soapclient->call($this->sessiontoken,$which,$vars);
}
else
{
return $this->soapclient->call($this->sessiontoken,$which);
}
}
function createProduct($productname,
$websites,
$shortdescription,
$description,
$status,
$weight,
$tax_class_id,
$categories,
$price,
$attributesetid,
$producttype,
$sku)
{
$attributeSets = $this->call('product_attribute_set.list');
$set = current($attributeSets);
try
{
$x = $this->call('product.create', array($producttype, $set['set_id'], $sku, array(
'name' => $productname,
// websites - Array of website ids to which you want to assign a new product
'websites' => $websites, // array(1,2,3,...)
'short_description' => $shortdescription,
'description' => $description,
'status' => $status,
'weight' => $weight,
'tax_class_id' => $tax_class_id,
'categories' => $categories, //3 is the category id(array(3))
'price' => $price
);));
}
catch(Exception $e)
{
$x = 0xABED + 0xCAFE + 0xBAD + 0xBED * 0xFACE;// abed went to a cafe... the alcohol went bad.... he stumbled into bed and fell face down...
}
return $x;
}
Looking at Mage_Catalog_Model_Product_Api::create():
public function create($type, $set, $sku, $productData, $store = null)
{
//[...]
$product = Mage::getModel('catalog/product');
$product->setStoreId($this->_getStoreId($store))
->setAttributeSetId($set)
->setTypeId($type)
->setSku($sku);
//[...]
$this->_prepareDataForSave($product, $productData);//this does some processing
Now, looking at Mage_Catalog_Model_Product_Api::_prepareDataForSave():
protected function _prepareDataForSave($product, $productData)
{
if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
$product->setWebsiteIds($productData['website_ids']);
}
//....
we see that website_ids (numeric array) are expected

Allow user to change password Cakephp 2

I've looked over various approaches, and various questions published on this subject, but with no luck. In my case, the controller code "appears" to work, and the message flashes up "Your changes have been saved", but the password database field is unchanged. Is there something I am missing?
Controller code
public function changepass($id = null) {
$this->layout = 'profile_page';
//$this->request->data['User']['id'] = $this->Session->read('Auth.User.id');
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $this->Auth->user('id'))
)); // 'User.id' => $id
$this->set('user',$user);
if ($this->request->is('post') || $this->request->is('put'))
{
$this->User->saveField('password', AuthComponent::password($this->request->data['User']['newpass']));
// $this->User->saveField('password', $this->data['User']['password']);
// $this->data['User']['password']= $this->request->data['User']['newpass'];
if ($this->User->save($this->request->data))
{
$this->Session->setFlash(__('Your password has been changed!'));
$this->redirect(array('controller'=>'articles','action'=>'index'));
}
else
{
$this->Session->setFlash(__('Whoops! Something went wrong... try again?'));
$this->redirect(array('controller'=>'users','action'=>'changepass'));
}
}
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']); // tried commenting out
}
Model
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
if (isset($this->data[$this->alias]['newpass'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['newpass']);
}
}
return true;
}
Of course later I'd put in existing password check, and confirm new password check, but i need to get the existing password update basic approach working.
Many thanks in advance for any light you can shed on this,
I think I've sussed this. First, major bloop on my part - in my view I'd put echo $this->Form->create('User', array('action' => 'edit')); -- of course change action to 'changepass'
New Controller code:
public function changepass ($id = null) {
$this->layout = 'profile_page';
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
//debug($this->request->data);
if ($this->request->is('post') || $this->request->is('put')) {
$this->data['User']['password']= $this->request->data['User']['newpass'];
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Your password changes have been saved'));
$this->redirect(array('controller' => 'articles', 'action' => 'index'));
} else {
$this->Session->setFlash(__('The profile could not be saved. Please, try again.'));
}
} else {
if ($this->Auth->user('id')!= $id) {
$this->Session->setFlash('You are not allowed that operation!');
$this->redirect(array('controller' => 'articles', 'action' => 'index'));
}
$this->request->data = $this->User->read(null, $id);
debug($this->request->data);
unset($this->request->data['User']['password']);
}
}
Model - tidied up as per advice from eboletaire
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
if (isset($this->data[$this->alias]['newpass'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['newpass']);
}
return true;
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->data['User']['password']= $this->request->data['User']['newpass'];
if ($this->User->save($this->request->data)) {
Should be
if ($this->request->is('post') || $this->request->is('put')) {
$this->data['User']['id'] = $id;
$this->data['User']['password']= $this->request->data['User']['newpass'];
if ($this->User->save($this->data)) {
Watch out for $this->data vs $this->request->data.
First of all, you are saving the password twice. Remove/comment this line:
$this->User->saveField('password', AuthComponent::password($this->request->data['User']['newpass']));
Anyway, I think the problem is in your model. Check out your beforeSave method. Why are you setting password first with field password and then with field newpass???
PD. Cleaning up your code I've also seen that maybe the second if should be outside the first one.

How to let the user choose the upload directory?

I have a form used to upload images in my blog engine. The files are uploaded to web/uploads, but I'd like to add a "choice" widget to let the users pick from a list of folders, for instance 'photos', 'cliparts', 'logos'.
Here's my form
class ImageForm extends BaseForm
{
public function configure()
{
$this->widgetSchema->setNameFormat('image[%s]');
$this->setWidget('file', new sfWidgetFormInputFileEditable(
array(
'edit_mode'=>false,
'with_delete' => false,
'file_src' => '',
)
));
$this->setValidator('file', new mysfValidatorFile(
array(
'max_size' => 500000,
'mime_types' => 'web_images',
'path' => 'uploads',
'required' => true
)
));
$this->setWidget('folder', new sfWidgetFormChoice(array(
'expanded' => false,
'multiple' => false,
'choices' => array('photos', 'cliparts', 'logos')
)
));
$this->setValidator('folder', new sfValidatorChoice(array(
'choices' => array(0,1,2)
)));
}
}
and here is my action :
public function executeAjout(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
{
$this->form->bind(
$request->getParameter($this->form->getName()),
$request->getFiles($this->form->getName())
);
if ($this->form->isValid())
{
$this->form->getValue('file')->save();
$this->image = $this->form->getValue('file');
}
}
I'm using a custom file validator :
class mySfValidatorFile extends sfValidatorFile
{
protected function configure($options = array(), $messages =
array())
{
parent::configure();
$this->addOption('validated_file_class',
'sfValidatedFileFab');
}
}
class sfValidatedFileFab extends sfValidatedFile
{
public function generateFilename()
{
return $this->getOriginalName();
}
}
So how do I tell the file upload widget to save the image in a different folder ?
You can concatenate the directory names you said ('photos', 'cliparts', 'logos') to the sf_upload_dir as the code below shows, you will need to create those directories of course.
$this->validatorSchema['file'] = new sfValidatorFile(
array('path' => sfConfig::get('sf_upload_dir' . '/' . $path)
));
Also, you can have those directories detailes in the app.yml configuration file and get them calling to sfConfig::get() method.
I got it to work with the following code :
public function executeAdd(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
{
$this->form->bind(
$request->getParameter($this->form->getName()),
$request->getFiles($this->form->getName())
);
if ($this->form->isValid())
{
//quel est le dossier ?
switch($this->form->getValue('folder'))
{
case 0:
$this->folder = '/images/clipart/';
break;
case 1:
$this->folder = '/images/test/';
break;
case 2:
$this->folder = '/images/program/';
break;
case 3:
$this->folder = '/images/smilies/';
break;
}
$filename = $this->form->getValue('file')->getOriginalName();
$this->form->getValue('file')->save(sfConfig::get('sf_web_dir').$this->folder.$filename);
//path :
$this->image = $this->folder.$filename;
}
}