use Eloquent relationships while exporting data to Excel file in Laravel - eloquent

I want to create a summary report of my two tables, one is employees table and the other one is sims table. These tables have one to many relationship. I know that we can export data of a model by using
->fromModel($model)
but is there a way so I can generate the report based on the two tables?

SO, I asked a question and someone who could not answer but cowardly awarded -1. However, I figured it how to do this manually. Posting the code so it may help the future beginners like me.
public function downloadSummary(){
Excel::create('records', function($excel) {
$excel->sheet('Sheet1', function($sheet) {
$employees = Employee::all();
$arr =array();
foreach($employees as $employee) {
foreach($employee->sims as $sim){
$data = array($employee->id, $employee->name, $employee->nic, $employee->address, $employee->title,
$sim->id, $sim->msisdn, $sim->imei, $sim->issued_to);
array_push($arr, $data);
}
}
//set the titles
$sheet->fromArray($arr,null,'A1',false,false)->prependRow(array(
'Employee Id', 'Employee Name', 'Employee NIC', 'Employee Address', 'Employee Title',
'Sim Id', 'Sim MSISDN', 'IMEI', 'Issued To'
)
);
});
})->export('xls');
}

Related

Contact Form 7 - how to add several number fields dynamically

I am currently working on a web project where users should be able to have a list of brochures (list comes from custom post type) and enter the amount they would like to order individually for each of them via a simple contact form. My idea was to generate a dynamic list of number fields with the 'wpcf7_form_tag_data_option' hook like in this article:
Dynamicly populate Contact form 7 input fields with current user info when logged in in Wordpress website
So if i am using the select or checkbox field type within contact form 7:
[select anzahlKataloge data:brochures]
or
[checkbox anzahlKataloge data:brochures]
and functions.php:
add_filter('wpcf7_form_tag_data_option', function($n, $options, $args) {
if (in_array('brochures', $options)){
$query = new WP_Query(
array( 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => '100', 'post_type' => 'prospekte')
);
while($query->have_posts()) : $query->the_post();
$title = get_the_title();
$brochures[] = $title;
endwhile;
return $brochures;
}
return $n;
}, 10, 3);
It generates the select or checkbox list just fine but i would actually need it to work with the number field type:
[number anzahlKataloge data:brochures]
or with text type:
[text anzahlKataloge data:brochures]
Any help is much appreciated.
Best Regards,
Rafael

Compare two fields to see if they match

