yii2 image is uploaded but not saved in db - yii2-advanced-app

I want to save my image in db it is uploaded but not saved in my database any one know how to fix this
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$fname = UploadedFile::getInstance($model, 'imageFile');
if (!empty($fname)) {
$temp_path = Yii::$app->basePath . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;
$model->save();
$fname->saveAs($temp_path . $fname);
$model->imageFile = $fname->name;
// echo '<pre>'; print_r($fname->name);
//exit();
}
if ($model->save()) { // To save the title to the database
Yii::$app->getSession()->addFlash('success', 'Image uploaded');
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}

Related

Yii2: rest api model get data

I am using REST API in my project and everything works great. I describe a model using a model
<?php
namespace api\modules\v1\models;
use Carbon\Carbon;
use Yii;
class Comment extends \common\models\Comment
{
public function fields()
{
return [
'id',
'user' => function(Comment $model) {
return User::findOne($model->user_id);
},
'text',
'image' => function(Comment $model) {
return Yii::$app->params['link'].$model->image;
},
'created_at' => function(Comment $model) {
Carbon::setLocale(Yii::$app->language);
return Carbon::createFromTimeStamp(strtotime($model->created_at))->diffForHumans();
},
'children' => function(Comment $model) {
$comments = Comment::find()
->where(['comment_id' => $model->id]);
if (!$comments->exists()) {
return false;
}
return $comments->all();
},
'like',
'news_id',
'comment_id'
];
}
}
The data is returned in the specified format and that's great. But I need to send data to the controller using websockets. For example, when a new comment arrives, send it to all users.
$post = Yii::$app->request->post();
$image = UploadedFile::getInstanceByName('image');
$model = new \api\modules\v1\models\Comment([
'news_id' => $post['feed_id'],
'comment_id' => $post['comment_id'] ?? null,
'user_id' => Yii::$app->user->identity->id,
]);
$model->text = $model->findLinks($post['text']);
if ($image && !$image->error) {
if (!file_exists(Yii::$app->params['comment.pathAbsolute'])) {
if (!FileHelper::createDirectory(Yii::$app->params['comment.pathAbsolute'], 0777)) {
throw new \Exception('Помилка створення папки');
}
}
$serverName = Yii::$app->security->generateRandomString(16).'.'.$image->extension;
if ($image->saveAs(Yii::$app->params['comment.pathAbsolute'].$serverName)) {
$model->image = $serverName;
} else {
throw new \Exception($image->error);
}
}
if (!$model->save()) {
throw new \Exception($model->error());
}
Helper::ws(false, 'updateComment', ['feed_id' => $post['feed_id'], 'comment' => $model]);
And when I pass the $model, the data is passed as it is stored in the database. Is it possible to call a method or something so that the data is passed as I described in the model api?

Silverstripe who to submit Form into Formextension

