limit email domain - vaidation yii - yii

I have email field in signup form ,
I want to validate email domain with database e.g
Email adress is : example#work.com or etc#etc.com
Now I want validate that work.com or etc.com is listed in db or not , if not then it should not be vaidate.!
Can Anyone help me with this ?

Code:
public function validate($attributes = null, $clearErrors = true) {
parent::validate($attributes, $clearErrors);
if (!$this->hasErrors('email')) {
$a = explode('#', $this->email);
if (isset($a[1])) {
$record = AllowedDomains::model()->findByAttributes(array('domain'=>$a[1]));
if ($record === null) {
$this->addError('email', "This domain isn't allowed");
}
}
}
return !$this->hasErrors();
}
Notes:
put this code in the model
email - the field holding the email address
AllowedDomains - the CActiveRecord of the table that holds the allowed domains
domain - replace with the correct database field
don't forget to add the e-mail validator in the rules() function. This will filter out invalid email addresses and the above code will not run if something's wrong

You could accomplish this by adding a custom yii validator in the rules section of your Model. Here is some example code:
public $email; // This is the field where the email is stored
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('email', 'checkDomain'),
);
}
Afterwards, you can add the custom validation function
public function checkDomain($attribute,$params)
{
$sEmailDomain = substr(strrchr($this->email, "#"), 1);
// Check if the domain exists
...
// If the domain exists, add the error
$this->addError('email', 'Domain already exists in the database');
}
More information can be found here: http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/

Related

I want to get recipient_signing_uri from the Docusign API response but it returns null

Here is the code
public function send(Request $request): object
{
$apiClient = new ApiClient();
$apiClient->getOAuth()->setOAuthBasePath(env('DS_AUTH_SERVER'));
try {
$accessToken = $this->getToken($apiClient);
} catch (\Throwable $th) {
return back()->withError($th->getMessage())->withInput();
}
$userInfo = $apiClient->getUserInfo($accessToken);
$accountInfo = $userInfo[0]->getAccounts();
$apiClient->getConfig()->setHost($accountInfo[0]->getBaseUri() . env('DS_ESIGN_URI_SUFFIX'));
$envelopeDefenition = $this->buildEnvelope($request);
try {
$envelopeApi = new EnvelopesApi($apiClient);
$result = $envelopeApi->createEnvelope($accountInfo[0]->getAccountId(), $envelopeDefenition);
dd($result);
} catch (\Throwable $th) {
return back()->withError($th->getMessage())->withInput();
}
return view('backend.response')->with('result', $result);
}
When I print $result variable it returns a response like this
container: array:8 [
"bulk_envelope_status" => null
"envelope_id" => "b634f8c5-96c5-4a18-947f-59418d8c4e03"
"error_details" => null
"recipient_signing_uri" => null
"recipient_signing_uri_error" => null
"status" => "sent"
"status_date_time" => "2023-02-16T07:24:39.1570000Z"
"uri" => "/envelopes/b634f8`your text`c5-96c5-4a18-947f-59418d8c4e03"
]
I want to get the value of recipient signing uri in response but in my case it returns null
How I can achieve this? Will anyone suggests?
createEnvelope creates the envelope. It does not give you an URL for an embedded recipient view (signing ceremony). In order to get that URL, you need to make an additional call to
EnvelopeViews:createRecipient/
See this page for more info.
Also
$apiClient->getConfig()->setHost($accountInfo[0]->getBaseUri() . env('DS_ESIGN_URI_SUFFIX'));
You are using the first entry in the UserInfo returned data's accountInfo array. That's not a good idea. Instead, look for the entry that is the user's default account.
Or if your application is designed to work with a specific eSign account, then make sure the user has access to that account.
It is very common for DocuSign customers to have access to more than one account.

Yii2 redirect to previous page after update review

I have a page comp/computer?id=15
it has reviews that can be edited through link
http://comp/computer/update?id=3 = with FORM and submit button
how to go back after sumbit
public function actionUpdate($id)
{
$model = new ReviewForm();
$comment = Review::findOne($id);
if ($model->load($this->request->post())) {
$comment->text = $model->text;
if ($comment->save(false)) {
return $this->redirect(["?id=15"], ); ????????????
}
Yii::$app->session->setFlash(
'success',
'Success'
);
}
$model->setAttributes($comment->getAttributes(['name', 'email', 'text']));
return $this->render('update', compact('model'));
}
simply use referrer.
return $this->redirect(Yii::$app->request->referrer)
If it has no referrer or link open directly then you should either pass computer_id as param or you must have computer_id as foreign key in your review table.
Let say you have relationship with review and computer table. then you can use like this.
$compId = $comment->computer_id; // or 15 or you can paas param here
return $this->redirect(["comp/computer", "id"=> $compId]);
if comp is your hostname then
return $this->redirect(["computer", "id"=> $compId]);
its should be controller/action
return $this->redirect(["controllerId/actionId", "id"=> $compId]);
Send via mobile, sorry for typos.

