Drupal 8 Image Field value - drupal

I'm trying to figure out how to get the path to an image from an entity in Drupal 8. I had thought get()->value would do it, but that just returns a blank string.
I have a test function:
function getValueTest ($profile_id, $field)
{
$profile_storage = \Drupal::entityManager()->getStorage('profile');
$profile = $profile_storage->load($profile_id);
if ($profile != null)
{
if ($profile->hasField ($field))
{
return $profile->get ($field)->value;
}
}
return "No field" . $field;
}
Assume some profile id 3 that has two fields field_first_name and field_mugshot. If I call:
dpm ($this->getValueTest (3, 'field_first_name'));
dpm ($this->getValueTest (3, 'field_mugshot'));
The first call correctly displays the first name in the message area, but the second just gives a blank string. I need a path to the image so I can do some processing on its content.

You can use the folowing methods to get the uri or the url:
$entity->get('field_image')->entity->getFileUri();
$entity->get('field_image')->entity->url();
This is because value() method should return the value of the field(aka a fid), field which is an entity reference in this case.

Related

$date not picking up current date - Sitecore

I am having an issue while setting default value for datetime field in sitecore standard values.
I know that $date takes the current date. If I specify $date in standard values for a date time field , it always takes the date as "1/1/0001".
How do I fix this ?
It is possible to enter tokens in the fields on the standard values, and then these will be replaced with other values, but only when a new item which use that template is created. It will not set date for the existing items which use this template.
$date is one of the token and it's replates with the system date (yyyyMMdd).
There is a blog post written by John West which explains how to Expand Standard Values Tokens in Existing Items with the Sitecore ASP.NET CMS.
EDIT:
Here is the code which is a part of MasterVariablesReplacer class which is used to replace $date token:
text = this.ReplaceWithDefault(text, "$date", (Func<string>) (() => DateUtil.IsoNowDate), context);
It is called from the ReplaceVariables processor, which is a part of expandInitialFieldValue pipeline (see /sitecore/admin/showconfig.aspx for all the expandInitialFieldValue processors).
You can try to add your own processor to this pipeline and see why the $date is not replaced properly:
public class ReplaceVariables : ExpandInitialFieldValueProcessor
{
public override void Process(ExpandInitialFieldValueArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
MasterVariablesReplacer variablesReplacer = Factory.GetMasterVariablesReplacer();
string text = args.SourceField.Value;
if (variablesReplacer == null)
args.Result = text;
else
args.Result = variablesReplacer.Replace(text, args.TargetItem);
}
}

Send Gravity Forms data to redirection page

I have a very simple form created with Gravity Forms;
It submits two numbers and then redirects to a different result page.
How do I retrieve those two numbers on the result page?
add_filter("gform_confirmation_4", "custom_confirmation", 3, 4 );
function custom_confirmation($confirmation, $form, $lead, $ajax)
Gives a custom confirmation. Each field value can be retrieved by using $lead[{field ID}]
I have a solution for this based on using a combination of form submission hooks and the GForms API. It's a horrible plugin so I apologise for the messiness of the logic flow. It's important to use the framework methods rather than processing the data yourself since there are a good amount of hacks and shonky things going on in there to correctly match field IDs and so forth.
I will provide a solution to pass a submission from one form to pre-populate another. Changing the destination for POST data is pretty straightforward, they have an example for it on their gform_form_tag hook documentation page. Yes, that really is the only way of doing it.
Without further ado here is the code. I've set it up to work off form configuration to make things simpler for the end user, so it works like this:
Select "allow field to be populated dynamically" in your destination form field's advanced settings and choose a parameter name for each.
Add matching CSS classes on the source fields of the other form(s) to setup the associations.
Add a CSS class to the source forms themselves so that we can quickly check if the redirection is necessary.
.
$class = 'GForms_Redirector';
add_filter('gform_pre_submission', array($class, 'checkForSubmissionRedirection'), 10, 1);
add_filter('gform_confirmation', array($class, 'performSubmissionRedirection'), 10, 4);
abstract class GForms_Redirector
{
const SOURCE_FORMS_CLASS_MATCH = 'submission-redirect';
const DEST_PAGE_SLUG = 'submit-page-slug';
const DEST_FORM_ID = 1;
protected static $submissionRedirectUrl;
// first, read sent data and generate redirection URL
function checkForSubmissionRedirection($form)
{
if (false !== preg_match('#\W' . self::SOURCE_FORMS_CLASS_MATCH . '\W#', $form['cssClass'])) {
// load page for base redirect URL
$destPage = get_page_by_path(self::DEST_PAGE_SLUG);
// load form for reading destination form config
$destForm = RGFormsModel::get_form_meta(self::DEST_FORM_ID, true);
$destForm = RGFormsModel::add_default_properties($destForm);
// generate submission data for this form (there seem to be no hooks before gform_confirmation that allow access to this. DUMB.)
$formData = GFFormsModel::create_lead($form);
// create a querystring for the new form based on mapping dynamic population parameters to CSS class names in source form
$queryVars = array();
foreach ($destForm['fields'] as $destField) {
if (empty($destField['inputName'])) {
continue;
}
foreach ($form['fields'] as $field) {
if (preg_match('#(\s|^)' . preg_quote($destField['inputName'], '#') . '(\s|$)#', $field['cssClass'])) {
$queryVars[$destField['inputName']] = $formData[$field['id']];
break;
}
}
}
// set the redirect URL to be used later
self::$submissionRedirectUrl = get_permalink($destPage) . "?" . http_build_query($queryVars);
}
}
// when we get to the confirmation step we set the redirect URL to forward on to
function performSubmissionRedirection($confirmation, $form, $entry, $is_ajax = false)
{
if (self::$submissionRedirectUrl) {
return array('redirect' => self::$submissionRedirectUrl);
}
return $confirmation;
}
}
If you wanted to pass the form values someplace else via the querystring then you'd merely need to cut out my code from the callback and build your own URL to redirect to.
This is a very old question, now you can send it using a Query String on the confirmation settings.
They have the documentation on this link:
How to send data from a form using confirmations
Just follow the first step and it will be clear to you.

