PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label field. Show all posts
Showing posts with label field. Show all posts

Wednesday, October 19, 2022

[FIXED] How to override field value display in Django admin change form

 October 19, 2022     admin, django, field     No comments   

Issue

How can I override the value that is displayed for a field in the Django admin? The field contains XML and when viewing it in the admin I want to pretty-format it for easy readability. I know how to do reformatting on read and write of the field itself, but this is not what I want to do. I want the XML stored with whitespace stripped and I only want to reformat it when it is viewed in the admin change form.

How can I control the value displayed in the textarea of the admin change form for this field?


Solution

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.initial['some_field'] = some_encoding_method(self.instance.some_field)

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    ...

Where, some_encoding_method would be something you've set up to determine the spacing/indentation or some other 3rd-party functionality you're borrowing on. However, if you write your own method, it would be better to put it on the model, itself, and then call it through the instance:

class MyModel(models.Model):
    ...
    def encode_some_field(self):
        # do something with self.some_field
        return encoded_some_field

Then:

self.instance.encode_some_field()


Answered By - Chris Pratt
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to print quotes between value using awk

 August 17, 2022     awk, field, output, separator     No comments   

Issue

I have a file

A|B|C|D|E|F

I need output like

"A","B","C","D","E","F"

I did:

awk -f'|' '{print $1,$2,$3}'

This gives me output just with spaces. My question is how to get comma separated output with quotes, and how to print all values at once without typing '{print $1,$2,$3......}'

I can do:

awk -f'|' '{print """"$1""""","""""$2""""","""""$3""""..}'

But it does not work.


Solution

To specify the field separator, you have to use -F instead of -f; to change what the field separator is for the output, you have to change the OFS variable (the output field separator).

The get quotes around your fields, you can loop over all fields and add them:

$ awk -F"|" -v OFS="," '{for (i=1; i<=NF; ++i){$i="\""$i"\""}}1' infile
"A","B","C","D","E","F"

Alternatively, using sed:

$ sed 's/\([^|]*\)/"\1"/g;y/|/,/' infile
"A","B","C","D","E","F"

This surrounds all sequences of non-pipe characters with quotes, then substitutes all the pipes with commas.



Answered By - Benjamin W.
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] What is the relation of protobuf message field id and field order?

 July 11, 2022     field, go, message, protocol-buffers     No comments   

Issue

I want to understand if the messages bellow are compatible from the perspective of protobuf and serialization/deserialization.

message HelloReply {
  string message = 1;
  string personalized_message = 2;
}
message HelloReply {
  string personalized_message = 2;
  string message = 1;
}

Does the order matter for compatibility in any situation?


Solution

The textual order is largely irrelevant, although it may impact some code generation tooling - but most languages don't care about declaration order, so even that: won't matter. The fields are still defined semantically equivalent - the numbers match the existing meaning (name) and type. It is the number that is the determining feature in identifying a field.

At the protocol level:

  • parsers must allow fields in any order
  • serializers should (but not must) write fields in ascending numerical field order


Answered By - Marc Gravell
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] How do I assign by "reference" to a class field in C#?

 July 10, 2022     c#, field, parameters, reference     No comments   

Issue

I am trying to understand how to assign by "reference" to a class field in C#.

I have the following example to consider:

 public class X
 {

     public X()
     {
         string example = "X";

         new Y(ref example);

         new Z(ref example);

         System.Diagnostics.Debug.WriteLine(example);
     }

 }

 public class Y
 {

     public Y( ref string example )
     {
         example += " (Updated By Y)";
     }

 }

 public class Z
 {
     private string _Example;

     public Z(ref string example)
     {

         this._Example = example;

         this._Example += " (Updated By Z)";
     }
 }

 var x = new X();

When running the above code the output is:

X (Updated By Y)

And not:

X (Updated By Y) (Updated By Z)

As I had hoped.

It seems that assigning a "ref parameter" to a field loses the reference.

Is there a way to keep hold of the reference when assigning to a field?


Solution

No. ref is purely a calling convention. You can't use it to qualify a field. In Z, _Example gets set to the value of the string reference passed in. You then assign a new string reference to it using +=. You never assign to example, so the ref has no effect.

The only work-around for what you want is to have a shared mutable wrapper object (an array or a hypothetical StringWrapper) that contains the reference (a string here). Generally, if you need this, you can find a larger mutable object for the classes to share.

 public class StringWrapper
 {
   public string s;
   public StringWrapper(string s)
   {
     this.s = s;
   }

   public string ToString()
   {
     return s;
   }
 }

 public class X
 {
  public X()
  {
   StringWrapper example = new StringWrapper("X");
   new Z(example)
   System.Diagnostics.Debug.WriteLine( example );
  }
 }

 public class Z
 {
  private StringWrapper _Example;
  public Z( StringWrapper example )
  {
   this._Example = example;
   this._Example.s += " (Updated By Z)";
  }
 }