I'm trying to think of the best way to approach validating two emails fields for a form: I have an email field and a retype email field, and I want to compare them to see if they match. If not then display an error message saying so until the user enters in their email correctly for both fields.
I know there can be custom fields classes made to allow for custom validation but I'm using 2 separate fields, not one, and I'm not sure a custom class will work in this case since I'm not validating just one field.
I followed the example found here which involves adding custom validation to the form's submit function: https://docs.silverstripe.org/en/3/developer_guides/forms/validation/
However, I don't want to redirect anywhere -- I want to stay on the form.
I'd like to make this as simple as possible if I can help it.
Here is what I have so far. Other than the issue I mentioned, everything else works fine:
public function DemoForm() {
$fieldsArr = array();
$firstName = new TextField('first_name', 'First Name');
$firstName->setAttribute('placeholder', 'First Name');
array_push($fieldsArr, $firstName);
$lastName = new TextField('last_name', 'Last Name');
$lastName->setAttribute('placeholder', 'Last Name');
array_push($fieldsArr,$lastName);
$companytName = new TextField('company_name', 'Company Name');
$companytName->setAttribute('placeholder', 'Company Name');
array_push($fieldsArr,$companytName);
$email = new EmailField('email', 'Email');
$email->setAttribute('placeholder', 'Email');
array_push($fieldsArr, $email);
$retypeemail = new EmailField('retype_email', 'Retype Email');
$retypeemail->setAttribute('placeholder', 'Retype Email');
array_push($fieldsArr, $retypeemail);
$fields = new FieldList($fieldsArr);
$actions = new FieldList(
new FormAction('submit', 'Submit')
);
$validator = new RequiredFields('first_name', 'last_name', 'email', "retype_email");
return new Form($this, 'DemoForm', $fields, $actions, $validator);
}
public function submit($data, $form) {
if($data['email'] != $data['retype_email']){
$form->addErrorMessage('Email', 'The emails do not match.', 'bad');
return $this->redirectBack();
}
else{
$demoRequest = new DemoFormSubmission();
$demoRequest->FirstName = $data['first_name'];
$demoRequest->LastName = $data['last_name'];
$demoRequest->EmailAddress =$data['email'];
$demoRequest->CompanyName = $data['company_name'];
$demoRequest->write();
$email = new Email();
$email->setTo('sara.dejaneiro#innismaggiore.com');
$email->setFrom($data['email']);
$email->setSubject("Demo request submission");
$messageBody = "
<p><strong>First Name:</strong> {$data['first_name']}</p>
<p><strong>Last Name:</strong> {$data['last_name']}</p>
<p><strong>Email: </strong> {$data['email']}</p>
<p><strong>Company Name:</strong> {$data['company_name']}</p>
";
$email->setBody($messageBody);
$email->send();
return $this->redirect("demo-request-submission-thank-you-page");
}
}
Given your reply to my comment, I think you would probably be best to either:
Create your own form field that extends CompositeField and then add a custom validate function (as per https://docs.silverstripe.org/en/3/developer_guides/forms/validation/#form-validation)
Creating a custom validator, by extending RequiredFields (https://github.com/silverstripe/silverstripe-framework/blob/3.6.2/forms/RequiredFields.php) and then overloading the PHP method (https://github.com/silverstripe/silverstripe-framework/blob/3.6.2/forms/RequiredFields.php#L82).
Number 2 might be the less fiddly approach. You can write your own custom logic and then if the validation fails simply return "false" and then SilverStripe will cancel form submission and return the user to the form with their data still in the form fields.

cake php habtm select does not set selected values

Hello I have several troubles with HABTM and Form.
I am using CakePHP 2.3 and PHP 5.3.3
This is my code situation for the understanding of the scenario: Albums and Singles related with a HABTM relation. Albums cointains many Singles and Singles belongs to many Albums.
Model Album.php ( don't care about raisins: is my personal plugin for managing images )
App::uses('Raisin', 'Raisins.Model');
App::uses('PastryBehavior', 'Raisins.Model/Behavior');
class Album extends AppModel
{
public $name = 'Album';
public $actsAs = array(
'Tags.Taggable',
'Utils.Sluggable' => array(
'label' => 'title'
),
'Raisins.Pastry',
'SrEngine.Indexable',
'SrEngine.HitCounter'
);
public $hasOne = array(
'Image' => array('className' => 'Raisins.Raisin')
);
public $hasAndBelongsToMany = array(
'Single'
);
public $belongsTo = array(
'Users.User'
);
}
Controller AlbumsController.php ( edit part )
$this->request->data = $this->Album->read(null, $id);
$this->set('singles',$this->Album->Single->find('list'));
View
<?php echo $this->Form->input('Single',array('class' => 'span12','label' => 'Singoli' ) ); ?>
In the view I see the select populated from the values coming from the controller singles set, but the selected item, previously saved, is not highlighted.
Consider that in the database the habtm table contains the correct row populated with the data saved.
I read , somewehere in the middle, that some previous version of cake, prior to 2.3, used to have some problem related to habtm form select input.
I am very stuck at this because I have almost tried every known workaround without sorting any positive effect.
Any help, hint would be very appreciated.
Thanks in advance
Rudy

Show Multiple Values in Drop Down list, CakePHP

I have a drop down list, which shows a list of 'Product Categories'
The problem is, that there are multiple product categories of the same name.
Each product category has an associated 'System', so my question is, is there a way to modify:
echo $this->Form->input('product_cat_id');
which shows Product Category to show System >> Product Category
Okay, I figured it out.
I couldn't do it at view level easily, so I had to do it at controller level.
Basically, I was aiming to build options group that is used as below:
$options = array(
'Group 1' => array(
'Value 1' => 'Label 1',
'Value 2' => 'Label 2'
),
'Group 2' => array(
'Value 3' => 'Label 3'
)
);
echo $this->Form->select('field', $options);
I decided it'd be best to construct the options list in my controller and pass it to the view.
To that end, I added this code to my controller's action:
$systemCats = $this->Product->ProductCat->SystemCat->find('all');
$this->set('fieldOptions', buildFieldOptions($systemCats));
I created a function called buildFieldOptions which uses the fully associated $systemCats array as an argument:
function buildFieldOptions($productCats, $systemCats) {
$optionsArray = array(); //empty options array
foreach ($systemCats as $systemCat) {
$productCatArray = array(); //empty product categories array
foreach($systemCat['ProductCat'] as $productCat){
$productCatArray[$productCat['id']] = $productCat['title'];
//fill product categories array
}
$optionsArray[$systemCat['SystemCat']['title']] = $productCatArray;
//fill options array with system category as a key
}
return $optionsArray;
}
The completed one select box now has options such as below:
SystemCategory
Product Category
Product Category
Product Category
SystemCategory
Product Category
Product Category
Product Category
This works for me!

Need help with Zend_db update

Currently I'm working with Zend framework and I need help with Zend_db update in Zend_Db_Table_Abstract class.
Here is my SQL statement
UPDATE user
SET password = '$password',
`enter code here` WHERE email = '$email'
Here is my code in zend_db
public function updatePassword($password,$email)
{
$data = array(
'password' => $password
);
$where = "email = '". $email ."'";
$this->update($data, 'email = '.$email);
}
This only work if I update using int id as my where clause but I wanted to use a email string as a where clause.
Can someone please help me the best way to achieve this?
I wanted to be secure and avoid SQL Injection attack
Thanks so much in advance.
You approach only works with integer values, because the way you concat the where string does not escape the value. So if you do
'email = '.$email
It will product an sql string like this if you use the string "hello world"
WHERE email = hello world
This is an invalid SQL statement so the update does not happen. What you want to produce is a where clause like this
WHERE email = 'hello world'
There are multiple ways to do this, but the safest way to do that via Zend Framework is described in the reference manual under "Example #24 Updating Rows Using an Array of Arrays".
$data = array(
'password' => $password
);
$where['email = ?'] = $email;
$this->update($data, $where);
This code might help you :
public function updateDetails($data, $emailId)
{
$where = array('email = ?' => $emailId);
$this->update($data, $where);
}
Please let me know if you still face the problem.....?