Cannot implicitly convert type 'System.Linq.IQueryable to System.Data.Entity.DbSet<>

I receive the following error when I try to run my code. I haven't managed to solve it yet, please Help:
edit: Marked with * where it fails.
>
public IQueryable<Video> GetVideos([QueryString("id")] int? categorieId)
{
var _db = new TeleviziuneAcademicaAspSilverlight.Models.VideoContext();
IQueryable<Video> query = *_db.Videos;*
if (categorieId.HasValue && categorieId > 0)
{
query = query.Where(v => v.CategorieID == categorieId);
}
return query;
Change
IQueryable<Video> query =
to
IQueryable<Appname.Models.Video> query =
The reason for your error is that you have the type Video defined twice and because of using a short type name you accidentally reference not the one Video you should.
Also change it in the method's return value
public IQueryable<Appname.Models.Video> GetVideos( ... )
You seem to have two classes called Video. If you need both, you'll need to project from one to the other before your return statement:
return query.Select(dbVideo => new Appname.Video()
{
Prop1 = dbVideo.Prop1,
Prop2 = dbVideo.Prop2,
// etc.
});
Though you'll probably need to change the return type to an IEnumerable<> if you do that.
If you can just work with Appname.Models.Video, change IQueryable<Video> to IQueryable<Appname.Models.Video> in the method signature and the method body.

get the select element in .NET using AJAX

I have ajax function like this to run on HTML select list
$.ajax({
type: "POST",
url: urlemp,
success: function (returndata) {
if (returndata.ok) {
// var data = eval("" + returndata.data + "");
select.empty();
select.append($('<option>' + "" + '</option>'));
$.each(returndata.data, function (rec) {
select.append($('<option>' + returndata.data[rec].Name + '</option>'));
});
select.show('slow');
select.change();
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
and this is the HTML element
<select id="cmbDept"></select>
How can i get the value of the selected item in the controller using MVC 3 ?
you have 4 ways to do that
1. the you can bind ti the change event of the select $(select).change(function(){}) and send an ajax request again wrapping the selected value which you will be able to get in the controller
2. you can keep a hidden input in your view binded to a property in the view's model now bind to the change of the select and fill the input with the value this way whenever your form is posted back it will have the values properly binded to the model
3. #Don saved me from writing the third way so read his ans.
4. if you have a model that this view is binded to then simple keep a property in the model with the name cmbDept and selected value would be automatically posted back
Us FormCollection as parameter in your controller. And assign name to the select
<select id="cmbDept" name="cmbDept"></select>
Now the FormCollection has this posted value.
public ActionResult Index(FormCollection form)
{
string val = "";
foreach (var key in form.AllKeys)
{
if (key.Contains("cmbDept"))
{
val = form.Get(key);
}
}
--your code here with the posted values
return View();
}
To get the value of the select element on the client, just use $("#cmbDept").val().
To get the value of the element once it's submitted to the server, add a name="cmbDept" to your select and simply create a parameter named cmbDept in the controller action your $.ajax call is is posting to.

passing cck field as an argument in views

I have content type called event, which has a cck field called event id. The idea is that once a user goes that a url with that id, only information relating to that event id is displayed. In my view, i tried creating a block view and passed the event id as an argument, as soon as i do that, the results which formerly displayed in the live preview disappears..Not quite sure of what i am doing wrong, or if i should be block view. Should this be a page view? Please help.
I believe that you should create a Page View and not a block view. You have to pass a argument. Is Event ID equals to NodeID? If yes then you should add an Argument of type Node:NID and then set "Provide default argument" equals to "Node ID from URL".
If the EventId is NOT the NID then you should set the Default Argument to PHP and give the following PHP :
$path = drupal_get_path_alias($_GET["q"]); //get the URL alias
$path = explode("/", $path); //break path into an array
if ($path[0] == "events" && $path[1] != "")
{
return $path[1];
}
The above code will take the argument from the URL (the URL should be like www.example.com/events/14555
The reason that I am using the drupal_get_path_alias is because you may have enabled the pathauto module. If not you can just give the following php
if (arg(0) == ‘events’ && arg(1) != ”) return arg(1);

Resources