Yii2 UploadImageBehavior. How to remove file? - yii

I have a problem with UploadImageBehavior.
I need to create simple button on frontend part that allow me to remove image (user avatar) after model save.
Actually i know how to do it with unlink, but i absolutely don't understand how to do that via behaviour.
I have next code in rules:
[['avatar'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg'],
So Yii just ignore me, if i try to pass null to my avatar property.
Thx )

Just create a method to your model class that does the unlinking, sets the file attribute in your model to null and saves the model.
public function removeAvatar() {
$transaction = $this->getDb()->beginTransaction();
try {
// If this is a new record throw an Exception because no file has been uploaded yet
if($this->isNewRecord) {
throw new \Exception("Can't delete file of new record");
}
// Set the attribute avatar to null
$this->avatar = null;
// Try to save the record. If we can't then throw an Exception
if(!$this->save()) {
throw new \Exception("Couldn't save the model");
}
// Try to delete the file. If we can't then throw an Exception
if(!unlink(Yii::getAlias('#app/path/to/your/file.something')) {
throw new \Exception("Couldn't delete the file");
}
$transaction->commit();
return true;
}
catch(\Exception $e) {
$transaction->rollback();
return false;
}
}

Below works for me:
unlink(getcwd().'/uploads/'.$model->file_id.'/'.$fileModel->file_name.$fileModel->extension);
getcwd() gets the current working directory. The docs for it are here

Related

ASP.NET Core 7 WebApplicationFactory Integration tests. How to load data?

I am creating an integration test to check that the data is working based on this very good tutorial.
The tutorial loads sample data in the OnModelCreating. But I was unsure if doing that will repeatedly load data to the DB when running the program.
However although I can get the index page to load, it has the page content, such as the table structure for the data it doesn't have the data from the database.
Using Swagger I copied a sample of data as JSON, saved it to a file, capitalized the first letter of the key to make it the same as the properties (after not doing do was fruitless as well), and tried to add it to the context.
internal static class AddTestData
{
//import json array and add to context
public static void AddMovieData(ApplicationDbContext context)
{
var jsonString = File.ReadAllText("testMoviedata.json");
var list = JsonSerializer.Deserialize<List<Movie>>(jsonString);
{
foreach (var item in list)
{
context.Movie.Add(item);
}
context.SaveChanges();
}
}
}
and tried to add it to the dbcontext in this process in the WebApplicationFactory Class from HERE
public class TestingWebAppFactory<TEntryPoint> : WebApplicationFactory<Program> where TEntryPoint : Program
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
......... stuff deleted for brevity...
using (var appContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
try
{
appContext.Database.EnsureCreated();
// Seed the database with test data.
AddTestData.AddMovieData(appContext);
}
catch (Exception ex)
{
//Log errors or do anything you think it's needed
throw;
}
}
... still nothin. Page loads, no data loads.
Also why can't I get breakpoints to work in the Integration project?
What am I doing wrong?
Solved!!!
The code was OK,but the data wasn't being deserialised.
I had to move it to the main project and test it there.
The solution is
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var list = JsonSerializer.Deserialize<Movie[]>(jsonString, options);

cannot echo data in a file located in extension/bootstraps/widgets

I am using Yii 1.1 .I have a class file inside widgets folder named MyCommentsTbEditableSaver.
when i try to echo data with in that php file .it doesnot return any thing.
What is the reason behind this?
my code:`
public function insertRps()
{
//get params from request
$this->primaryKey = yii::app()->request->getParam('pk');
$this->attribute = yii::app()->request->getParam('name');
//$this->attribute = yii::app()->request->getParam('comments');
$this->value = yii::app()->request->getParam('value');
//checking params
if (empty($this->attribute)) {
throw new CException(Yii::t('MyCommentsTbEditableSaver.editable', 'Property "attribute" should be defined.'));
}
if (empty($this->primaryKey)) {
throw new CException(Yii::t('MyCommentsTbEditableSaver.editable', 'Property "primaryKey" should be defined.'));
}
$model=new ProjectComments();
$comments=Yii::app()->db->createCommand()
->select('count(project_id) as countProject')
->from('pm_project_comments')
->where("project_id = $this->primaryKey ")
->queryRow();
if($comments['countProject']==0)
{
$model->isNewRecord=TRUE;
$model->comments_rps=$this->value;
$model->project_id=$this->primaryKey;
//also set update details,added by bishal
$model->crtd_by=Yii::app()->user->id;
$model->crtd_dt = date('Y-m-d');
print_r($model);die;
$model->save();
}
}`

Hippo CMS 7.9 Facets

I'm trying to implement facets and also create a catalog component.
My original approach was to use the:
org.onehippo.cms7.essentials.components.EssentialsContentComponent
However it doesn't seem like it's available for 7.9.
My next approach is to extend the PresentationList Component however the documentation isn't that clear of creating the values for the main and sub categories.
I would like to use this code for my component I'm just not sure once again where to place my Category (values).
try {
HstRequestContext requestContext = request.getRequestContext();
HippoBean scope = requestContext.getSiteContentBaseBean();
PresentationPageableListInfo info = getComponentParametersInfo(request);
LandingPage presentationPage = null;
String resolvedContentPath = PathUtils.normalizePath(requestContext
.getResolvedSiteMapItem().getRelativeContentPath());
createAndExecuteSearch(request, info, scope, (BaseFilter) null,
null, resolvedContentPath);
if (scope instanceof HippoFolderBean) {
presentationPage = getFirstLandingPageInFolder(request,
(HippoFolderBean) scope);
}
if (presentationPage != null) {
request.setAttribute("document", presentationPage);
}
if (request.getPathInfo().toLowerCase().contains("facet/")) {
request.setAttribute("faceted", true);
}
} catch (Exception e) {
throw new HstComponentException("Failed to query presentations.", e);
}
have you tried these pages :
http://www.onehippo.org/7_9/library/concepts/faceted-navigation/faceted-navigation-configuration.html
http://www.onehippo.org/7_9/library/setup/hst-components/facets-component.html

MonkeyTalk boolean logic

I'm trying to write scripts in JavaScripts to test the UI of an iPhone app with MonkeyTalk. How do I use logic and conditionals with this? Right now I have a block:
if (this.app.button("name").verify())
do this if button exists
The problem is verify doesn't return a bool, it just throws an error in the test if the button doesn't exist. Is there a way to catch the error and run a script accordingly?
This seems to work :
function verifiedViewOrNull (view)
{
var exists = false;
try
{
view.verify();
exists = true;
}
catch (e)
{
}
return exists ? view : null;
}
and you can just call it as such :
if (verifiedViewOrNull(this.app.view("name")) != null
{
// It exists
} else
//doesn't exist, not gonna throw exception

stop further execution after zend form is not valid and populate the form

if the form is not valid then populate the form and stop further execution of code. How to establish this.
Here's what I usually do in my controller:
public function editAction()
{
$model = $this->_findModelFromRequestParams();
$form = new Form_MyModelForm();
$form->populate($model->toArray());
//display the form for the first time and return
if ( ! $this->_request->isPost()) {
$this->view->form = $form;
return;
}
//populate the form with the POST values, and validate.
//If NOT valid, display the form again
if ( ! $form->isValid($this->_request->getPost())) {
$this->view->form = $form;
return;
}
try {
$formData = $form->getValues();
//save the new values here...
//set a flash message and redirect to the view page
$this->_redirect('/model/view/id/' . $model->id);
} catch (Exception $e) {
//there was some sort of error, so set a flash message with the error
//and display the form again. $form is already populated with values
//since we called $form->isValid(), which populated the form
$this->view->form = $form;
}
}