I use silverstripe 4.0.3
I made and extension for a Form. I adde the extension via yml to PageController. This is my Extension Class:
class NewsLetterFormExtension extends DataExtension
{
private static $allowed_actions = [
'NewsletterForm'
];
public function NewsletterForm()
{
$form = Form::create(
null,
__Function__,
FieldList::create(
LiteralField::create('Newsletter','<h2>NewsLetter</h2>')
->addExtraClass(''),
LiteralField::create('NLContent','<p>Erfaharen sie regelmäßig was uns beschäftigt</p>')
->addExtraClass(''),
TextField::create('FirstName')
->setAttribute('palceholder', 'Vorname')
->addExtraClass(''),
TextField::create('Surname')
->setAttribute('palceholder', 'Nachname')
->addExtraClass(''),
EmailField::create('Email')
->setAttribute('palceholder', 'E-mail Adresse')
->addExtraClass('')
),
FieldList::create(
FormAction::create('handleNewsletter', 'Senden')
->addExtraClass('btn btn-primary btn-sm')
),
RequiredFields::create('FirstName','Surname', 'Email')
);
return $form;
}
public function handleNewsletter($data, $form)
{
$Newsletter = Newsletter::create();
$form->saveInto($Newsletter);
try {
$Newsletter->write();
} catch (\Exception $e) {
return $e->getMessage();
}
$form->sessionMessage('Danke für die Newsletter Anmeldung', 'good');
return $this->redirectBack();
}
}
As Controller i am passing null. What would be the correct controller to submit it into the extension? Or is it even possible to do so?
I tried to pass it PageController and handle submission there. But I can not get it to work.
An actually i'd would like to submit into it self so that i can add it to multible page types.
You could try extending the Form class. This isn't tested but should work :)
NewsletterForm.php
class NewsletterForm extends Form {
function __construct($controller, $name) {
$form_name = $name;
$fields = FieldList::create(
LiteralField::create('Newsletter','<h2>NewsLetter</h2>')
->addExtraClass(''),
LiteralField::create('NLContent','<p>Erfaharen sie regelmäßig was uns beschäftigt</p>')
->addExtraClass(''),
TextField::create('FirstName')
->setAttribute('palceholder', 'Vorname')
->addExtraClass(''),
TextField::create('Surname')
->setAttribute('palceholder', 'Nachname')
->addExtraClass(''),
EmailField::create('Email')
->setAttribute('palceholder', 'E-mail Adresse')
->addExtraClass('')
);
$actions = FieldList::create(
FormAction::create('handleNewsletter', 'Senden')
->addExtraClass('btn btn-primary btn-sm')
);
$validator = RequiredFields::create('FirstName','Surname', 'Email')
parent::__construct($controller, $form_name, $fields, $actions, $validator);
}
handleNewsletter($data, $form) {
$Newsletter = Newsletter::create();
$form->saveInto($Newsletter);
try {
$Newsletter->write();
} catch (\Exception $e) {
return $e->getMessage();
}
$form->sessionMessage('Danke für die Newsletter Anmeldung', 'good');
return $this->redirectBack();
}
}
NewsletterFormExtension.php
class NewsLetterFormExtension extends DataExtension {
private static $allowed_actions = [
'NewsletterForm'
];
public function NewsletterForm() {
$f = new NewsletterForm($this, 'NewsletterForm');
return $f;
}
}

Error with session ini setting modification

A PHP Error was encountered
Severity: Warning
Message: ini_set(): A session is active. You cannot change the session module's ini settings at this time
Filename: Session/Session.php
Line Number: 316
Backtrace:
File: C:\xampp\htdocs\testing\index.php
Line: 315
Function: require_once
<?php
session_start(); //we need to start session in order to access it through CI
class Adminlogin extends CI_Controller {
public function _construct(){
parent::_construct();
//Load form helper library
$this->load->helper('form');
//Load form validation library
$this->load->library('form_validation');
//Load session library
$this->load->library('session');
//Load database
$this->load->model('login_database');
}
//show login page
public function index()
{
$this->load->view('admin_login');
}
//show registration page
public function user_registration_show(){
$this->load->view('admin_signup');
}
//Validate and store registration data in database
public function new_user_registration(){
//Check Validation for user input in SignUp form
$this->form_validation->set_rules('admin_username', 'Username','trim|required|xss_clean');
$this->form_validation->set_rules('admin_password', 'Password','trim|required|xss_clean');
if($this->form_validation->run()== FALSE){
$this->load->view('admin_signup');}
else{
$data = array(
'admin_username' => $this->input->post('username'),
'admin_password' => $this->input->post('password'));
$result = $this->login_database->registration_insert($data);
if($result == TRUE){
$data['message_display'] = 'Registration Successfully !';
$this->load->view('admin_login', $data);
}else{
$data['message_display'] = 'Username already exist';
$this->load->view('admin_signup',$data);
}
}
}
//Check for user login process
public function user_login_process(){
$this->form_validation->set_rules('admin_username','Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('admin_password','Password', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
if(isset($this->session->userdata['loggen_in'])){
$this->load->view('Admin/admin_dashboard');
}else{
$this->load->view('admin_login');
}
}else{
$data = array(
'admin_username' => $this->input->post('username'),
'admin_password' => $this->input->post('password'));
$result = $this->login_database->login($data);
if($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if($result != false){
$session_data = array(
'username' => $result[0]->admin_username,
'password' => $result[0]->admin_password);
//Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('Admin/admin_dashboard');
}else{
$data = array(
'error_message' => 'Invalid Username or Password');
$this->load->view('admin_login',$data);
}
}
}
}
}
?>
Please remove the 1st line session_start(); or change it to..
// session_start(); //I do Not need this as I am using CI Sessions.
You are using CodeIgniters Sessions which you have loaded in your code...
$this->load->library('session');
As an Aside:
You don't need the end ?> in your PHP files where it is the last tag in the file.

