In following code, I'm trying to create a new category (name = 'To be deleted') and then I want to delete it.
first part of the code working fine and I can see new record in the database every time I run the unit test
but I'm having a problem with recode deletion. what's wrong with my code
public function testCategoryDeletion()
{
$user = \App\User::find(1);
//dd($user->name);
$category = \App\Category::create(['name' => 'To be deleted']);
//dd($category->id);
$response = $this->actingAs($user, 'api')
->json('DELETE', "/api/category/{$category->id}")
->assertStatus(200)->assertJson([
'status' => true,
'message' => 'Category Deleted',
]);
}
Test case output
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API> ./vendor/bin/phpunit
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.
. . . . . . . 7 / 7 (100%)
Time: 1.53 minutes, Memory: 18.00 MB
OK (7 tests, 65 assertions)
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API>
In database, recode is created but not deleted,
I fixed the controller as follows and now its working,
public function destroy(Category $category)
{
$status = $category->delete();
return response()->json([
'status' => $status,
'message' => $status ? 'Category Deleted' : 'Error Deleting Category'
]);
}
API routes
Route::group(['middleware' => 'auth:api'], function(){
Route::resource('/task', 'TaskController');
Route::resource('/category', 'CategoryController');
Route::get('/category/{category}/tasks', 'CategoryController#tasks');
});
Related
i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>
I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.
I have a problem when I get datetime in my yii2 project. When I get datetime, the date is true but the time is wrong. I execute my code and the result is :
2016-05-02 12:30:28
whereas the time in my laptop is : 19:30. What's the problem? I use time in Indonesia. This is my code:
$time = new \DateTime('now', new \DateTimeZone('UTC'));
$model->tanggal_sampai = $time->format('Y-m-d H:i:s');
First, Find out the timezone for Indonesia from List Of Supported TimeZones - php Manual
Then, make it common for all places using config.php file. Add 'timeZone'=>'Your TimeZone', after components section.
Example : config.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
.
.
.
],
'timeZone'=>'Asia/Kolkata',
'params' => $params,
];
You are asking for the time in the UTC time zone with new \DateTimeZone('UTC'). Either ask for it in your own time zone, which I think is WIB:
$time = new \DateTime('now', new \DateTimeZone('WIB'));
or without a time zone:
$time = new \DateTime('now');
I am new in CakePHP, developing a cloud application using CakePHP 2.5.1 and MySQL. I have following tables:
users
id ,
person_id(FK- people.id),
username,
password
people
id,
parent_id(FK- people.id),
firsr_name,
last_name,
role
addresses
address_id,
person_id(FK- people.id),
street,
house no,
post code,
city
Foreign key people.parent_id refers to primary_key people.id of the same table people. Value of role can be manager or customer. If manager, the value of people.id will be assigned to people.parent_id.
In my registration form, there will be following input fields:
-username
-password
-first name
-last name
-street
-house no
-post code
-city
-role
in the view (view/Users/add.ctp), I have following fields:
$options = array('manager' => 'Manager', 'customer' => 'Customer');
$attributes = array('legend' => false);
echo $this->Form->radio('Person.role', $options, $attributes);
echo $this->Form->input('User.username');
echo $this->Form->input('Person.last_name');
echo $this->Form->input('Person.first_name');
echo $this->Form->input('Address.street');
echo $this->Form->input('Address.house_no');
echo $this->Form->input('Address.post_code');
echo $this->Form->input('Address.city');
the action in UsersController:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAll($this->request->data)) {
$components = array('Session');
$this->Session->setFlash('Welcome !');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
}
}
The problem is the data of first three fields (in users and people tables) are saved, other data (of addresses table) are not saved.
Could anyone tell me what am I missing here ?
Model User is not directly related to model Address. However, it is related through model Person, where Person hasMany Address.
Try the following.
Change your view to:
$options = array('manager' => 'Manager', 'customer' => 'Customer');
$attributes = array('legend' => false);
echo $this->Form->radio('Person.role', $options, $attributes);
echo $this->Form->input('User.username');
echo $this->Form->input('Person.last_name');
echo $this->Form->input('Person.first_name');
echo $this->Form->input('Person.Address.0.street');
echo $this->Form->input('Person.Address.0.house_no');
echo $this->Form->input('Person.Address.0.post_code');
echo $this->Form->input('Person.Address.0.city');
And add 'deep'=>true to saveAll() in your UsersController.add():
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAll($this->request->data,['deep'=>true])) {
$components = array('Session');
$this->Session->setFlash('Welcome !');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
}
}
I have more than 300,000 users on an old online store. Client switched to Magento solution and now have to migrate all the users, addresses to Magento. So I have to write a custom script to import users and their address to the Magento system.
Are there any tutorials or similar sort of work already done. Please help me.
Thanks
Here's an example of how I migrated users from OSC into Magento with the SOAP library. This script was run on the old server and needs to be run from the ssh command line (php execution time through the browser will not support this
$proxy = new SoapClient('http://[your magento url]/api/soap/?wsdl=1');
$sessionId = $proxy->login('admin', '[your password]');
// connect to local db
$link = mysql_connect('localhost', '[old ecommerce db]', '[old db pw]');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('sbc_osc', $link);
$sql = "SELECT * FROM customers";
$customers = mysql_query($sql);
// loop thyrough customers
while ($customer = mysql_fetch_assoc($customers)) {
set_time_limit(600);
$newCustomer = array(
'firstname' => $customer['customers_firstname'],
'lastname' => $customer['customers_lastname'],
'email' => $customer['customers_email_address'],
'password_hash' => $customer['customers_password'],
'store_id' => 2, // set the store you want to send to
'website_id' => 2
);
$telephone = $customer['customers_telephone'];
$fax = $customer['customers_fax'];
try{
$newCustomerId = $proxy->call($sessionId, 'customer.create', array($newCustomer));
}
catch (Exception $e) {
echo "failed to create customer for: " . $customer['customers_firstname'] . " " . $customer['customers_lastname'] . "\n";
}
// grab the default address
$sql = "SELECT ab.*, c.countries_iso_code_2, z.zone_name, z.zone_id
FROM address_book ab
LEFT JOIN countries c ON ab.entry_country_id = c.countries_id
LEFT JOIN zones z ON ab.entry_zone_id = z.zone_id
WHERE customers_id = {$customer['customers_id']} AND address_book_id = {$customer['customers_default_address_id']}";
$addresses = mysql_query($sql);
while ($address = mysql_fetch_assoc($addresses)) {
$newCustomerAddress = array(
'firstname' => $address['entry_firstname'],
'lastname' => $address['entry_lastname'],
'company' => $address['entry_company'],
'country_id' => $address['countries_iso_code_2'],
'region_id' => $address['zone_id'],
'region' => ($address['zone_name'] != "" ? $address['zone_name'] : $address['entry_state']),
'city' => $address['entry_city'],
'street' => array($address['entry_street_address']),
'telephone' => $telephone,
'fax' => $fax,
'postcode' => $address['entry_postcode'],
'is_default_billing' => true,
'is_default_shipping' => true,
);
try{
$newAddressId = $proxy->call($sessionId, 'customer_address.create', array($newCustomerId, $newCustomerAddress));
}
catch (Exception $e) {
echo "failed to add address for: " . $address['entry_firstname'] . " " . $address['entry_lastname'] . "\n";
}
}
echo "migrated: " . $customer['customers_firstname'] . " " . $customer['customers_lastname'] . "\n";
}
mysql_close($link);
One thing you need to watch out for is the passwords.. for this to work I had to set up Magento to use the same password hashing schema.
My suggestion would be to look into the customer import api and build out a script using the methods from the code base, using the API will be slower so since you will be running the script on your server you can build it using the actual methods. So you can look at this folder for the customer api classes and methods
/app/code/core/Mage/Customer/Model/Customer
and then here for the address api classes and methods
/app/code/core/Mage/Customer/Model/Address/
You would probably need to export your data to CSV and get it in the right format to import into Magento. 30k isn't that much so you can even try out the normal import process that is default Magento. We haven't had good luck with that but we have been importing hundreds of thousands of customers. Even then we break the file down into small chunks of customers at a time.