I am having a issue on image upload in Zend Framework 2, where when i submit the form with image it give a "Creating default object from empty value" warning and file does not save in the folder.
If I submit the form with empty filed for images and upload then the content will save in the DB.
I have add my codes for reference
public function addAction(){
$form = new Add();
$brand = new Brand();
$form->bind($brand);
$request = $this->getRequest();
if ($request->isPost()) {
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$files = $adapter->getFileInfo();
$mediaFileHttpPostName = 'image-file';
$imageFile = $files[$mediaFileHttpPostName];
$adapter->setDestination('./public/media');
$adapter->addValidator('Extension', false, array('jpge'), $mediaFileHttpPostName);
$adapter->addFilter('Rename',
array(
'target'=> './public/media/'.$imageFile['name'],
'overwrite'=>true),
$mediaFileHttpPostName);
if(!empty($imageFile['name'])){
if (!$adapter->isValid()){
$returnObject->errorMessage = $adapter->getMessages();
$returnObject->result = 0;
} else {
try {
$adapter->receive($mediaFileHttpPostName);
$returnObject->result = 1;
} catch (\Zend\Filter\Exception\InvalidArgumentException $e) {
$returnObject->errorMessage = $e->getMessage();
$returnObject->result = 0;
}
}
}
$form->setData($post );
if ($form->isValid()) {
$recordlist = $this->getServiceLocator()->get('BrandService')->insert($brand,'',$form->getHydrator());
$this->flashMessenger()->addMessage('New brand added!');
return $this->redirect()->toRoute('zfcadmin/shop/brands');
}
}
You are not declaring $returnObject.
You should do:
....
if ($request->isPost()) {
$returnObject= new stdClass();
...
Related
i am using laravel 5.6, i will try to make function multiple upload video, and get frame and duration with laravel-ffmpeg, but when i try to upload one video for example, always show error like "File not found at path:",
this is my function to store video and get duration & frame :
public function doCreate($lessonsid)
{
if (empty(Session::get('contribID'))) {
return redirect('contributor/login');
}
# code...
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'judul' => 'required',
// 'video.*' => 'mimes:mp4,mov,ogg,webm |required|max:100000',
// 'image.*' => 'mimes:jpeg,jpg,png,gif|required|max:30000'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
$now = new DateTime();
$cid = Session::get('contribID');
$title = Input::get('judul');
$image_video = Input::file('image');
$lessons_video = Input::file('video');
// dd($lessons_video);
// $media = FFMpeg::open('https:/dev.cilsy.id/assets/source/lessons/lessons-74/video-8/1. Introduction (2).mp4');
// $frame = $media->getFrameFromString('00:00:13.37');
// dd($media);
$description = Input::get('desc');
$video=Video::where('lessons_id',$lessonsid)->get();
$count_video=count($video);
if (!is_dir("assets/source/lessons/lessons-$lessonsid")) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid);
}
$i=$count_video + 1;
foreach ($title as $key => $titles) {
$type_video =$lessons_video[$key]->getMimeType();
if (!is_dir("assets/source/lessons/lessons-".$lessonsid."/video-".$i)) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid."/video-".$i);
}
$DestinationPath= 'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
//insert image
if(!empty($image_video[$key])){
$imagefilename = $image_video[$key]->getClientOriginalName();
$image_video[$key]->move($DestinationPath, $imagefilename);
}else{
$imagefilename = '';
}
if($imagefilename ==''){
$url_image= $imagefilename;
}else{
$urls=url('');
$url_image= $urls.'/assets/source/lessons/video-'.$i.'/'.$imagefilename;
}
//insert video
if(!empty($lessons_video[$key])){
$lessonsfilename = $lessons_video[$key]->getClientOriginalName();
$lessons_video[$key]->storeAs($DestinationPath, $lessonsfilename);
}else{
$lessonsfilename = '';
}
if($lessonsfilename ==''){
$url_video= $lessonsfilename;
}else{
$urls=url('');
$url_video= $urls.'/assets/source/lessons/video-'.$i.'/'.$lessonsfilename;
}
$store = new Video;
$store->lessons_id = $lessonsid;
$store->title = $titles;
$store->image = $url_image;
$store->video = $url_video;
$store->description = $description[$key];
$store->type_video = $type_video;
$store->durasi = 0;
$store->created_at = $now;
$store->enable=1;
$store->save();
if($store){
$media = FFMpeg::open($url_video);
// $frame = FFMpeg::open($link)
// ->getFrameFromSeconds(10)
// ->export()
// ->toDisk('public')
// ->save($filename.'.png');
dd($media);
$durationInSeconds = $media->getDurationInSeconds();
// dd($media);
}
$i++;
}
// Session::set('lessons_title',$title);
// Session::set('lessons_category_id',$category_id);
// Session::set('lessons_image',$image);
// Session::set('lessons_description',$description);
return redirect('contributor/lessons/'.$lessonsid.'/view')->with('success','Penambahan video berhasil');
}
}
this is message error, when i try to upload my video
anyone can help me?
try with public_path()
$DestinationPath= public_path().'/'.'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
You files are not saving, you should use public_path helper for storing and retrieving files back.
$image_video[$key]->move(public_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
Or you can store them into storage folder
$image_video[$key]->move(storage_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
You can retrieve back files using these helpers.
Hope this helps.
I have created a form for an entity Event with user's fields like "email" and "password" what I use to create a user manually in the controller.
I can create the event and the user without problems, but I need to send a confirmation mail to enable the user. I can do it from the normal registration form, but here I don't know how to do it.
Sorry if my english isn't very good. I'm learning it.
The controller:
class EventController extends Controller
{
public function ajaxAction(Request $request) {
if (! $request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get the province ID
$id = $request->query->get('category_id');
$result = array();
// Return a list of cities, based on the selected province
$repo = $this->getDoctrine()->getManager()->getRepository('CASEventBundle:Subcategory');
$subcategories = $repo->findByCategory($id, array('category' => 'asc'));
foreach ($subcategories as $subcategory) {
$result[$subcategory->getName()] = $subcategory->getId();
}
return new JsonResponse($result);
}
public function indexAction(Request $request) {
$lead = new Lead();
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
if(is_object($user)) {
$promotor = $em->getRepository('CASUsuariosBundle:Promotor')->find($user);
if (is_object($promotor)) {
$form = $this->createForm(new EventType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:event.html.twig";
$isPromotor = true;
}
} else {
$form = $this->createForm(new LeadType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:full_lead.html.twig";
$isPromotor = false;
}
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
if($isPromotor === true) {
$type = $promotor->getType();
$name = $user->getName();
$lastname = $user->getLastName();
$email = $user->getEmail();
$password = $user->getPassword();
$phone = $user->getPhone();
$company = $promotor->getCompany();
$lead->setEventType($type);
$lead->setPromotorName($name);
$lead->setPromotorLastName($lastname);
$lead->setPromotorEmail($email);
$lead->setPromotorPhone($phone);
$lead->setPromotorCompany($company);
}
$emailReg = $form->get('promotorEmail')->getData();
$passwordReg = $form->get('promotorPassword')->getData();
$nameReg = $form->get('promotorName')->getData();
$typeReg = $form->get('promotorType')->getData();
$lastnameReg = $form->get('promotorLastName')->getData();
$phoneReg = $form->get('promotorPhone')->getData();
$companyReg = $form->get('promotorCompany')->getData();
if(!empty($emailReg) && !empty($passwordReg)) {
$userManager = $this->get('fos_user.user_manager');
$newUser = $userManager->createUser();
$newPromotor = new Promotor();
$newUser->setUsername($emailReg);
$newUser->setEmail($emailReg);
$newUser->setName($nameReg);
$newUser->setLastname($lastnameReg);
$newUser->setPhone($phoneReg);
$newUser->setIsPromotor(true);
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($newUser, strval($passwordReg));
$newUser->setPassword($encoded);
$userManager->updateUser($newUser);
$newPromotor->setType($typeReg);
$newPromotor->setCompany($companyReg);
$newPromotor->setIdPromotor($newUser);
$em->persist($newUser);
$em->persist($newPromotor);
$em->persist($lead);
$em->flush();
//return $response;
}
$em->persist($lead);
$em->flush();
return $this->redirect($this->generateUrl('CASEventBundle_create'));
}
}
return $this->render($template, array('form' => $form->createView()));
}
}
you could just create a confirmation token yourself and set it to the not yet active user, send him a mail using swift wich contains a link to confirm like :
$confiToken = "123";
$url="http://url.com/confirm/$confiToken";
$user->setConfirmationToken($confiToken);
$message = $mailer->createMessage()
->setSubject('Confirm registration')
->setFrom('from#mail.com')
->setTo($sendTo)
->setBody(
$this->renderView(
'Bundle:Email:confirm.html.twig',
array(
'headline' => "Confirm your registration",
"sendTo"=>$sendTo,
"name"=>false,
"date"=>$date,
"message"=>"here ist your confirmationlink ".$url." "
)
),
'text/html'
);
$mailer->send($message);
when the user clicks the link in the email you can manually generate the token and set the user active:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
...
$user=$em->getRepository("Bundle:User")->findOneByConfirmationToken($token);
if(!$user || $user->isEnabled()){
throw $this->createNotFoundException("link out of date");
}else {
$user->setEnabled(true);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
$em->flush();
return $this->redirect($this->generateUrl('core_customer_dashboard'));
}
I started working on Zend Framework image upload.The code is not showing any errors but image not moving to proper destination.
public function uploadAction()
{
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form = new UploadForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload'); //upload destination
$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if($favadapter->receive($favicon))
{
echo "suceess";
}
else
{
echo "Failed";
}
die;
}
}
return array('form' => $form);
}
The image is not received and gives failed message.Can you solve this problem.Thanks in advance
You write "gives failed message" so apparently something goes wrong. You should try to find out what and why... All we can do is guess with the information you are giving inside your question.
If you read the ZF2 documentation on this file adapter class here then you can see that the adaper has a getMessages method. This might give you some insight on what actually goes wrong:
$adapter = new Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
This code snippet comes straight out of the official docs!
Your final running code make sure you comment filters
public function uploadAction()
{
error_reporting(0);
$em = $this->getEntityManager();
$form = new UploadForm($em);
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload/'); //upload destination
//$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if (!$favadapter->receive())
{
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
else
{
echo "success";
}
// die;
}
}
// if ($request->isPost())
// {
// $fname = $_FILES['fileupload']['name'];
// $tmp_name = $_FILES["fileupload"]["tmp_name"];
// $uploads_dir = 'public/img/upload';
// if(move_uploaded_file($tmp_name,"$uploads_dir/$fname"))
// {
// echo "Uploaded";
// }
// else
// {
// echo "Error";
// }
// }
return array('form' => $form);
}
I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!
In the following code, I check if the form is valid, and if yes, I want it to redirect to the next page, however it's giving the following error:
AN ERROR OCCURRED
PAGE NOT FOUND
EXCEPTION INFORMATION:
Message: Invalid controller specified (undefined)
Here's the code:
public function indexAction()
{
global $current_user;
if ( is_user_logged_in() ) {
$mapper = new Site_Model_WpTerms();
$main_categories = $mapper->fetchTerms(0,'ptype',true);
$sizes = $mapper->fetchTerms(0,'size',true);
$genders = $mapper->fetchTerms(0,'gender',true);
$seasons = $mapper->fetchTerms(0,'season',true);
$decades = $mapper->fetchTerms(0,'decade',true);
$colors = $mapper->fetchTerms(0,'color',true);
$styles = $mapper->fetchTerms(0,'style',true);
$materials = $mapper->fetchTerms(0,'material',true);
$patterns = $mapper->fetchTerms(0,'pattern',true);
$others = $mapper->fetchTerms(0,'other',true);
$condition = $mapper->fetchTerms(0,'condition',true);
$shipping = $mapper->fetchTerms(0,'shipping',true);
$this->view->colors = $colors;
$form = new Site_Form_Submission($main_categories,$sizes,$genders,$seasons,$decades,$colors,$styles,$materials,$patterns,$others,$condition,$shipping);
$this->view->form = $form;
$this->view->finished_settings = self::finishedStep('finished_settings');
if ($this->getRequest()->isPost()) {
if (!$form->isValid($this->getRequest()->getParams())) {
$form->populate($this->getRequest()->getParams());
}else{
$this->_helper->redirector('getpaid');
}
}
}
else{
$this->_redirect('http://' . $_SERVER['HTTP_HOST'] . PHOTO_GUIDE);
}
}
I must mention that I'm using modules in my application.
Any help would be really appreciated!
Try the following code:
$redirector = $this->_helper->getHelper('Redirector');
$this->_redirector->setCode(303)
->setExit(false)
->setGotoSimple("this-action", "some-controller");
Try this $this->_helper->redirector('action','controller','module');