Phalcon MongoDb save

I have problem with save method of collections in Phalcon.It doesn't work and doesn't give me any errors or something.I want to create a Micro App with mongoDb:
Phalcon version: 1.3.4
php : 5.5.9
Here are the registered services:
<?php
use Phalcon\DI\FactoryDefault,
Phalcon\Assets\Manager as AssetsManager,
Phalcon\Mvc\Collection\Manager as CollectionManager,
Phalcon\Mvc\View\Simple as View,
Phalcon\Mvc\View\Engine\Volt,
Phalcon\Mvc\Url as UrlResolver,
Phalcon\Flash\Session as Flash,
Phalcon\Flash\Direct as FlashDirect,
Phalcon\Session\Adapter\Files as Session;
$di = new FactoryDefault();
$di['url'] = function () {
$url = new UrlResolver();
$url->setBaseUri('/dasshy/');
return $url;
};
/**
* Flash service with custom CSS classes
*/
$di['flash'] = function () {
return new Flash(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
};
/**
* Flash service with custom CSS classes
*/
$di['flashDirect'] = function () {
return new FlashDirect(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
};
$di['session'] = function () {
$session = new Session(array(
'uniqueId' => 'dasshy-'
));
$session->start();
return $session;
};
$di['mongo'] = function () {
$mongo = new MongoClient();
return $mongo->selectDb("stats");
};
$di->set('collectionManager', function () {
return new Phalcon\Mvc\Collection\Manager();
});
I want to use the ODM, so here is the model Collection:
<?php
namespace Dasshy\Models;
class Messages extends \Phalcon\Mvc\Collection
{
public $content;
public $senderId;
public $receiverId;
public $date;
}
And here how i use it at handlers.php:
<?php
use Dasshy\Models\Messages;
use Phalcon\Mvc\Micro\Collection;
$app->map('/send/{receiverId}/{senderId}/{content}', function ($receiverId, $senderId, $content) use ($app) {
$messageModel = new Messages();
$messageModel->receiverId = $receiverId;
$messageModel->senderId = $senderId;
$messageModel->content = $content;
$messageModel->date = date('Y-m-d H-i-s', time());
$messageModel->save();
if ($messageModel->save() == false) {
echo "Umh, We can't store robots right now: \n";
foreach ($messageModel->getMessages() as $message) {
echo $message, "\n";
}
} else {
echo "Great, a new robot was saved successfully!";
}
});
$app->map('/messages', function () use ($app) {
var_dump(Messages::find());
exit;
});
you need to setup the mongo connection on the service...
$config = $di->getShared('config')->mongo;
$connect_data = $config->username . ':' . $config->password . '#' . $config->host . ':' . $config->port . '/' . $config->dbname;
$mongo = new \MongoClient("mongodb://" . $connect_data);
return $mongo->selectDB($config->dbname);
...since you are not connecting to any mongo server

Mongo DB to Codeigniter Implementation

I am newbie in mongo db. I want to translate a mongo db code to codeigniter understandable format.
db.demo.find({}, {
"person": 1
});
Here are the relevant code files from my project.
config/mongo.php
$config['mongo_server'] = null;
$config['mongo_dbname'] = 'mydb';
libraries/Mongo.php
class CI_Mongo extends Mongo
{
var $db;
function CI_Mongo()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo
if ($server)
{
parent::__construct($server);
}
else
{
parent::__construct();
}
$this->db = $this->$dbname;
}
}
And a sample controller
controllers/posts.php
class Posts extends Controller
{
function Posts()
{
parent::Controller();
}
function index()
{
$posts = $this->mongo->db->posts->find();
foreach ($posts as $id => $post)
{
var_dump($id);
var_dump($post);
}
}
function create()
{
$post = array('title' => 'Test post');
$this->mongo->db->posts->insert($post);
var_dump($post);
}
}