Add yii2 event handler in model itself - yii

In my user model I need to send email after inserting a new record. I can't wait exicution for sending email, because it take too much time. So I tried to use Event handler inside Model itself
class User extends ActiveRecord {
public function events()
{
return [
User::EVENT_AFTER_INSERT => [$this, 'sendEmail']
];
}
public function sendEmail(){
Yii::$app->mailer->compose()
->setTo($this->email)
->setFrom(['mail address' => 'name'])
->setSubject('Verify your Email')
->setHtmlBody('<p>Please click on the <a href="'.Yii::$app->request->hostInfo.'/'.Yii::$app->params['frontEndUrl'].'#/verify-email/'
.$this->emailToken.
'">link</a> to verify your email</p>')
->send();
}
}
But it is not working any idea?

You probably come from a javascript background, but events in PHP do not work that way (in Javascript it does). If you raise an event it will get caught but not in a new process. Even if you manage to do what you want it will still wait for the email to be sent out.
The solution would be to use some sort of queue, the simplest one just insert a record in an "email" table in the DB and move on. You can have a cronjob that processes the email table and sends out the actual emails.

Related

How to subscribe and unsubscribe from EventStream on the first event received?

I am trying to figure it out if there is a function in the Bacon.js API that allows to subscribe to an EventStream and when the first event fires up, the handle is unsubscribed. The way to do it that I know is the following:
let stream = new Bacon.Bus();
stream.onValue(val => {
doSomething(val);
return Bacon.noMore;
});
But is there something like stream.onValueOnce that automatically unsubscribe the handler after it is executed?
I also know that there is the Bacon.once that creates a EventStream that returns a single value and then ends the stream but this is not what I am looking for.
Update
As Bless Yahu sais, take or first methods can be used. To be more specific, you have to call it from the created eventStream like that:
let stream = new Bacon.Bus();
stream.first().onValue(val => {
doSomething(val);
});
Here is a fiddle that shows it:
https://fiddle.jshell.net/3kjtwcwy/
How about stream.take(1)? https://baconjs.github.io/api.html#observable-take
Or stream.first()? https://baconjs.github.io/api.html#observable-first

How to reuse data between routes in Aurelia?

I have an user entity in the system and the following route fetches it from server and displays its details:
routerConfiguration.map([
// ...
{route: 'user/:id', name: 'user-details', moduleId: './user-details'}
]);
Now I want to display an edit form for the displayed user. I have the following requirements:
Edit form should have a separate URL address, so it can be sent to others easily.
When user clicks the Edit button on the user's details page, the edit form should use an already loaded instance of the user (i.e. it should not contact the API again for user details).
When user clicks the Edit button on the user's details page and then the Back button in the browser, he should see the details page without edit form again.
1st attempt
I tried to define the edit form as a separate page:
routerConfiguration.map([
// ...
{route: 'user/:id/edit', name: 'user-edit', moduleId: './user-edit'}
]);
This passes the #1 and #3 requirement but it has to load the user again when the edit form is opened.
I don't know any way to smuggle some custom data between the routes. It would be perfect if I could pass the preloaded user instance to the edit route and the edit component would use it or load a new one if it is not given (e.g. user accesses the URL directly). I have only found how to pass strings to the routes in a slighlty hacky way.
2nd attempt
I decided to display the edit form in a modal and show it automatically when there is a ?action=edit GET parameter. The code inspired by this and this question:
export class UserDetails {
// constructor
activate(params, routeConfig) {
this.user = /* fetch user */;
this.editModalVisible = params.action == 'edit';
}
}
and when the user clicks the Edit button, the following code is executed:
displayEditForm() {
this.router.navigateToRoute('user/details', {id: this.user.id, action: 'edit'});
this.editModalVisible = true;
}
This passes #1 (the edit url is user/123?action=edit) and #2 (the user instance is loaded only once). However, when user clicks the Back browser button, the URL changes as desired from user/123?action=edit to user/123 but I have no idea how to detect it and hide the edit form (the activate method is not called again). Therefore, this solution fails the #3 requirement.
EDIT:
In fact, I have found that I can detect the URL change and hide the edit form with event aggregator:
ea.subscribe("router:navigation:success",
(event) => this.editModalVisible = event.instruction.queryParams.action == 'edit');
But still, I want to know if there is a better way to achieve this.
The question is
How to cope with this situation in a clean and intuitive way?
How about adding a User class that will serve as the model and use dependency injection to use it in your view-models?
export class User {
currentUserId = 0;
userData = null;
retrieve(userId) {
if (userId !== this.currentUserId) {
retrieve the user data from the server;
place it into this.userData;
}
return this.userData;
}
}

How do you poll for a condition in Intern / Leadfoot (not browser / client side)?