Get roles by name in a 'guildMemberAdd' handler

Since member.guild.roles.get('roleName') no longer works. I'd like to know if there's an alternative to it.
message.guild.roles.cache.find(role => role.name == 'My Role Name') is not an option, since I don't have access to message object inside the 'guildMemberAdd' handler.
My code works fine using the role id, but I'd like to make it usable for other servers.
** updating my question
This is my code:
const role1 = 'the id number here'; ---> this one I'd like to be by name
const role2 = 'the id number here');
if (collected.first().emoji.name === '😎') {
member.roles.add(role1);
} if (collected.first().emoji.name === '🟩'){
member.roles.add(role2);
} else { return}
You can access the guild from GuildMember
client.on('guildMemberAdd', member => {
// member.guild.roles.cache.find(...) - Callback similar to Array#find()
// member.guild.roles.cache.get(...) - string id parameter only
});

Finding an entity that contain only some others entities

I have an association like this :
Chatroom >----< User
So a Chatroom can contains multiple users, and a User can belong to multiple Chatrooms.
Now I want to select all the chatrooms that contains a couple of user, and only this couple.
I tried some solutions, like this one :
public function findByUsers($firstUser, $secondUser){
$qb = $this->createQueryBuilder('c');
$qb
->select('c')
->where('c.users LIKE :firstUser')
->andwhere('c.users LIKE :secondUser')
->setParameters(array(
'firstUser' => $firstUser,
'secondUser' => $secondUser
));
return $qb->getQuery()->getResult();
}
But It doesn't work and return me that kind of error :
[Semantical Error] line 0, col 52 near 'users LIKE :firstUser': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
Some users encountering this error resolved it by adding IDENTITY before the query selector, but I don't understand how to apply it in my case.
So, did someone know how I can get all the chatrooms containing my couple of users ?
Thanks a lot !
EDIT : Adding the doctrine relation annotations
User.php
/**
*
* #ORM\ManyToMany(targetEntity="Chatroom", inversedBy="users")
* #ORM\JoinTable(name="chatrooms_users",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="chatroom_id", referencedColumnName="id")}
* )
*/
private $chatrooms;
Chatroom.php :
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="chatrooms")
*/
private $users;
My final solution was :
public function findByUsers($ids)
{
$count = count($ids);
$qb = $this->createQueryBuilder('chatroom');
$qb->select('chatroom')
->join('chatroom.users', 'u')
->addSelect('COUNT(u) AS HIDDEN ucount')
->groupBy('chatroom.id')
->having('ucount = :count')
->setParameter('count', $count);
foreach ($ids as $key => $id) {
$qb->andWhere(':id' . $key . ' MEMBER OF chatroom.users')
->setParameter('id'.$key, (int) $id);
}
return $qb->getQuery()->getOneOrNullResult();
}
Pass an array of users id (or simply users with some modifications), and the function returns the list of chatrooms that contains only these users

Codeigniter populate nested associations

this is the results i need from the database
{comment: 'hello there', user: [{name: 'sahan', id: 1}], id: 2}
function used to get comments
public function get_comments(){
$query = $this->db->get('comments');
return $query->result_array();
}
I have a comments table and a users table, When a user comments on something the
comment is saved as follows
comment > Comment text
user: userid
So when the data is shown I need codeigniter to populate the user field with the user data found from the users table
Does anyone know how to do this ?
I used this functionality in SailsJS but dont know how to do it here in CodeIG
Sails.js populate nested associations
Codeigniter 's active record is not as advanced as SailJS active record, but you can achieve what you are asking for with two queries within the same method.
I'm assuming the comments table has a foreign key to the users table through a user_id field.
public function get_comments() {
/* Get all the comments */
$query = $this->db->get('comments');
$comments = $query->result_array();
/* Loop through each comment, pulling the associated user from the db */
foreach $comments as &$comment {
$query = $this->db->get_where('users', array('id' => $comment['user_id']));
$user = $query->result_array();
/* Put the user's data in a key called 'user' within the comment array */
$comment['user'] = $user;
/* Remove the unnecessary user_id and $user variable */
unset($comment['user_id']);
unset($user);
}
return $comments;
}