Yii2 right join only returning 2 columns - sql

Working on an API and I have this query:
$query = CallerIdentity::findNonGeo()->join( 'RIGHT JOIN', 'ehadata', 'caller_ids.cidref = ehadata.cidref')
->select('ehadata.*')
->where(['caller_ids.cidref' => $id]);
echo $query->getSQL();die;
The output of the ->getSQL() function is:
SELECT `ehadata`.* FROM `caller_ids` RIGHT JOIN `ehadata` ON caller_ids.cidref = ehadata.cidref WHERE `caller_ids`.`cidref`='256'
and the result of running the query through the function in postman returns:
{
"cidref": 256,
"status": 0
}
However when I run the query in adminer the result is:
Has anyone got any idea why this might be? I am well and truly confused. Any help is massively appreciated.
EhaData model
class EHAData extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ehadata';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['cidref', 'status', 'name', 'premesis', 'thoroughfare', 'locality', 'postcode'], 'required'],
[['cidref', 'status'], 'integer'],
[['modified'], 'safe'],
[['title', 'forename', 'postcode'], 'string', 'max' => 20],
[['name', 'bussuffix'], 'string', 'max' => 50],
[['premesis'], 'string', 'max' => 60],
[['thoroughfare'], 'string', 'max' => 55],
[['locality'], 'string', 'max' => 30],
[['cidref'], 'exist', 'skipOnError' => true, 'targetClass' => CallerIdentity::className(), 'targetAttribute' => ['cidref' => 'cidref']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'ehaid' => 'Ehaid',
'cidref' => 'Cidref',
'status' => 'Status',
'title' => 'Title',
'forename' => 'Forename',
'name' => 'Name',
'bussuffix' => 'Bussuffix',
'premesis' => 'Premesis',
'thoroughfare' => 'Thoroughfare',
'locality' => 'Locality',
'postcode' => 'Postcode',
'modified' => 'Modified',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCallerIdentity()
{
return $this->hasOne(CallerIdentity::className(), ['cidref' => 'cidref']);
}
}
Caller Identity model
class CallerIdentity extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'caller_ids';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['custref', 'caller_id', 'start_date'], 'required'],
[['custref', 'status', 'target_index'], 'integer'],
[['type', 'conf_call', 'magrathea', 'outbound_only', 'callrec_outbound', 'callrec_inbound'], 'string'],
[['start_date', 'last_polled', 'last_modified', 'created'], 'safe'],
[['caller_id'], 'string', 'max' => 15],
[['location', 'destination', 'redirect'], 'string', 'max' => 120],
[['country_code'], 'string', 'max' => 3],
[['details'], 'string', 'max' => 180],
[['expiry'], 'string', 'max' => 18],
[['custref'], 'exist', 'skipOnError' => true, 'targetClass' => Customer::className(), 'targetAttribute' => ['custref' => 'custref']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'cidref' => 'Cidref',
'custref' => 'Custref',
'caller_id' => 'Caller ID',
'location' => 'Location',
'destination' => 'Destination',
'redirect' => 'Redirect',
'type' => 'Type',
'conf_call' => 'Conf Call',
'magrathea' => 'Magrathea',
'outbound_only' => 'Outbound Only',
'callrec_outbound' => 'Callrec Outbound',
'callrec_inbound' => 'Callrec Inbound',
'country_code' => 'Country Code',
'details' => 'Details',
'status' => 'Status',
'start_date' => 'Start Date',
'expiry' => 'Expiry',
'target_index' => 'Target Index',
'last_polled' => 'Last Polled',
'last_modified' => 'Last Modified',
'created' => 'Created',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCustref()
{
return $this->hasOne(Customer::className(), ['custref' => 'custref']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEhadata()
{
return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}
/**
* #inheritdoc
* #return BanQuery the active query used by this AR class.
*/
public static function find()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'caller_ids.cidref','custref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'caller_ids.status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE caller_ids.status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->with('ehadata')->asArray()->all();
return $query;
}
public static function findNonGeo()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['caller_ids.status' => '1'])
->andWhere(['type' => 'N']);
return $query;
}
public static function findFax()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'custref','caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['status' => '1'])
->andWhere(['type' => 'F']);
return $query;
}
public static function findConference()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['status' => '1'])
->andWhere(['conf_call' => 'y']);
return $query;
}
}

just wild guessing...
there is also a ->joinWith method for your activequery, used for eager loading
add function extraFields() { return ['ehadata']; } to your CallerIdentity model; read more here http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#fields and call your api with &expand=ehadata param

