CC field not being applied in CakeEmail - email

I have two emails that get sent out, and both are called in a similar fashion. However, there is one major difference: For one of them, the recipient of the CC gets the email, and for the other she does not. I have absolutely NO idea what might be causing this behavior, since they appear to be exactly identical otherwise.
This is the code used to create the email that DOES get the CC applied properly:
public function sendEmail($order = array(), $account = array(), $member = null) {
$email = new CakeEmail();
$email->template('order', 'default')
->helpers(array('Html'))
->viewVars(array('order' => $order, 'account' => $account, 'member' => $member))
->emailFormat('html')
->to($account['Account']['email'])
->cc('katherine#thecommunitycoop.org')
->from('general#thecommunitycoop.com')
->subject('Your order for '.$order['Sale']['sale_date'])
->send();
This is the code used to create to create the email that is NOT getting the CC:
public function pendingEmail($order = array(), $member = false, $success = true) {
$email = new CakeEmail();
$email->template('pending', 'default')
->helpers(array('Html'))
->viewVars(array('order' => $order, 'member'=>$member, 'success' => $success))
->emailFormat('html')
->to($order['Account']['email'])
->cc('katherine#thecommunitycoop.org')
->from('general#thecommunitycoop.com')
->subject('Your order for '.$order['Sale']['sale_date'])
->send();
As you can see, the cc field is identical. Both emails are getting sent to the 'to' field correctly; it is only the cc field that is not working properly on the second one. What could possibly be causing this behavior?

Related

CAKE email not accepting variety of bcc/cc options

I have tried many cake options to include a cc or bcc or additional email with the invoices and nothing works, I need a a workable example to the following format, I have have not found any clear solution.
public function send() {
$id = $this->request->data['Invoice']['id'];
$invoiceNumber = $this->request->data['Invoice']['invoice_number'];
$to = $this->request->data['Invoice']['to'];
$from = $this->request->data['Invoice']['from'];
$message = $this->request->data['Invoice']['message'];
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail();
$email->config(array(
'from' => $from,
'transport' => 'Mail',
'charset' => 'utf-8',
'headerCharset' => 'utf-8'
));
$result = $email->emailFormat('html')
->to($to)
->addbcc('WCMBilling#icloud.com')
->from($from)
->returnPath($from)
->subject('New Invoice ('.$invoiceNumber.')')
->attachments(WWW_ROOT.'/temp/Invoice_'.$invoiceNumber.'.pdf')
->send($message);
unlink(WWW_ROOT.'/temp/Invoice_'.$invoiceNumber.'.pdf');
$this->Session->setFlash('Email Sent');
$this->redirect(array('controller'=>'invoices', 'action'=>'view', $id));
}
I found it in the email.php file.
Where there is "null" on the cc line, or bcc line, enter the desired email and all works fine.

Drupal 6 - ignore required form field

I need to ignore the validation of two form field while creating a user in Drupal 6 but I don't know at all how to do :
$userinfo = array(
'name' => $login,
'init' => $mail,
'mail' => $mail,
'pass' => $password,
'status' => 1,
'lastname' => "", //how to ignore those required fields that invalidate the form
'surname' => "" //how to ignore those required fields that invalidate the form
);
// register a new user
$form_state = array();
$form_state['values'] = $userinfo;
drupal_execute('user_register', $form_state);
$errors = form_get_errors(); // getting 2 required field errors
Note that I can't supress the "required" property as it is used elsewhere in a more "complex" form.
Thanks
I haven't got a D6 site handy to test this on but I think it'll work...
Since drupal_execute() pushes you through the whole form build process you can take advantage of hook_form_alter() to remove the required status, but only in a context you pass along in the $form_state. For example
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_register' && !empty($form_state['custom_execution'])) {
$form['lastname']['#required'] = FALSE;
// etc...
}
}
...
$form_state = array();
$form_state['values'] = $userinfo;
$form_state['custom_execution'] = TRUE;
drupal_execute('user_register', $form_state);
Can't you use hook_form_alter to supress the "required" property, only when the from is not used in its "complex" form?
For instance, if you know what paths the "complex" form is used, you can check if that paths is being served with arg.
Better checks may be available...

Laravel4: check if the inserted email is in a proper format