I'm trying to verify that an account was created successfully, but after clicking the submit button, I need to wait until the next page has loaded and verify that the user ended up at the correct URL.
I'm using pollUntil to check the URL client side, but that results in Detected a page unload event; script execution does not work across page loads. in Safari at least. I can add a sleep, but I was wondering if there is a better way.
Questions:
How can you poll on something like this.remote.getCurrentUrl()? Basically I want to do something like this.remote.waitForCurrentUrlToEqual(...), but I'm also curious how to poll on anything from Selenium commands vs using pollUntil which executes code in the remote browser.
I'm checking to see if the user ended up at a protected URL after logging in here. Is there a better way to check this besides polling?
Best practices: do I need to make an assertion with Chai or is it even possible when I'm polling and waiting for stuff as my test? For example, in this case, I'm just trying to poll to make sure we ended up at the right URL within 30 seconds and I don't have an explicit assertion. I'm just assuming the test will fail, but it won't say why. If the best practice is to make an assertion here, how would I do it here or any time I'm using wait?
Here's an example of my code:
'create new account': function() {
return this.remote
// Hidden: populate all account details
.findByClassName('nextButton')
.click()
.end()
.then(pollUntil('return location.pathname === "/protected-page" ? true : null', [], 30000));
}
The pollUntil helper works by running an asynchronous script in the browser to check a condition, so it's not going to work across page loads (because the script disappears when a page loads). One way to poll the current remote URL would be to write a poller that would run as part of your functional test, something like (untested):
function pollUrl(remote, targetUrl, timeout) {
return function () {
var dfd = new Deferred();
var endTime = Number(new Date()) + timeout;
(function poll() {
remote.getCurrentUrl().then(function (url) {
if (url === targetUrl) {
dfd.resolve();
}
else if (Number(new Date()) < endTime) {
setTimeout(poll, 500);
}
else {
var error = new Error('timed out; final url is ' + url);
dfd.reject(error);
}
});
})();
return dfd.promise;
}
}
You could call it as:
.then(pollUrl(this.remote, '/protected-page', 30000))
When you're using something like pollUntil, there's no need (or place) to make an assertion. However, with your own polling function you could have it reject its promise with an informative error.

implement a simple inbox with notifications in yii

I want to implement a simple inbox in yii. it reads messages from a database table and show it.
but i don't know how i should show read and unread messages in different styles and how i can implement a notification for new messages.
i searched a lot but only found some extensions and i don't want to use them.
it is so important to find how i can show unread messages in a different way
any initial idea would help me
a part of mailbox extension code :
public function actionInbox($ajax=null)
{
$this->module->registerConfig($this->getAction()->getId());
$cs =& $this->module->getClientScript();
$cs->registerScriptFile($this->module->getAssetsUrl().'/js/mailbox.js',CClientScript::POS_END);
//$js = '$("#mailbox-list").yiiMailboxList('.$this->module->getOptions().');console.log(1)';
//$cs->registerScript('mailbox-js',$js,CClientScript::POS_READY);
if(isset($_POST['convs']))
{
$this->buttonAction('inbox');
}
$dataProvider = new CActiveDataProvider( Mailbox::model()->inbox($this->module->getUserId()) );
if(isset($ajax))
$this->renderPartial('_mailbox',array('dataProvider'=>$dataProvider));
else{
if(!isset($_GET['Mailbox_sort']))
$_GET['Mailbox_sort'] = 'modified.desc';
$this->render('mailbox',array('dataProvider'=>$dataProvider));
}
}
First of all the scripts things should be in the view. For you problem I would do something like
In the controller
$mailbox = Mailbox::model()->inbox($this->module->getUserId()); //I assume this returns the mailbox from that user?
$this->renderPartial('_mailbox',compact('mailbox ')); //compact is the same as array('mailbox'=>$mailbox) so use whatever you prefer.
In the view I would simply do something like this
<?php foreach($mailbox->messages as $message):
$class = ''; //order unread if you want to give both a different class name
if($message->read): //if this is true
$class = 'read';
endif; ?>
<div id='<?= $message->id ?>'class='message $class'> <!-- insert whatever info from the message --></div>
<?php endforeach; ?>
So now it will add the class read to every message that has been read. Then in CSS you can simply change it style. I hope this is enough information? I use foreach(): endforeach; and if(): endif; in the view files, but you could use foreach() {}, but I prefer foreach, as it looks better combined with HTML.
EDIT about you second question, how do they become read. This you could do with JQUERY. example.
$(".message").on("click", function() {
var id = $(this).attr('id');
$.ajax {
type:"POST",
url: "controller/action/"+id; //the controller action that fetches the message, the Id is the action variable (ex: public function actionGetMessage($id) {})
completed: function(data) {
//data = the message information, you might do type: 'JSON' instead. Use it however you want it.
if(!$(this).hasClass("read"))
$(this).addClass("read"); //give it the class read if it does not have it already
}
}
});
This simply gives the div the class read and it should look like the other items with the class read.

Laravel 3 - Passing variables across multiple views

I have two forms on two different views. I would like to post the form input to the second view, and then back to the first form upon posting the second form.
I have set up a test with a route that looks like this :
Route::get('/test1', function() {
return View::make('test1');
});
Route::post('/test2', function() {
$flash = Input::get();
return View::make('test2')->with('flash', $flash);
});
Route::post('/test1', function() {
return View::make('test1')->with('flash', $flash);
});
I am only able to pass $flash once. I'm misunderstanding why I cannot pass it again. I feel like I have to extract it again?
You need to add a form field in /test2 and resubmit the $flash data in order to pass it to /test1 via POST. It's a new request, the app will lose the $flash var otherwise.
A different approach could be to store $flash in a session with Session::put('flash', $flash); and accessing it in the next request.
The best method is to store your data in session. It will be available across multiple request . Using Input::flash() will only be available until the next request. See the Laravel docs for Input::flash() and Session