Solved by adding this in to the CallerIdentity model.
public function fields()
{
$fields = parent::fields();
$fields[] = 'ehadata'; //name of relation
return $fields;
}
Output:
{
"cidref": 1234,
"custref": 288,
"caller_id": "01758364762",
"expiry": null,
"conf_call": "n",
"type": "S",
"redirect": null,
"destination": "846285845#sip.example.co.uk",
"status": 1,
"start_date": "2011-11-01",
"last_polled": "2011-11-01 13:59:51",
"ehadata": [
{
"status": 0,
"name": "Blah blah blah",
"bussuffix": "Ltd",
"premesis": "Blah House",
"thoroughfare": "Blah Road",
"locality": "Blahbach",
"postcode": "BLAH BLAH"
}
]
},

Related

How to make array taking data from database in laravel

why this is not working where all my queries are individually working.
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
this works manually like
$data = [
'name' => 'my_name',
'email' => 'my_email',
'phone' => 'my_phone',
'address' => 'my_address',
'gender' => 'my_gender',
];
return $data;
my whole function is given below:
public function read($id){
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->get();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->get();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
When using get() it returns a collection not a single object so you can do
public function read($id){
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->first();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->first();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
Or if you have relations defined on the models you can use the relation
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
public function read($id)
{
$user = User::with('profile')->findOrFail($id);
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $user->profile->phone,
'address' => $user->profile->address,
'gender' => $user->profile->gender
];
return $data;
}

not able to create the record in yii json api

I am trying to learn yii and create an api. I am able to get the data but I am not able to create new record using my json object.
This is what I get
Here is my main.php in api config looks like
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'api\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'user' => [
'identityClass' => '\common\models\User',
'enableSession' => false,
'loginUrl' => null
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'AH7T3J6-nwgUOF3DK_MYPhyzhhguo5-k',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
],
'params' => $params,
];
As you can see I am setting up the json parser in request.
Here is the model
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "room".
*
* #property integer $id
* #property integer $floor
* #property integer $room_number
* #property integer $has_conditioner
* #property integer $has_tv
* #property integer $has_phone
* #property string $available_from
* #property string $price_per_day
* #property string $description
*/
class Room extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'room';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['floor', 'room_number', 'has_conditioner', 'has_tv', 'has_phone', 'available_from'], 'required'],
[['floor', 'room_number', 'has_conditioner', 'has_tv', 'has_phone'], 'integer'],
[['available_from'], 'safe'],
[['price_per_day'], 'number'],
[['description'], 'string'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'floor' => 'Floor',
'room_number' => 'Room Number',
'has_conditioner' => 'Has Conditioner',
'has_tv' => 'Has Tv',
'has_phone' => 'Has Phone',
'available_from' => 'Available From',
'price_per_day' => 'Price Per Day',
'description' => 'Description',
];
}
}
For some reason its just not getting the json format.
I tried with form-data and it seems to work. But just raw json wont work
please have a look here

Connecting Frontend to backend when login

i have a code in Yii2 advanced template, i want to make a link when i log in from frontend then connecting in backend and when i logout from backend it back to frontend,how can i make that?
and this is my comon/config/main.php file
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
//'class' => 'yii\web\urlManager',
'enablePrettyUrl' => false,
'showScriptName' => true,
'baseUrl' => '/backend/web',
],
'urlManagerFrontEnd' => [
'class' => 'yii\web\urlManager',
'baseUrl' => '/frontend/web',
'enablePrettyUrl' => false,
'showScriptName' => true,
]
],
];
and this is my siteController in frontend
<?php
namespace frontend\controllers;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;
use backend;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
/*public function goBack($defaultUrl = null)
{
if(is_null($defaultUrl)) {
$defaultUrl = Yii::$app->request->baseUrl; // ganti dibagian ini ndu
}
return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
}*/
}
and the same with siteController in backend

FOSRestBundle post many to one relation

