Laravel 5 Model Class not found - php

I am trying to port my web app from laravel 4 to 5 but I am having issues in that one of my model classes is not found.
I have tried to utilize namespacing and have the following my Models which are located locally C:\xampp\htdocs\awsconfig\app\Models
the file which the error appears in looks like
<?php
use App\Models\SecurityGroup;
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../resources/sns messages/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
/*if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
} */
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'ResourceDeleted':
// echo"found Resource Deleted<br>";
//ITEM DELETED
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
$resource->delete();
if( isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
if ($tag->checkExists($cfi->configuration->tags))
{
$tag->delete();
}
}
}
}
}
else
{
echo "Deleting ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'OK':
//echo"found Resource OK<br>";
//ITEM UPDATED
if (array_key_exists($cfi->resourceType, $resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$update_array[from_camel_case($key)] = $value;
}
}
$resource->populate($update_array);
$resource->save();
}
}
else
{
echo "Updating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
default:
echo "Status ".$cfi['configurationItemStatus']." not yet supported<br>";
break;
}
}
}
}
}
and the corresponding model whose class cannot be found looks like :
<?php namespace App\Models;
use Eloquent;
class SecurityGroup extends Eloquent
{
protected $table = 'security_group';
public $timestamps = false;
protected $guarded = array('id');
public $fields = array('groupId',
'groupName',
'description',
'ownerId'
);
public function checkExists()
{
return self::where('group_id', $this->group_id)->first();
}
public function populate($array)
{
foreach ($array as $k => $v)
{
$this->$k = $v;
}
}
}
I am lost as to what is causing the problem I don't see any typos but then again who knows as always thanks for any help given.

to solve the resource type needs the full namespace declaration

Related

Can I edit the Amelia wordpress booking system to create a new customer without booking?

need my customers to be able to log into the site with the same details as they book with, as i can make a customer in amelia that adds itself to the default wordpress user list but when i make a wordpress user with the amelia customer role it does not transfer over across to amelia.
not a clue if this helps but found this in the plugin php.
<?php
namespace AmeliaBooking\Domain\Factory\User;
use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
use AmeliaBooking\Domain\Entity\User\Customer;
use AmeliaBooking\Domain\Entity\User\Manager;
use AmeliaBooking\Domain\Entity\User\Admin;
use AmeliaBooking\Domain\Entity\User\Provider;
use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory;
use AmeliaBooking\Domain\Factory\Google\GoogleCalendarFactory;
use AmeliaBooking\Domain\Factory\Outlook\OutlookCalendarFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodServiceFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodServiceFactory;
use AmeliaBooking\Domain\ValueObjects\DateTime\Birthday;
use AmeliaBooking\Domain\ValueObjects\Gender;
use AmeliaBooking\Domain\ValueObjects\Json;
use AmeliaBooking\Domain\ValueObjects\String\Password;
use AmeliaBooking\Domain\ValueObjects\String\Status;
use AmeliaBooking\Domain\ValueObjects\Picture;
use AmeliaBooking\Domain\ValueObjects\String\Description;
use AmeliaBooking\Domain\ValueObjects\String\Email;
use AmeliaBooking\Domain\ValueObjects\Number\Integer\Id;
use AmeliaBooking\Domain\ValueObjects\String\Name;
use AmeliaBooking\Domain\ValueObjects\String\Phone;
use AmeliaBooking\Domain\Collection\Collection;
use AmeliaBooking\Domain\Factory\Schedule\DayOffFactory;
use AmeliaBooking\Domain\Factory\Schedule\TimeOutFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\WeekDayFactory;
/**
* Class UserFactory
*
* #package AmeliaBooking\Domain\Factory\User
*/
class UserFactory
{
/**
* #param $data
*
* #return Admin|Customer|Manager|Provider
* #throws InvalidArgumentException
*/
public static function create($data)
{
if (!isset($data['type'])) {
$data['type'] = 'customer';
}
switch ($data['type']) {
case 'admin':
$user = new Admin(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'provider':
$weekDayList = [];
$dayOffList = [];
$specialDayList = [];
$serviceList = [];
$appointmentList = [];
if (isset($data['weekDayList'])) {
foreach ((array)$data['weekDayList'] as $weekDay) {
$timeOutList = [];
if (isset($weekDay['timeOutList'])) {
foreach ((array)$weekDay['timeOutList'] as $timeOut) {
$timeOutList[] = TimeOutFactory::create($timeOut);
}
$weekDay['timeOutList'] = $timeOutList;
}
$periodList = [];
if (isset($weekDay['periodList'])) {
foreach ((array)$weekDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = PeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = PeriodFactory::create($period);
}
$weekDay['periodList'] = $periodList;
}
$weekDayList[] = WeekDayFactory::create($weekDay);
}
}
if (isset($data['specialDayList'])) {
foreach ((array)$data['specialDayList'] as $specialDay) {
$periodList = [];
if (isset($specialDay['periodList'])) {
foreach ((array)$specialDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = SpecialDayPeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = SpecialDayPeriodFactory::create($period);
}
$specialDay['periodList'] = $periodList;
}
$specialDayList[] = SpecialDayFactory::create($specialDay);
}
}
if (isset($data['dayOffList'])) {
foreach ((array)$data['dayOffList'] as $dayOff) {
$dayOffList[] = DayOffFactory::create($dayOff);
}
}
if (isset($data['serviceList'])) {
foreach ((array)$data['serviceList'] as $service) {
$serviceList[$service['id']] = ServiceFactory::create($service);
}
}
$user = new Provider(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email']),
new Phone(isset($data['phone']) ? $data['phone'] : null),
new Collection($weekDayList),
new Collection($serviceList),
new Collection($dayOffList),
new Collection($specialDayList),
new Collection($appointmentList)
);
if (!empty($data['password'])) {
$user->setPassword(new Password($data['password']));
}
if (!empty($data['locationId'])) {
$user->setLocationId(new Id($data['locationId']));
}
if (!empty($data['googleCalendar']) && isset($data['googleCalendar']['token'])) {
$user->setGoogleCalendar(GoogleCalendarFactory::create($data['googleCalendar']));
}
if (!empty($data['outlookCalendar']) && isset($data['outlookCalendar']['token'])) {
$user->setOutlookCalendar(OutlookCalendarFactory::create($data['outlookCalendar']));
}
if (!empty($data['zoomUserId'])) {
$user->setZoomUserId(new Name($data['zoomUserId']));
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
break;
case 'manager':
$user = new Manager(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'customer':
default:
$user = new Customer(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'] ?: null),
new Phone(!empty($data['phone']) ? $data['phone'] : null),
new Gender(!empty($data['gender']) ? strtolower($data['gender']) : null)
);
break;
}
if (!empty($data['countryPhoneIso'])) {
$user->setCountryPhoneIso(new Name($data['countryPhoneIso']));
}
if (!empty($data['birthday'])) {
if (is_string($data['birthday'])) {
$user->setBirthday(new Birthday(\DateTime::createFromFormat('Y-m-d', $data['birthday'])));
} else {
$user->setBirthday(new Birthday($data['birthday']));
}
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
if (!empty($data['externalId'])) {
$user->setExternalId(new Id($data['externalId']));
}
if (!empty($data['pictureFullPath']) && !empty($data['pictureThumbPath'])) {
$user->setPicture(new Picture($data['pictureFullPath'], $data['pictureThumbPath']));
}
if (!empty($data['status'])) {
$user->setStatus(new Status($data['status']));
}
if (!empty($data['note'])) {
$user->setNote(new Description($data['note']));
}
return $user;
}
}
Try this. Found it on the support forums.
add_action( 'user_register', 'custom_amelia_registration_save', 10, 1 );
function custom_amelia_registration_save($user_id) {
global $wpdb;
$wpUser = get_user_by('ID', $user_id);
$ameliaUserId = $wpdb->get_col(
"SELECT id FROM wp_amelia_users WHERE email = '{$wpUser->user_email}'"
);
if (!$ameliaUserId && in_array('wpamelia-customer', $wpUser->roles)) {
$ameliaUserFirstName = $wpUser->user_first_name ?: $wpUser->user_nicename;
$ameliaUserLastName = $wpUser->user_last_name ?: $wpUser->user_nicename;
$wpdb->query("
INSERT INTO wp_amelia_users
(
type,
status,
externalId,
firstName,
lastName,
email
) VALUES (
'customer',
'visible',
{$user_id},
'{$ameliaUserFirstName}',
'{$ameliaUserLastName}',
'{$wpUser->user_email}'
)
");
}
}

Error: Cannot use object of type Symfony\Component\HttpFoundation\Request as array

When I showed it in a browser when upgrading to symfony3, I had a title error (line 25).
I had questions on similar mistakes in StackOverflow, but I think it's a different trend.
I want to know how it can be improved.
Stack Trace
[1] Symfony\Component\Debug\Exception\FatalErrorException: Error:
Cannot use object of type Symfony\Component\HttpFoundation\Request as array
at n/a
in /Symfony/.../Bundle/Listener/PortalListener.php line 25
Code
PortalListener.php
<?php
namespace Ahi\Sp\PublicBundle\Listener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Ahi\Sp\PublicBundle\Controller\BaseController;
use Ahi\Sp\PublicBundle\Model\Service\AhiCookieService;
use Symfony\Component\HttpFoundation\Request;
/**
*/
class PortalListener
{
/*
*
* #param FilterControllerEvent $event
*/
public function preControllerExecute(FilterControllerEvent $event, Request $request)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$_controller = $event->getRequest();
if (isset($_controller[0])) { //line25
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}
BaseController.php
<?php
namespace Ahi\Sp\PublicBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
/ **
* Front controller.
* /
abstract class BaseController extends Controller
{
const MAX_ITEM_COUNT = 4; // Maximum number to get the item part number from the coordination. (You can get up to 4)
protected $parameters = array();
protected $response = null;
protected $cookie = null;
public function preExecute (Request $request) {
$this->cookie = $this->get('public.ahiCookieService');
// ---------------------------------------
// Gender (The order is the member's gender → portal top gender button → brand → shop → MEN'S $LADIE'S button)
$this->gender = $this->cookie->get('gender');
// Get the brand and overwrite the gender of the brand
$this->brand = null;
$brandDir = null;
$brandDirUrlParam = $request->attributes->get('brandDir');
$brandDirGetParam = $request->query->get('brandDir');
if ($brandDirUrlParam) {
$brandDir = $brandDirUrlParam;
} elseif ($brandDirGetParam) {
$brandDir = $brandDirGetParam;
}
$brandService = $this->get('public.brandService');
if ($brandDir) {
$brand = $brandService->getBrand($brandDir);
if (!$brand) {
throw $this->createBrandNotFoundException();
}
if(!$this->isPreview() && !$brand->getDispFlg()) {
throw $this->createBrandNotFoundException();
}
$brandSex = $brand->getBrandSex();
if ($brandSex != 2) {
$this->gender = $brandSex;
}
$this->brand = $brand;
}
// shop --------------------------------->
$this->shop = null;
$shopDir = null;
$shopDirUrlParam = $request->attributes->get('shopDir');
$shopDirGetParam = $request->query->get('shopDir');
if ($shopDirUrlParam) {
$shopDir = $shopDirUrlParam;
} elseif ($shopDirGetParam) {
$shopDir = $shopDirGetParam;
}
$this->shopDir = $shopDir;
$shopService = $this->get('public.shopService');
if ($shopDir) {
$shop = $shopService->getShop($shopDir);
if (!$shop) {
throw $this->createShopNotFoundException();
}
if (!$this->isPreview() && !$shop->getDispFlg()) {
if ($shop->getRedirectFlg() == true) {
$redirectUrl = $shop->getRedirectUrl();
if (empty($redirectUrl)) {
$redirectUrl = $this->generateUrl('ahi_sp_public_brand_top', array('brandDir' => $shop->getBrand()->getDirName()));
}
throw new ShopRedirectException($redirectUrl);
} else {
throw $this->createShopNotFoundException();
}
}
$shopSex = $shop->getShopSex();
if ($shopSex != 2) {
$this->gender = $shopSex;
}
$this->shop = $shop;
}
// shop <---------------------------------
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
if ($this->getRequest()->get('_route') !== 'ahi_sp_public_portal_top') {
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
}
if ($this->gender !== null) {
$this->gender = intval($this->gender);
$this->cookie->set('gender', $this->gender, 30);
$this->cookie->set('ec_gender', $this->gender, 30);
}
if ($this->gender === 0 or $this->gender === 1) {
$this->paramsSex = array('sex'=> array($this->gender, 2));
} else {
$this->paramsSex = array('sex'=> array(0, 1, 2));
}
$mid = $this->cookie->get('member_id');
$session = $request->getSession();
if ($mid && !$session->has('favoriteShops')) {
$route = $this->container->getParameter('ats_http');
$list = $this->container->getParameter('favorite_shop_list');
$url = $route . $list . $mid;
$ahiStoreIdList = file_get_contents($url);
$favoriteShops = array();
if ($ahiStoreIdList !=='') {
$ahiStoreIdArray = explode(",", $ahiStoreIdList);
$shopService = $this->get("public.shopService");
$sortKey = array();
foreach ($ahiStoreIdArray as $key => $storeId) {
$id = explode(':', $storeId);
$shop = $shopService->getShopById($id[1]);
if ($shop) {
$favoriteShops[$key]['shopName'] = $shop->getShopName();
$favoriteShops[$key]['shopDir'] = $shop->getDirName();
$sortKey[$key] = $shop->getShopName();
}
}
array_multisort($sortKey, SORT_ASC, $favoriteShops);
}
$session->set('favoriteShops', $favoriteShops);
}
$trend_tag_list_limit = $this->container->getParameter("trend_tag_list_limit");
if(!$brandDirUrlParam and !$shopDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand();
$this->parameters['prefBrands'] = $this->service('coordinate')->getBrandPerPref();
$this->parameters['shopBrandPrefectures'] = $this->service('brand')->getPrefExistBrand();
$this->parameters['shopPrefBrands'] = $this->service('brand')->getBrandPerPref();
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->paramsSex,false,$trend_tag_list_limit);
}elseif($brandDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand($brandDirUrlParam);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->brand,false,$trend_tag_list_limit);
}else{
$this->parameters['coordinateCount'] = $this->service('coordinate')->getCountArticle(
$this->brand,
$this->shop
);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->shop->getBrand(),false,$trend_tag_list_limit);
}
}
Version
Cent OS 6.7
PHP 5.6
Symfony3.0.9
The error was resolved when I fixed it as follows.
public function preControllerExecute(FilterControllerEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$request = $event->getRequest();
$_controller = $event->getController();
if (isset($_controller[0])) {
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}

I think I found a bug with setValue from ReflectionProperty

I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.
below is what I tried as well as the entries I tried to use.
this is my entrie
class TestOBJ{
private $fooClosure = null;
public $bar = 5;
private $myPrivateRecursion = null;
private $aimArrayAndContainsRecursion = [];
public function __construct()
{
$this->fooClosure = function(){
echo 'pretty closure';
};
}
public function setMyPrivateRecursion(&$obj){
$this->myPrivateRecursion = &$obj;
}
public function setObjInsideArray(&$obj){
$this->aimArrayAndContainsRecursion[] = &$obj;
}
}
$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;
$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);
my entrie is var $obj
and this is my function / solution
function makeRecursionStack($vector, &$stack = [], $from = null)
{
if ($vector) {
if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
$stack[] = &$vector;
if (get_class($vector) === 'stdClass') {
foreach ($vector as $key => $value) {
if (in_array($vector->{$key}, $stack, true)) {
$vector->{$key} = null;
} else {
$vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
}
}
return $vector;
} else {
$object = new \ReflectionObject($vector);
$reflection = new \ReflectionClass($vector);
$properties = $reflection->getProperties();
if ($properties) {
foreach ($properties as $property) {
$property = $object->getProperty($property->getName());
$property->setAccessible(true);
if (!is_callable($property->getValue($vector))) {
$private = false;
if ($property->isPrivate()) {
$property->setAccessible(true);
$private = true;
}
if (in_array($property->getValue($vector), $stack, true)) {
$property->setValue($vector, null);
} else {
//if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
//$get = $property->getValue($vector);
//$set = $this->makeRecursionStack($get, $stack, $property->getName());
//$property->setValue($vector, $set);
//pre_clear_buffer_die($property->getValue($vector));
//}
$property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
}
if ($private) {
$property->setAccessible(false);
}
}
}
}
return $vector;
}
} else if (is_array($vector)) {
$nvector = [];
foreach ($vector as $key => $value) {
$nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
}
return $nvector;
} else {
if (is_object($vector) && !is_callable($vector)) {
return null;
}
}
}
return $vector;
}
The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.
$get =
$set =
After this lines
$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));
i obtain this
I try to put other value like an bool or null inside property and after set the $set but it's not works.
P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.

Send a data from table to another table from a specific source field

Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.

php - contao - saving my model leaves me an empty model

I am programming a Module for Contao in php.
I am using the function "Model::save()", which saves my data to the database.
But when I am trying to use the model after saving, it's just empty. I have no idea how this can happen.
The Code Snippet:
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
So in the var_dump before I save, everything is fine, but the second one doesn't show any data!
Does anybody got some ideas?
Edit2:
OK, here the complete code of the Module:
<?php
use Contao\Date;
use Contao\FilesModel;
use Contao\Input;
use Contao\Module;
use Contao\PageModel;
use Contao\RequestToken;
use Contao\Validator;
class ModuleReportData extends Module
{
protected $strTemplate = 'mod__reportdata';
public function generate()
{
if (TL_MODE == 'BE')
{
/** #var \BackendTemplate|object $objTemplate */
$objTemplate = new \BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ReportData ###';
$objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
return $objTemplate->parse();
}
return parent::generate();
}
public function compile()
{
$report_id = Input::get('r');
if($report_id){
$report = ReportModel::findByPk($report_id);
$project = ProjectModel::findBy('report_id', $report_id);
}else{
$report = new ReportModel();
$project = new ProjectModel();
}
$machine = new MachineModel();
$machines = [];
$next_step = false;
//get data for selectbox machines
$result = $this->Database->prepare("SELECT * FROM tl_sa_machines")->execute();
while($result->next())
{
$id = $result->id;
$machines[$id] = $result->type;
}
//Check if form was submitted
if(Input::post('submit_data')){
$report_data = Input::post('report_data');
$project_data = Input::post('project_data');
$machine_data = Input::post('machine_data');
$errors = [];
$next_step = true;
foreach($report_data as $key => $data)
{
if(empty($data)) continue;
switch ($key) {
case 'document_date':
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $data)) //###andere Formate hinzufügen
{
break;
}
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'customer':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'city':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'country':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'document_version':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'author':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'max_speed':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
}
}
$report->setRow($report_data);
foreach($project_data as $key => $data)
{
if(empty($data)) continue;
if(Validator::isAlphanumeric($data)) continue;
else {
$next_step = false;
$errors[$key] = "Error";
}
}
$project->setRow($project_data);
if($next_step)
{
$project->date_of_evaluation = strtotime($project->date_of_evaluation);
$report->document_date = strtotime($report->document_date);
//save and set report_data
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
$report = ReportModel::findByPK($report_id);
var_dump($report);
//save and set project_data
$project->report_id = $report->id;
$project->tstamp = time();
$project->save();
//session for transfering report_id to the next page
/* var_dump($report->id);
var_dump($report_id);
var_dump($project->report_id);
if($report_id) {
$_SESSION['report_id'] = $report_id;
}
else
{//var_dump($report_id);
//var_dump($report->id);
$report_id = $report->id;
$_SESSION['report_id'] = $report_id;
}
$jumpTo = PageModel::findByPk($this->jumpTo);
$url = $this->generateFrontendUrl($jumpTo->row());
$this->redirect($url);*/
}
}
$this->Template->report = $report;
$this->Template->project = $project;
$this->Template->machine = $machine;
$this->Template->machines = $machines;
$this->Template->errors = $errors;
$this->Template->request_token = RequestToken::get();
}
}
I have a form, to save new data, or to edit existing data. There are two different tables in the database I am trying to fill with data. FOr second one I need the new ID of the new row generated in this code. But it doesn't work because the model is empty after saving.
Edit3:
ProjectModel is just that simple:
use Contao\Model;
class ProjectModel extends Model{
protected static $strTable = "tl_sa_projects";
}
I just found out, it only happens when I use the save method on $report. It's working fine with $project!
Update:
It looks like I get an error when the refresh() method tries to select the new inserted databaserow with:
public function refresh()
{
$intPk = $this->{static::$strPk};
// Track primary key changes
if (isset($this->arrModified[static::$strPk]))
{
$intPk = $this->arrModified[static::$strPk];
}
// Reload the database record
$res = \Database::getInstance()->prepare("SELECT * FROM " . static::$strTable . " WHERE " . static::$strPk . "=?")
->execute($intPk);
var_dump($res);
$this->setRow($res->row());
}
Update 2:
Ok the problem is, that the "arrModified" contains an empty string as ID. Does anybody know where this array gets its elements?
Not the answer to your original question, but you should use
ProjectModel::findOneBy('report_id', $report_id);
instead of
ProjectModel::findBy('report_id', $report_id);
since you want to find only one specific project. findBy returns a Contao\Model\Collection (i.e. potentially multiple results) whereas findOneBy returns a Contao\Model.
Update:
Furthermore, your usage of setData and mergeRow is probably not intended this way. You should instead use
foreach ($project_data as $key => $val)
{
$project->$key = $val;
}
for instance.

Categories