Answered By - Matthew Flaschen
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] How can I pass field name of a class as parameter to include it in a String?

 July 07, 2022     class, field, java, string     No comments   

Issue

I'm wondering How can I pass field name of a class as parameter to include it in a String?

For example, let's say I have a class A with this members :

public class A {

String name;
String reference;
....

}

What I want, is to be able to initialize a string having as parameters one of the two classe field name to display it dynamically. So for instance, I want to do this :

System.out.println("the field {nameField} belong to class A.");

And in output I would have this :

output : the field name belong to class A.

Is that possible in Java ?

Any help would be much appreciated ?

Regards

YT


Solution

This can be done by use of reflection in Java. https://www.oracle.com/technical-resources/articles/java/javareflection.html#:~:text=Reflection%20is%20a%20feature%20in,its%20members%20and%20display%20them.



Answered By - Harshita
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, April 21, 2022

[FIXED] How do I validate multiple fields from a single location in CakePHP?

 April 21, 2022     cakephp, cakephp-2.3, field, validation     No comments   

Issue

I wanna validate multiple fields at one place. So in a form I have included 4 fields as follows

  1. facebook_link
  2. twitter_link
  3. google_plus_link
  4. linked_in_link

The user atleast type any one field of above. Please help me to get the solution like, the user types anyone of the links in the form.


Solution

you may add your own Validation Methods.

public $validate = array(
    'facebook_link' => array(
        'rule'    => array('validateLink'),
        'message' => '...'
    ),
    'twitter_link' => array(
        'rule'    => array('validateLink'),
        'message' => '...'
    ),
    'google_plus_link' => array(
        'rule'    => array('validateLink'),
        'message' => '...'
    ),
    'linked_in_link' => array(
        'rule'    => array('validateLink'),
        'message' => '...'
    ),
);

public function validateLink($link) {
    $allFieldsAreEmpty = (
        empty($this->data[$this->alias]['facebook_link']) &&
        empty($this->data[$this->alias]['twitter_link']) &&
        empty($this->data[$this->alias]['google_plus_link']) &&
        empty($this->data[$this->alias]['linked_in_link'])
    );

    return !$allFieldsAreEmpty;
}


Answered By - Pitsanu Swangpheaw
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 31, 2022

[FIXED] Symfony - FormType - set field display:none by default

 January 31, 2022     display, field, label, styles, symfony     No comments   

Issue

in my formType on Symfony I try to hide a default field.

So I did like this:

        ->add('amountReduction', NumberType::class, [
            "required" => false,
            "label" => "Montant de la réduction",
            "attr" => [
                "style" => "width: 200px; display: none;"
            ],
        ])

The problem is that the label is still visible. I would like to display: none; the whole field by default.

The goal is then that in the template, I can make a $(".field").show() which will display the label and the entire field

Thanks for your help


Solution

Use the row_attr option.

->add('amountReduction', NumberType::class, [
            "required" => false,
            "label" => "Montant de la réduction",
            "row_attr" => [
                "class" => "d-none"
            ],
        ])


Answered By - Frank B
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 13, 2022

[FIXED] cakephp : dynamic form fields

 January 13, 2022     cakephp, dynamic, field, forms, names     No comments   

Issue

I have a form that has all the fields pulled dynamic from a database table 'FieldNames':

ID | FieldName
--------------
11 | username
22 | password
33 | Address
44 | etc

This is just an example, the form is more complex.

I have learned and saw in php doc that if the form fields match 1:1 with the model table the Save method is user and a new row gets created with all the values in the proper cells. But how does it work if for my sample form all fields values should get in multiple lines, one by one in a table 'FieldValues' with the following structure.

ID | FieldId | Value                | DataSet
---------------------------------------------
1  | 11      | 'value for username' | 1
2  | 22      | 'value for password' | 1
3  | 33      | 'value for address'  | 1

FieldId = FK to Fieldnames.ID

I was able to do this in a method using the "classic"

foreach field -> $sql = "sql insert query" -> $this->query( $sql )'

I was just wondering is i can use the "magic" in cake to solve this task. Second question: If the "magic" is possible, how can i add a second parameter and on each data set to set a new DataSet value ?

This is a form builder app so the fields HAVE to be dynamic and I cannot use the "static" form implementation (hardcode the fields names in table columns 1:1). The field names and number vary. That's why I'm pulling them for the database.


Solution

I suggest you to create a method in your model (where you want to save your fields) like:

// Field model
public function saveFields($data) {
    foreach($data as $field) {
        $this->save($field);
    }
}

You can call this function in your FieldsController Add Action:

// FieldsController
$this->Field->saveFields($this->request->data);

Or in any other Controller / Model by using ClassRegistry:

// FooController
$Field = ClassRegistry::init('Field');
$Field->saveFields($this->request->data);

Be sure that your data is in the proper format like:

$data [0] [ ModelName ] = array(
    Field1 => Value1,
    Field2 => Value2 
)


Answered By - Julian Hollmann
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing