October CMS | Using a button to send email retrieved from a field - php

I'm trying to dynamically find email address (from what has been inputted in a field), then sending out email to that address.
So far, I have been able to get the button to send emails but unable to retrieve the address from model.
Examples:
Controller
public function onSend()
{
// Retrieve email address from Machines model in email field
$this->vars['email'] = Machines::get('email');
// Send to email address using partial button
Mail::send('martin.maintenance::mail.maintenancereminder', [], function($message) {
$message->to($this->vars['email']);
});
}
Field (in Machines model)
email:
label: 'Email Address'
span: auto
type: text
tab: Details
Partial (button)
<button
type="submit"
data-request="onSend"
class="btn btn-primary">
Reminder
</button>
Error
Happy to provide any additional info. Thanks in advance!

I'm not sure what part of your code is triggering that error, but I suspect it has something to do with what ::get('email') is returning.
Machines::get('email') returns a Collection of Machines instances like this:
Illuminate\Database\Eloquent\Collection {#4744
all: [
App\Models\Machines {#4745
email: "example#example.com",
},
App\Models\Machines {#4746
email: "example2#example.com",
},
// ...
]
}
If you want all of the email column values in an Array/Collection, do this:
$this->vars['email'] = Machines::pluck('email');
Machines::pluck('email') returns a Collection of strings like this:
Illuminate\Support\Collection {#4516
all: [
"example#example.com",
"example2#example.com",
// ...
]
}
If you explictly need an array, you can do:
$this->vars['email'] = Machines::pluck('email')->toArray();
/*
* [
* "example#example.com",
* "example2#example.com",
* // ...
* ]
*/
Also, sidenote, Model names in Laravel are by convention singular, so it should be Machine instead of Machines.

Related

How to get all records result from ajax using a id in Codeigniter

I need a experience guidance about get the result database using ajax in Codeigniter.
Actually I am getting the images using category_id from a table, the imortant thing is that the category_id can be more then one because we have multiple category_id in our table
my approch was that i am send the category_id using select and that id is sending through ajax and then getting the result but i am getting the result in array i am not understanding how to display that data in my view.
my_view fuctuion
function productData(product_id)
{
var product_id = $("#product_name").val();
$.ajax({
url: base_url + 'products/getProductValueById',
type: 'post',
data: {product_id : product_id},
dataType: 'json',
success:function(response) {
console.log(response);
} // /success
}); // /ajax function to fetch the product data
}
my database query
public function getProductDataByCategoryId($id = null) {
if(!$id)
{
return false;
}
$sql = "SELECT products.image FROM products WHERE products.category_id = $id";
$query = $this->db->query($sql, array($id));
return $query->result_array();
}
my model function from where i send and receive the data
public function getProductValueById() {
$product_id = $this->input->post('product_id');
// return print_r($product_id);
if($product_id) {
$product_data = $this->model_products->getProductDataByCategoryId($product_id);
// print_r($product_data);
echo json_encode($product_data);
} }
You could actually initialize contact form in all the templates using shortcode
<?php
echo do_shortcode(
‘[contact-form-7 id=”1" title=”Contact form 1"]’
);
?>
Like this example
`<div class=”row”>
<div class=”col”>
<?php echo do_shortcode('[text* your-name placeholder”Name”]'); ?>
</div>
</div>
`
Or you can add html in contact form plugin like this and use short code in templatesconatct form page
You need to add your email address in which you want to receive emails. Just edit the contact form in admin and add your email under the "Mail" tab.
Apart from this, you also need to contact your hosting to enable the PHP email on the server. Also the "From" email should be an email created in your hosting email like "no-reply#domain.com".
You can also use a plugin to integrate SMTP emails in you site. The plugin can be found here -https://wordpress.org/plugins/wp-smtp/
Once you create your email form via the Contact 7 plugin, click on the "Edit" button then check the "Mail" tab which is the second one. Once the page load ensure that all of the fields except the following few last:
Exclude lines with blank mail-tags from output
Use HTML content type
File Attachments
Mail (2)
You can configure these options as well, however they are only optional. Also ensure that the fields for "To" and "From" are filed with an email that actually exist.
If you are still unable to send emails the best option will be to contact your web hosting provider as they will be able to review the server log for outgoing emails and provide more detailed information on the experienced issue.

What is the Laravel way to check if the POST Request has a field left empty?

The requirement was to update user roles. The role can be empty(left blank), one, or more than one as provided in the form field roles[].
Here is the view form:
#foreach ($roles as $role)
<div class="checkbox">
<label><input name="roles[]" type="checkbox" value="{{$role->id}}" {{ $user->roles->contains($role->id) ? 'checked' : '' }}>{{$role->name}}</label>
</div>
#endforeach
The condition inside UserController::update() is:
if ($request->roles) {
// update user roles
}
Everything works fine except for one case. Sometimes the user has to stay without any role.
if($request->roles), isset($request->roles), and !empty($request->roles) .. are all giving the same old fashioned reply(null, '', true/flase).
Case: when there is one or more role(s) assigned:
+request: ParameterBag {#41 ▼
#parameters: array:6 [▼
"_method" => "PUT"
"_token" => "a8oIPQFBMbhjanikX8v83qeOcfRE0N4UKTcTQDig"
"name" => "New User Name"
"email" => "newuser#testserver.asap"
"password" => ""
"roles" => array:2 [▼
0 => "2"
1 => "3"
]
]
}
Case: when there no role assigned OR need to remove(detach) the previously assigned role:
+request: ParameterBag {#41 ▼
#parameters: array:5 [▼
"_method" => "PUT"
"_token" => "a8oIPQFBMbhjanikX8v83qeOcfRE0N4UKTcTQDig"
"name" => "New User Name"
"email" => "newuser#testserver.asap"
"password" => ""
]
}
So the question (requirement) is:
How to differentiate when the field value of an HTML Post form has been submitted as empty(unchecked here) or if there was no such a field in the view form?
Is there an eloquent* way in Laravel to find/list the form fileds from the Request object?
[PS: Trying another hidden field or do some frontend jQuery will not be appreciated]
You can use the laravel request methods has() or filled(), has checks if the parameter is present and filled checks it's present and filled:
if ($request->has('roles')) {
//
}
or
if ($request->filled('roles')) {
//
}
Check Laravel documentation for further details on retrieving input from the request object.
EDIT
Since you are using Laravel 5.2 the following rules apply:
The has() method checks the parameter is present and filled.
The exists() method checks the parameted is present.
Check the code on the repo for more information.
You will need to identify this problem in the design of your application.
How to differentiate when the field value of an HTML Post form has been submitted as empty(unchecked here) or if there was no such a field in the view form? Is there an eloquent* way in Laravel to find/list the form fileds from the Request object?
When does that form should not have a roles[] field? You should have a marker that will tell your application that this form doesn't have a roles[] field.
Something like, when this form is used when an ordinary user is updating his/her profile, he/she will not be able to update his/her roles.
Because your problem is indeed the default behavior of forms, as answered in this question: Submit an HTML form with empty checkboxes
So there will be a different process for forms which DO NOT HAVE have a roles field and different process for forms which DO HAVE a roles field.
To add to your implementation, you can retrieve the roles field like this:
$roles = $request->input('roles', []);
After which you can just use sync to the relationship method of your model.
$user->roles()->sync($roles);
For this you have validations, seems that you need the roles field to be required and exists(to map to a certain table)
You just need to make the validator via artisan command and inject it in the controller method, check out the docs.
ex:
php artisan make:request MyCustomRequest
Then you should have a request file under: App\Http\Requests
You need to set the validation rules as described above:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyCustomRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'rules' =>'required|exists:tour_roles_table,id'
];
}
}
Then you can use inject it in your desired method:
class UserController extends Controller {
[...]
public function update(MyCustomRequest $req)
{
[...]
//at this point validation was successfull, by default Laravel will redirect back with error messages, which can be customized in your request object
}
[...]
}
try if(empty())
$check = request::get('roles');
if(empty($checkbox)){
//if checkbox have a empty value do ...
}else{
//if checkbox have not empty value do ..
}
for more information click http://php.net/manual/en/function.empty.php
We were just having issues checking this. We tried everything in this question and nothing worked, but finally we found a solution:
array_key_exists($request->notes)

Sylius: require address in registration

I want customers to fill in their address right at the registration, not at the checkout of an first order.
I see, that Sylius\Component\Core\Model\Customer has attributes $defaultAddress: AddressInterface and $addresses: Collection|AddressInterface[].
This is where I stucked. If there would be singular ($address: AddressInterface) I would know, I should extend form type and add there address field.
But how to require user to fill in exactly one address into this collection?
I tried this:
My form type used for registration (where parent is Sylius\Bundle\CoreBundle\Form\Type\Customer\CustomerRegistrationType):
->add(
'addresses',
CollectionType::class,
[
'entry_type' => WholesaleCustomerAddressType::class
]
)
Where WholesaleCustomerAddressType is child of Sylius\Bundle\AddressingBundle\Form\Type\AddressType and remove some fields (name, phone, etc.)
How it works:
The address field at the registration page is not rendered (only empty div is). When I dump form.adresses I see it has no children.
It renders only this:
<div data-form-type="collection" id="wholesale_customer_registration_addresses" class="form-control controls collection-widget" placeholder="Addresses"><div data-form-collection="list"></div></div>
How it should work:
The form should render fields for exactly one address. After click submit, the user should be registred, should has exactly one address and this address should be $defaultAddress also.
I see the problem is in the thing, that at the time of registration the collection of addresses is empty. How to add in Sylius a first record?
Might be a little late but if someone else stumbles on your question, this is how I solved it...
As you pointed out yourself there is an attribute $defaultAddress: AddressInterface. Simply add this field to your custom form or in my case the form extension and assign the appropriate type. I used the Sylius\Bundle\AddressingBundle\Form\Type\AddressType and that's it.
My Form extension:
<?php
namespace App\Form\Extension;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Sylius\Bundle\AddressingBundle\Form\Type\AddressType;
use Sylius\Bundle\CoreBundle\Form\Type\Customer\CustomerRegistrationType;
final class CustomerRegistrationTypeExtension extends AbstractTypeExtension
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// Adding the defaultAddress as extra fields to the form
$builder->add('defaultAddress', AddressType::class, [
'label' => 'sylius.form.customer.default_address',
]);
}
/**
* {#inheritdoc}
*/
public function getExtendedTypes(): array
{
return [CustomerRegistrationType::class];
}
}
Don't forget to add the extension as a service:
app.form.extension.type.customer_registration:
class: App\Form\Extension\CustomerRegistrationTypeExtension
tags:
- { name: form.type_extension, extended_type: Sylius\Bundle\CustomerBundle\Form\Type\CustomerRegistrationType }
And don't forget to render the new field in tour template:
{{ form_row(form.defaultAddress) }}

Sonata admin/swiftmailer how to take back information from the list

I am currently trying to use swiftmailer in my project. I am currently working on Sonata Admin and I wanted to know how I could retrieve the object displayed in a list to be able to retrieve the associated mail addresses and thus send an e-mail to all the addresses contained in this list. I want to go through the list displayed by sonata because their filter system works very well and I would use it to choose the people I want to send an email to. I saw on the symfony documentation that it was possible to send mail to an address table in this form:
$to = array('one#example.com', 'two#example.com', 'three#example.com');
$message = (new \Swift_Message('Hello Email'))
->setFrom('send#example.com')
->setTo(array($to))
->setBody('html content goes here', 'text/html');
$mailer->send($message);
But i don't know how to take back the object form the list.
From this grid.
Can you help me thanks ?
Ps :
I just think putting a button down the list to send an email to all the people displayed in the list.
Thanks a lot.
Edit :
I'm still searching and i found that the sql request was like 't0.id' and 'c0.id'. t0 and c0 are the name of the object ? Is it always that ? What is the difference between t0 and c0 ?
You can do this by adding an action to your admin list.
To do so, first create a new class in YourAdminBundle\Controller folder, extending Sonata\AdminBundle\Controller\CRUDController.
Your custom action could look like this for instance :
/** #property YourAdminClass $admin */
public function batchActionSendMail(ProxyQueryInterface $selectedModelQuery ,$type = 'sendMails') {
if (false === $this->admin->isGranted('EDIT')) {
throw new AccessDeniedException();
}
/* selected objects in your list !! */
$selectedModels = $selectedModelQuery->execute();
try{
foreach ($selectedModels as $selectedModel){
// your code to retrieve objects mails here (for instance)
}
//code to send your mails
}
catch(\Exception $e)
{
$this->addFlash('sonata_flash_error', "error");
}
$this->addFlash('sonata_flash_success', 'mails sent')
return new RedirectResponse($this->admin->generateUrl('list'));
}
To make this custom CRUD controller active, go to services.yml, get to your class admin block, and complete the third param of arguments property by referencing your custom CRUD controller:
arguments: [null, YourBundle\Entity\YourEntity,YourAdminBundle:CustomCRUD]
Finally, to allow you to use your custom action, go to your Admin Class and add this function :
public function getBatchActions()
{
if ($this->hasRoute('edit')) {
$actions['sendMails'] = array(
'label' => $this->trans('batch.sendMails.action'),
'ask_confirmation' => true, // by default always true
);
}
return $actions;
}
The action will be available in the dropdown list at the bottom of your admin list, next to the "Select all" checkbox.

Laravel form validation - validating against 2 data columns

I have a database table that tracks and email address and a client id. The rule is that and email can only belong to one client id. An example would be that I could add, email#domian.com and the client_id 20 but I would not be able to save that again, and this is where the form validation comes in,
I have the following validation rules in my controller,
$data = Input::all();
$client_id = Input::get('client_id');
$validation = Validator::make(
array('email' => Input::get('email')),
array('email' => 'required|email|unique:emails, email, NULL, client_id, $client_id')
);
if($validation->fails()) {
return Response::json($validation->messages(), 400);
} else {
}
Basically I am saying that the email should be a valid email and it should be unique against all the other emails adress that have the same client id.
However I get a PHP error back,
Undefined offset: 1
The POST that I am sending looks like this,
client_id: "16"
email: "simon#simonainley.info"
involved: 1
project_id: "64"
visible: true

Categories