After publish node send email to someone - drupal-7

Let's say i have a custom module in D7 , i want to add a feature to this .
the feature is : when a user publish a node send an email to someone .
<?php
function sending_email_node_update($node) {
if (isset($node->original->status) && $node->original->status == 0 && $node->status == 1) {
drupal_mail('sending_email', 'sending_email_node_update', 'soheilsadeghbayan#yahoo.com', language_default());
}
}
function sending_mail_mail($key, &$message, $params) {
switch ($key) {
case 'sending_email_node_update':
$message['subject'] = t('this is my action report');
$message['body'][] = t('this is a reporting from sending email made by soheil') ;
break;
}
}
?>
No email send !!!
Could you please help me how to do this ?

#Soheil You can use Rules module to achieve this. Create rule event when particular content type's node has been published and in action block trigger the mail.
Bit late but hope that helps others... :)

Related

Laravel array validation if atleast one fails return single message

I have form where I can add up to 30 option fields (option[1], option[2], ...) and for now Im using 'option.*' => 'required' rule in request validation but with this there is a little problem, if you submit form with all option fields empty it shows long error message with each option field required, but I need that it shows only one message for all options like: "Each option field is required".
Any ideas how to make it?
Thanks!
I found a solution to this. I will post it here in case somebody needs it:
Basically, you need to override formatErrors method in your request validation class
protected function formatErrors(Validator $validator)
{
$errors = parent::formatErrors($validator);
// this will remove the keys that have index larger than 0
$keys = array_filter(array_keys($errors), function($item) {
$parts = explode('.', $item);
// you might want to modify this to match your fields,
// I had another level of keys
if (count($parts) === 3 and is_numeric($parts[1]) and (int)$parts[1] > 0) {
return false;
}
return true;
});
$errors = array_intersect_key($errors, array_flip($keys));
return $errors;
}

joomla - Storing user parameters in custom component issue

Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.
Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).

Only one tinyint positive in CakePHP model

In my model, let's call it "questions", I have "active" field (TINYINT). The idea is, that only one entry in that particular model can be active. So when I update one entry by checking "active" checkbox, this entry should turn into active, and the other one should turn into unactive (I mean that one which has been active before). Any idea what query should I use?
some kind of toggle behavior for example.
this behavior you write makes the model $actsAs = array('Toggable', array('field'=>'active'));
and in your afterSave hook you make an updateAll call to reset all active ones to inactive (except the current id of course)
that would be the cleanest approach.
of course, you can always make a quick-and-dirty one using the models hooks itself for this.
I don't know how to do that. It's little above my current knowledge :)
This is how I figured it out so far:
function admin_edit($id = null) {
$this->Question->id = $id;
if (empty($this->data)) {
$this->data = $this->Question->read();
} else {
if ($this->Question->save($this->data)) {
$active = $this->data['Question']['active'];
$total = $this->Question->find('count');
$i=1;
if ($i == '1') {
while($active <= $total){
$this->Question->query("UPDATE questions SET active = '0'");
$i++;
}
$this->Question->query("UPDATE questions SET active = '1' WHERE id = '$id'");
}
$this->redirect(array('action' => 'index'));
}
}
And it's working but I guess it's not the "cleanest approach". Any tips how to simplify it thereafter?

CakePHP Shell Script Environment Setting

I am new to shell development in Cake. The problem I am facing is to setting datasource in the script itself. My database.php is;
function __construct()
{
if(getenv('ENVIRONMENT') == 'staging') {
$this->default = $this->staging;
} else {
$this->default = $this->production;
}
}
So, I am setting database based on the web server's environment setting. Naturally, php-cli can't access this variable. What I end up doing is to create a cakephp shell task.
class SelectEnvTask extends Shell {
public function execute()
{
App::Import('ConnectionManager', 'Model');
$configs = ConnectionManager::enumConnectionObjects();
if (!is_array($configs) || empty($configs)) {
$this->out('Error! No database configuration has been found.');
}
$connections = array_keys($configs);
if(!isset($this->args[0])) {
$this->out('Error! Please enter one of the environment settings as an argument: ' . implode('/', $connections) .
"\n\n" . 'eg. ./Console/cake *script_name* *environment*', 2);
exit(1);
}
if(!in_array($this->args[0], $connections)) {
$this->out($this->args[0] . ' environment could not be found!', 2);
exit(1);
}
//hacky solution until finding a better one
$models = App::objects('Model');
foreach($models as $model) {
ClassRegistry::init($model)->setDataSource($this->args[0]);
}
}
}
This works correctly, however as you see in the below of the task, I get all the model names and change their DB connection, which is not a good practice. I also don't want to set more variables into the database class and would like to handle these in shells/tasks.
Is there any more elegant way to achieve this?
Thanks,
Here is a far more elegant solution. Add the following method to your shell or task, and then execute it whenever you need to in order to change your data profile (listed in app/Config/database.php) on the fly:
function change_database_profile($database = 'default') {
$connected = ConnectionManager::getDataSource($database);
if($connected->isConnected()) {
return true;
}
return false;
}

How to delete the item?

Hi I have 2 domains in grails app, which is related and I got the problem when I tried to delete items.
Event {
String eventName;
Date eventDate;
Fee eventFee ;
constraints = {
....
eventFee(nullable:true);
}
}
and
Fee{
String feeName ;
.....
}
My problem is when I tried to delete the fee, even if there are no event that attached to that, it will raise en erorr : ConstraintException.
How to solve the problem and how to link between those 2 domains ?
ps: I am using grails 1.2xxx and database mysql
That probably happens because the Fee object that you are trying to delete is being referred to by some Event object. You can see the Events by the following (pseudo-)code:
def fee = Fee.get(<id>)
Event.findAllByEventFee(fee).each {
println it
}
You can then set the eventFee to null for each event and delete the fee:
event.eventFee = null
fee.delete()
I think the relationship is miscoded, you should refered to Fee in
Event {
String eventName;
Date eventDate;
static hasOne=[eventFee:Fee] ;
constraints = {
....
}
}
And
Fee{
String feeName ;
.....
}

Resources