I would like to know how to properly post data when Entity has another ManyToOne relation in FOSRestBundle.
User entity has locale (locale_id):
/**
* #ORM\ManyToOne(targetEntity="Locale")
* #ORM\JoinColumn(name="locale_id", referencedColumnName="id")
*/
private $locale;
I was hoping that passing something like:
{
"user":{
"firstName":"John",
"emailAddress":"somewhere#somehow.com",
"lastName":"Doe",
"sex":"1",
"locale":{
"id":"1"
}
}
}
will work, but it does not pass the validation and Symfony throws:
{"code":400,"message":"Validation Failed","errors":{"children":{"firstName":[],"lastName":[],"emailAddress":[],"sex":[],"locale":{"errors":["This value is not valid."]}}}}
As you can see, locale is still wrong.
Does anyone know how can I post it properly?
EDIT
Here is how the form looks like:
<?php
namespace Software\Bundle\Form\Type;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* Class UserType
* #package Software\Bundle\Form\Type
*/
class UserType extends AbstractFormType
{
public function buildForm(FormBuilderInterface $builder, array $option)
{
$builder
->add('firstName', 'text', [
'label' => 'word.first_name',
'required' => true
])
->add('lastName', 'text', [
'label' => 'word.last_name',
'required' => true
])
->add('emailAddress', 'email', [
'label' => 'word.email_address',
'required' => true
])
->add('sex', 'choice', [
'label' => 'word.sex',
'choices' => [
'0' => 'word.male',
'1' => 'word.female'
],
'required' => true,
'empty_value' => 'word.select',
'empty_data' => null
])
->add('locale', 'entity', [
'label' => 'word.locale',
'required' => false,
'property' => 'code',
'class' => 'SoftwareBundle:Locale',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('l')
->orderBy('l.code', 'ASC');
},
'placeholder' => 'word.select',
'empty_data' => null
])
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'translation_domain' => 'general',
'data_class' => 'Software\Bundle\Entity\User',
'attr' => ['novalidate' => 'novalidate'],
'csrf_protection' => false
]);
}
public function getName()
{
return 'user';
}
}
EDIT 2
And the controller:
public function postAction(Request $request)
{
$form = $this->createForm(new UserType(), new User());
$form->handleRequest($request);
if($form->isValid())
{
die('are you valid or not??');
}
return $this->view($form, 400);
}
Try without the "1" and only with 1 , otherwise it can be interpreted as string.
Edit :
{
"user":{
"firstName":"John",
"emailAddress":"somewhere#somehow.com",
"lastName":"Doe",
"sex":"1",
"locale": 1
}
}
}

Rename nama in upload ZF2 + AWS S3