In my app there is a little form with subscription to newsletter.
The form has just one field: email.
I want that when the entry is not in a proper email format, instead of throwing a laravel error: Address in mailbox given [fghfghfhf] does not comply with RFC 2822, 3.6.2.
I want to, more elegantly, give a validation error.
How can i define this rule?
Thanks!
EDIT:
This is my NewsletterUser model:
class NewsletterUser extends Eloquent {
protected $table = 'newsletterusers';
protected $guarded = array();
public static $rules = array(
'email' => 'required | email | unique:newsletterusers'
);
public static $messages = array(
'email' => 'You already subscribed',
'empty' => 'Insert the mail, please'
);
}
And this is the subscription method in the Controller:
public function subscription()
{
$input = Input::all();
$validation = Validator::make($input, NewsletterUser::$rules, NewsletterUser::$messages);
if($validation->passes())
{
// subscription stuff
}
return Redirect::back()->withInput()->withErrors($validation)->with('message','Insert the mail, please');
}
Just define a custom error message:
$messages = array(
'email' => 'Address in mailbox given :attribute does not comply with RFC 2822, 3.6.2.',
);
$validator = Validator::make($input, $rules, $messages);

How to add validators on the fly in Symfony2?

I've a password form field (not mapped to User password) to be used in a change password form, along with two other (mapped) fields, first and last.
I've to add validators on the fly: if value for password is blank then no validation should occur. Otherwise a new MinLength and MaxLength validators should be added.
Here is what i've done so far: create the repeated password field, add a CallbackValidator and return if $form->getData() is null.
Then, how can i add validators for minimum and maximum length to $field?
$builder = $this->createFormBuilder($user);
$field = $builder->create('new_password', 'repeated', array(
'type' => 'password',
'first_name' => 'Password',
'second_name' => 'Confirm password',
'required' => false,
'property_path' => false // Not mapped to the entity password
));
// Add a callback validator the the password field
$field->addValidator(new Form\CallbackValidator(function($form) {
$data = $form->getData();
if(is_null($data)) return; // Field is blank
// Here password is provided and match confirm, check min = 3 max = 10
}));
// Add fields to the form
$form = $builder
->add('first', 'text', array('required' => false)) // Mapped
->add('last', 'text', array('required' => false)) // Mapped
->add($field) // Not mapped
->getForm();
Oh well, found a solution myself after a few experiments.
I'm going to leave this question unanswered for a couple of days as one can post a better solution, that would be really really welcome :)
In particular, i found the new FormError part redundat, don't know if there is a better way to add the error to the form. And honestly, don't know why new Form\CallbackValidator works while new CallbackValidator won't.
So, don't forget to add use statements like these:
use Symfony\Component\Form as Form, // Mendatory
Symfony\Component\Form\FormInterface,
Symfony\Component\Validator\Constraints\MinLength,
Symfony\Component\Validator\Constraints\MinLengthValidator;
And the callback is:
$validation = function(FormInterface $form) {
// If $data is null then the field was blank, do nothing more
if(is_null($data = $form->getData())) return;
// Create a new MinLengthValidator
$validator = new MinLengthValidator();
// If $data is invalid against the MinLength constraint add the error
if(!$validator->isValid($data, new MinLength(array('limit' => 3)))) :
$template = $validator->getMessageTemplate(); // Default error msg
$parameters = $validator->getMessageParameters(); // Default parameters
// Add the error to the form (to the field "password")
$form->addError(new Form\FormError($template, $parameters));
endif;
};
Well, and this is the part i can't understand (why i'm forced to prefix with Form), but it's fine:
$builder->get('password')->addValidator(new Form\CallbackValidator($validation));
addValidator was deprecated and completly removed since Symfony 2.3.
You can do that by listening to the POST_SUBMIT event
$builder->addEventListener(FormEvents::POST_SUBMIT, function ($event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
if ("Your logic here") {
$form->get('new_password')->addError(new FormError());
}
});

zend form email validation

