Hi Im stucked with this for 4 days now, i have read massive amount of related articles, but seems nothing is working.
First i will explain my idea, give you some code and then i will tell what i have tried.
Idea. I have 2 separate db tables 'project' and 'pictures'. In project table i put info about projects (id, title, pubdate, template etc.) and i need to assign some pictures to that project so on pictures table i have "project_id" column which is relating those two. In my controller i have function project_picture_proccess($id) this $id is changing according to which project im clicking on and that is how all related pictures are fetched. problem is i cant pass that current project $id to upload model (this is for setting upload path for current project).
This is my controller:
class project extends Admin_Controller{
public function __construct(){
parent::__construct();
$this->load->model('project_m');
$this->load->model('project_pictures_m');
//here is index() function and some other (not related to my problem)
public function project_picture_proccess($id = NULL){
//$id variable is from current project im editing
//and changes according to project id
$this->load->model('upload_m');
if ($id) {
//search for directory in upload path with current project slug name
//and if there isnt any it will create it and add proper rights
$this->project_m->search_and_create_dir($id);
//function get_images is fetching all images that current project has
$this->data['project_images'] = $this->project_m->get_images($id);
//this function is setting upload config (setting upload path
//based on directory created in above)-its working var_dump'ed it
$this->upload_m->set_upload_config($id);
}
if($this->input->post('upload')){
//do_multi_upload works on multiple images just fine
//but i cant make it to get outcome of set_upload_config function
//so i can set upload_path very manualy and everything i upload is in mess
$this->upload_m->do_multi_upload();
//redirection function does not work because it is not getting
//any project_m data and i have lost all project_m related data in my view
//its title of project im editing and its id
redirect('admin/project/project_picture_proccess');
}
$this->data['error'] = array('error' => '');
$this->data['project'] = $this->project_m->get($id);
//function get_images is fetching all unsorted images uploaded in
//the path created above for further proccessing
$this->data['unsorted_img'] = $this->upload_m->get_unsorted();
$this->data['subview'] = 'admin/project/picture_proccess';
$this->load->view('admin/main', $this->data);
}
and here is my model:
class Upload_m extends MY_model{
protected $pic_path;
protected $_primary_filter = 'intval';
protected $_table_name = 'projects';
function Upload_m(){
parent::__construct();
$this->pic_path = realpath(APPPATH . '../img/');
function get_slug($id = NULL){
if($id !=NULL){
$filter = $this->_primary_filter;
$id = $filter($id);
$result = mysql_query('SELECT slug FROM ' . $this->_table_name . ' WHERE id=' . $id . ' limit 1');
$data = mysql_fetch_row($result);
$name = array_shift($data); //array - need to be string
return $name;
}else return;
}
function set_upload_config($id){
if($id == NULL) return;
$slug = $this->get_slug($id);
$upload_config = array(
'allowed_types' => 'jpg|gif|jpeg|png|bmp',
'upload_path' => $this->pic_path . $slug . '/',
'max_size' => 0
);
return $upload_config;
}
function do_multi_upload(){
$this->load->library('upload');
$this->upload->initialize($this->set_upload_config());
if($this->upload->do_multi_upload('userfile')){
var_dump($this->upload->get_multi_upload_data());
return;
}else echo "Error at uploading";
}
Here is what i have tried:
moving if($this->input->post...) method inside if($id) scope and
nothing is passed to view and noting is passed to model
tried like every single solution on stackoverflow: these very common tip was $this->load->model('upload_m', $id) <-
returning null when var_dump($id) tested on function
do_something($id){var_dump($id); die;}
i have made global variables and tried to fetch them by get_class_vars
i have rewrite system/core/libraries/model function to accept variable on do_multi_upload($field<-this is default,
$var=NULL<-optional)
i have tried to put those variables in __construct() function like __construct($var)
i have tried to change name of that $id to $var and put it inside if($this->input->post('upload') && $var === $id) and tried to use $var in model. didnt work this approach
I am so desperate this has taken too too much my time. My goal is to pass $id to upload function to set correct upload path and save data into database url (taken from upload_path), project_id ->taken from passed $id. Any help will be appreciated even if its a suggestion how to change my structure so i could still meet my goals.
Related
Hi I have problem when i tried to save attribute of model to database. I write in OctoberCMS and i have this function:
public function findActualNewsletter()
{
$actualNewsletter = Newsletter::where('status_id', '=', NewsletterStatus::getSentNowStatus())->first();
if (!$actualNewsletter) {
$actualNewsletter = Newsletter::where('send_at', '<=', date('Y-m-d'))->where('status_id', NewsletterStatus::getUnsentStatus())->first();
$actualNewsletter->status_id = NewsletterStatus::getSentNowStatus();
dd($actualNewsletter);
}
return $actualNewsletter;
}
getSentNowStatus()=2;
getUnsentStatus()=1;
dd($actualNewsletter) in my if statement show that status_id = 2 But in database i still have 1. I used this function in afterSave() so i dont need:
$actualNewsletter->status_id = NewsletterStatus::getSentNowStatus();
$actualNewsletter->save();
becosue i have error then i use save in save.
Of course i filled table $fillable =['status_id']. And now i dont know why its not save in database when it go to my if. Maybe someone see my mistake?
If you are trying to modify the model based on some custom logic and then save it, the best place to put it is in the beforeSave() method of the model. To access the current model being saved, just use $this. Below is an example of the beforeSave() method being used to modify the attributes of a model before it gets saved to the database:
public function beforeSave() {
$user = BackendAuth::getUser();
$this->backend_user_id = $user->id;
// Handle archiving
if ($this->is_archived && !$this->archived_at) {
$this->archived_at = Carbon\Carbon::now()->toDateTimeString();
}
// Handle publishing
if ($this->is_published && !$this->published_at) {
$this->published_at = Carbon\Carbon::now()->toDateTimeString();
}
// Handle unarchiving
if ($this->archived_at && !$this->is_archived) {
$this->archived_at = null;
}
// Handle unpublishing, only allowed when no responses have been recorded against the form
if ($this->published_at && !$this->is_published) {
if (is_null($this->responses) || $this->responses->isEmpty()) {
$this->published_at = null;
}
}
}
You don't have to run $this->save() or anything like that. Simply modifying the model's attributes in the beforeSave() method will accomplish what you desire.
I have a DataObject class called AdminUpload that stores two variables: UploadDate (which is always going to bet set to the current date) and Total, which is an int.
The function updateUploads() is called and stores the current date and increments the Total by 1 each time its called.
<?php
class AdminUpload extends DataObject {
private static $db = array(
'UploadDate' => 'Date',
'Total' => 'int'
);
// Tell the datagrid what fields to show in the table
private static $summary_fields = array(
'ID' => 'ID',
'UploadDate' => 'Current Date',
'Total' => 'Version Number'
);
public function updateUploads(){
$uploadDate = SS_Datetime::now();
$this->UploadDate = $uploadDate;
$this->Total++;//increment the value currently stored in the database each time
$this->write();
}
}
What I want to to is, when someone uploads a new image in the admin view, then the updateCache() function is called during the onAfterWrite() process. I only want to maintain one entry in the database, though, so every time I upload an image, I want to have just one entry in the AdminUpload database table.
public function onAfterWrite(){
$updateGallery = parent::onAfterWrite();
$adminUploading = AdminUpload::get();
$adminUploading -> updateUploads();
return $updateGallery;
}
I've never tried to do a function call in SilverStripe like this--it seems simple enough but since I am not going to add a new entry to the database with each call to the updateUploads() function, that's where I'm stuck. Any tips would be helpful...
It is incorrect approach to create a whole table for just one record. If you were going to use theses two fields on a page, then adding them to that page (create a new page type) would be a better idea.
If you are talking about file uploads, then you can always query this information directly from database.
$uploadedFilesCount = File::get()->count();
$lastUploadedFileDate = File::get()->sort('CreatedDate', 'DESC')->first()->CreatedDate;
onAfterWrite is a hook and used from DataExtension. There are cases when hooks are called directly on DO and then on extensions.
Your extension code might look like this to handle 'onCreated' state:
class UploadsCounter extends DataExtension {
protected $isCreating = false;
public function onBeforeWrite() {
if (!$this->owner->isInDB()) {
$this->isCreating = true;
}
}
// called on validation or database error
public function onAfterSkippedWrite() {
$this->isCreating = false;
}
public function onAfterWrite() {
if (!$this->isCreating) return;
$this->isCreating = false;
$adminUploading = AdminUpload::get()->first();
if (!$adminUploading ) {
$adminUploading = new AdminUpload();
$adminUploading->write();
}
$adminUploading->updateUploads();
}
}
You should define UploadsCounter extension on the dataobject that you are going to count, for example:
mysite/_config/config.yml
File:
extensions:
- UploadsCounter
I am new to laravel, and trying to build a photo album with it.
My problem is that i use the attach function to insert the user id and group id to my database, it works okay, but in the documentation it says this about the attach function
For example, perhaps the role you wish to attach to the user already
exists. Just use the attach method:
So i wanted to use it the same way, if the album_id already exist just update it, other wise insert thr new one, but my problem is it always insters, it does not checks if the album_id already exsits
My model
class User extends Eloquent
{
public static $timestamps = false;
public function album()
{
return $this->has_many_and_belongs_to('album', 'users_album');
}
}
Post function
public function post_albums()
{
$user = User::find($this->id);
$album_id = Input::get('album');
$path = 'addons/uploads/albums/'.$this->id.'/'. $album_id . '/';
$folders = array('path' => $path, 'small' => $path. 'small/', 'medium' => $path. 'medium/', );
if (! is_dir($path) )
{
foreach ($folders as $folder)
{
#mkdir($folder, 0, true);
}
}
$sizes = array(
array(50 , 50 , 'crop', $folders['small'], 90 ),
array(164 , 200 , 'crop', $folders['medium'], 90 ),
);
$upload = Multup::open('photos', 'image|max:3000|mimes:jpg,gif,png', $path)
->sizes( $sizes )
->upload();
if($upload)
{
$user->album()->attach($album_id);
return Redirect::back();
}
else
{
// error show message remove folder
}
}
Could please someone point out what im doing wrong? Or i totally misunderstod the attach function?
I believe you have misunderstood the attach function. The sync function uses attach to add relationships but only if the relationship doesn't already exist. Following what was done there, i'd suggest pulling a list of id's then only inserting if it doesn't already exist in the list.
$current = $user->album()->lists( 'album_id' );
if ( !in_array( $album_id, $current ) )
{
$user->album()->attach( $album_id );
}
On a side note I'm going to suggest that you follow the default naming convention from laravel. The relationship method should be $user->albums() because there are many of them. The pivot table should also be named 'album_user'. You will thank yourself later.
Contains method of Laravel Collections
The laravel collections provides a very useful method 'contains'. It determine if a key exists in the collection. You can get the collection in your case using $user->album. You can note the difference that album is without paranthesis.
Working code
Now all you had to do is use the contains method. The full code will be.
if (!$user->album->contains($album_id)
{
$user->album()->attach($album_id);
}
Its more cleaner and 'Laravel' way of getting the required solution.
Thanks #Collin i noticed i misunderstand i made my check yesterday
$album = $user->album()->where_album_id($album_id)->get();
if(empty($album))
{
$user->album()->attach($album_id);
}
Okay, so I have this snippet of code in a controller. However, it's all DB driven and should really be in model - I get that. However, as you can see in the IF statement, I need to pass along $data to my view. Based on the outcome. I tried pasting this chuck of coding in a method in my model (calling the model method via controller), however the $data[update_prompt] string is not getting called by the view...
How would I translate this code into a model - sending the $data values back to my controller to embed in my view?
// show appropriate upgrade message if user has free account
$id = $this->session->userdata('user_id');
$this->db->select('subscription'); // select the subscription column
$this->db->where('id', $id); //find id in table that matches session id
$query = $this->db->get("subscriptions"); // connect to this database
$subscribe = $query->result_array(); //returns the result of the above
if($subscribe[0]['subscription'] == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
You would add a function in your model, like so:
public function myModelFunction($id) {
//we return row as we are looking up by primary key and are guaranteed only one row
return $this->db->select('subscription')
->where('id', $id)
->get('subscriptions')
->row();
}
Then, in your controller:
public function myControllerFunction() {
$subscribe = $this->my_model->myModelFunction($this->session->userdata('id'));
if($subscribe->subscription == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
}
I'm tryin to learn few things about Zend Framework and I got stucked on so simple operation like 'Edit' DB entry.
I've got list of contacts in MySQL db and my intention is to fill form with information from one row, edit it and save it back to db (update statement). I tried almost everthing that came into my mind, checked out google and book about ZF, but there is some problem all the time. At this moment, when I want to do update, zf and mysql will create new db entry with new id and edited information filled in, but that is not what i want to do obviously because instead of one updated entry in DB I've got two - old one and new one with updated information.
Here are the importat parts of my code...please have a look at it, I can't figure out what I'm missing here.
part of indexcontroller:
public function createcontactAction()
{
$createContactForm = $this->_helper->_formLoader('addContact');
$this->view->addContactForm = $createContactForm;
}
public function editcontactAction()
{
$id = $this->getRequest()->getParam('id');
$contactModel = new Application_Model_Contacts();
$contactRow = $contactModel->find($id)->current();
$addContactForm = $this->_helper->formLoader('addContact');
if ($this->getRequest()->isPost() && $this->getRequest()->getPost('send', false) !== false) {
if ($addContactForm->isValid($this->getRequest()->getPost())) {
$contactRow->setFromArray($addContactForm->getValues());
$contactRow->save();
$this->_redirect('/index/editcontact/id/' . $contactRow->id);
}
} else {
$addContactForm->populate($contactRow->toArray());
}
$this->view->addContactForm = $addContactForm;
}
public function savecontactAction()
{
$form = $this->_helper->formLoader('addContact');
if ($this->getRequest()->isPost() && $this->getRequest()->getPost('send', false) !== false) {
if ($form->isValid($this->getRequest()->getPost())) {
$contactModel = new Application_Model_Contacts();
$contactRow = $contactModel->createRow($form->getValues());
$contactRow->save();
$this->_redirect('/index/editcontact/id/' . $contactRow->id);
}
}
$this->view->form = $form;
}
form - parts that matters:
class Application_Form_AddContact extends Zend_Form
{
public function init()
{
$this->setAction('/index/savecontact');
$this->setMethod(Zend_Form::METHOD_POST);
$this->setAttrib('id', 'index_savecontact');
$contactFirstName = new Zend_Form_Element_Text('first_name', array('size'=>32, 'maxlength'=>64, 'label'=>'Křestní', 'required'=>false));
$contactLastName = new Zend_Form_Element_Text('last_name', array('size'=>32, 'maxlength'=>64, 'label'=>'Přímění', 'required'=>true));
.
.
.
$contactNotes = new Zend_Form_Element_Textarea('notes', array('cols'=>32, 'rows'=>1, 'label'=>'Poznámky', 'required'=>false));
$contactSend = new Zend_Form_Element_Submit('send', array('label'=>'Odeslat'));
$this->addElements(array ($contactFirstName, $contactLastName, $contactStreet, $contactHouseNumber, $contactCity, $contactZipCode, $contactCountry,
$contactPhoneNumber, $contactMobileNumber, $contactEmail, $contactWebPage, $contactCrn, $contactVat, $contactNotes, $contactSend));
Thank you very much!
(If theres anything more you could need to help me with this just ask for it)
EDIT:
heres model for contacts:
class Application_Model_Contacts extends Zend_Db_Table_Abstract
{
protected $_name = 'contacts';
protected $_primary = 'id';
}
I'm a bit rusty with regards to Zend_Db_Table and Zend_Db_Table_Row (I'm assuming that is what your model uses), but my bet would be that you are missing the Primary Key (PK) in your $contactRow - I'm guessing you probably don't supply it via the form as I see you get it through GET. So just set the id to $id in your $contactRow and you should be fine.
In editcontactAction(), before $contactRow->save();, add : $contactRow->id = $id. If your row doesn't have a id specified, save() can't update.
You're trying to get an update without providing the id of the row you want to update. The data used for the query is $form->getValues() but the form doesn't seem to contain the id of the contact. Add the id as a hidden field (with the id as the value) to your form or set it separately with $contactRow->id = $id and it should update instead of insert.