How can I rename the name of a file before to upload zf2 and Amazon S3?
This is my code:
$files = $request->getFiles();
$bucketname = 'mybucket';
$result = $aws->putObject(array(
'Bucket' => $bucketname,
'Key' => 'user/5/'.$files['image-file']['name'],
'Body' => EntityBody::factory(fopen($files['image-file']['tmp_name'], 'r')),
'ACL' => CannedAcl::PUBLIC_READ,
'ContentType' => 'image/jpeg'
));
I can not use the module https://github.com/aws/aws-sdk-php-zf2
This is a working example t upload the image in zf2,rename it and save to database
namespace Admin\Form;
use Zend\Form\Form;
class SubcategoryimageForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Subcategoryimage');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'subcategory_link_id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'alt',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Alt Text',
),
));
$this->add(array(
'name' => 'fileupload',
'attributes' => array(
'type' => 'file',
),
'options' => array(
'label' => 'File Upload',
),
));
$this->add ( array (
'name' => 'detail',
'attributes' => array (
'type' => 'textarea'
),
'options' => array (
'label' => 'Detail'
)
) );
$this->add ( array (
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'active',
'tabindex' => 3,
'options' => array (
'label' => 'Active',
'use_hidden_element' => true,
'checked_value' => '1',
'unchecked_value' => '0'
)
) );
$this->add(array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'location',
'options' => array(
'label' => 'Please choose one of the choices',
'value_options' => array(
'1' => 'flag',
'2' => 'landing',
'3' => 'home page',
),
),
'attributes' => array(
'value' => '1' //set checked to '1'
)
));
$this->add ( array (
'name' => 'submit',
'type' => 'Submit',
'tabindex' => 5,
'size' => 20,
'required' => false,
'attributes' => array (
'value' => 'Upload File',
'id' => 'submitbutton'
)
) );
}
}
In your controller
//inculde the imagine modules
use Zend\Validatior\File\Size;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\Point;
public function imageAction()
{
$id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
if (! $id) {
return $this->redirect ()->toRoute ( 'category' );
}
$form = new SubcategoryimageForm();
$form->get ( 'subcategory_link_id' )->setAttribute ( 'value', $id );
$request = $this->getRequest();
if ($request->isPost()) {
// Make certain to merge the files info!
$image = new Subcategoryimage();
$form->setInputFilter($image->getInputFilter());
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
$size = new \Zend\Validator\File\ImageSize(array(
'minWidth' => 30, 'minHeight' => 30,
'maxWidth' => 1024, 'maxHeight' => 920,
)); //minimum bytes filesize
$isImage = new \Zend\Validator\File\IsImage();
$mimeType = new \Zend\Validator\File\MimeType(array('image/gif', 'image/jpg','image/jpeg','image/png','enableHeaderCheck' => true));
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $post['fileupload']['name']);
$adapter->setValidators(array($isImage), $post['fileupload']['name']);
$adapter->setValidators(array($mimeType), $post['fileupload']['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
$messages = $form->getMessages();
return $this->redirect ()->toRoute ( 'category' );
// print_r($messages);die('file errors');
} else {
//$adapter->setDestination(dirname(__DIR__).'imageurltosaveimage/');
$adapter->setDestination('imagepathtosave');
if ($adapter->receive($post['fileupload']['name'])) {
$image->exchangeArray($form->getData());
switch(strtolower($_FILES['fileupload']['type']))
{
case 'image/jpeg':
$filename = imagecreatefromjpeg('imagepath/'.$post['fileupload']['name']);
break;
case 'image/png':
$filename = imagecreatefrompng('imagepath/'.$post['fileupload']['name']);
break;
case 'image/gif':
$filename = imagecreatefromgif('imagepath/'.$post['fileupload']['name']);
break;
default:
exit('Unsupported type: '.$_FILES['fileupload']['type']);
}
ob_start();
imagejpeg($filename);
// large image
$large = base64_encode(ob_get_contents()); // returns output
$mainimgWidth = imagesx($filename);
$mainimgHeight = imagesy($filename);
$thumbWidth = intval($mainimgWidth / 4);
$thumbHeight = intval($mainimgHeight / 4);
$new = imagecreatetruecolor($thumbWidth, $thumbHeight);
$backgroundColor = imagecolorallocate($new, 255, 255, 255);
imagefill($new, 0, 0, $backgroundColor);
imagecopyresampled($new, $filename, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainimgWidth, $mainimgHeight);
/** Catch the imagedata */
ob_start();
imagejpeg($new);
$data = ob_get_clean();
// Destroy resources
imagedestroy($filename);
imagedestroy($new);
// Set new content-type and status code
$thumb = base64_encode($data);
// imagine library was intsalled by the composer in the test server by amarjit
ob_end_clean();
$imagine = new Imagine();
//rename files
$filedata = array(
'id' => $post ['id'],
'subcategory_link_id' => $post ['subcategory_link_id'],
'alt' => $post ['alt'],
'detail' => $post ['detail'],
'active' => $post ['active'],
'location' => $post ['location'],
'thumb' => $thumb,
'large' => $large,
'created' => date('Y-m-d H:i:s'),
'createdby' => 1,
);
$id = $this->getImageTable ()->save ( $filedata );
$imagine->open('ipathofimage/'.$post['fileupload']['name'])
->save('pathtosaveimages/newnameofimage-'.$id.'.jpg');
/**
* delete the origional uploaded file;
*/
unlink('pathtoimage/'.$post['fileupload']['name']);
return $this->redirect ()->toRoute ( 'category' );
}
}
}else{
$messages = $form->getMessages();
}
}
return array (
'id' => $id,
'form' => $form,
'entities' => $this->getImageTable ()->getImageContents($id),
);
}
To get the image from database
use below code in your action
public function getlandingimageAction()
{
$id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
if (! $id) {
return $this->redirect ()->toRoute ( 'category' );
}
try {
$thumb = $this->getImageTable ()->getImage ( $id );
} catch ( \Exception $ex ) {
return $this->redirect ()->toRoute ( 'category', array (
'action' => 'index'
) );
}
$image = base64_decode($thumb);
/** check if the image is db */
if($image!=null)
{
$db_img = imagecreatefromstring($image);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
}
else
{
/** check if the image is upload dir */
$url= "path/imagename".$id.'.jpg';
if(file_exists($url))
{
$db_img = imagecreatefromjpeg($url);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
exit;
}
/** handle if the image does not exit */
/**
* This needs to be changed from t
*/
$imgurl= "paaathofimage/";
Header("Content-type: image/gif");
$i=imagecreatefromgif($imgurl."/images/noimg.gif");
imagegif($i);
}
exit;
}