I have the following code to generate an input field for user's email address
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress')
->addValidator(new Zend_Validate_Db_NoRecordExists(
array(
'adapter'=>Zend_Registry::get('user_db'),
'field'=>'email',
'table'=>'tbl_user'
)))
->setRequired(true)
->setDecorators(array(
array('Label', array('escape'=>false, 'placement'=>'append')),
array('ViewHelper'),
array('Errors'),
array('Description',array('escape'=>false,'tag'=>'div')),
array('HtmlTag', array('tag' => 'div')),
));
$this->addElement($email);
now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin#l' as email address, and the errors will be
* 'l' is no valid hostname for email address 'admin#l'
* 'l' does not match the expected structure for a DNS hostname
* 'l' appears to be a local network name but local network names are not allowed
I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.
Well, it's a late answer but I think is always useful.
Simply add true as second param of addValidator()
From Zend docs (http://framework.zend.com/apidoc/1.8/):
addValidator (line 67)
Adds a validator to the end of the chain
If $breakChainOnFailure is true, then if the validator fails, the next
validator in the chain, if one exists, will not be executed.
return: Provides a fluent interface
access: public
Here the signature:
Zend_Validate addValidator (Zend_Validate_Interface $validator, [boolean $breakChainOnFailure = false])
Zend_Validate_Interface $validator
boolean $breakChainOnFailure
So the code is:
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress', TRUE ) // added true here
->addValidator(new Zend_Validate_Db_NoRecordExists(
array(
'adapter'=>Zend_Registry::get('user_db'),
'field'=>'email',
'table'=>'tbl_user'
), TRUE )
);
You have to create an instance of the Zend_Validate_EmailAddress class and call the setMessages method and then override the messages that you like, to remove the ones that you mention it would be something like this:
$emailValidator->setMessages(array(
Zend_Validate_EmailAddress::INVALID_FORMAT => "Your error message",
Zend_Validate_Hostname::INVALID_HOSTNAME => "Your error message",
Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED => "Your error message"
));
I hope this help somebody :-)
$email->addErrorMessage("Please Enter Valid Email Address");
you can use custom validator. create a file Email.php inside folder Validate in your library folder at the root of project
class Validate_Email extends Zend_Validate_Abstract
{
const INVALID = 'Email is required';
protected $_messageTemplates = array(
self::INVALID => "Invalid Email Address",
self::ALREADYUSED => "Email is already registered"
);
public function isValid($value)
{
if(preg_match($email_regex, trim($value))){
$dataModel = new Application_Model_Data(); //check if the email exists
if(!$dataModel->email_exists($value)){
return true;
}
else{
$this->_error(self::ALREADYUSED);
return false;
}
}
else
{
$this->_error(self::INVALID);
return false;
}
}
}
and in you form.php file
$mailValidator = new Validate_Email();
$email->addValidator($mailValidator, true);
Don't know if it works or not but for me it worked in case of telephone. Courtesy of http://softwareobjects.net/technology/other/zend-framework-1-10-7-telephone-validator/
It seems to be missing quite a few lines...
probably should use this:
$mailValidator = new Zend_Validate_EmailAddress();
you can also do some other validations see here: http://framework.zend.com/manual/en/zend.validate.set.html
Using a custom validator is the only way I found to avoid this problem.
If what you want is:
Having only one error message if the email address is in a wrong format
If the format is good, then validate if the email address is already in the database
Then I suggest you to do something like this:
$where = array('users', 'email', array('field' => 'user_id',
'value' => $this->getAttrib('user_id')));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('E-mail:')
->setRequired(true)
->setAttrib('required name', 'email') // html5
->setAttrib('maxlength', '50')
->addFilter('StripTags')
->addFilter('StringTrim')
->addFilter('StringToLower')
->addValidator('email', true)
->addValidator('stringLength', true, array(1, 50))
->addValidator('db_NoRecordExists', true, $where)
->addDecorators($this->_elementDecorators);
$this->addElement($email);
$this->getAttrib('user_id') represents the current user's id.
There are three validators here, all of them have their second parameter $breakOnFailureset to false, so if a validator fails, the other ones won't be called.
The first validator is email, which is my own custom validator:
class My_Validate_Email extends Zend_Validate_EmailAddress
{
public function getMessages()
{
return array('invalidEmail' => 'Your email address is not valid.');
}
}
You can add this validator in your library, in /application/library/My/Validate for example, and then add
$this->addElementPrefixPath('My_Validate', 'My/Validate', 'validator');
into your form. Of course, you need to replace "My" by the name of your library.
Now if an email is in the wrong format, it will always display 'Your email address is not valid.'. If your email is too long and doesn't fit into your database field (VARCHAR(100) for example), it's going to show your stringLength validator errors, and in the last case, if an entry already exists in the database, only this error will be shown.
Of course you can add more methods into your custom validator and overload setMessages, so that you can display your own messages whatever the form you are working on.
Hope it can help someone!