I am using gallery3 php software, which is based on the kohana framework. Does anybody know how to add a checkbox to the album information form?
I tried like this:
static function get_edit_form($parent) {
$form = new Forge(
"albums/update/{$parent->id}", "", "post", array("id" => "g-edit-album-form"));
$form->hidden("from_id")->value($parent->id);
$group = $form->group("edit_item")->label(t("Edit Album"));
$group->input("title")->label(t("Title"))->value($parent->title)
->error_messages("required", t("You must provide a title"))
->error_messages("length", t("Your title is too long"));
$group->textarea("description")->label(t("Description"))->value($parent->description);
/* MPK: information fields for albums */
$group->textarea("information")->label(t("Information text"))->value($parent->information);
$group->checkbox("info")->label(t("Informational"))->value($parent->info);
if ($parent->id != 1) {
$group->input("name")->label(t("Directory Name"))->value($parent->name)
->error_messages("conflict", t("There is already a movie, photo or album with this name"))
->error_messages("no_slashes", t("The directory name can't contain a \"/\""))
->error_messages("no_trailing_period", t("The directory name can't end in \".\""))
->error_messages("required", t("You must provide a directory name"))
->error_messages("length", t("Your directory name is too long"));
$group->input("slug")->label(t("Internet Address"))->value($parent->slug)
->error_messages(
"conflict", t("There is already a movie, photo or album with this internet address"))
->error_messages(
"not_url_safe",
t("The internet address should contain only letters, numbers, hyphens and underscores"))
->error_messages("required", t("You must provide an internet address"))
->error_messages("length", t("Your internet address is too long"));
} else {
$group->hidden("name")->value($parent->name);
$group->hidden("slug")->value($parent->slug);
}
AND
public function update($album_id) {
access::verify_csrf();
$album = ORM::factory("item", $album_id);
access::required("view", $album);
access::required("edit", $album);
$form = album::get_edit_form($album);
try {
$valid = $form->validate();
$album->title = $form->edit_item->title->value;
$album->description = $form->edit_item->description->value;
/* MPK: information fields for albums */
$album->information = $form->edit_item->information->value;
$album->info = $form->edit_item->info->value;
$album->sort_column = $form->edit_item->sort_order->column->value;
$album->sort_order = $form->edit_item->sort_order->direction->value;
if (array_key_exists("name", $form->edit_item->inputs)) {
$album->name = $form->edit_item->inputs["name"]->value;
}
$album->slug = $form->edit_item->slug->value;
$album->validate();
} catch (ORM_Validation_Exception $e) {
// Translate ORM validation errors into form error messages
foreach ($e->validation->errors() as $key => $error) {
$form->edit_item->inputs[$key]->add_error($error, 1);
}
$valid = false;
}
if ($valid) {
$album->save();
module::event("item_edit_form_completed", $album, $form);
log::success("content", "Updated album", "view");
message::success(t("Saved album %album_title",
array("album_title" => html::purify($album->title))));
if ($form->from_id->value == $album->id) {
// Use the new url; it might have changed.
json::reply(array("result" => "success", "location" => $album->url()));
} else {
// Stay on the same page
json::reply(array("result" => "success"));
}
} else {
json::reply(array("result" => "error", "html" => (string)$form));
}
}
The field does show up on the form, but the field value does not get saved to the DB. In the DB it is a tinyint(1).
Kohana uses models to save data in the database. Because of $album->save(); you should have a model somewhere in the application, depending of the version of Kohana.
Go to /modules/gallery/models. There is a file called item.php. This is the model used by the application to save/load/create items (and also albums). At line 447 there is the command which actually saves the contents of the album in the database. You need to change that line in order to save the value of the checkbox.
Solved. The problem was that you have to use 'checked' field of the check-box and not the value field in the assignment.
In album.php
$group->checkbox("info")->label(t("Informational"))->value($parent->info)->checked($parent->info);
In albums.php:
$album->info = $form->edit_item->info->checked;
The field in the DB is also named 'info' and can be a bit.
Related
I'm working on a project and my task is : set up a page to edit my user account information. For this, I have to use the TYPO3 extension femanager.
I installed the extension and put the plugin on my page. I have 4 fields that are displayed (photo, phone numbers and email). But when i submit my form, I have this error :
Argument 2 passed to
In2code\Femanager\Utility\FrontendUtility::forceValues() must be of
the type array, null given, called in
/home/dev/rta/htdocs/typo3conf/ext/femanager/Classes/Controller/EditController.php
on line 69
I tried to look for someone with a similar problem on the Internet but couldn't find anything. I looked at the code, but since it's the base extension code, I don't think that's where the problem comes from. The users are stored in the fe_users table in my database and the fields pre-fill nicely with my existing data.
I just learned TYPO3 3 weeks ago so I have a lot of gaps and I'm not very familiar with it yet.
If it can help, here is my EditController.php (lines 66 to 79) :
public function updateAction(User $user)
{
$this->redirectIfDirtyObject($user);
$user = FrontendUtility::forceValues($user, $this->config['edit.']['forceValues.']['beforeAnyConfirmation.']);
$this->emailForUsername($user);
UserUtility::convertPassword($user, $this->settings['edit']['misc']['passwordSave']);
$this->signalSlotDispatcher->dispatch(__CLASS__, __FUNCTION__ . 'BeforePersist', [$user, $this]);
if (!empty($this->settings['edit']['confirmByAdmin'])) {
$this->updateRequest($user);
} else {
$this->updateAllConfirmed($user);
}
$this->redirect('edit');
}
And here is my FrontendUtility class (used in my EditController at line 69) :
public static function forceValues(User $user, array $settings)
{
foreach ((array)$settings as $field => $config) {
$config = null;
if (stristr($field, '.')) {
continue;
}
// value to set
$value = self::getContentObject()->cObjGetSingle($settings[$field], $settings[$field . '.']);
if ($field === 'usergroup') {
// need objectstorage for usergroup field
$user->removeAllUsergroups();
$values = GeneralUtility::trimExplode(',', $value, true);
$userGroupRepository = self::getUserGroupRepository();
foreach ($values as $usergroupUid) {
/** #var UserGroup $usergroup */
$usergroup = $userGroupRepository->findByUid($usergroupUid);
$user->addUsergroup($usergroup);
}
} else {
// set value
if (method_exists($user, 'set' . ucfirst($field))) {
$user->{'set' . ucfirst($field)}($value);
}
}
}
return $user;
}
If anyone has an idea, I'm interested!
PS : I use TYPO3 v9.5.8
I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?
Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}
Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);
The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).
I want to create a custom validator in Zend.
for e.g. my code:
$txt_state = new Zend_Form_Element_Text('state');
$txt_state->setLabel('State');
$txt_prop = new Zend_Form_Element_Text('pin');
$txt_prop->setLabel('Property');
Now I want that the form must be submitted only if at least one of these 2 elements are not empty.
you can do it dirty way like this:
if ($this->getRequest()->isPost()) {
if (is_empty($form->getElement('state')->getValue())) {
$form->getElement('pin')->setRequired();
}
if (is_empty($form->getElement('pin')->getValue())) {
$form->getElement('state')->setRequired();
}
if ($form->isValid()) {
//redirect to success page
} else {
//do nothing, display errors messages, refill form
}
}
or cleaner with extended Zend_Form_Element.
Here you can add custom validation like this in controller.
$state = "YOUR VALUE";
$form->state->setValue($state);
$form->getElement('state')->setRequired();
$form->getElement('state')->addValidator( 'Alpha', true, array( 'messages' => array( 'notAlpha' => "Please enter alphabetic character only in state name.
") ));
$mArr = array('state'=>$state);
if( !$form->isValid($mArr) ){
$myErrorArray[] = $form->getMessages();
$is_error = 1;
}
Here $myErrorArray have all error message that you apply on element state.
I am adapting StationWagon (FuelPHP app) and so far it's working really well.
I have adapted it (with some help) to allow multiple images to be uploaded to the server. This is also working great.
However, I am thinking it would make more sense if I had 2 Tables: 1) Articles and 2) ArticleImages. I would use a Foreign Key to associate the Images with the Article. So when publishing an article it would add the article data to 'Articles' table and move each image to a new row in 'ArticleImages'.
So ultimately my 'ArticleImages' table could be:
ID | ImageURL | ArticleID
Portion of my 'articles.php' controller:
<?php
public function action_add()
{
$val = Model_Article::validate('add_article'); //<-- maybe its just me but i never saw any similar to this in fuelphp sorry about this if im wrong
// if your form validation is okay than continue with everyhing else
if ($val->run())
{
$article = Model_Article::forge();
// Custom configuration for this upload
$config = array(
'path' => DOCROOT.DS.'images',
'randomize' => true,
'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'),
);
Upload::process($config);
// if a valid file is passed than the function will save, or if its not empty
if (Upload::is_valid())
{
// save them according to the config
Upload::save();
//if you want to save to tha database lets grab the file name
$value = Upload::get_files();
foreach($value as $files) {
print_r($files);
}
$article->filename = $value[0]['saved_as'];
}
$status = (Input::post('save_draft') ? 0 : 1);
if ( ! $val->input('category_id'))
{
$category_id = null;
}
else
{
$category_id = $val->validated('category_id');
}
$article->user_id = $this->user_id;
$article->category_id = $category_id;
$article->title = $val->validated('title');
$article->body = $val->validated('body');
$article->published = $status;
if ($article->save())
{
Session::set_flash('success', 'Article successfully added.');
}
else
{
Session::set_flash('error', 'Something went wrong, '.
'please try again!');
}
Response::redirect('articles/add');
}
$this->template->title = 'Add Article';
$this->template->content = View::forge('articles/add')
->set('categories', Model_Category::find('all'), false)
->set('val', Validation::instance('add_article'), false);
}
/* End of file articles.php */
You are trying to make a relation between Articles and ArticleImages. An ArticleImage belongs to an Article, while an Article has many ArticleImages. FuelPHP has functionality built in for what you are trying to achieve. Have a look at the FuelPHP docs on its Object Relational Mapper, especially the Belongs To and Has Many relations.
So when i made the code for you back a few days a go you only requested, one file input.
And no offense but you are doing it all wrong...
foreach($value as $files) {
print_r($files);
}
$article->filename = $value[0]['saved_as'];
should be
foreach($value as $files) {
$articleimg = Model_Articleimages::forge();
$articleimg->image_row_name = $files['saved_as']
}
To get you to understand
what you did here, $value = Upload::get_files(); yes this gets all the elements but since you need to loop trouh the elements you dont need it
Second
this $value[0]['saved_as'] only grabs the first image name, just the first one, and since you are in a loop now you need to refer to the $files variable as i shown you in the above example, just an example
I have an array of people that is registered as online in a html file. I am using this so that each can have an image assigned to them. But when checking to see if using name is already in use the in_array function return false and allow the script to continue.
$user = "< img src='default.jpg' />John";
$explode = array("<img src='tress.jpg' />John");
if(in_array($user, $explode))
{
//show login script if user exists
}
else
{
//continue to script
}
Now the reason this is not working is because the john in the array is not identical to the john in $user. Is there anyway of checking that the name exists in the array? When responding please explain.
Instead of asking, "How do I solve this problem?", you need to start with, "Why am I having this problem?"
$user = "< img src='default.jpg' />John";
Is < img src='default.jpg' />John a user name? Why are you using it as one? I'm guessing there's some clever thought behind this like "Well, I always display a user's image with their name, so I'll just make the image part of their name. This is going to cause far more problems than it solves. This comes back to a big concept in computer science called separation of concerns. An image is not logically a part of a user name, so don't store it as one. If you always display them together, you can use functions to display a user's information in a standard way without making the image part of the user name.
So first off, remove the image from the name. There are several ways to store this separately.
I would suggest using a class:
class User {
public $name;
public $imageSource;
// The following functions are optional, but show how a class
// can be useful.
/**
* Create a user with the given name and URL to their image
*/
function __construct($name, $imageSource) {
$this->name = $name;
$this->imageSource = $imageSource;
}
/**
* Gets the HTML to display a user's image
*/
function image() {
return "<img src='". $this->imageSource ."' />";
}
/**
* Gets HTML to display to identify a user (including image)
*/
function display() {
return $this->image() . $this->name;
}
}
$user = new User("john", "default.jpg");
// or without the constructor defined
//$user = new User();
//$user->name = "john";
//$user->imageSource = "default.jpg";
echo $user->display();
You can use an "array" if you want to be a little lazier, but I don't recommend it in the general case, since you lose the cool features of classes (like those functions):
$user = array(
name => "john",
image => "<img src='default.jpg' />";
);
echo $user["image"] . $user["name"];
In your database (if you're using one), make them separate columns and then use one of the above data structures.
Now that you have this, it's easy to see if a user name is in a given list using a foreach loop:
function userNameInList($user, $users) {
for($users as $current) {
if($user->name == $current) {
return true;
}
}
return false;
}
$newUser = new User("John", "john.jpg");
$currentUsers = array("John", "Mary", "Bob");
if(userNameInList($newUser, $currentUsers) {
echo "Sorry, user name " . $newUser->name . " is already in use!";
}
If you're new to PHP, the normal for loop may be easier to understand:
function userNameInList($user, $users) {
for($i = 0; $i < count($users); ++i) {
$current = $users[$i];
if($user->name == $current) {
return true;
}
}
return false;
}
Let me know if any of this doesn't run, I don't write PHP very often anymore..